Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 83bf719

Browse files
committedMay 9, 2024
Suggest borrowing on fn argument that is impl AsRef
When encountering a move conflict, on an expression that is `!Copy` passed as an argument to an `fn` that is `impl AsRef`, suggest borrowing the expression. ``` error[E0382]: use of moved value: `bar` --> f204.rs:14:15 | 12 | let bar = Bar; | --- move occurs because `bar` has type `Bar`, which does not implement the `Copy` trait 13 | foo(bar); | --- value moved here 14 | let baa = bar; | ^^^ value used here after move | help: borrow the value to avoid moving it | 13 | foo(&bar); | + ``` Fix #41708
1 parent e6e262f commit 83bf719

File tree

5 files changed

+224
-20
lines changed

5 files changed

+224
-20
lines changed
 

‎compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+70-20
Original file line numberDiff line numberDiff line change
@@ -449,31 +449,81 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
449449
} else {
450450
(None, &[][..], 0)
451451
};
452+
let mut can_suggest_clone = true;
452453
if let Some(def_id) = def_id
453454
&& let node = self.infcx.tcx.hir_node_by_def_id(def_id)
454455
&& let Some(fn_sig) = node.fn_sig()
455456
&& let Some(ident) = node.ident()
456457
&& let Some(pos) = args.iter().position(|arg| arg.hir_id == expr.hir_id)
457458
&& let Some(arg) = fn_sig.decl.inputs.get(pos + offset)
458459
{
459-
let mut span: MultiSpan = arg.span.into();
460-
span.push_span_label(
461-
arg.span,
462-
"this parameter takes ownership of the value".to_string(),
463-
);
464-
let descr = match node.fn_kind() {
465-
Some(hir::intravisit::FnKind::ItemFn(..)) | None => "function",
466-
Some(hir::intravisit::FnKind::Method(..)) => "method",
467-
Some(hir::intravisit::FnKind::Closure) => "closure",
468-
};
469-
span.push_span_label(ident.span, format!("in this {descr}"));
470-
err.span_note(
471-
span,
472-
format!(
473-
"consider changing this parameter type in {descr} `{ident}` to borrow \
474-
instead if owning the value isn't necessary",
475-
),
476-
);
460+
let mut is_mut = false;
461+
if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = arg.kind
462+
&& let Res::Def(DefKind::TyParam, param_def_id) = path.res
463+
&& self
464+
.infcx
465+
.tcx
466+
.predicates_of(def_id)
467+
.instantiate_identity(self.infcx.tcx)
468+
.predicates
469+
.into_iter()
470+
.any(|pred| {
471+
if let ty::ClauseKind::Trait(predicate) = pred.kind().skip_binder()
472+
&& [
473+
self.infcx.tcx.get_diagnostic_item(sym::AsRef),
474+
self.infcx.tcx.get_diagnostic_item(sym::AsMut),
475+
self.infcx.tcx.get_diagnostic_item(sym::Borrow),
476+
self.infcx.tcx.get_diagnostic_item(sym::BorrowMut),
477+
]
478+
.contains(&Some(predicate.def_id()))
479+
&& let ty::Param(param) = predicate.self_ty().kind()
480+
&& let generics = self.infcx.tcx.generics_of(def_id)
481+
&& let param = generics.type_param(*param, self.infcx.tcx)
482+
&& param.def_id == param_def_id
483+
{
484+
if [
485+
self.infcx.tcx.get_diagnostic_item(sym::AsMut),
486+
self.infcx.tcx.get_diagnostic_item(sym::BorrowMut),
487+
]
488+
.contains(&Some(predicate.def_id()))
489+
{
490+
is_mut = true;
491+
}
492+
true
493+
} else {
494+
false
495+
}
496+
})
497+
{
498+
// The type of the argument corresponding to the expression that got moved
499+
// is a type parameter `T`, which is has a `T: AsRef` obligation.
500+
err.span_suggestion_verbose(
501+
expr.span.shrink_to_lo(),
502+
"borrow the value to avoid moving it",
503+
format!("&{}", if is_mut { "mut " } else { "" }),
504+
Applicability::MachineApplicable,
505+
);
506+
can_suggest_clone = is_mut;
507+
} else {
508+
let mut span: MultiSpan = arg.span.into();
509+
span.push_span_label(
510+
arg.span,
511+
"this parameter takes ownership of the value".to_string(),
512+
);
513+
let descr = match node.fn_kind() {
514+
Some(hir::intravisit::FnKind::ItemFn(..)) | None => "function",
515+
Some(hir::intravisit::FnKind::Method(..)) => "method",
516+
Some(hir::intravisit::FnKind::Closure) => "closure",
517+
};
518+
span.push_span_label(ident.span, format!("in this {descr}"));
519+
err.span_note(
520+
span,
521+
format!(
522+
"consider changing this parameter type in {descr} `{ident}` to \
523+
borrow instead if owning the value isn't necessary",
524+
),
525+
);
526+
}
477527
}
478528
let place = &self.move_data.move_paths[mpi].place;
479529
let ty = place.ty(self.body, self.infcx.tcx).ty;
@@ -491,10 +541,10 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
491541
ClosureKind::Coroutine(CoroutineKind::Desugared(_, CoroutineSource::Block)),
492542
..
493543
} = move_spans
544+
&& can_suggest_clone
494545
{
495546
self.suggest_cloning(err, ty, expr, None, Some(move_spans));
496-
} else if self.suggest_hoisting_call_outside_loop(err, expr) {
497-
// The place where the type moves would be misleading to suggest clone.
547+
} else if self.suggest_hoisting_call_outside_loop(err, expr) && can_suggest_clone {
498548
// #121466
499549
self.suggest_cloning(err, ty, expr, None, Some(move_spans));
500550
}

‎library/core/src/borrow.rs

+1
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ pub trait Borrow<Borrowed: ?Sized> {
184184
/// an underlying type by providing a mutable reference. See [`Borrow<T>`]
185185
/// for more information on borrowing as another type.
186186
#[stable(feature = "rust1", since = "1.0.0")]
187+
#[rustc_diagnostic_item = "BorrowMut"]
187188
pub trait BorrowMut<Borrowed: ?Sized>: Borrow<Borrowed> {
188189
/// Mutably borrows from an owned value.
189190
///
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//@ run-rustfix
2+
#![allow(unused_mut)]
3+
use std::borrow::{Borrow, BorrowMut};
4+
use std::convert::{AsMut, AsRef};
5+
struct Bar;
6+
7+
impl AsRef<Bar> for Bar {
8+
fn as_ref(&self) -> &Bar {
9+
self
10+
}
11+
}
12+
13+
impl AsMut<Bar> for Bar {
14+
fn as_mut(&mut self) -> &mut Bar {
15+
self
16+
}
17+
}
18+
19+
fn foo<T: AsRef<Bar>>(_: T) {}
20+
fn qux<T: AsMut<Bar>>(_: T) {}
21+
fn bat<T: Borrow<T>>(_: T) {}
22+
fn baz<T: BorrowMut<T>>(_: T) {}
23+
24+
pub fn main() {
25+
let bar = Bar;
26+
foo(&bar);
27+
let _baa = bar; //~ ERROR use of moved value
28+
let mut bar = Bar;
29+
qux(&mut bar);
30+
let _baa = bar; //~ ERROR use of moved value
31+
let bar = Bar;
32+
bat(&bar);
33+
let _baa = bar; //~ ERROR use of moved value
34+
let mut bar = Bar;
35+
baz(&mut bar);
36+
let _baa = bar; //~ ERROR use of moved value
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//@ run-rustfix
2+
#![allow(unused_mut)]
3+
use std::borrow::{Borrow, BorrowMut};
4+
use std::convert::{AsMut, AsRef};
5+
struct Bar;
6+
7+
impl AsRef<Bar> for Bar {
8+
fn as_ref(&self) -> &Bar {
9+
self
10+
}
11+
}
12+
13+
impl AsMut<Bar> for Bar {
14+
fn as_mut(&mut self) -> &mut Bar {
15+
self
16+
}
17+
}
18+
19+
fn foo<T: AsRef<Bar>>(_: T) {}
20+
fn qux<T: AsMut<Bar>>(_: T) {}
21+
fn bat<T: Borrow<T>>(_: T) {}
22+
fn baz<T: BorrowMut<T>>(_: T) {}
23+
24+
pub fn main() {
25+
let bar = Bar;
26+
foo(bar);
27+
let _baa = bar; //~ ERROR use of moved value
28+
let mut bar = Bar;
29+
qux(bar);
30+
let _baa = bar; //~ ERROR use of moved value
31+
let bar = Bar;
32+
bat(bar);
33+
let _baa = bar; //~ ERROR use of moved value
34+
let mut bar = Bar;
35+
baz(bar);
36+
let _baa = bar; //~ ERROR use of moved value
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
error[E0382]: use of moved value: `bar`
2+
--> $DIR/moved-value-on-as-ref-arg.rs:27:16
3+
|
4+
LL | let bar = Bar;
5+
| --- move occurs because `bar` has type `Bar`, which does not implement the `Copy` trait
6+
LL | foo(bar);
7+
| --- value moved here
8+
LL | let _baa = bar;
9+
| ^^^ value used here after move
10+
|
11+
help: borrow the value to avoid moving it
12+
|
13+
LL | foo(&bar);
14+
| +
15+
16+
error[E0382]: use of moved value: `bar`
17+
--> $DIR/moved-value-on-as-ref-arg.rs:30:16
18+
|
19+
LL | let mut bar = Bar;
20+
| ------- move occurs because `bar` has type `Bar`, which does not implement the `Copy` trait
21+
LL | qux(bar);
22+
| --- value moved here
23+
LL | let _baa = bar;
24+
| ^^^ value used here after move
25+
|
26+
note: if `Bar` implemented `Clone`, you could clone the value
27+
--> $DIR/moved-value-on-as-ref-arg.rs:5:1
28+
|
29+
LL | struct Bar;
30+
| ^^^^^^^^^^ consider implementing `Clone` for this type
31+
...
32+
LL | qux(bar);
33+
| --- you could clone this value
34+
help: borrow the value to avoid moving it
35+
|
36+
LL | qux(&mut bar);
37+
| ++++
38+
39+
error[E0382]: use of moved value: `bar`
40+
--> $DIR/moved-value-on-as-ref-arg.rs:33:16
41+
|
42+
LL | let bar = Bar;
43+
| --- move occurs because `bar` has type `Bar`, which does not implement the `Copy` trait
44+
LL | bat(bar);
45+
| --- value moved here
46+
LL | let _baa = bar;
47+
| ^^^ value used here after move
48+
|
49+
help: borrow the value to avoid moving it
50+
|
51+
LL | bat(&bar);
52+
| +
53+
54+
error[E0382]: use of moved value: `bar`
55+
--> $DIR/moved-value-on-as-ref-arg.rs:36:16
56+
|
57+
LL | let mut bar = Bar;
58+
| ------- move occurs because `bar` has type `Bar`, which does not implement the `Copy` trait
59+
LL | baz(bar);
60+
| --- value moved here
61+
LL | let _baa = bar;
62+
| ^^^ value used here after move
63+
|
64+
note: if `Bar` implemented `Clone`, you could clone the value
65+
--> $DIR/moved-value-on-as-ref-arg.rs:5:1
66+
|
67+
LL | struct Bar;
68+
| ^^^^^^^^^^ consider implementing `Clone` for this type
69+
...
70+
LL | baz(bar);
71+
| --- you could clone this value
72+
help: borrow the value to avoid moving it
73+
|
74+
LL | baz(&mut bar);
75+
| ++++
76+
77+
error: aborting due to 4 previous errors
78+
79+
For more information about this error, try `rustc --explain E0382`.

0 commit comments

Comments
 (0)
Failed to load comments.