Skip to content

improve error message when resolution via Deref actually required DerefMut #28419

Closed
@pnkfelix

Description

@pnkfelix

If a type B implements Deref to get out &A, then auto-deref based method resolution of instances of B will include methods of A that require &mut self, even when there is no DerefMut that would be necessary for such auto-deref to work.

We still reject the code, with the message "cannot borrow immutable borrowed content as mutable"

What I would prefer is for the message to say something like:

error: cannot do mutable borrow via Deref alone
note: would need (at least) impl DerefMut for A

  • (i included some weasel language in the above that might be better editted out of a good error report.)

(I think @nikomatsakis is well aware of this problem; he's mentioned the issue about how the auto-deref code needs to use a conservative guess during method resolution and rely on later compiler stages to reject the method lookup.)

Here is an example of code exhibiting the problem playpen:

use std::ops::Deref;

struct A(i32);
struct B(A);

impl A {
    fn yow(&mut self) { println!("Hi"); }
}

impl Deref for B {
    type Target = A;
    fn deref(&self) -> &Self::Target { &self.0 }
}

fn main() {
    let mut b = B(A(3));
    b.yow();
}

The error message when you run this (on nightly) is:

<anon>:17:5: 17:6 error: cannot borrow immutable borrowed content as mutable
<anon>:17     b.yow();
              ^
error: aborting due to previous error

This message can be frustrating, especially when the content appears mutable at the point that is highlighted by the span of the error message; after all, I did use let mut b = ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.WG-diagnosticsWorking group: Diagnostics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions