Skip to content

Suggest use .get_mut instead of &mut when overloaded index type not impl IndexMut - #144018

Closed
xizheyin wants to merge 2 commits into
rust-lang:masterfrom
xizheyin:143732
Closed

Suggest use .get_mut instead of &mut when overloaded index type not impl IndexMut#144018
xizheyin wants to merge 2 commits into
rust-lang:masterfrom
xizheyin:143732

Conversation

@xizheyin

@xizheyinxizheyin commented Jul 16, 2025

Copy link
Copy Markdown
Member

Fixes#143732

r? compiler

@rustbotrustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Jul 16, 2025
@fee1-dead

Copy link
Copy Markdown
Member

You need to compare the defid with the defid of the HashMap/BTreeMap diagnostic item and hard code the special case

@xizheyinxizheyin changed the title Suggest use .get_mut instead of &mut when occur overloaded index expressionSuggest use .get_mut instead of &mut when occur HashMap and BtreeMapJul 16, 2025

@xizheyinxizheyin left a comment

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The second commit shows the testcase difference.

Comment threadcompiler/rustc_borrowck/src/diagnostics/mutability_errors.rs Outdated
@fee1-dead

fee1-dead commented Jul 17, 2025

Copy link
Copy Markdown
Member

In your first version you checked if the assignment on the type came from an overloaded index. You should check whether the overloaded index type implements IndexMut and return instead of passing the bool into the suggest_ampmut function if they don't implement IndexMut, then before returning you can suggest get_mut

@rustbot author

@rustbotrustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 17, 2025
@rustbot

Copy link
Copy Markdown
Collaborator

Reminder, once the PR becomes ready for a review, use @rustbot ready.

@xizheyin
xizheyinforce-pushed the 143732 branch 2 times, most recently from 8d3b265 to c43a91fCompareJuly 20, 2025 10:07

@xizheyinxizheyin left a comment

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rustbot ready

Comment on lines +16 to +38
let mut vec = vec![String::new(), String::new()];
let string = &vec[0];
string.push_str("test"); //~ ERROR cannot borrow `*string` as mutable, as it is behind a `&` reference [E0596]

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I add a case that type impls IndexMut, i.e. Vec.

Comment on lines +1449 to +1455
.type_implements_trait(
index_mut_trait,
[ty, index_ty],
self.infcx.param_env,
)
.must_apply_modulo_regions()

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I use type_implements_trait to judge if the type impl IndexMut.

@rustbotrustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Jul 20, 2025
@rust-log-analyzer

This comment has been minimized.

@xizheyinxizheyin changed the title Suggest use .get_mut instead of &mut when occur HashMap and BtreeMapSuggest use .get_mut instead of &mut when overloaded index type not impl IndexMutJul 20, 2025
@fee1-dead

Copy link
Copy Markdown
Member

#144018 (comment)

@rustbot author

@rustbotrustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 21, 2025
@xizheyin

xizheyin commented Jul 21, 2025

Copy link
Copy Markdown
MemberAuthor

#144018 (comment)

This comment asks me to check the type which use overloaded index but not implement IndexMut, HashMap and BTreeMap are in that category, my understanding is that this is a enhancement over hardcoded. Why we should still hard-coding HashMap and BTreeMap? 😵‍💫

@fee1-dead

Copy link
Copy Markdown
Member

because there are other types that aren't IndexMutand that aren't HashMap or BTreeMap?

@xizheyin

Copy link
Copy Markdown
MemberAuthor

#143732 (comment)

@Kobzol suggest to consider all the types in this category? What do you think?

If we only consider a special case, we don't have to check whether it implements IndexMut. Because these two types didnt implement IndexMut, it seems to be enough to judge directly by using defid.

@Kobzol

Copy link
Copy Markdown
Member

My suggestion was:

  • If T doesn't implement IndexMut, don't show the hint at all
  • If T is a Hashmap/HashSet, suggest get_mut

@xizheyin

Copy link
Copy Markdown
MemberAuthor

This is clear. I forgot that some types do not have get_mut.

Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>

@xizheyinxizheyin left a comment

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rustbot ready

This time, I considered different scenarios:

  1. suggest to use &mut
  2. suggest to use .get_mut
  3. dont suggest

I also added a new testcase.

Comment threadtests/ui/borrowck/suggest-use-as-mut-for-map.stderr Outdated
@rustbotrustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Jul 21, 2025
Comment threadtests/ui/borrowck/suggest-use-as-mut-for-map.rs
@xizheyin

Copy link
Copy Markdown
MemberAuthor

I spilt the testcase into two. One is marked run-rustfix, the other not.

Comment threadcompiler/rustc_borrowck/src/diagnostics/mutability_errors.rs Outdated
Comment threadcompiler/rustc_borrowck/src/diagnostics/mutability_errors.rs Outdated
@rustbotrustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 25, 2025
…or BTreeMap
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>

@xizheyinxizheyin left a comment

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rustbot ready

Comment on lines +1174 to +1178
// If there is a assignment, we should return the rhs
rhs = Some(rvalue);
if let mir::Rvalue::Use(mir::Operand::Copy(place)) = rvalue {
span = self.body.local_decls[place.local].source_info.span;
}

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To dedup if let StatementKind..., I return the RValue if it is a Assign and pass it into suggest_get_mut_or_ref_mut.

Comment on lines +1467 to +1482
// We only suggest use `.get_mut()` for HashMap or BTreeMap
// We don't try suggesting use `&mut`, so break
ControlFlow::Break(Some(AmpMutSugg {
has_sugg: true,
span: rhs_span,
suggestion: format!("{}.get_mut({}).unwrap()", map_part, key_part),
additional: None,
}))
} else {
// Type not implemented `IndexMut` but not HashMap or BTreeMap or error
// and we did not suggest either `.get_mut()` or `&mut`, so break
ControlFlow::Break(None)
}
} else {
// Type Impl IndexMut, we should continue to try suggesting use `&mut`
ControlFlow::Continue(())

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In these three situations, we return different values. If we don't want to try suggesting &mut, it return Break. Or we return Continue, which indicates continue to try suggesting &mut.

@rustbotrustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Jul 27, 2025
@xizheyinxizheyin closed this Aug 6, 2025
@rustbotrustbot removed the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Aug 6, 2025
Zalathar added a commit to Zalathar/rust that referenced this pull request Aug 19, 2025
…m, r=nnethercote
overhaul `&mut` suggestions in borrowck errors
* This refactors the logic so that it does not use fuzzy string matching for suggestions; it instead uses information directly from MIR.
* If something comes from a custom `Index` impl for which the `IndexMut` trait does not apply, do not suggest adding `mut` after `&`.
* Suggest `get_mut` with `unwrap` if error is fired on `BTreeMap` or `HashMap`.
Supersedes rust-lang#144018 cc `@xizheyin`
Closesrust-lang#143732
Zalathar added a commit to Zalathar/rust that referenced this pull request Aug 19, 2025
…m, r=nnethercote
overhaul `&mut` suggestions in borrowck errors
* This refactors the logic so that it does not use fuzzy string matching for suggestions; it instead uses information directly from MIR.
* If something comes from a custom `Index` impl for which the `IndexMut` trait does not apply, do not suggest adding `mut` after `&`.
* Suggest `get_mut` with `unwrap` if error is fired on `BTreeMap` or `HashMap`.
Supersedes rust-lang#144018 cc ``@xizheyin``
Closesrust-lang#143732
Zalathar added a commit to Zalathar/rust that referenced this pull request Aug 19, 2025
…m, r=nnethercote
overhaul `&mut` suggestions in borrowck errors
* This refactors the logic so that it does not use fuzzy string matching for suggestions; it instead uses information directly from MIR.
* If something comes from a custom `Index` impl for which the `IndexMut` trait does not apply, do not suggest adding `mut` after `&`.
* Suggest `get_mut` with `unwrap` if error is fired on `BTreeMap` or `HashMap`.
Supersedes rust-lang#144018 cc ```@xizheyin```
Closesrust-lang#143732
rust-timer added a commit that referenced this pull request Aug 19, 2025
Rollup merge of #145013 - fee1-dead-contrib:push-vwvsqsqnrxqm, r=nnethercote
overhaul `&mut` suggestions in borrowck errors
* This refactors the logic so that it does not use fuzzy string matching for suggestions; it instead uses information directly from MIR.
* If something comes from a custom `Index` impl for which the `IndexMut` trait does not apply, do not suggest adding `mut` after `&`.
* Suggest `get_mut` with `unwrap` if error is fired on `BTreeMap` or `HashMap`.
Supersedes #144018 cc ```@xizheyin```
Closes#143732
github-actionsBot pushed a commit to rust-lang/rustc-dev-guide that referenced this pull request Aug 25, 2025
…hercote
overhaul `&mut` suggestions in borrowck errors
* This refactors the logic so that it does not use fuzzy string matching for suggestions; it instead uses information directly from MIR.
* If something comes from a custom `Index` impl for which the `IndexMut` trait does not apply, do not suggest adding `mut` after `&`.
* Suggest `get_mut` with `unwrap` if error is fired on `BTreeMap` or `HashMap`.
Supersedes rust-lang/rust#144018 cc ```@xizheyin```
Closesrust-lang/rust#143732
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rust suggests using IndexMut for maps, even though they don't implement the trait

6 participants

@xizheyin@fee1-dead@rustbot@rust-log-analyzer@Kobzol@estebank