diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 362052e9fdbdd..1dc1588842f2c 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -1511,12 +1511,15 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { 'outer: loop { while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind { count += 1; - let span = if expr.span.eq_ctxt(borrowed.span) { - expr.span.until(borrowed.span) - } else { - expr.span.with_hi(expr.span.lo() + BytePos(1)) - }; + let span = + if let Some(borrowed_span) = borrowed.span.find_ancestor_inside(expr.span) { + expr.span.until(borrowed_span) + } else { + break 'outer; + }; + // Double check that the span we extracted actually corresponds to a borrow, + // rather than some macro garbage. match self.tcx.sess.source_map().span_to_snippet(span) { Ok(snippet) if snippet.starts_with("&") => {} _ => break 'outer, diff --git a/tests/ui/suggestions/suggest-remove-refs-6.rs b/tests/ui/suggestions/suggest-remove-refs-6.rs new file mode 100644 index 0000000000000..0d06aed480688 --- /dev/null +++ b/tests/ui/suggestions/suggest-remove-refs-6.rs @@ -0,0 +1,12 @@ +// Regression test for #143523. + +trait Trait {} + +impl Trait for Vec {} + +fn foo(_: impl Trait) {} + +fn main() { + foo(&mut vec![1]); + //~^ ERROR the trait bound `&mut Vec<{integer}>: Trait` is not satisfied +} diff --git a/tests/ui/suggestions/suggest-remove-refs-6.stderr b/tests/ui/suggestions/suggest-remove-refs-6.stderr new file mode 100644 index 0000000000000..bdc5a8a904909 --- /dev/null +++ b/tests/ui/suggestions/suggest-remove-refs-6.stderr @@ -0,0 +1,22 @@ +error[E0277]: the trait bound `&mut Vec<{integer}>: Trait` is not satisfied + --> $DIR/suggest-remove-refs-6.rs:10:9 + | +LL | foo(&mut vec![1]); + | --- ^^^^^^^^^^^^ the trait `Trait` is not implemented for `&mut Vec<{integer}>` + | | + | required by a bound introduced by this call + | +note: required by a bound in `foo` + --> $DIR/suggest-remove-refs-6.rs:7:16 + | +LL | fn foo(_: impl Trait) {} + | ^^^^^ required by this bound in `foo` +help: consider removing the leading `&`-reference + | +LL - foo(&mut vec![1]); +LL + foo(vec![1]); + | + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`.