Skip to content

Commit 4b12aa1

Browse files
Rollup merge of #166006 - estebank:issue-93726, r=wesleywiser
Detect method shadowed by another when accessing a field or calling method that isn't found in method chain When failing to find a field after a method call, look for other methods with the same name on the receiver that are shadowed and have a return typethat has the field name we couldn't find: ``` error[E0609]: no field `next` on type `&mut Rc<RefCell<Node>>` --> tests/ui/methods/method-shadowed-by-trait.rs:41:53 | 41 | Some(old_tail) => old_tail.borrow_mut().next = Some(node.clone()), | ---------- ^^^^ unknown field | | | this method is `std::borrow::BorrowMut::borrow_mut` | note: this returns `&mut Rc<RefCell<Node>>` --> library/core/src/borrow.rs:207:5 | 190 | pub const trait BorrowMut<Borrowed: ?Sized>: [const] Borrow<Borrowed> { ... 207 | fn borrow_mut(&mut self) -> &mut Borrowed; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: you might have meant to call `std::cell::RefCell::<T>::borrow_mut` instead --> library/core/src/cell.rs:1226:5 | 1089 | impl<T: ?Sized> RefCell<T> { ... 1226 | pub const fn borrow_mut(&self) -> RefMut<'_, T> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `std::cell::RefCell::<T>::borrow_mut` using the fully-qualified path | 41 - Some(old_tail) => old_tail.borrow_mut().next = Some(node.clone()), 41 + Some(old_tail) => RefCell::borrow_mut(&old_tail).next = Some(node.clone()), | ``` Do the same for method calls: ``` error[E0599]: no method named `method` found for unit type `()` in the current scope --> $DIR/method-shadowed-by-trait.rs:104:13 | LL | x.foo().method(); | --- ^^^^^^ method not found in `()` | | | this method is `a::T::foo` | note: this returns `()` --> $DIR/method-shadowed-by-trait.rs:71:9 | LL | pub trait T { LL | fn foo(&self) {} | ^^^^^^^^^^^^^ note: you might have meant to call `S::foo` instead --> $DIR/method-shadowed-by-trait.rs:64:5 | LL | impl S { LL | fn foo(&self) -> Other { Other { field: () } } | ^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `S::foo` using the fully-qualified path | LL - x.foo().method(); LL + S::foo(&x).method(); | ``` Do the same thing for the LHS of binops: ``` error[E0369]: binary operation `>` cannot be applied to type `std::sync::MutexGuard<'_, RefCell<i32>>` --> tests/ui/methods/method-shadowed-by-trait-in-binop.rs:20:29 | 13 | let opt_target = cell.borrow(); | ------ this method is `std::borrow::Borrow::borrow` ... 20 | let _ = *opt_target > 1; //~ ERROR: binary operation `>` cannot be applied | ----------- ^ - {integer} | | | std::sync::MutexGuard<'_, RefCell<i32>> | note: `std::sync::MutexGuard<'_, RefCell<i32>>` does not implement `PartialOrd<{integer}>` --> library/std/src/sync/poison/mutex.rs:277:1 | 277 | / pub struct MutexGuard< 278 | | #[rustc_assert_variance(covariant)] 'a, 279 | | #[rustc_assert_variance(invariant)] T: ?Sized + 'a, 280 | | > { | |_^ `std::sync::MutexGuard<'_, RefCell<i32>>` is defined in another crate note: this returns `std::sync::MutexGuard<'_, RefCell<i32>>` --> library/core/src/borrow.rs:179:5 | 158 | pub const trait Borrow<Borrowed: ?Sized> { ... 179 | fn borrow(&self) -> &Borrowed; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: you might have meant to call `std::cell::RefCell::<T>::borrow` instead --> library/core/src/cell.rs:1126:5 | 1089 | impl<T: ?Sized> RefCell<T> { ... 1126 | pub const fn borrow(&self) -> Ref<'_, T> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `std::cell::RefCell::<T>::borrow` using the fully-qualified path | 13 - let opt_target = cell.borrow(); 13 + let opt_target = RefCell::borrow(&cell); | ``` Fix #93726, cc #94858, fix #132133, fix #66630.
2 parents 9553ff7 + d3b12e6 commit 4b12aa1

10 files changed

Lines changed: 1817 additions & 1072 deletions

File tree

‎compiler/rustc_hir_typeck/src/errors.rs‎

Lines changed: 1316 additions & 0 deletions
Large diffs are not rendered by default.

‎compiler/rustc_hir_typeck/src/expr.rs‎

Lines changed: 6 additions & 1055 deletions
Large diffs are not rendered by default.

‎compiler/rustc_hir_typeck/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ mod coercion;
1717
mod demand;
1818
mod diagnostics;
1919
mod diverges;
20+
mod errors;
2021
mod expectation;
2122
mod expr;
2223
mod inline_asm;

‎compiler/rustc_hir_typeck/src/method/suggest.rs‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -583,10 +583,27 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
583583
Applicability::MachineApplicable,
584584
);
585585
}
586-
586+
self.detect_shadowed_method_on_incorrect_method_access(
587+
&mut err, source, item_ident, rcvr_ty,
588+
);
587589
err
588590
}
589591

592+
fn detect_shadowed_method_on_incorrect_method_access(
593+
&self,
594+
err: &mut Diag<'_>,
595+
source: SelfSource<'tcx>,
596+
method_ident: Ident,
597+
base_ty: Ty<'tcx>,
598+
) {
599+
let SelfSource::MethodCall(expr) = source else { return };
600+
self.find_shadowed_method_and_provide_diagnostic_context(err, base_ty, expr, |ty| {
601+
self.autoderef(method_ident.span, ty)
602+
.silence_errors()
603+
.any(|(ty, _)| self.all_methods(method_ident, ty).next().is_some())
604+
});
605+
}
606+
590607
fn suggest_use_shadowed_binding_with_method(
591608
&self,
592609
self_source: SelfSource<'tcx>,

‎compiler/rustc_hir_typeck/src/op.rs‎

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
343343
let lhs_ty_str = self.tcx.short_string(lhs_ty, &mut path);
344344
let rhs_ty_str = self.tcx.short_string(rhs_ty, &mut path);
345345

346+
let is_compatible_after_call = |lhs_ty, rhs_ty| {
347+
let op_ok = self
348+
.lookup_op_method(
349+
(lhs_expr, lhs_ty),
350+
Some((rhs_expr, rhs_ty)),
351+
lang_item_for_binop(self.tcx, op),
352+
op.span(),
353+
expected,
354+
)
355+
.is_ok();
356+
357+
op_ok || self.can_eq(self.param_env, lhs_ty, rhs_ty)
358+
};
359+
346360
let (mut err, output_def_id) = match op {
347361
// Try and detect when `+=` was incorrectly
348362
// used instead of `==` in a let-chain
@@ -439,6 +453,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
439453
);
440454
let suggest_derive = self.can_eq(self.param_env, lhs_ty, rhs_ty);
441455
self.note_unmet_impls_on_type(&mut err, &errors, suggest_derive);
456+
457+
// The other case, where RHS had a shadowed method call earlier in the chain
458+
// produces an E0277 instead, so adding a second call to
459+
// `find_shadowed_method_and_provide_diagnostic_context` would be dead code.
460+
self.find_shadowed_method_and_provide_diagnostic_context(
461+
&mut err,
462+
lhs_ty,
463+
lhs_expr,
464+
|ty| {
465+
self.autoderef(lhs_expr.span, ty)
466+
.silence_errors()
467+
.any(|(ty, _)| is_compatible_after_call(ty, rhs_ty))
468+
},
469+
);
442470
(err, output_def_id)
443471
}
444472
};
@@ -454,20 +482,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
454482
err.downgrade_to_delayed_bug();
455483
}
456484

457-
let is_compatible_after_call = |lhs_ty, rhs_ty| {
458-
let op_ok = self
459-
.lookup_op_method(
460-
(lhs_expr, lhs_ty),
461-
Some((rhs_expr, rhs_ty)),
462-
lang_item_for_binop(self.tcx, op),
463-
op.span(),
464-
expected,
465-
)
466-
.is_ok();
467-
468-
op_ok || self.can_eq(self.param_env, lhs_ty, rhs_ty)
469-
};
470-
471485
// We should suggest `a + b` => `*a + b` if `a` is copy, and suggest
472486
// `a += b` => `*a += b` if a is a mut ref.
473487
self.suggest_deref_or_call_for_binop_error(

‎tests/ui/async-await/in-trait/dont-project-to-specializable-projection.stderr‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,23 @@ error[E0599]: no method named `poll` found for struct `Pin<&mut impl Future<Outp
2626
--> $DIR/dont-project-to-specializable-projection.rs:48:28
2727
|
2828
LL | match fut.as_mut().poll(ctx) {
29-
| ^^^^ method not found in `Pin<&mut impl Future<Output = ()>>`
29+
| ------ ^^^^ method not found in `Pin<&mut impl Future<Output = ()>>`
30+
| |
31+
| this method is `std::pin::Pin::<Ptr>::as_mut`
3032
|
3133
--> $SRC_DIR/core/src/future/future.rs:LL:COL
3234
|
3335
= note: the method is available for `Pin<&mut impl Future<Output = ()>>` here
34-
|
36+
note: this returns `Pin<&mut impl Future<Output = ()>>`
37+
--> $SRC_DIR/core/src/pin.rs:LL:COL
38+
note: you might have meant to call `std::convert::AsMut::as_mut` instead
39+
--> $SRC_DIR/core/src/convert/mod.rs:LL:COL
3540
= help: items from traits can only be used if the trait is in scope
41+
help: consider calling `std::convert::AsMut::as_mut` using the fully-qualified path
42+
|
43+
LL - match fut.as_mut().poll(ctx) {
44+
LL + match <_ as AsMut<_>>::as_mut(&mut fut).poll(ctx) {
45+
|
3646
help: trait `Future` which provides `poll` is implemented but not in scope; perhaps you want to import it
3747
|
3848
LL + use std::future::Future;
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Regression test for #66630.
2+
use std::sync::Mutex;
3+
use std::cell::RefCell;
4+
use std::borrow::Borrow;
5+
6+
struct A {
7+
child: Mutex<RefCell<i32>>,
8+
}
9+
10+
impl A {
11+
fn is_good(&self) -> bool {
12+
let cell = self.child.lock().unwrap();
13+
let opt_target = cell.borrow();
14+
//~^ NOTE: this method is `std::borrow::Borrow::borrow`
15+
//~| NOTE: this method is `std::borrow::Borrow::borrow`
16+
let _ = opt_target.abs(); //~ ERROR: no method named `abs` found for
17+
//~^ NOTE: method not found in `&std::sync::MutexGuard<'_, RefCell<i32>>`
18+
//~| NOTE: this returns `&std::sync::MutexGuard<'_, RefCell<i32>>`
19+
//~| NOTE: you might have meant to call `std::cell::RefCell::<T>::borrow` instead
20+
let _ = *opt_target > 1; //~ ERROR: binary operation `>` cannot be applied
21+
//~^ NOTE: std::sync::MutexGuard<'_, RefCell<i32>>
22+
//~| NOTE: `std::sync::MutexGuard<'_, RefCell<i32>>` does not implement `PartialOrd<{integer}>`
23+
//~| NOTE: this returns `std::sync::MutexGuard<'_, RefCell<i32>>`
24+
//~| NOTE: you might have meant to call `std::cell::RefCell::<T>::borrow` instead
25+
//~| NOTE: {integer}
26+
1 < *opt_target //~ ERROR: E0277
27+
//~^ NOTE: no implementation for `{integer} < std::sync::MutexGuard<'_, RefCell<i32>>`
28+
}
29+
}
30+
31+
fn main() {}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
error[E0599]: no method named `abs` found for reference `&std::sync::MutexGuard<'_, RefCell<i32>>` in the current scope
2+
--> $DIR/method-shadowed-by-trait-in-binop.rs:16:28
3+
|
4+
LL | let opt_target = cell.borrow();
5+
| ------ this method is `std::borrow::Borrow::borrow`
6+
...
7+
LL | let _ = opt_target.abs();
8+
| ^^^ method not found in `&std::sync::MutexGuard<'_, RefCell<i32>>`
9+
|
10+
note: this returns `&std::sync::MutexGuard<'_, RefCell<i32>>`
11+
--> $SRC_DIR/core/src/borrow.rs:LL:COL
12+
note: you might have meant to call `std::cell::RefCell::<T>::borrow` instead
13+
--> $SRC_DIR/core/src/cell.rs:LL:COL
14+
help: consider calling `std::cell::RefCell::<T>::borrow` using the fully-qualified path
15+
|
16+
LL - let opt_target = cell.borrow();
17+
LL + let opt_target = RefCell::<i32>::borrow(&cell);
18+
|
19+
20+
error[E0369]: binary operation `>` cannot be applied to type `std::sync::MutexGuard<'_, RefCell<i32>>`
21+
--> $DIR/method-shadowed-by-trait-in-binop.rs:20:29
22+
|
23+
LL | let opt_target = cell.borrow();
24+
| ------ this method is `std::borrow::Borrow::borrow`
25+
...
26+
LL | let _ = *opt_target > 1;
27+
| ----------- ^ - {integer}
28+
| |
29+
| std::sync::MutexGuard<'_, RefCell<i32>>
30+
|
31+
note: `std::sync::MutexGuard<'_, RefCell<i32>>` does not implement `PartialOrd<{integer}>`
32+
--> $SRC_DIR/std/src/sync/poison/mutex.rs:LL:COL
33+
::: $SRC_DIR/std/src/sync/poison/mutex.rs:LL:COL
34+
|
35+
= note: `std::sync::MutexGuard<'_, RefCell<i32>>` is defined in another crate
36+
note: this returns `std::sync::MutexGuard<'_, RefCell<i32>>`
37+
--> $SRC_DIR/core/src/borrow.rs:LL:COL
38+
note: you might have meant to call `std::cell::RefCell::<T>::borrow` instead
39+
--> $SRC_DIR/core/src/cell.rs:LL:COL
40+
help: consider calling `std::cell::RefCell::<T>::borrow` using the fully-qualified path
41+
|
42+
LL - let opt_target = cell.borrow();
43+
LL + let opt_target = RefCell::<i32>::borrow(&cell);
44+
|
45+
46+
error[E0277]: can't compare `{integer}` with `std::sync::MutexGuard<'_, RefCell<i32>>`
47+
--> $DIR/method-shadowed-by-trait-in-binop.rs:26:11
48+
|
49+
LL | 1 < *opt_target
50+
| ^ no implementation for `{integer} < std::sync::MutexGuard<'_, RefCell<i32>>` and `{integer} > std::sync::MutexGuard<'_, RefCell<i32>>`
51+
|
52+
= help: the trait `PartialOrd<std::sync::MutexGuard<'_, RefCell<i32>>>` is not implemented for `{integer}`
53+
= help: the following other types implement trait `PartialOrd<Rhs>`:
54+
f128
55+
f16
56+
f32
57+
f64
58+
i128
59+
i16
60+
i32
61+
i64
62+
and 8 others
63+
64+
error: aborting due to 3 previous errors
65+
66+
Some errors have detailed explanations: E0277, E0369, E0599.
67+
For more information about an error, try `rustc --explain E0277`.
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
// Show the diagnostic for cases where a method is expected by the user but a different one is
2+
// shaddowing it causing a field access to fail. Test for #93726.
3+
4+
use std::cell::RefCell;
5+
use std::rc::Rc;
6+
use std::borrow::BorrowMut;
7+
8+
type NodeAlias = Option<Rc<RefCell<Node>>>;
9+
10+
#[derive(Clone, Debug, PartialEq)]
11+
struct Node {
12+
value: String,
13+
next: NodeAlias,
14+
}
15+
16+
#[derive(Clone, Debug, PartialEq)]
17+
struct TransactionLog {
18+
head: NodeAlias,
19+
tail: NodeAlias,
20+
length: i32,
21+
}
22+
23+
impl Node {
24+
fn new(value: String) -> Rc<RefCell<Node>> {
25+
Rc::new(RefCell::new(Node { value, next: None }))
26+
}
27+
}
28+
29+
impl TransactionLog {
30+
pub fn empty_list() -> TransactionLog {
31+
TransactionLog {
32+
head: None,
33+
tail: None,
34+
length: 0,
35+
}
36+
}
37+
38+
pub fn append(&mut self, value: String) {
39+
let node = Node::new(value);
40+
match self.tail.take() {
41+
Some(old_tail) => old_tail.borrow_mut().next = Some(node.clone()),
42+
//~^ ERROR: no field `next` on type `&mut Rc<RefCell<Node>>`
43+
//~| NOTE: unknown field
44+
//~| NOTE: this method is `std::borrow::BorrowMut::borrow_mut`
45+
//~| NOTE: you might have meant to call `std::cell::RefCell::<T>::borrow_mut` instead
46+
//~| NOTE: this returns `&mut Rc<RefCell<Node>>`
47+
None => self.head = Some(node.clone()),
48+
}
49+
self.length += 1;
50+
self.tail = Some(node);
51+
}
52+
}
53+
54+
55+
struct S;
56+
struct Other {
57+
field: (),
58+
}
59+
impl Other {
60+
fn method(&self) {}
61+
}
62+
63+
impl S {
64+
fn foo(&self) -> Other { Other { field: () } }
65+
//~^ NOTE: you might have meant to call
66+
//~| NOTE: you might have meant to call
67+
//~| NOTE: you might have meant to call
68+
//~| NOTE: you might have meant to call
69+
}
70+
mod a {
71+
use crate::{S, Other};
72+
pub trait T {
73+
fn foo(&self) {}
74+
//~^ NOTE: this returns `()`
75+
//~| NOTE: this returns `()`
76+
//~| NOTE: this returns `()`
77+
//~| NOTE: this returns `()`
78+
}
79+
impl T for S {}
80+
impl T for Box<S> {}
81+
pub trait K<P> {
82+
fn foo(&self) -> Other { Other { field : () } }
83+
//~^ NOTE: you might have meant to call
84+
//~| NOTE: you might have meant to call
85+
//~| NOTE: you might have meant to call
86+
//~| NOTE: you might have meant to call
87+
}
88+
impl K<()> for S {}
89+
impl K<i32> for Box<S> {}
90+
pub trait V {
91+
fn foo(&self) -> Other;
92+
//~^ NOTE: you might have meant to call
93+
//~| NOTE: you might have meant to call
94+
//~| NOTE: you might have meant to call
95+
//~| NOTE: you might have meant to call
96+
}
97+
impl V for Box<S> {
98+
fn foo(&self) -> Other { Other { field : () } }
99+
}
100+
pub trait U {
101+
fn foo(&self) {} // not suggested because its return type doesn't have the field
102+
}
103+
impl U for Box<S> {}
104+
}
105+
use a::T;
106+
107+
fn main() {
108+
let x = Box::new(S);
109+
x.foo().field; //~ ERROR: no field `field` on type `()`
110+
//~^ NOTE: unknown field
111+
//~| NOTE: this method is `a::T::foo`
112+
let y = x.foo();
113+
//~^ NOTE: this method is `a::T::foo`
114+
//~| NOTE: this method is `a::T::foo`
115+
let _ = y.field; //~ ERROR: no field `field` on type `()`
116+
//~^ NOTE: unknown field
117+
x.foo().method(); //~ ERROR: no method named `method` found for unit type `()` in the current scope
118+
//~^ NOTE: method not found in `()`
119+
//~| NOTE: this method is `a::T::foo`
120+
let _ = y.method(); //~ ERROR: no method named `method` found for unit type `()` in the current scope
121+
//~^ NOTE: method not found in `()`
122+
}

0 commit comments

Comments
 (0)