Skip to content

Commit fe07531

Browse files
author
Yuki Okushi
authored
Rollup merge of #106410 - clubby789:borrow-mut-self-mut-self-diag, r=compiler-errors
Suggest `mut self: &mut Self` for `?Sized` impls Closes #106325 Closes #93078 The suggestion is _probably_ not what the user wants (hence `MaybeIncorrect`) but at least makes the problem in the above issues clearer. It might be better to add a note explaining why this is the case, but I'm not sure how best to word that so this is a start. ``@rustbot`` label +A-diagnostics
2 parents ed77ffe + 23c3a30 commit fe07531

File tree

3 files changed

+43
-11
lines changed

3 files changed

+43
-11
lines changed

compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -344,20 +344,25 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
344344
} else {
345345
err.span_help(source_info.span, "try removing `&mut` here");
346346
}
347-
} else if decl.mutability == Mutability::Not
348-
&& !matches!(
347+
} else if decl.mutability == Mutability::Not {
348+
if matches!(
349349
decl.local_info,
350350
Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
351351
hir::ImplicitSelfKind::MutRef
352-
))))
353-
)
354-
{
355-
err.span_suggestion_verbose(
356-
decl.source_info.span.shrink_to_lo(),
357-
"consider making the binding mutable",
358-
"mut ",
359-
Applicability::MachineApplicable,
360-
);
352+
),)))
353+
) {
354+
err.note(
355+
"as `Self` may be unsized, this call attempts to take `&mut &mut self`",
356+
);
357+
err.note("however, `&mut self` expands to `self: &mut Self`, therefore `self` cannot be borrowed mutably");
358+
} else {
359+
err.span_suggestion_verbose(
360+
decl.source_info.span.shrink_to_lo(),
361+
"consider making the binding mutable",
362+
"mut ",
363+
Applicability::MachineApplicable,
364+
);
365+
};
361366
}
362367
}
363368

src/test/ui/borrowck/issue-93078.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
trait Modify {
2+
fn modify(&mut self) ;
3+
}
4+
5+
impl<T> Modify for T {
6+
fn modify(&mut self) {}
7+
}
8+
9+
trait Foo {
10+
fn mute(&mut self) {
11+
self.modify(); //~ ERROR cannot borrow `self` as mutable
12+
}
13+
}
14+
15+
fn main() {}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
error[E0596]: cannot borrow `self` as mutable, as it is not declared as mutable
2+
--> $DIR/issue-93078.rs:11:9
3+
|
4+
LL | self.modify();
5+
| ^^^^^^^^^^^^^ cannot borrow as mutable
6+
|
7+
= note: as `Self` may be unsized, this call attempts to take `&mut &mut self`
8+
= note: however, `&mut self` expands to `self: &mut Self`, therefore `self` cannot be borrowed mutably
9+
10+
error: aborting due to previous error
11+
12+
For more information about this error, try `rustc --explain E0596`.

0 commit comments

Comments
 (0)