rust-lang/rust · #165216
Clearer diagnostics when `&FnOnce` was provided when `FnOnce` was expected
compiler/rustc_middle/src/middle/lang_items.rs17 + / 1 −
@@ -12,7 +12,7 @@ use rustc_hir::def_id::DefId; use rustc_span::Span; use rustc_target::spec::PanicStrategy; -use crate::ty::{self, TyCtxt};+use crate::ty::{self, Asyncness, TyCtxt}; impl<'tcx> TyCtxt<'tcx> { /// Returns the `DefId` for a given `LangItem`.@@ -44,6 +44,22 @@ impl<'tcx> TyCtxt<'tcx> { } } + /// Given a [`DefId`] of one of the [`Fn`], [`FnMut`], [`FnOnce`], [`AsyncFn`], [`AsyncFnMut`], or [`AsyncFnOnce`] traits,+ /// returns a corresponding [`ty::ClosureKind`] and [`Asyncness`].+ /// For any other [`DefId`] return `None`.+ pub fn maybe_async_fn_trait_kind_from_def_id(+ self,+ id: DefId,+ ) -> Option<(Asyncness, ty::ClosureKind)> {+ if let Some(kind) = self.fn_trait_kind_from_def_id(id) {+ Some((Asyncness::No, kind))+ } else if let Some(kind) = self.async_fn_trait_kind_from_def_id(id) {+ Some((Asyncness::Yes, kind))+ } else {+ return None;+ }+ }+ /// Given a [`DefId`] of one of the `AsyncFn`, `AsyncFnMut` or `AsyncFnOnce` traits, /// returns a corresponding [`ty::ClosureKind`]. /// For any other [`DefId`] return `None`.compiler/rustc_middle/src/ty/mod.rs8 + / 0 −
@@ -243,6 +243,14 @@ impl Asyncness { pub fn is_async(self) -> bool { matches!(self, Asyncness::Yes) }++ /// Returns "Async" if [`Self::Yes`], otherwise returns an empty string slice.+ pub fn as_trait_prefix_str(&self) -> &'static str {+ match self {+ Asyncness::Yes => "Async",+ Asyncness::No => "",+ }+ } } #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, BlobDecodable, StableHash)]compiler/rustc_trait_selection/src/diagnostics.rs13 + / 0 −
@@ -141,6 +141,19 @@ pub(crate) struct ClosureKindMismatch { pub fn_mut_label: Option<ClosureFnMutLabel>, } +#[derive(Diagnostic)]+#[diag("expected `{$trait_prefix}FnOnce`, found reference", code = E0525)]+#[note("`{$trait_prefix}FnOnce` isn't implemented for references")]+pub(crate) struct RefToFnOnce {+ #[primary_span]+ #[label("closure passed by reference here")]+ pub cause_span: Span,+ pub trait_prefix: &'static str,++ #[subdiagnostic]+ pub fn_once_label: Option<ClosureFnOnceLabel>,+}+ #[derive(Subdiagnostic)] #[label( "closure is `{$trait_prefix}FnOnce` because it moves the variable `{$place}` out of its environment"compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs87 + / 20 −
@@ -43,7 +43,7 @@ use super::suggestions::get_explanation_based_on_obligation; use super::{ArgKind, CandidateSimilarity, GetSafeTransmuteErrorAndReason, ImplCandidate}; use crate::diagnostics::{ AssocTypeWithSameName, ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch,- CoroClosureNotFn,+ CoroClosureNotFn, RefToFnOnce, }; use crate::error_reporting::TypeErrCtxt; use crate::error_reporting::infer::TyCategory;@@ -1060,17 +1060,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let self_ty = if is_ref_to_closure { peeled_self_ty } else { original_self_ty }; - let (expected_kind, is_async) =- if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) {- (expected_kind, false)- } else if let Some(expected_kind) =- self.tcx.async_fn_trait_kind_from_def_id(trait_pred.def_id())- {- (expected_kind, true)- } else {- return None;- };- let trait_prefix = if is_async { "Async" } else { "" };+ let (asyncness, expected_kind) =+ self.tcx.maybe_async_fn_trait_kind_from_def_id(trait_pred.def_id())?;++ let trait_prefix = asyncness.as_trait_prefix_str(); let (closure_def_id, found_args, has_self_borrows) = match *self_ty.kind() { ty::Closure(def_id, args) => {@@ -1104,14 +1097,39 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { if found_kind.is_none() && is_ref_to_closure- && !is_async+ && !asyncness.is_async() && let Some(local_def_id) = closure_def_id.as_local() && let Some((inferred_kind, origin)) = (self.infer_closure_kind)(local_def_id) { found_kind = Some(inferred_kind); kind_origin = origin; } + let (_, root_trait_pred) = obligation.cause.code().peel_derives_with_predicate();+ let root_expected = root_trait_pred+ .and_then(|pred| self.tcx.maybe_async_fn_trait_kind_from_def_id(pred.def_id()));++ // Prevent confusing errors when `&FnOnce` was provided when `FnOnce` was expected+ // in function arguments+ if let ty::ClosureKind::Fn | ty::ClosureKind::FnMut = expected_kind+ && let Some(ty::ClosureKind::FnOnce) = found_kind+ && let Some((root_asyncness, ty::ClosureKind::FnOnce)) = root_expected+ && let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()+ && let arg = self.tcx.hir_expect_expr(*arg_hir_id)+ && asyncness == root_asyncness+ {+ let mut err = self.report_ref_to_fn_once_error(+ closure_def_id,+ trait_prefix,+ kind_origin,+ arg.span,+ );++ self.suggest_remove_ref_for_closure(&mut err, obligation);+ self.note_obligation_cause(&mut err, obligation);+ return Some(err.emit_err());+ }+ if let Some(found_kind) = found_kind && !found_kind.extends(expected_kind) {@@ -1123,7 +1141,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { trait_prefix, kind_origin, );- self.suggest_change_mut_ref_for_closure(&mut err, &obligation);++ self.suggest_change_mut_ref_for_closure(&mut err, obligation); self.note_obligation_cause(&mut err, &obligation); return Some(err.emit_err()); }@@ -3127,6 +3146,26 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } + fn suggest_remove_ref_for_closure(+ &self,+ err: &mut Diag<'_>,+ obligation: &PredicateObligation<'tcx>,+ ) {+ if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()+ && let (_, Some(root_trait_pred)) =+ obligation.cause.code().peel_derives_with_predicate()+ && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)+ && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, _) = arg.kind+ {+ let mut obligation = obligation.clone();+ // Error reporting may narrow the cause span to the borrow's operand.+ // Use the whole argument so `suggest_remove_reference` can replace the borrow.+ obligation.cause.span = arg.span;++ self.suggest_remove_reference(&obligation, err, root_trait_pred);+ }+ }+ /// Register when multiple obligations come from the same statement and only emit one. /// /// This can significantly reduce the number of `_: Sized` failures on method chains.@@ -3675,6 +3714,38 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } + fn infer_closure_origin(+ &self,+ closure_def_id: DefId,+ ) -> Option<(Span, rustc_middle::hir::place::Place<'tcx>)> {+ let typeck_results = self.typeck_results.as_ref()?;+ let local_def_id = closure_def_id.as_local()?;+ let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id);+ typeck_results.closure_kind_origins().get(hir_id).cloned()+ }++ fn report_ref_to_fn_once_error(+ &self,+ closure_def_id: DefId,+ trait_prefix: &'static str,+ kind_origin: Option<(Span, rustc_middle::hir::place::Place<'tcx>)>,+ cause_span: Span,+ ) -> Diag<'a> {+ let origin = kind_origin.or_else(|| self.infer_closure_origin(closure_def_id));++ let err = RefToFnOnce {+ cause_span,+ trait_prefix,+ fn_once_label: origin.map(|(span, place)| ClosureFnOnceLabel {+ span,+ place: ty::place_to_string_for_capture(self.tcx, &place),+ trait_prefix,+ }),+ };++ self.dcx().create_err(err)+ }+ fn report_closure_error( &self, obligation: &PredicateObligation<'tcx>,@@ -3698,12 +3769,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // Additional context information explaining why the closure only implements // a particular trait.- let origin = kind_origin.or_else(|| {- let typeck_results = self.typeck_results.as_ref()?;- let local_def_id = closure_def_id.as_local()?;- let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id);- typeck_results.closure_kind_origins().get(hir_id).cloned()- });+ let origin = kind_origin.or_else(|| self.infer_closure_origin(closure_def_id)); match (found_kind, origin) { (ty::ClosureKind::FnOnce, Some((span, place))) => {@@ -3722,6 +3788,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } _ => {} }+ self.dcx().create_err(err) } tests/ui/closures/ref-to-fn-once.rsadded58 + / 0 −
@@ -0,0 +1,58 @@+// Provide clear diagnostics when `&FnOnce` was provided+// when `FnOnce` was expected in function arguments.+// Related issue: #47648+//@ edition:2024++struct Foo {}++fn call<F: FnOnce() -> Foo>(f: F) {+ call(&f);+ //~^ ERROR expected `FnOnce()` signature, found `&F`+}++fn async_call<F: AsyncFnOnce() -> Foo>(f: F) {+ async_call(&f);+ //~^ ERROR the trait bound `&F: AsyncFnOnce()` is not satisfied+}++fn main() {+ let foo = Foo {};+ let once = move || foo;++ call(&once);+ //~^ ERROR expected `FnOnce`, found reference [E0525]+ call(&mut once);+ //~^ ERROR expected `FnOnce`, found reference [E0525]++ let foo = Foo {};+ let once = &move || foo;++ call(once);+ //~^ ERROR expected `FnOnce`, found reference [E0525]++ let foo = Foo {};+ let once = &mut move || foo;++ call(once);+ //~^ ERROR expected `FnOnce`, found reference [E0525]++ let foo = Foo {};+ let async_once = async move || foo;++ async_call(&async_once);+ //~^ ERROR expected `AsyncFnOnce`, found reference [E0525]+ async_call(&mut async_once);+ //~^ ERROR expected `AsyncFnOnce`, found reference [E0525]++ let foo = Foo {};+ let async_once = &async move || foo;++ async_call(async_once);+ //~^ ERROR expected `AsyncFnOnce`, found reference [E0525]++ let foo = Foo {};+ let async_once = &mut async move || foo;++ async_call(async_once);+ //~^ ERROR expected `AsyncFnOnce`, found reference [E0525]+}tests/ui/closures/ref-to-fn-once.stderradded212 + / 0 −
@@ -0,0 +1,212 @@+error[E0277]: expected `FnOnce()` signature, found `&F`+ --> $DIR/ref-to-fn-once.rs:9:11+ |+LL | call(&f);+ | ---- ^ expected `FnOnce()` signature, found `&F`+ | |+ | required by a bound introduced by this call+ |+ = note: wrap the `&F` in a closure with no arguments: `|| { /* code */ }`+ = note: `F` implements `FnOnce`, but it must implement `Fn`, which is more general+ = note: required for `&F` to implement `FnOnce()`+note: required by a bound in `call`+ --> $DIR/ref-to-fn-once.rs:8:12+ |+LL | fn call<F: FnOnce() -> Foo>(f: F) {+ | ^^^^^^^^^^^^^^^ required by this bound in `call`++error[E0277]: the trait bound `&F: AsyncFnOnce()` is not satisfied+ --> $DIR/ref-to-fn-once.rs:14:17+ |+LL | async_call(&f);+ | ---------- ^ the trait `AsyncFn()` is not implemented for `F`+ | |+ | required by a bound introduced by this call+ |+ = note: required for `&F` to implement `AsyncFnOnce()`+note: required by a bound in `async_call`+ --> $DIR/ref-to-fn-once.rs:13:18+ |+LL | fn async_call<F: AsyncFnOnce() -> Foo>(f: F) {+ | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call`+help: consider further restricting type parameter `F` with trait `AsyncFn`+ |+LL | fn async_call<F: AsyncFnOnce() -> Foo + AsyncFn()>(f: F) {+ | +++++++++++++error[E0525]: expected `FnOnce`, found reference+ --> $DIR/ref-to-fn-once.rs:22:10+ |+LL | let once = move || foo;+ | --- closure is `FnOnce` because it moves the variable `foo` out of its environment+LL |+LL | call(&once);+ | ---- ^^^^^ closure passed by reference here+ | |+ | required by a bound introduced by this call+ |+ = note: `FnOnce` isn't implemented for references+ = note: required for `&{closure@$DIR/ref-to-fn-once.rs:20:16: 20:23}` to implement `FnOnce()`+note: required by a bound in `call`+ --> $DIR/ref-to-fn-once.rs:8:12+ |+LL | fn call<F: FnOnce() -> Foo>(f: F) {+ | ^^^^^^^^^^^^^^^ required by this bound in `call`+help: consider removing the leading `&`-reference+ |+LL - call(&once);+LL + call(once);+ |++error[E0525]: expected `FnOnce`, found reference+ --> $DIR/ref-to-fn-once.rs:24:10+ |+LL | let once = move || foo;+ | --- closure is `FnOnce` because it moves the variable `foo` out of its environment+...+LL | call(&mut once);+ | ---- ^^^^^^^^^ closure passed by reference here+ | |+ | required by a bound introduced by this call+ |+ = note: `FnOnce` isn't implemented for references+ = note: required for `&mut {closure@$DIR/ref-to-fn-once.rs:20:16: 20:23}` to implement `FnOnce()`+note: required by a bound in `call`+ --> $DIR/ref-to-fn-once.rs:8:12+ |+LL | fn call<F: FnOnce() -> Foo>(f: F) {+ | ^^^^^^^^^^^^^^^ required by this bound in `call`+help: consider removing the leading `&`-reference+ |+LL - call(&mut once);+LL + call(once);+ |++error[E0525]: expected `FnOnce`, found reference+ --> $DIR/ref-to-fn-once.rs:30:10+ |+LL | let once = &move || foo;+ | --- closure is `FnOnce` because it moves the variable `foo` out of its environment+LL |+LL | call(once);+ | ---- ^^^^ closure passed by reference here+ | |+ | required by a bound introduced by this call+ |+ = note: `FnOnce` isn't implemented for references+ = note: required for `&{closure@$DIR/ref-to-fn-once.rs:28:17: 28:24}` to implement `FnOnce()`+note: required by a bound in `call`+ --> $DIR/ref-to-fn-once.rs:8:12+ |+LL | fn call<F: FnOnce() -> Foo>(f: F) {+ | ^^^^^^^^^^^^^^^ required by this bound in `call`++error[E0525]: expected `FnOnce`, found reference+ --> $DIR/ref-to-fn-once.rs:36:10+ |+LL | let once = &mut move || foo;+ | --- closure is `FnOnce` because it moves the variable `foo` out of its environment+LL |+LL | call(once);+ | ---- ^^^^ closure passed by reference here+ | |+ | required by a bound introduced by this call+ |+ = note: `FnOnce` isn't implemented for references+ = note: required for `&mut {closure@$DIR/ref-to-fn-once.rs:34:21: 34:28}` to implement `FnOnce()`+note: required by a bound in `call`+ --> $DIR/ref-to-fn-once.rs:8:12+ |+LL | fn call<F: FnOnce() -> Foo>(f: F) {+ | ^^^^^^^^^^^^^^^ required by this bound in `call`++error[E0525]: expected `AsyncFnOnce`, found reference+ --> $DIR/ref-to-fn-once.rs:42:16+ |+LL | let async_once = async move || foo;+ | --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment+LL |+LL | async_call(&async_once);+ | ---------- ^^^^^^^^^^^ closure passed by reference here+ | |+ | required by a bound introduced by this call+ |+ = note: `AsyncFnOnce` isn't implemented for references+ = note: required for `&{async closure@$DIR/ref-to-fn-once.rs:40:22: 40:35}` to implement `AsyncFnOnce()`+note: required by a bound in `async_call`+ --> $DIR/ref-to-fn-once.rs:13:18+ |+LL | fn async_call<F: AsyncFnOnce() -> Foo>(f: F) {+ | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call`+help: consider removing the leading `&`-reference+ |+LL - async_call(&async_once);+LL + async_call(async_once);+ |++error[E0525]: expected `AsyncFnOnce`, found reference+ --> $DIR/ref-to-fn-once.rs:44:16+ |+LL | let async_once = async move || foo;+ | --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment+...+LL | async_call(&mut async_once);+ | ---------- ^^^^^^^^^^^^^^^ closure passed by reference here+ | |+ | required by a bound introduced by this call+ |+ = note: `AsyncFnOnce` isn't implemented for references+ = note: required for `&mut {async closure@$DIR/ref-to-fn-once.rs:40:22: 40:35}` to implement `AsyncFnOnce()`+note: required by a bound in `async_call`+ --> $DIR/ref-to-fn-once.rs:13:18+ |+LL | fn async_call<F: AsyncFnOnce() -> Foo>(f: F) {+ | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call`+help: consider removing the leading `&`-reference+ |+LL - async_call(&mut async_once);+LL + async_call(async_once);+ |++error[E0525]: expected `AsyncFnOnce`, found reference+ --> $DIR/ref-to-fn-once.rs:50:16+ |+LL | let async_once = &async move || foo;+ | --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment+LL |+LL | async_call(async_once);+ | ---------- ^^^^^^^^^^ closure passed by reference here+ | |+ | required by a bound introduced by this call+ |+ = note: `AsyncFnOnce` isn't implemented for references+ = note: required for `&{async closure@$DIR/ref-to-fn-once.rs:48:23: 48:36}` to implement `AsyncFnOnce()`+note: required by a bound in `async_call`+ --> $DIR/ref-to-fn-once.rs:13:18+ |+LL | fn async_call<F: AsyncFnOnce() -> Foo>(f: F) {+ | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call`++error[E0525]: expected `AsyncFnOnce`, found reference+ --> $DIR/ref-to-fn-once.rs:56:16+ |+LL | let async_once = &mut async move || foo;+ | --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment+LL |+LL | async_call(async_once);+ | ---------- ^^^^^^^^^^ closure passed by reference here+ | |+ | required by a bound introduced by this call+ |+ = note: `AsyncFnOnce` isn't implemented for references+ = note: required for `&mut {async closure@$DIR/ref-to-fn-once.rs:54:27: 54:40}` to implement `AsyncFnOnce()`+note: required by a bound in `async_call`+ --> $DIR/ref-to-fn-once.rs:13:18+ |+LL | fn async_call<F: AsyncFnOnce() -> Foo>(f: F) {+ | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call`++error: aborting due to 10 previous errors++Some errors have detailed explanations: E0277, E0525.+For more information about an error, try `rustc --explain E0277`.