Skip to content

Commit 14473ad

Browse files
committed
Detect when move of !Copy value occurs within loop and should likely not be cloned
When encountering a move error on a value within a loop of any kind, identify if the moved value belongs to a call expression that should not be cloned and avoid the semantically incorrect suggestion. Also try to suggest moving the call expression outside of the loop instead. ``` error[E0382]: use of moved value: `vec` --> $DIR/recreating-value-in-loop-condition.rs:6:33 | LL | let vec = vec!["one", "two", "three"]; | --- move occurs because `vec` has type `Vec<&str>`, which does not implement the `Copy` trait LL | while let Some(item) = iter(vec).next() { | ----------------------------^^^-------- | | | | | value moved here, in previous iteration of loop | inside of this loop | note: consider changing this parameter type in function `iter` to borrow instead if owning the value isn't necessary --> $DIR/recreating-value-in-loop-condition.rs:1:17 | LL | fn iter<T>(vec: Vec<T>) -> impl Iterator<Item = T> { | ---- ^^^^^^ this parameter takes ownership of the value | | | in this function help: consider moving the expression out of the loop so it is only moved once | LL ~ let mut value = iter(vec); LL ~ while let Some(item) = value.next() { | ``` We use the presence of a `break` in the loop that would be affected by the moved value as a heuristic for "shouldn't be cloned". Fix #121466.
1 parent 22e241e commit 14473ad

13 files changed

+437
-42
lines changed

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+160-2
Original file line numberDiff line numberDiff line change
@@ -447,8 +447,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
447447
err.span_note(
448448
span,
449449
format!(
450-
"consider changing this parameter type in {descr} `{ident}` to \
451-
borrow instead if owning the value isn't necessary",
450+
"consider changing this parameter type in {descr} `{ident}` to borrow \
451+
instead if owning the value isn't necessary",
452452
),
453453
);
454454
}
@@ -747,8 +747,166 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
747747
true
748748
}
749749

750+
/// In a move error that occurs on a call wihtin a loop, we try to identify cases where cloning
751+
/// the value would lead to a logic error. We infer these cases by seeing if the moved value is
752+
/// part of the logic to break the loop, either through an explicit `break` or if the expression
753+
/// is part of a `while let`.
754+
fn suggest_hoisting_call_outside_loop(&self, err: &mut Diag<'_>, expr: &hir::Expr<'_>) -> bool {
755+
let tcx = self.infcx.tcx;
756+
let mut can_suggest_clone = true;
757+
758+
// If the moved value is a locally declared binding, we'll look upwards on the expression
759+
// tree until the scope where it is defined, and no further, as suggesting to move the
760+
// expression beyond that point would be illogical.
761+
let local_hir_id = if let hir::ExprKind::Path(hir::QPath::Resolved(
762+
_,
763+
hir::Path { res: hir::def::Res::Local(local_hir_id), .. },
764+
)) = expr.kind
765+
{
766+
Some(local_hir_id)
767+
} else {
768+
// This case would be if the moved value comes from an argument binding, we'll just
769+
// look within the entire item, that's fine.
770+
None
771+
};
772+
773+
/// This will allow us to look for a specific `HirId`, in our case `local_hir_id` where the
774+
/// binding was declared, within any other expression. We'll use it to search for the
775+
/// binding declaration within every scope we inspect.
776+
struct Finder {
777+
hir_id: hir::HirId,
778+
found: bool,
779+
}
780+
impl<'hir> Visitor<'hir> for Finder {
781+
fn visit_pat(&mut self, pat: &'hir hir::Pat<'hir>) {
782+
if pat.hir_id == self.hir_id {
783+
self.found = true;
784+
}
785+
hir::intravisit::walk_pat(self, pat);
786+
}
787+
fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
788+
if ex.hir_id == self.hir_id {
789+
self.found = true;
790+
}
791+
hir::intravisit::walk_expr(self, ex);
792+
}
793+
}
794+
// The immediate HIR parent of the moved expression. We'll look for it to be a call.
795+
let mut parent = None;
796+
// The top-most loop where the moved expression could be moved to a new binding.
797+
let mut outer_most_loop: Option<&hir::Expr<'_>> = None;
798+
for (_, node) in tcx.hir().parent_iter(expr.hir_id) {
799+
let e = match node {
800+
hir::Node::Expr(e) => e,
801+
hir::Node::Local(hir::Local { els: Some(els), .. }) => {
802+
let mut finder = BreakFinder { found_break: false };
803+
finder.visit_block(els);
804+
if finder.found_break {
805+
// Don't suggest clone as it could be will likely end in an infinite
806+
// loop.
807+
// let Some(_) = foo(non_copy.clone()) else { break; }
808+
// --- ^^^^^^^^ -----
809+
can_suggest_clone = false;
810+
}
811+
continue;
812+
}
813+
_ => continue,
814+
};
815+
if let Some(&hir_id) = local_hir_id {
816+
let mut finder = Finder { hir_id, found: false };
817+
finder.visit_expr(e);
818+
if finder.found {
819+
// The current scope includes the declaration of the binding we're accessing, we
820+
// can't look up any further for loops.
821+
break;
822+
}
823+
}
824+
if parent.is_none() {
825+
parent = Some(e);
826+
}
827+
match e.kind {
828+
hir::ExprKind::Let(_) => {
829+
match tcx.parent_hir_node(e.hir_id) {
830+
hir::Node::Expr(hir::Expr {
831+
kind: hir::ExprKind::If(cond, ..), ..
832+
}) => {
833+
let mut finder = Finder { hir_id: expr.hir_id, found: false };
834+
finder.visit_expr(cond);
835+
if finder.found {
836+
// The expression where the move error happened is in a `while let`
837+
// condition Don't suggest clone as it will likely end in an
838+
// infinite loop.
839+
// while let Some(_) = foo(non_copy.clone()) { }
840+
// --------- ^^^^^^^^
841+
can_suggest_clone = false;
842+
}
843+
}
844+
_ => {}
845+
}
846+
}
847+
hir::ExprKind::Loop(..) => {
848+
outer_most_loop = Some(e);
849+
}
850+
_ => {}
851+
}
852+
}
853+
854+
/// Look for `break` expressions within any arbitrary expressions. We'll do this to infer
855+
/// whether this is a case where the moved value would affect the exit of a loop, making it
856+
/// unsuitable for a `.clone()` suggestion.
857+
struct BreakFinder {
858+
found_break: bool,
859+
}
860+
impl<'hir> Visitor<'hir> for BreakFinder {
861+
fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
862+
if let hir::ExprKind::Break(..) = ex.kind {
863+
self.found_break = true;
864+
}
865+
hir::intravisit::walk_expr(self, ex);
866+
}
867+
}
868+
if let Some(in_loop) = outer_most_loop
869+
&& let Some(parent) = parent
870+
&& let hir::ExprKind::MethodCall(..) | hir::ExprKind::Call(..) = parent.kind
871+
{
872+
// FIXME: We could check that the call's *parent* takes `&mut val` to make the
873+
// suggestion more targeted to the `mk_iter(val).next()` case. Maybe do that only to
874+
// check for wheter to suggest `let value` or `let mut value`.
875+
876+
let span = in_loop.span;
877+
let mut finder = BreakFinder { found_break: false };
878+
finder.visit_expr(in_loop);
879+
let sm = tcx.sess.source_map();
880+
if (finder.found_break || true)
881+
&& let Ok(value) = sm.span_to_snippet(parent.span)
882+
{
883+
// We know with high certainty that this move would affect the early return of a
884+
// loop, so we suggest moving the expression with the move out of the loop.
885+
let indent = if let Some(indent) = sm.indentation_before(span) {
886+
format!("\n{indent}")
887+
} else {
888+
" ".to_string()
889+
};
890+
err.multipart_suggestion(
891+
"consider moving the expression out of the loop so it is only moved once",
892+
vec![
893+
(parent.span, "value".to_string()),
894+
(span.shrink_to_lo(), format!("let mut value = {value};{indent}")),
895+
],
896+
Applicability::MaybeIncorrect,
897+
);
898+
}
899+
}
900+
can_suggest_clone
901+
}
902+
750903
fn suggest_cloning(&self, err: &mut Diag<'_>, ty: Ty<'tcx>, expr: &hir::Expr<'_>, span: Span) {
751904
let tcx = self.infcx.tcx;
905+
if !self.suggest_hoisting_call_outside_loop(err, expr) {
906+
// The place where the the type moves would be misleading to suggest clone. (#121466)
907+
return;
908+
}
909+
752910
// Try to find predicates on *generic params* that would allow copying `ty`
753911
let suggestion =
754912
if let Some(symbol) = tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) {

compiler/rustc_hir/src/hir.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2049,7 +2049,7 @@ impl LoopSource {
20492049
}
20502050
}
20512051

2052-
#[derive(Copy, Clone, Debug, HashStable_Generic)]
2052+
#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)]
20532053
pub enum LoopIdError {
20542054
OutsideLoopScope,
20552055
UnlabeledCfInWhileCondition,

tests/ui/borrowck/mut-borrow-in-loop-2.fixed

-35
This file was deleted.

tests/ui/borrowck/mut-borrow-in-loop-2.rs

-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
//@ run-rustfix
21
#![allow(dead_code)]
32

43
struct Events<R>(R);

tests/ui/borrowck/mut-borrow-in-loop-2.stderr

+8-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error[E0382]: use of moved value: `value`
2-
--> $DIR/mut-borrow-in-loop-2.rs:31:23
2+
--> $DIR/mut-borrow-in-loop-2.rs:30:23
33
|
44
LL | fn this_does_not<'a, R>(value: &'a mut Events<R>) {
55
| ----- move occurs because `value` has type `&mut Events<R>`, which does not implement the `Copy` trait
@@ -9,12 +9,18 @@ LL | Other::handle(value);
99
| ^^^^^ value moved here, in previous iteration of loop
1010
|
1111
note: consider changing this parameter type in function `handle` to borrow instead if owning the value isn't necessary
12-
--> $DIR/mut-borrow-in-loop-2.rs:9:22
12+
--> $DIR/mut-borrow-in-loop-2.rs:8:22
1313
|
1414
LL | fn handle(value: T) -> Self;
1515
| ------ ^ this parameter takes ownership of the value
1616
| |
1717
| in this function
18+
help: consider moving the expression out of the loop so it is only moved once
19+
|
20+
LL ~ let mut value = Other::handle(value);
21+
LL ~ for _ in 0..3 {
22+
LL ~ value;
23+
|
1824
help: consider creating a fresh reborrow of `value` here
1925
|
2026
LL | Other::handle(&mut *value);

tests/ui/liveness/liveness-move-call-arg-2.stderr

+6
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ LL | fn take(_x: Box<isize>) {}
1616
| ---- ^^^^^^^^^^ this parameter takes ownership of the value
1717
| |
1818
| in this function
19+
help: consider moving the expression out of the loop so it is only moved once
20+
|
21+
LL ~ let mut value = take(x);
22+
LL ~ loop {
23+
LL ~ value;
24+
|
1925
help: consider cloning the value if the performance cost is acceptable
2026
|
2127
LL | take(x.clone());

tests/ui/liveness/liveness-move-call-arg.stderr

+6
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ LL | fn take(_x: Box<isize>) {}
1616
| ---- ^^^^^^^^^^ this parameter takes ownership of the value
1717
| |
1818
| in this function
19+
help: consider moving the expression out of the loop so it is only moved once
20+
|
21+
LL ~ let mut value = take(x);
22+
LL ~ loop {
23+
LL ~ value;
24+
|
1925
help: consider cloning the value if the performance cost is acceptable
2026
|
2127
LL | take(x.clone());

tests/ui/moves/borrow-closures-instead-of-move.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
fn takes_fn(f: impl Fn()) {
2-
loop {
2+
loop { //~ HELP consider moving the expression out of the loop so it is only computed once
33
takes_fnonce(f);
44
//~^ ERROR use of moved value
55
//~| HELP consider borrowing

tests/ui/moves/borrow-closures-instead-of-move.stderr

+6
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ LL | fn takes_fnonce(_: impl FnOnce()) {}
1515
| ------------ ^^^^^^^^^^^^^ this parameter takes ownership of the value
1616
| |
1717
| in this function
18+
help: consider moving the expression out of the loop so it is only moved once
19+
|
20+
LL ~ let mut value = takes_fnonce(f);
21+
LL ~ loop {
22+
LL ~ value;
23+
|
1824
help: consider borrowing `f`
1925
|
2026
LL | takes_fnonce(&f);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
fn main() {
2+
let foos = vec![String::new()];
3+
let bars = vec![""];
4+
let mut baz = vec![];
5+
let mut qux = vec![];
6+
for foo in foos {
7+
//~^ NOTE this reinitialization might get skipped
8+
//~| NOTE move occurs because `foo` has type `String`
9+
for bar in &bars {
10+
//~^ NOTE inside of this loop
11+
//~| HELP consider moving the expression out of the loop
12+
//~| NOTE in this expansion of desugaring of `for` loop
13+
if foo == *bar {
14+
baz.push(foo);
15+
//~^ NOTE value moved here
16+
//~| HELP consider cloning the value
17+
continue;
18+
}
19+
}
20+
qux.push(foo);
21+
//~^ ERROR use of moved value
22+
//~| NOTE value used here
23+
}
24+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
error[E0382]: use of moved value: `foo`
2+
--> $DIR/nested-loop-moved-value-wrong-continue.rs:20:18
3+
|
4+
LL | for foo in foos {
5+
| ---
6+
| |
7+
| this reinitialization might get skipped
8+
| move occurs because `foo` has type `String`, which does not implement the `Copy` trait
9+
...
10+
LL | for bar in &bars {
11+
| ---------------- inside of this loop
12+
...
13+
LL | baz.push(foo);
14+
| --- value moved here, in previous iteration of loop
15+
...
16+
LL | qux.push(foo);
17+
| ^^^ value used here after move
18+
|
19+
help: consider moving the expression out of the loop so it is only moved once
20+
|
21+
LL ~ let mut value = baz.push(foo);
22+
LL ~ for bar in &bars {
23+
LL |
24+
...
25+
LL | if foo == *bar {
26+
LL ~ value;
27+
|
28+
help: consider cloning the value if the performance cost is acceptable
29+
|
30+
LL | baz.push(foo.clone());
31+
| ++++++++
32+
33+
error: aborting due to 1 previous error
34+
35+
For more information about this error, try `rustc --explain E0382`.

0 commit comments

Comments
 (0)