Skip to content
1,316 changes: 1,316 additions & 0 deletions compiler/rustc_hir_typeck/src/errors.rs

Large diffs are not rendered by default.

1,061 changes: 6 additions & 1,055 deletions compiler/rustc_hir_typeck/src/expr.rs

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions compiler/rustc_hir_typeck/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ mod coercion;
mod demand;
mod diagnostics;
mod diverges;
mod errors;
mod expectation;
mod expr;
mod inline_asm;
Expand Down
19 changes: 18 additions & 1 deletion compiler/rustc_hir_typeck/src/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -583,10 +583,27 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
Applicability::MachineApplicable,
);
}

self.detect_shadowed_method_on_incorrect_method_access(
&mut err, source, item_ident, rcvr_ty,
);
err
}

fn detect_shadowed_method_on_incorrect_method_access(
&self,
err: &mut Diag<'_>,
source: SelfSource<'tcx>,
method_ident: Ident,
base_ty: Ty<'tcx>,
) {
let SelfSource::MethodCall(expr) = source else { return };
self.find_shadowed_method_and_provide_diagnostic_context(err, base_ty, expr, |ty| {
self.autoderef(method_ident.span, ty)
.silence_errors()
.any(|(ty, _)| self.all_methods(method_ident, ty).next().is_some())
});
}

fn suggest_use_shadowed_binding_with_method(
&self,
self_source: SelfSource<'tcx>,
Expand Down
42 changes: 28 additions & 14 deletions compiler/rustc_hir_typeck/src/op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let lhs_ty_str = self.tcx.short_string(lhs_ty, &mut path);
let rhs_ty_str = self.tcx.short_string(rhs_ty, &mut path);

let is_compatible_after_call = |lhs_ty, rhs_ty| {
let op_ok = self
.lookup_op_method(
(lhs_expr, lhs_ty),
Some((rhs_expr, rhs_ty)),
lang_item_for_binop(self.tcx, op),
op.span(),
expected,
)
.is_ok();

op_ok || self.can_eq(self.param_env, lhs_ty, rhs_ty)
};

let (mut err, output_def_id) = match op {
// Try and detect when `+=` was incorrectly
// used instead of `==` in a let-chain
Expand Down Expand Up @@ -439,6 +453,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
);
let suggest_derive = self.can_eq(self.param_env, lhs_ty, rhs_ty);
self.note_unmet_impls_on_type(&mut err, &errors, suggest_derive);

// The other case, where RHS had a shadowed method call earlier in the chain
// produces an E0277 instead, so adding a second call to
// `find_shadowed_method_and_provide_diagnostic_context` would be dead code.
self.find_shadowed_method_and_provide_diagnostic_context(
&mut err,
lhs_ty,
lhs_expr,
|ty| {
self.autoderef(lhs_expr.span, ty)
.silence_errors()
.any(|(ty, _)| is_compatible_after_call(ty, rhs_ty))
},
);
(err, output_def_id)
}
};
Expand All @@ -454,20 +482,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.downgrade_to_delayed_bug();
}

let is_compatible_after_call = |lhs_ty, rhs_ty| {
let op_ok = self
.lookup_op_method(
(lhs_expr, lhs_ty),
Some((rhs_expr, rhs_ty)),
lang_item_for_binop(self.tcx, op),
op.span(),
expected,
)
.is_ok();

op_ok || self.can_eq(self.param_env, lhs_ty, rhs_ty)
};

// We should suggest `a + b` => `*a + b` if `a` is copy, and suggest
// `a += b` => `*a += b` if a is a mut ref.
self.suggest_deref_or_call_for_binop_error(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,23 @@ error[E0599]: no method named `poll` found for struct `Pin<&mut impl Future<Outp
--> $DIR/dont-project-to-specializable-projection.rs:48:28
|
LL | match fut.as_mut().poll(ctx) {
| ^^^^ method not found in `Pin<&mut impl Future<Output = ()>>`
| ------ ^^^^ method not found in `Pin<&mut impl Future<Output = ()>>`
| |
| this method is `std::pin::Pin::<Ptr>::as_mut`
|
--> $SRC_DIR/core/src/future/future.rs:LL:COL
|
= note: the method is available for `Pin<&mut impl Future<Output = ()>>` here
|
note: this returns `Pin<&mut impl Future<Output = ()>>`
--> $SRC_DIR/core/src/pin.rs:LL:COL
note: you might have meant to call `std::convert::AsMut::as_mut` instead
--> $SRC_DIR/core/src/convert/mod.rs:LL:COL
= help: items from traits can only be used if the trait is in scope
help: consider calling `std::convert::AsMut::as_mut` using the fully-qualified path
|
LL - match fut.as_mut().poll(ctx) {
LL + match <_ as AsMut<_>>::as_mut(&mut fut).poll(ctx) {
|
help: trait `Future` which provides `poll` is implemented but not in scope; perhaps you want to import it
|
LL + use std::future::Future;
Expand Down
31 changes: 31 additions & 0 deletions tests/ui/methods/method-shadowed-by-trait-in-binop.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Regression test for #66630.
use std::sync::Mutex;
use std::cell::RefCell;
use std::borrow::Borrow;

struct A {
child: Mutex<RefCell<i32>>,
}

impl A {
fn is_good(&self) -> bool {
let cell = self.child.lock().unwrap();
let opt_target = cell.borrow();
//~^ NOTE: this method is `std::borrow::Borrow::borrow`
//~| NOTE: this method is `std::borrow::Borrow::borrow`
let _ = opt_target.abs(); //~ ERROR: no method named `abs` found for
//~^ NOTE: method not found in `&std::sync::MutexGuard<'_, RefCell<i32>>`
//~| NOTE: this returns `&std::sync::MutexGuard<'_, RefCell<i32>>`
//~| NOTE: you might have meant to call `std::cell::RefCell::<T>::borrow` instead
let _ = *opt_target > 1; //~ ERROR: binary operation `>` cannot be applied
//~^ NOTE: std::sync::MutexGuard<'_, RefCell<i32>>
//~| NOTE: `std::sync::MutexGuard<'_, RefCell<i32>>` does not implement `PartialOrd<{integer}>`
//~| NOTE: this returns `std::sync::MutexGuard<'_, RefCell<i32>>`
//~| NOTE: you might have meant to call `std::cell::RefCell::<T>::borrow` instead
//~| NOTE: {integer}
1 < *opt_target //~ ERROR: E0277
//~^ NOTE: no implementation for `{integer} < std::sync::MutexGuard<'_, RefCell<i32>>`
}
}

fn main() {}
67 changes: 67 additions & 0 deletions tests/ui/methods/method-shadowed-by-trait-in-binop.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
error[E0599]: no method named `abs` found for reference `&std::sync::MutexGuard<'_, RefCell<i32>>` in the current scope
--> $DIR/method-shadowed-by-trait-in-binop.rs:16:28
|
LL | let opt_target = cell.borrow();
| ------ this method is `std::borrow::Borrow::borrow`
...
LL | let _ = opt_target.abs();
| ^^^ method not found in `&std::sync::MutexGuard<'_, RefCell<i32>>`
|
note: this returns `&std::sync::MutexGuard<'_, RefCell<i32>>`
--> $SRC_DIR/core/src/borrow.rs:LL:COL
note: you might have meant to call `std::cell::RefCell::<T>::borrow` instead
--> $SRC_DIR/core/src/cell.rs:LL:COL
help: consider calling `std::cell::RefCell::<T>::borrow` using the fully-qualified path
|
LL - let opt_target = cell.borrow();
LL + let opt_target = RefCell::<i32>::borrow(&cell);
|

error[E0369]: binary operation `>` cannot be applied to type `std::sync::MutexGuard<'_, RefCell<i32>>`
--> $DIR/method-shadowed-by-trait-in-binop.rs:20:29
|
LL | let opt_target = cell.borrow();
| ------ this method is `std::borrow::Borrow::borrow`
...
LL | let _ = *opt_target > 1;
| ----------- ^ - {integer}
| |
| std::sync::MutexGuard<'_, RefCell<i32>>
|
note: `std::sync::MutexGuard<'_, RefCell<i32>>` does not implement `PartialOrd<{integer}>`
--> $SRC_DIR/std/src/sync/poison/mutex.rs:LL:COL
::: $SRC_DIR/std/src/sync/poison/mutex.rs:LL:COL
|
= note: `std::sync::MutexGuard<'_, RefCell<i32>>` is defined in another crate
note: this returns `std::sync::MutexGuard<'_, RefCell<i32>>`
--> $SRC_DIR/core/src/borrow.rs:LL:COL
note: you might have meant to call `std::cell::RefCell::<T>::borrow` instead
--> $SRC_DIR/core/src/cell.rs:LL:COL
help: consider calling `std::cell::RefCell::<T>::borrow` using the fully-qualified path
|
LL - let opt_target = cell.borrow();
LL + let opt_target = RefCell::<i32>::borrow(&cell);
|

error[E0277]: can't compare `{integer}` with `std::sync::MutexGuard<'_, RefCell<i32>>`
--> $DIR/method-shadowed-by-trait-in-binop.rs:26:11
|
LL | 1 < *opt_target
| ^ no implementation for `{integer} < std::sync::MutexGuard<'_, RefCell<i32>>` and `{integer} > std::sync::MutexGuard<'_, RefCell<i32>>`
|
= help: the trait `PartialOrd<std::sync::MutexGuard<'_, RefCell<i32>>>` is not implemented for `{integer}`
= help: the following other types implement trait `PartialOrd<Rhs>`:
f128
f16
f32
f64
i128
i16
i32
i64
and 8 others

error: aborting due to 3 previous errors

Some errors have detailed explanations: E0277, E0369, E0599.
For more information about an error, try `rustc --explain E0277`.
122 changes: 122 additions & 0 deletions tests/ui/methods/method-shadowed-by-trait.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
// Show the diagnostic for cases where a method is expected by the user but a different one is
// shaddowing it causing a field access to fail. Test for #93726.

use std::cell::RefCell;
use std::rc::Rc;
use std::borrow::BorrowMut;

type NodeAlias = Option<Rc<RefCell<Node>>>;

#[derive(Clone, Debug, PartialEq)]
struct Node {
value: String,
next: NodeAlias,
}

#[derive(Clone, Debug, PartialEq)]
struct TransactionLog {
head: NodeAlias,
tail: NodeAlias,
length: i32,
}

impl Node {
fn new(value: String) -> Rc<RefCell<Node>> {
Rc::new(RefCell::new(Node { value, next: None }))
}
}

impl TransactionLog {
pub fn empty_list() -> TransactionLog {
TransactionLog {
head: None,
tail: None,
length: 0,
}
}

pub fn append(&mut self, value: String) {
let node = Node::new(value);
match self.tail.take() {
Some(old_tail) => old_tail.borrow_mut().next = Some(node.clone()),
//~^ ERROR: no field `next` on type `&mut Rc<RefCell<Node>>`
//~| NOTE: unknown field
//~| NOTE: this method is `std::borrow::BorrowMut::borrow_mut`
//~| NOTE: you might have meant to call `std::cell::RefCell::<T>::borrow_mut` instead
//~| NOTE: this returns `&mut Rc<RefCell<Node>>`
None => self.head = Some(node.clone()),
}
self.length += 1;
self.tail = Some(node);
}
}


struct S;
struct Other {
field: (),
}
impl Other {
fn method(&self) {}
}

impl S {
fn foo(&self) -> Other { Other { field: () } }
//~^ NOTE: you might have meant to call
//~| NOTE: you might have meant to call
//~| NOTE: you might have meant to call
//~| NOTE: you might have meant to call
}
mod a {
use crate::{S, Other};
pub trait T {
fn foo(&self) {}
//~^ NOTE: this returns `()`
//~| NOTE: this returns `()`
//~| NOTE: this returns `()`
//~| NOTE: this returns `()`
}
impl T for S {}
impl T for Box<S> {}
pub trait K<P> {
fn foo(&self) -> Other { Other { field : () } }
//~^ NOTE: you might have meant to call
//~| NOTE: you might have meant to call
//~| NOTE: you might have meant to call
//~| NOTE: you might have meant to call
}
impl K<()> for S {}
impl K<i32> for Box<S> {}
pub trait V {
fn foo(&self) -> Other;
//~^ NOTE: you might have meant to call
//~| NOTE: you might have meant to call
//~| NOTE: you might have meant to call
//~| NOTE: you might have meant to call
}
impl V for Box<S> {
fn foo(&self) -> Other { Other { field : () } }
}
pub trait U {
fn foo(&self) {} // not suggested because its return type doesn't have the field
}
impl U for Box<S> {}
}
use a::T;

fn main() {
let x = Box::new(S);
x.foo().field; //~ ERROR: no field `field` on type `()`
//~^ NOTE: unknown field
//~| NOTE: this method is `a::T::foo`
let y = x.foo();
//~^ NOTE: this method is `a::T::foo`
//~| NOTE: this method is `a::T::foo`
let _ = y.field; //~ ERROR: no field `field` on type `()`
//~^ NOTE: unknown field
x.foo().method(); //~ ERROR: no method named `method` found for unit type `()` in the current scope
//~^ NOTE: method not found in `()`
//~| NOTE: this method is `a::T::foo`
let _ = y.method(); //~ ERROR: no method named `method` found for unit type `()` in the current scope
//~^ NOTE: method not found in `()`
}
Loading
Loading