Skip to content

Commit

Permalink
Explain error with &mut self for unsized trait impls
Browse files Browse the repository at this point in the history
  • Loading branch information
clubby789 committed Jan 5, 2023
1 parent b435960 commit 23c3a30
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 11 deletions.
27 changes: 16 additions & 11 deletions compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,20 +344,25 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
} else {
err.span_help(source_info.span, "try removing `&mut` here");
}
} else if decl.mutability == Mutability::Not
&& !matches!(
} else if decl.mutability == Mutability::Not {
if matches!(
decl.local_info,
Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
hir::ImplicitSelfKind::MutRef
))))
)
{
err.span_suggestion_verbose(
decl.source_info.span.shrink_to_lo(),
"consider making the binding mutable",
"mut ",
Applicability::MachineApplicable,
);
),)))
) {
err.note(
"as `Self` may be unsized, this call attempts to take `&mut &mut self`",
);
err.note("however, `&mut self` expands to `self: &mut Self`, therefore `self` cannot be borrowed mutably");
} else {
err.span_suggestion_verbose(
decl.source_info.span.shrink_to_lo(),
"consider making the binding mutable",
"mut ",
Applicability::MachineApplicable,
);
};
}
}

Expand Down
15 changes: 15 additions & 0 deletions src/test/ui/borrowck/issue-93078.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
trait Modify {
fn modify(&mut self) ;
}

impl<T> Modify for T {
fn modify(&mut self) {}
}

trait Foo {
fn mute(&mut self) {
self.modify(); //~ ERROR cannot borrow `self` as mutable
}
}

fn main() {}
12 changes: 12 additions & 0 deletions src/test/ui/borrowck/issue-93078.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
error[E0596]: cannot borrow `self` as mutable, as it is not declared as mutable
--> $DIR/issue-93078.rs:11:9
|
LL | self.modify();
| ^^^^^^^^^^^^^ cannot borrow as mutable
|
= note: as `Self` may be unsized, this call attempts to take `&mut &mut self`
= note: however, `&mut self` expands to `self: &mut Self`, therefore `self` cannot be borrowed mutably

error: aborting due to previous error

For more information about this error, try `rustc --explain E0596`.

0 comments on commit 23c3a30

Please sign in to comment.