do not suggest method call removal if it changes receiver type

This commit is contained in:
Deadbeef 2025-12-27 14:34:20 -05:00
parent 4c6706452c
commit bc2853f4c1
3 changed files with 41 additions and 11 deletions

View file

@ -4069,15 +4069,25 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
))
&& expr.span.hi() != rcvr.span.hi()
{
err.span_suggestion_verbose(
expr.span.with_lo(rcvr.span.hi()),
format!(
"consider removing this method call, as the receiver has type `{ty}` and \
`{pred}` trivially holds",
),
"",
Applicability::MaybeIncorrect,
);
match tcx.hir_node(call_hir_id) {
// Do not suggest removing a method call if the argument is the receiver of the parent call:
// `x.a().b()`, suggesting removing `.a()` would change the type and could make `.b()` unavailable.
Node::Expr(hir::Expr {
kind: hir::ExprKind::MethodCall(_, call_receiver, _, _),
..
}) if call_receiver.hir_id == arg_hir_id => {}
_ => {
err.span_suggestion_verbose(
expr.span.with_lo(rcvr.span.hi()),
format!(
"consider removing this method call, as the receiver has type `{ty}` and \
`{pred}` trivially holds",
),
"",
Applicability::MaybeIncorrect,
);
}
}
}
if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr {
let inner_expr = expr.peel_blocks();

View file

@ -9,3 +9,11 @@ fn main() {
//~| HELP try using a fully qualified path to specify the expected types
//~| HELP consider removing this method call, as the receiver has type `Bar` and `Bar: From<Bar>` trivially holds
}
// regression test for https://github.com/rust-lang/rust/issues/149487.
fn quux() {
let mut tx_heights: std::collections::BTreeMap<(), Option<()>> = <_>::default();
tx_heights.get(&()).unwrap_or_default();
//~^ ERROR the trait bound `&Option<()>: Default` is not satisfied
//~| HELP: the trait `Default` is implemented for `Option<T>`
}

View file

@ -23,6 +23,18 @@ LL - qux(Bar.into());
LL + qux(Bar);
|
error: aborting due to 1 previous error
error[E0277]: the trait bound `&Option<()>: Default` is not satisfied
--> $DIR/argument-with-unnecessary-method-call.rs:16:25
|
LL | tx_heights.get(&()).unwrap_or_default();
| ^^^^^^^^^^^^^^^^^ the trait `Default` is not implemented for `&Option<()>`
|
help: the trait `Default` is implemented for `Option<T>`
--> $SRC_DIR/core/src/option.rs:LL:COL
note: required by a bound in `Option::<T>::unwrap_or_default`
--> $SRC_DIR/core/src/option.rs:LL:COL
For more information about this error, try `rustc --explain E0283`.
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0277, E0283.
For more information about an error, try `rustc --explain E0277`.