Skip to content

Commit 9f06855

Browse files
committed
Auto merge of #61143 - estebank:issue-61106, r=eddyb
When suggesting borrow, remove useless clones Fix #61106.
2 parents dbebcee + 34c4117 commit 9f06855

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

Diff for: src/librustc_typeck/check/demand.rs

+18-1
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
379379
}
380380
};
381381
if self.can_coerce(ref_ty, expected) {
382-
if let Ok(src) = cm.span_to_snippet(sp) {
382+
let mut sugg_sp = sp;
383+
if let hir::ExprKind::MethodCall(segment, _sp, args) = &expr.node {
384+
let clone_trait = self.tcx.lang_items().clone_trait().unwrap();
385+
if let ([arg], Some(true), "clone") = (
386+
&args[..],
387+
self.tables.borrow().type_dependent_def_id(expr.hir_id).map(|did| {
388+
let ai = self.tcx.associated_item(did);
389+
ai.container == ty::TraitContainer(clone_trait)
390+
}),
391+
&segment.ident.as_str()[..],
392+
) {
393+
// If this expression had a clone call when suggesting borrowing
394+
// we want to suggest removing it because it'd now be unecessary.
395+
sugg_sp = arg.span;
396+
}
397+
}
398+
if let Ok(src) = cm.span_to_snippet(sugg_sp) {
383399
let needs_parens = match expr.node {
384400
// parenthesize if needed (Issue #46756)
385401
hir::ExprKind::Cast(_, _) |
@@ -425,6 +441,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
425441
}
426442
}
427443
}
444+
428445
return Some(match mutability {
429446
hir::Mutability::MutMutable => (
430447
sp,

Diff for: src/test/ui/issues/issue-61106.rs

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
fn main() {
2+
let x = String::new();
3+
foo(x.clone()); //~ ERROR mismatched types
4+
}
5+
6+
fn foo(_: &str) {}

Diff for: src/test/ui/issues/issue-61106.stderr

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error[E0308]: mismatched types
2+
--> $DIR/issue-61106.rs:3:9
3+
|
4+
LL | foo(x.clone());
5+
| ^^^^^^^^^
6+
| |
7+
| expected &str, found struct `std::string::String`
8+
| help: consider borrowing here: `&x`
9+
|
10+
= note: expected type `&str`
11+
found type `std::string::String`
12+
13+
error: aborting due to previous error
14+
15+
For more information about this error, try `rustc --explain E0308`.

0 commit comments

Comments
 (0)