Skip to content

Commit 331019e

Browse files
committed
Find the correct span in suggesting using clone
Signed-off-by: xizheyin <[email protected]>
1 parent ab6db3a commit 331019e

File tree

3 files changed

+30
-11
lines changed

3 files changed

+30
-11
lines changed

compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1297,17 +1297,28 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
12971297
)
12981298
.must_apply_modulo_regions()
12991299
{
1300-
let suggestion = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1301-
Some(ident) => format!(": {ident}.clone()"),
1302-
None => ".clone()".to_string(),
1303-
};
1300+
let (suggestion, shorthand) =
1301+
match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1302+
Some(ident) => (format!(": {ident}.clone()"), Some(ident)),
1303+
None => (".clone()".to_string(), None),
1304+
};
13041305

1305-
diag.span_suggestion_verbose(
1306-
expr.span.shrink_to_hi(),
1307-
"consider using clone here",
1308-
suggestion,
1309-
Applicability::MachineApplicable,
1310-
);
1306+
let span = expr.span.find_oldest_ancestor_in_same_ctxt().shrink_to_hi();
1307+
1308+
if expr.span.from_expansion()
1309+
&& let Some(ident) = shorthand
1310+
{
1311+
let suggestion =
1312+
format!("bind the field to a variable: let {ident} = {ident}.clone();");
1313+
diag.span_help(span, suggestion);
1314+
} else {
1315+
diag.span_suggestion_verbose(
1316+
span,
1317+
"consider using clone here",
1318+
suggestion,
1319+
Applicability::MachineApplicable,
1320+
);
1321+
}
13111322
return true;
13121323
}
13131324
false

tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,4 @@ fn test1() {
1616
let c: S = dbg!(dbg!(field)); //~ ERROR mismatched types [E0308]
1717
}
1818

19-
fn main() {}
19+
fn main() {}

tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@ LL | let c: S = dbg!(field);
2727
| ^^^^^^^^^^^ expected `S`, found `&S`
2828
|
2929
= note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info)
30+
help: consider using clone here
31+
|
32+
LL | let c: S = dbg!(field).clone();
33+
| ++++++++
3034

3135
error[E0308]: mismatched types
3236
--> $DIR/suggest-clone-in-macro-issue-139253.rs:16:16
@@ -35,6 +39,10 @@ LL | let c: S = dbg!(dbg!(field));
3539
| ^^^^^^^^^^^^^^^^^ expected `S`, found `&S`
3640
|
3741
= note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info)
42+
help: consider using clone here
43+
|
44+
LL | let c: S = dbg!(dbg!(field)).clone();
45+
| ++++++++
3846

3947
error: aborting due to 4 previous errors
4048

0 commit comments

Comments
 (0)