Skip to content

Commit 7850fc4

Browse files
authored
Rollup merge of #149101 - reddevilmidzy:mutable, r=eholk
Improve mutable-binding suggestion to include name resolve: #148467
2 parents a308ab8 + d49075f commit 7850fc4

File tree

3 files changed

+44
-1
lines changed

3 files changed

+44
-1
lines changed

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3940,13 +3940,30 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
39403940
if let Some(decl) = local_decl
39413941
&& decl.can_be_made_mutable()
39423942
{
3943+
let is_for_loop = matches!(
3944+
decl.local_info(),
3945+
LocalInfo::User(BindingForm::Var(VarBindingForm {
3946+
opt_match_place: Some((_, match_span)),
3947+
..
3948+
})) if matches!(match_span.desugaring_kind(), Some(DesugaringKind::ForLoop))
3949+
);
3950+
let message = if is_for_loop
3951+
&& let Ok(binding_name) =
3952+
self.infcx.tcx.sess.source_map().span_to_snippet(decl.source_info.span)
3953+
{
3954+
format!("(mut {}) ", binding_name)
3955+
} else {
3956+
"mut ".to_string()
3957+
};
39433958
err.span_suggestion_verbose(
39443959
decl.source_info.span.shrink_to_lo(),
39453960
"consider making this binding mutable",
3946-
"mut ".to_string(),
3961+
message,
39473962
Applicability::MachineApplicable,
39483963
);
3964+
39493965
if !from_arg
3966+
&& !is_for_loop
39503967
&& matches!(
39513968
decl.local_info(),
39523969
LocalInfo::User(BindingForm::Var(VarBindingForm {
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
//! regression test for <https://github.com/rust-lang/rust/issues/148467>
2+
//! Ensure the diagnostic suggests `for &(mut x) ...` (parenthesized) instead of `&mut x`.
3+
4+
fn main() {
5+
let nums: &[u32] = &[1, 2, 3];
6+
for &num in nums {
7+
num *= 2; //~ ERROR cannot assign twice to immutable variable `num`
8+
println!("{num}");
9+
}
10+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error[E0384]: cannot assign twice to immutable variable `num`
2+
--> $DIR/borrowck-for-loop-deref-pattern-assignment.rs:7:9
3+
|
4+
LL | for &num in nums {
5+
| --- first assignment to `num`
6+
LL | num *= 2;
7+
| ^^^^^^^^ cannot assign twice to immutable variable
8+
|
9+
help: consider making this binding mutable
10+
|
11+
LL | for &(mut num) num in nums {
12+
| +++++++++
13+
14+
error: aborting due to 1 previous error
15+
16+
For more information about this error, try `rustc --explain E0384`.

0 commit comments

Comments
 (0)