about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMatthias Krüger <matthias.krueger@famsik.de>2024-07-23 19:42:37 +0200
committerGitHub <noreply@github.com>2024-07-23 19:42:37 +0200
commitc2ba4b1cb02e680f262e239ea0f317581049fe03 (patch)
tree73a92ac9550a2585afda38ddf127a7f9053c8453
parent417bdc703663fc0870b78260a01ce5b53393e114 (diff)
parentb7495b401caa7379a19191c491088dc4de95b4c9 (diff)
Rollup merge of #128082 - compiler-errors:closure-cap, r=estebank
Note closure captures when reporting cast to fn ptr failed

Fixes #128078

We already had logic to point out a closure having captures when that's possibly the source of a coercion error to `fn()`, but we weren't reporting it during an explicit `as` cast.
-rw-r--r--compiler/rustc_hir_typeck/src/cast.rs1
-rw-r--r--tests/ui/closures/closure-no-fn-3.stderr6
2 files changed, 7 insertions, 0 deletions
diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs
index 341d533492d..65229722771 100644
--- a/compiler/rustc_hir_typeck/src/cast.rs
+++ b/compiler/rustc_hir_typeck/src/cast.rs
@@ -495,6 +495,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
                     err.span_label(self.span, "invalid cast");
                 }
 
+                fcx.suggest_no_capture_closure(&mut err, self.cast_ty, self.expr_ty);
                 self.try_suggest_collection_to_bool(fcx, &mut err);
 
                 err.emit();
diff --git a/tests/ui/closures/closure-no-fn-3.stderr b/tests/ui/closures/closure-no-fn-3.stderr
index bbf3677fb72..7711347c568 100644
--- a/tests/ui/closures/closure-no-fn-3.stderr
+++ b/tests/ui/closures/closure-no-fn-3.stderr
@@ -3,6 +3,12 @@ error[E0605]: non-primitive cast: `{closure@$DIR/closure-no-fn-3.rs:6:28: 6:30}`
    |
 LL |     let baz: fn() -> u8 = (|| { b }) as fn() -> u8;
    |                           ^^^^^^^^^^^^^^^^^^^^^^^^ invalid cast
+   |
+note: closures can only be coerced to `fn` types if they do not capture any variables
+  --> $DIR/closure-no-fn-3.rs:6:33
+   |
+LL |     let baz: fn() -> u8 = (|| { b }) as fn() -> u8;
+   |                                 ^ `b` captured here
 
 error: aborting due to 1 previous error