Skip to content

Commit b83ab0c

Browse files
committedJan 25, 2023
Suggest mutable borrows correctly
1 parent 800f1f3 commit b83ab0c

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed
 

‎compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs

+18-8
Original file line numberDiff line numberDiff line change
@@ -3775,12 +3775,12 @@ fn hint_missing_borrow<'tcx>(
37753775

37763776
let args = fn_decl.inputs.iter().map(|ty| ty);
37773777

3778-
fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, usize) {
3779-
let mut refs = 0;
3778+
fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
3779+
let mut refs = vec![];
37803780

3781-
while let ty::Ref(_, new_ty, _) = ty.kind() {
3781+
while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
37823782
ty = *new_ty;
3783-
refs += 1;
3783+
refs.push(*mutbl);
37843784
}
37853785

37863786
(ty, refs)
@@ -3794,11 +3794,21 @@ fn hint_missing_borrow<'tcx>(
37943794
let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
37953795

37963796
if infcx.can_eq(param_env, found_ty, expected_ty).is_ok() {
3797-
if found_refs < expected_refs {
3798-
to_borrow.push((arg.span.shrink_to_lo(), "&".repeat(expected_refs - found_refs)));
3799-
} else if found_refs > expected_refs {
3797+
// FIXME: This could handle more exotic cases like mutability mismatches too!
3798+
if found_refs.len() < expected_refs.len()
3799+
&& found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
3800+
{
3801+
to_borrow.push((
3802+
arg.span.shrink_to_lo(),
3803+
expected_refs[..expected_refs.len() - found_refs.len()]
3804+
.iter()
3805+
.map(|mutbl| format!("&{}", mutbl.prefix_str()))
3806+
.collect::<Vec<_>>()
3807+
.join(""),
3808+
));
3809+
} else if found_refs.len() > expected_refs.len() {
38003810
let mut span = arg.span.shrink_to_lo();
3801-
let mut left = found_refs - expected_refs;
3811+
let mut left = found_refs.len() - expected_refs.len();
38023812
let mut ty = arg;
38033813
while let hir::TyKind::Ref(_, mut_ty) = &ty.kind && left > 0 {
38043814
span = span.with_hi(mut_ty.ty.span.lo());

‎tests/ui/suggestions/late-bound-in-borrow-closure-sugg.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ LL | pub fn set_closure(&mut self, function: impl Fn(&mut Trader) + 'a) {
1818
| ^^^^^^^^^^^^^^^ required by this bound in `Trader::<'a>::set_closure`
1919
help: consider borrowing the argument
2020
|
21-
LL | let closure = |trader : &Trader| {
22-
| +
21+
LL | let closure = |trader : &mut Trader| {
22+
| ++++
2323

2424
error: aborting due to previous error
2525

0 commit comments

Comments
 (0)