Skip to content

Commit 29a4cff

Browse files
committed
Check & before suggest remove deref when trait_selection
Signed-off-by: xizheyin <[email protected]>
1 parent f46806f commit 29a4cff

File tree

2 files changed

+11
-9
lines changed

2 files changed

+11
-9
lines changed

compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs

+10-4
Original file line numberDiff line numberDiff line change
@@ -1510,13 +1510,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
15101510
let mut suggested_ty = trait_pred.self_ty().skip_binder();
15111511
'outer: loop {
15121512
while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
1513-
count += 1;
15141513
let span = if expr.span.eq_ctxt(borrowed.span) {
15151514
expr.span.until(borrowed.span)
15161515
} else {
15171516
expr.span.with_hi(expr.span.lo() + BytePos(1))
15181517
};
1519-
suggestions.push((span, String::new()));
15201518

15211519
let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
15221520
break 'outer;
@@ -1525,8 +1523,16 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
15251523

15261524
expr = borrowed;
15271525

1528-
if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1529-
return true;
1526+
if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
1527+
&& snippet.starts_with("&")
1528+
{
1529+
// Only when the expr has leading `&`-reference,
1530+
// we record it and suggest removing it.
1531+
count += 1;
1532+
suggestions.push((span, String::new()));
1533+
if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1534+
return true;
1535+
}
15301536
}
15311537
}
15321538
if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind

tests/ui/traits/suggest-remove-deref-issue-140166.stderr

+1-5
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ LL | format_args!("{:?}", FlatMap(&Chars));
66
| |
77
| required by a bound introduced by this call
88
|
9+
= help: the trait `Trait` is implemented for `Chars`
910
note: required for `FlatMap<&Chars>` to implement `Debug`
1011
--> $DIR/suggest-remove-deref-issue-140166.rs:7:16
1112
|
@@ -15,11 +16,6 @@ LL | impl<T: Trait> std::fmt::Debug for FlatMap<T> {
1516
| unsatisfied trait bound introduced here
1617
note: required by a bound in `core::fmt::rt::Argument::<'_>::new_debug`
1718
--> $SRC_DIR/core/src/fmt/rt.rs:LL:COL
18-
help: consider removing the leading `&`-reference
19-
|
20-
LL - format_args!("{:?}", FlatMap(&Chars));
21-
LL + format_args!("{:?}", latMap(&Chars));
22-
|
2319

2420
error: aborting due to 1 previous error
2521

0 commit comments

Comments
 (0)