Rollup merge of #156301 - TaKO8Ki:fix-156299-closure-receiver-suggestion-ice, r=wesleywiser

Avoid ICE when suggesting as_ref for ill-typed closure receivers

Fixes rust-lang/rust#156299

When building mismatch suggestions, `can_use_as_ref` may inspect the receiver of a method call that is itself an ill-typed closure expression. In that recovery path, the receiver may not have a recorded type in `TypeckResults`.

Use `expr_ty_opt` instead of `expr_ty` so the optional `as_ref()` suggestion is skipped when the receiver type is unavailable.
This commit is contained in:
Jonathan Brouwer
2026-05-08 16:18:42 +02:00
committed by GitHub
3 changed files with 42 additions and 1 deletions
@@ -2787,7 +2787,7 @@ fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Vec<(Span, String)>, &
return None;
};
let self_ty = self.typeck_results.borrow().expr_ty(receiver);
let self_ty = self.typeck_results.borrow().expr_ty_opt(receiver)?;
let name = method_path.ident.name;
let is_as_ref_able = match self_ty.peel_refs().kind() {
ty::Adt(def, _) => {
@@ -0,0 +1,13 @@
// Regression test for https://github.com/rust-lang/rust/issues/156299.
struct A;
fn foo(_: &A) {}
fn test_foo() {
(|a: A| foo(a)).bar();
//~^ ERROR mismatched types
//~| ERROR no method named `bar` found
}
fn main() {}
@@ -0,0 +1,28 @@
error[E0308]: mismatched types
--> $DIR/closure-arg-type-mismatch-method-receiver.rs:8:17
|
LL | (|a: A| foo(a)).bar();
| --- ^ expected `&A`, found `A`
| |
| arguments to this function are incorrect
|
note: function defined here
--> $DIR/closure-arg-type-mismatch-method-receiver.rs:5:4
|
LL | fn foo(_: &A) {}
| ^^^ -----
help: consider borrowing here
|
LL | (|a: A| foo(&a)).bar();
| +
error[E0599]: no method named `bar` found for closure `{closure@$DIR/closure-arg-type-mismatch-method-receiver.rs:8:6: 8:12}` in the current scope
--> $DIR/closure-arg-type-mismatch-method-receiver.rs:8:21
|
LL | (|a: A| foo(a)).bar();
| ^^^ method not found in `{closure@$DIR/closure-arg-type-mismatch-method-receiver.rs:8:6: 8:12}`
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0308, E0599.
For more information about an error, try `rustc --explain E0308`.