Skip to content

Commit 95b0f9e

Browse files
authored
Rollup merge of #143532 - compiler-errors:mut-ref-sugg, r=davidtwco
More carefully consider span context when suggesting remove `&mut` Use `find_ancestor_inside` to compute a relative span that is macro-aware, rather than falling back to using BytePos arithmetic which is wrong for `&mut`. Fixes #143523
2 parents 8222dd3 + b63f920 commit 95b0f9e

File tree

3 files changed

+42
-5
lines changed

3 files changed

+42
-5
lines changed

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

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1581,12 +1581,15 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
15811581
'outer: loop {
15821582
while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
15831583
count += 1;
1584-
let span = if expr.span.eq_ctxt(borrowed.span) {
1585-
expr.span.until(borrowed.span)
1586-
} else {
1587-
expr.span.with_hi(expr.span.lo() + BytePos(1))
1588-
};
1584+
let span =
1585+
if let Some(borrowed_span) = borrowed.span.find_ancestor_inside(expr.span) {
1586+
expr.span.until(borrowed_span)
1587+
} else {
1588+
break 'outer;
1589+
};
15891590

1591+
// Double check that the span we extracted actually corresponds to a borrow,
1592+
// rather than some macro garbage.
15901593
match self.tcx.sess.source_map().span_to_snippet(span) {
15911594
Ok(snippet) if snippet.starts_with("&") => {}
15921595
_ => break 'outer,
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// Regression test for #143523.
2+
3+
trait Trait {}
4+
5+
impl Trait for Vec<i32> {}
6+
7+
fn foo(_: impl Trait) {}
8+
9+
fn main() {
10+
foo(&mut vec![1]);
11+
//~^ ERROR the trait bound `&mut Vec<{integer}>: Trait` is not satisfied
12+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
error[E0277]: the trait bound `&mut Vec<{integer}>: Trait` is not satisfied
2+
--> $DIR/suggest-remove-refs-6.rs:10:9
3+
|
4+
LL | foo(&mut vec![1]);
5+
| --- ^^^^^^^^^^^^ the trait `Trait` is not implemented for `&mut Vec<{integer}>`
6+
| |
7+
| required by a bound introduced by this call
8+
|
9+
note: required by a bound in `foo`
10+
--> $DIR/suggest-remove-refs-6.rs:7:16
11+
|
12+
LL | fn foo(_: impl Trait) {}
13+
| ^^^^^ required by this bound in `foo`
14+
help: consider removing the leading `&`-reference
15+
|
16+
LL - foo(&mut vec![1]);
17+
LL + foo(vec![1]);
18+
|
19+
20+
error: aborting due to 1 previous error
21+
22+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)