Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clone suggestions #95115

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
182 changes: 117 additions & 65 deletions compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
location, desired_action, moved_place, used_place, span, mpi
);

let tcx = self.infcx.tcx;
let use_spans =
self.move_spans(moved_place, location).or_else(|| self.borrow_spans(span, location));
let span = use_spans.args_or_use();
Expand Down Expand Up @@ -174,12 +175,15 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
let mut is_loop_move = false;
let mut in_pattern = false;

let mut to_clone_spans = Vec::new();

for move_site in &move_site_vec {
let move_out = self.move_data.moves[(*move_site).moi];
let moved_place = &self.move_data.move_paths[move_out.path].place;

let move_spans = self.move_spans(moved_place.as_ref(), move_out.source);
let move_span = move_spans.args_or_use();
to_clone_spans.push(move_spans.var_or_use_path_span());

let move_msg = if move_spans.for_closure() { " into closure" } else { "" };

Expand Down Expand Up @@ -243,11 +247,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
);
}

let ty = used_place.ty(self.body, self.infcx.tcx).ty;
let ty = used_place.ty(self.body, tcx).ty;
let needs_note = match ty.kind() {
ty::Closure(id, _) => {
let tables = self.infcx.tcx.typeck(id.expect_local());
let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(id.expect_local());
let tables = tcx.typeck(id.expect_local());
let hir_id = tcx.hir().local_def_id_to_hir_id(id.expect_local());

tables.closure_kind_origins().get(hir_id).is_none()
}
Expand All @@ -256,7 +260,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {

let mpi = self.move_data.moves[move_out_indices[0]].path;
let place = &self.move_data.move_paths[mpi].place;
let ty = place.ty(self.body, self.infcx.tcx).ty;
let ty = place.ty(self.body, tcx).ty;

// If we're in pattern, we do nothing in favor of the previous suggestion (#80913).
if is_loop_move & !in_pattern {
Expand Down Expand Up @@ -285,61 +289,69 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
};

// Try to find predicates on *generic params* that would allow copying `ty`
let tcx = self.infcx.tcx;
let generics = tcx.generics_of(self.mir_def_id());
if let Some(hir_generics) = tcx
.typeck_root_def_id(self.mir_def_id().to_def_id())
.as_local()
.and_then(|def_id| tcx.hir().get_generics(def_id))
{
let predicates: Result<Vec<_>, _> = tcx.infer_ctxt().enter(|infcx| {
let mut fulfill_cx =
<dyn rustc_infer::traits::TraitEngine<'_>>::new(infcx.tcx);

let copy_did = infcx.tcx.lang_items().copy_trait().unwrap();
let cause = ObligationCause::new(
span,
self.mir_hir_id(),
rustc_infer::traits::ObligationCauseCode::MiscObligation,
);
fulfill_cx.register_bound(
&infcx,
self.param_env,
// Erase any region vids from the type, which may not be resolved
infcx.tcx.erase_regions(ty),
copy_did,
cause,
);
// Select all, including ambiguous predicates
let errors = fulfill_cx.select_all_or_error(&infcx);

// Only emit suggestion if all required predicates are on generic
errors
.into_iter()
.map(|err| match err.obligation.predicate.kind().skip_binder() {
PredicateKind::Trait(predicate) => {
match predicate.self_ty().kind() {
ty::Param(param_ty) => Ok((
generics.type_param(param_ty, tcx),
predicate.trait_ref.print_only_trait_path().to_string(),
)),
_ => Err(()),
}
}
_ => Err(()),
})
.collect()
});
let copy_did = tcx.lang_items().copy_trait().unwrap();
Copy link
Contributor

Choose a reason for hiding this comment

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

There's a method, I think called expect_lang_item or similar (don't have the editor open right now to find it) that does that unwrap for you in a non-ICEy way.

let copy_predicates =
self.try_find_missing_generic_bounds(ty, copy_did, generics, span);

let clone_did = tcx.lang_items().clone_trait().unwrap();
let clone_predicates =
self.try_find_missing_generic_bounds(ty, clone_did, generics, span);

match (copy_predicates, clone_predicates) {
// The type is already `Clone`, suggest cloning all values
(_, Ok(clone_predicates)) if clone_predicates.is_empty() => {
err.multipart_suggestion_verbose(
&format!("consider cloning {}", note_msg),
to_clone_spans
.into_iter()
.map(|move_span| {
(move_span.shrink_to_hi(), ".clone()".to_owned())
})
.collect(),
Applicability::MaybeIncorrect,
);
}
// The type can *not* be `Copy`, but can be `Clone`, suggest adding bounds to make the type `Clone` and then cloning all values
(Err(_), Ok(clone_predicates)) => {
suggest_constraining_type_params(
tcx,
hir_generics,
&mut err,
clone_predicates.iter().map(|(param, constraint)| {
(param.name.as_str(), &**constraint, None)
}),
);

if let Ok(predicates) = predicates {
suggest_constraining_type_params(
tcx,
hir_generics,
&mut err,
predicates.iter().map(|(param, constraint)| {
(param.name.as_str(), &**constraint, None)
}),
);
err.multipart_suggestion_verbose(
&format!("...and cloning {}", note_msg),
to_clone_spans
.into_iter()
.map(|move_span| {
(move_span.shrink_to_hi(), ".clone()".to_owned())
})
.collect(),
Applicability::MaybeIncorrect,
);
}
// The type can be `Copy`, suggest adding bound to make it `Copy`
(Ok(copy_predicates), _) => {
suggest_constraining_type_params(
tcx,
hir_generics,
&mut err,
copy_predicates.iter().map(|(param, constraint)| {
(param.name.as_str(), &**constraint, None)
}),
);
}
// The type can never be `Clone` or `Copy`, there is nothing to suggest :(
(Err(_), Err(_)) => {}
}
}

Expand All @@ -364,7 +376,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
));

// Check first whether the source is accessible (issue #87060)
if self.infcx.tcx.sess.source_map().span_to_snippet(deref_target).is_ok() {
if tcx.sess.source_map().span_to_snippet(deref_target).is_ok() {
err.span_note(deref_target, "deref defined here");
}
}
Expand Down Expand Up @@ -1047,6 +1059,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
location, name, borrow, drop_span, borrow_spans
);

let tcx = self.infcx.tcx;
let borrow_span = borrow_spans.var_or_use_path_span();
if let BorrowExplanation::MustBeValidFor {
category,
Expand Down Expand Up @@ -1083,19 +1096,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
format!(
"...but `{}` will be dropped here, when the {} returns",
name,
self.infcx
.tcx
.hir()
tcx.hir()
.opt_name(fn_hir_id)
.map(|name| format!("function `{}`", name))
.unwrap_or_else(|| {
match &self
.infcx
.tcx
.typeck(self.mir_def_id())
.node_type(fn_hir_id)
.kind()
{
match &tcx.typeck(self.mir_def_id()).node_type(fn_hir_id).kind() {
ty::Closure(..) => "enclosing closure",
ty::Generator(..) => "enclosing generator",
kind => bug!("expected closure or generator, found {:?}", kind),
Expand All @@ -1117,7 +1122,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
if let BorrowExplanation::MustBeValidFor { .. } = explanation {
} else {
explanation.add_explanation_to_diagnostic(
self.infcx.tcx,
tcx,
&self.body,
&self.local_names,
&mut err,
Expand All @@ -1135,7 +1140,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
borrow_spans.args_span_label(&mut err, format!("value captured here{}", within));

explanation.add_explanation_to_diagnostic(
self.infcx.tcx,
tcx,
&self.body,
&self.local_names,
&mut err,
Expand Down Expand Up @@ -2256,6 +2261,53 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
}
}
}

/// Tries to find bounds on `generics` that satisfy `ty: required_trait_did` bound.
fn try_find_missing_generic_bounds(
&self,
ty: Ty<'tcx>,
required_trait_did: DefId,
generics: &'tcx ty::Generics,
obligation_cause_span: Span,
) -> Result<Vec<(&'tcx ty::GenericParamDef, String)>, ()> {
let tcx = self.infcx.tcx;
let predicates: Result<Vec<_>, _> = tcx.infer_ctxt().enter(|infcx| {
let mut fulfill_cx = <dyn rustc_infer::traits::TraitEngine<'_>>::new(infcx.tcx);

let cause = ObligationCause::new(
obligation_cause_span,
self.mir_hir_id(),
rustc_infer::traits::ObligationCauseCode::MiscObligation,
);
fulfill_cx.register_bound(
&infcx,
self.param_env,
// Erase any region vids from the type, which may not be resolved
infcx.tcx.erase_regions(ty),
required_trait_did,
cause,
);
// Select all, including ambiguous predicates
let errors = fulfill_cx.select_all_or_error(&infcx);

// Only emit suggestion if all required predicates are on generic
errors
.into_iter()
.map(|err| match err.obligation.predicate.kind().skip_binder() {
PredicateKind::Trait(predicate) => match predicate.self_ty().kind() {
ty::Param(param_ty) => Ok((
generics.type_param(param_ty, tcx),
predicate.trait_ref.print_only_trait_path().to_string(),
)),
_ => Err(()),
},
_ => Err(()),
})
.collect()
});

predicates
}
}

#[derive(Debug)]
Expand Down
5 changes: 5 additions & 0 deletions src/test/ui/moves/issue-46099-move-in-macro.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ LL | let b = Box::new(true);
| - move occurs because `b` has type `Box<bool>`, which does not implement the `Copy` trait
LL | test!({b});
| ^ value used here after move
|
help: consider cloning `b`
|
LL | test!({b.clone()});
| ++++++++

error: aborting due to previous error

Expand Down
17 changes: 17 additions & 0 deletions src/test/ui/moves/move-fn-self-receiver.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ note: this function takes ownership of the receiver `self`, which moves `val.0`
LL | fn into_iter(self) -> Self::IntoIter;
| ^^^^
= note: move occurs because `val.0` has type `Vec<bool>`, which does not implement the `Copy` trait
help: consider cloning `val.0`
|
LL | val.0.clone().into_iter().next();
| ++++++++

error[E0382]: use of moved value: `foo`
--> $DIR/move-fn-self-receiver.rs:34:5
Expand Down Expand Up @@ -96,6 +100,10 @@ note: this function takes ownership of the receiver `self`, which moves `rc_foo`
|
LL | fn use_rc_self(self: Rc<Self>) {}
| ^^^^
help: consider cloning `rc_foo`
|
LL | rc_foo.clone().use_rc_self();
| ++++++++

error[E0382]: use of moved value: `foo_add`
--> $DIR/move-fn-self-receiver.rs:59:5
Expand Down Expand Up @@ -127,6 +135,10 @@ help: consider iterating over a slice of the `Vec<bool>`'s content to avoid movi
|
LL | for _val in &implicit_into_iter {}
| +
help: consider cloning `implicit_into_iter`
|
LL | for _val in implicit_into_iter.clone() {}
| ++++++++

error[E0382]: use of moved value: `explicit_into_iter`
--> $DIR/move-fn-self-receiver.rs:67:5
Expand All @@ -137,6 +149,11 @@ LL | for _val in explicit_into_iter.into_iter() {}
| ----------- `explicit_into_iter` moved due to this method call
LL | explicit_into_iter;
| ^^^^^^^^^^^^^^^^^^ value used here after move
|
help: consider cloning `explicit_into_iter`
|
LL | for _val in explicit_into_iter.clone().into_iter() {}
| ++++++++

error[E0382]: use of moved value: `container`
--> $DIR/move-fn-self-receiver.rs:71:5
Expand Down
5 changes: 5 additions & 0 deletions src/test/ui/moves/move-guard-same-consts.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ LL | (1, 2) if take(x) => (),
| - value moved here
LL | (1, 2) if take(x) => (),
| ^ value used here after move
|
help: consider cloning `x`
|
LL | (1, 2) if take(x.clone()) => (),
| ++++++++

error: aborting due to previous error

Expand Down
5 changes: 5 additions & 0 deletions src/test/ui/moves/move-in-guard-1.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ LL | (1, _) if take(x) => (),
| - value moved here
LL | (_, 2) if take(x) => (),
| ^ value used here after move
|
help: consider cloning `x`
|
LL | (1, _) if take(x.clone()) => (),
| ++++++++

error: aborting due to previous error

Expand Down
5 changes: 5 additions & 0 deletions src/test/ui/moves/move-in-guard-2.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ LL | let x: Box<_> = Box::new(1);
...
LL | (_, 2) if take(x) => (),
| ^ value used here after move
|
help: consider cloning `x`
|
LL | (_, 2) if take(x.clone()) => (),
| ++++++++

error: aborting due to previous error

Expand Down
8 changes: 8 additions & 0 deletions src/test/ui/moves/move-out-of-tuple-field.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ LL | let z = x.0;
| ^^^ value used here after move
|
= note: move occurs because `x.0` has type `Box<i32>`, which does not implement the `Copy` trait
help: consider cloning `x.0`
|
LL | let y = x.0.clone();
| ++++++++

error[E0382]: use of moved value: `x.0`
--> $DIR/move-out-of-tuple-field.rs:12:13
Expand All @@ -17,6 +21,10 @@ LL | let z = x.0;
| ^^^ value used here after move
|
= note: move occurs because `x.0` has type `Box<isize>`, which does not implement the `Copy` trait
help: consider cloning `x.0`
|
LL | let y = x.0.clone();
| ++++++++

error: aborting due to 2 previous errors

Expand Down
Loading