Skip to main content

rustc_hir_typeck/
closure.rs

1//! Code for type-checking closure expressions.
2
3use std::iter;
4use std::ops::ControlFlow;
5
6use rustc_abi::ExternAbi;
7use rustc_errors::ErrorGuaranteed;
8use rustc_hir as hir;
9use rustc_hir::attrs::lang_items::LangItem;
10use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
11use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk, InferResult};
12use rustc_infer::traits::{ObligationCauseCode, PredicateObligations};
13use rustc_macros::{TypeFoldable, TypeVisitable};
14use rustc_middle::span_bug;
15use rustc_middle::ty::{
16    self, ClosureKind, FnSigKind, GenericArgs, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
17    TypeVisitableExt, TypeVisitor, Unnormalized,
18};
19use rustc_span::def_id::LocalDefId;
20use rustc_span::{DUMMY_SP, Span};
21use rustc_trait_selection::error_reporting::traits::ArgKind;
22use rustc_trait_selection::traits;
23use tracing::{debug, instrument, trace};
24
25use super::{CoroutineTypes, Expectation, FnCtxt, check_fn};
26use crate::fn_ctxt::UseSubtyping;
27
28/// What signature do we *expect* the closure to have from context?
29#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ExpectedSig<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "ExpectedSig",
            "cause_span", &self.cause_span, "sig", &&self.sig)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ExpectedSig<'tcx> {
    #[inline]
    fn clone(&self) -> ExpectedSig<'tcx> {
        ExpectedSig {
            cause_span: ::core::clone::Clone::clone(&self.cause_span),
            sig: ::core::clone::Clone::clone(&self.sig),
        }
    }
}Clone, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ExpectedSig<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        ExpectedSig { cause_span: __binding_0, sig: __binding_1 } =>
                            {
                            ExpectedSig {
                                cause_span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                sig: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    ExpectedSig { cause_span: __binding_0, sig: __binding_1 } =>
                        {
                        ExpectedSig {
                            cause_span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            sig: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ExpectedSig<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    ExpectedSig {
                        cause_span: ref __binding_0, sig: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
30struct ExpectedSig<'tcx> {
31    /// Span that gave us this expectation, if we know that.
32    cause_span: Option<Span>,
33    sig: ty::PolyFnSig<'tcx>,
34}
35
36#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ClosureSignatures<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ClosureSignatures", "bound_sig", &self.bound_sig,
            "liberated_sig", &&self.liberated_sig)
    }
}Debug)]
37struct ClosureSignatures<'tcx> {
38    /// The signature users of the closure see.
39    bound_sig: ty::PolyFnSig<'tcx>,
40    /// The signature within the function body.
41    /// This mostly differs in the sense that lifetimes are now early bound and any
42    /// opaque types from the signature expectation are overridden in case there are
43    /// explicit hidden types written by the user in the closure signature.
44    liberated_sig: ty::FnSig<'tcx>,
45}
46
47impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
48    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_expr_closure",
                                    "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                    ::tracing_core::__macro_support::Option::Some(48u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expr_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expr_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expected")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expected");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            let body = tcx.hir_body(closure.body);
            let expr_def_id = closure.def_id;
            let (expected_sig, expected_kind) =
                match expected.to_option(self) {
                    Some(ty) =>
                        self.deduce_closure_signature(self.deeply_resolve_ignoring_regions_with_obligations(ty),
                            closure.kind),
                    None => (None, None),
                };
            let ClosureSignatures { bound_sig, mut liberated_sig } =
                self.sig_of_closure(expr_def_id, closure.fn_decl,
                    closure.kind, expected_sig);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:73",
                                    "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                    ::tracing_core::__macro_support::Option::Some(73u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("bound_sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("bound_sig");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("liberated_sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("liberated_sig");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_sig)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&liberated_sig)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let parent_args =
                GenericArgs::identity_for_item(tcx,
                    tcx.typeck_root_def_id_local(expr_def_id));
            let tupled_upvars_ty = self.next_ty_var(expr_span);
            let (closure_ty, coroutine_types) =
                match closure.kind {
                    hir::ClosureKind::Closure => {
                        let sig =
                            bound_sig.map_bound(|sig|
                                    {
                                        tcx.mk_fn_sig([Ty::new_tup(tcx, sig.inputs())],
                                            sig.output(), sig.fn_sig_kind)
                                    });
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:92",
                                                "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                                ::tracing_core::__macro_support::Option::Some(92u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("sig")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("sig");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("expected_kind")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("expected_kind");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sig)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_kind)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let closure_kind_ty =
                            match expected_kind {
                                Some(kind) => Ty::from_closure_kind(tcx, kind),
                                None => self.next_ty_var(expr_span),
                            };
                        let closure_args =
                            ty::ClosureArgs::new(tcx,
                                ty::ClosureArgsParts {
                                    parent_args,
                                    closure_kind_ty,
                                    closure_sig_as_fn_ptr_ty: Ty::new_fn_ptr(tcx, sig),
                                    tupled_upvars_ty,
                                });
                        (Ty::new_closure(tcx, expr_def_id.to_def_id(),
                                closure_args.args), None)
                    }
                    hir::ClosureKind::Coroutine(kind) => {
                        let yield_ty =
                            match kind {
                                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen,
                                    _) | hir::CoroutineKind::Coroutine(_) => {
                                    let yield_ty = self.next_ty_var(expr_span);
                                    self.require_type_is_sized(yield_ty, expr_span,
                                        ObligationCauseCode::SizedYieldType);
                                    yield_ty
                                }
                                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen,
                                    _) => {
                                    let yield_ty = self.next_ty_var(expr_span);
                                    self.require_type_is_sized(yield_ty, expr_span,
                                        ObligationCauseCode::SizedYieldType);
                                    Ty::new_adt(tcx,
                                        tcx.adt_def(tcx.require_lang_item(LangItem::Poll,
                                                expr_span)),
                                        tcx.mk_args(&[Ty::new_adt(tcx,
                                                                tcx.adt_def(tcx.require_lang_item(LangItem::Option,
                                                                        expr_span)), tcx.mk_args(&[yield_ty.into()])).into()]))
                                }
                                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                                    _) => {
                                    tcx.types.unit
                                }
                            };
                        let resume_ty =
                            liberated_sig.inputs().get(0).copied().unwrap_or(tcx.types.unit);
                        let kind_ty =
                            match kind {
                                hir::CoroutineKind::Desugared(_,
                                    hir::CoroutineSource::Closure) => {
                                    self.next_ty_var(expr_span)
                                }
                                _ => tcx.types.unit,
                            };
                        let coroutine_args =
                            ty::CoroutineArgs::new(tcx,
                                ty::CoroutineArgsParts {
                                    parent_args,
                                    kind_ty,
                                    resume_ty,
                                    yield_ty,
                                    return_ty: liberated_sig.output(),
                                    tupled_upvars_ty,
                                });
                        (Ty::new_coroutine(tcx, expr_def_id.to_def_id(),
                                coroutine_args.args),
                            Some(CoroutineTypes { resume_ty, yield_ty }))
                    }
                    hir::ClosureKind::CoroutineClosure(kind) => {
                        let (bound_return_ty, bound_yield_ty) =
                            match kind {
                                hir::CoroutineDesugaring::Gen => {
                                    (tcx.types.unit, self.infcx.next_ty_var(expr_span))
                                }
                                hir::CoroutineDesugaring::Async => {
                                    (bound_sig.skip_binder().output(), tcx.types.unit)
                                }
                                hir::CoroutineDesugaring::AsyncGen => {
                                    {
                                        ::core::panicking::panic_fmt(format_args!("not implemented: {0}",
                                                format_args!("`async gen` closures not supported yet")));
                                    }
                                }
                            };
                        let resume_ty = self.next_ty_var(expr_span);
                        let closure_kind_ty =
                            match expected_kind {
                                Some(kind) => Ty::from_closure_kind(tcx, kind),
                                None => self.next_ty_var(expr_span),
                            };
                        let coroutine_captures_by_ref_ty =
                            self.next_ty_var(expr_span);
                        let closure_args =
                            ty::CoroutineClosureArgs::new(tcx,
                                ty::CoroutineClosureArgsParts {
                                    parent_args,
                                    closure_kind_ty,
                                    signature_parts_ty: Ty::new_fn_ptr(tcx,
                                        bound_sig.map_bound(|sig|
                                                {
                                                    tcx.mk_fn_sig([resume_ty,
                                                                Ty::new_tup_from_iter(tcx, sig.inputs().iter().copied())],
                                                        Ty::new_tup(tcx, &[bound_yield_ty, bound_return_ty]),
                                                        sig.fn_sig_kind)
                                                })),
                                    tupled_upvars_ty,
                                    coroutine_captures_by_ref_ty,
                                });
                        let coroutine_kind_ty =
                            match expected_kind {
                                Some(kind) => Ty::from_coroutine_closure_kind(tcx, kind),
                                None => self.next_ty_var(expr_span),
                            };
                        let coroutine_upvars_ty = self.next_ty_var(expr_span);
                        let coroutine_output_ty =
                            tcx.liberate_late_bound_regions(expr_def_id.to_def_id(),
                                closure_args.coroutine_closure_sig().map_bound(|sig|
                                        {
                                            sig.to_coroutine(tcx, parent_args, coroutine_kind_ty,
                                                tcx.coroutine_for_closure(expr_def_id), coroutine_upvars_ty)
                                        }));
                        liberated_sig =
                            tcx.mk_fn_sig(liberated_sig.inputs().iter().copied(),
                                coroutine_output_ty, liberated_sig.fn_sig_kind);
                        (Ty::new_coroutine_closure(tcx, expr_def_id.to_def_id(),
                                closure_args.args), None)
                    }
                };
            check_fn(&mut FnCtxt::new(self, self.param_env, closure.def_id),
                liberated_sig, coroutine_types, closure.fn_decl, expr_def_id,
                body, false);
            closure_ty
        }
    }
}#[instrument(skip(self, closure), level = "debug")]
49    pub(crate) fn check_expr_closure(
50        &self,
51        closure: &hir::Closure<'tcx>,
52        expr_span: Span,
53        expected: Expectation<'tcx>,
54    ) -> Ty<'tcx> {
55        let tcx = self.tcx;
56        let body = tcx.hir_body(closure.body);
57        let expr_def_id = closure.def_id;
58
59        // It's always helpful for inference if we know the kind of
60        // closure sooner rather than later, so first examine the expected
61        // type, and see if can glean a closure kind from there.
62        let (expected_sig, expected_kind) = match expected.to_option(self) {
63            Some(ty) => self.deduce_closure_signature(
64                self.deeply_resolve_ignoring_regions_with_obligations(ty),
65                closure.kind,
66            ),
67            None => (None, None),
68        };
69
70        let ClosureSignatures { bound_sig, mut liberated_sig } =
71            self.sig_of_closure(expr_def_id, closure.fn_decl, closure.kind, expected_sig);
72
73        debug!(?bound_sig, ?liberated_sig);
74
75        let parent_args =
76            GenericArgs::identity_for_item(tcx, tcx.typeck_root_def_id_local(expr_def_id));
77
78        let tupled_upvars_ty = self.next_ty_var(expr_span);
79
80        // FIXME: We could probably actually just unify this further --
81        // instead of having a `FnSig` and a `Option<CoroutineTypes>`,
82        // we can have a `ClosureSignature { Coroutine { .. }, Closure { .. } }`,
83        // similar to how `ty::GenSig` is a distinct data structure.
84        let (closure_ty, coroutine_types) = match closure.kind {
85            hir::ClosureKind::Closure => {
86                // Tuple up the arguments and insert the resulting function type into
87                // the `closures` table.
88                let sig = bound_sig.map_bound(|sig| {
89                    tcx.mk_fn_sig([Ty::new_tup(tcx, sig.inputs())], sig.output(), sig.fn_sig_kind)
90                });
91
92                debug!(?sig, ?expected_kind);
93
94                let closure_kind_ty = match expected_kind {
95                    Some(kind) => Ty::from_closure_kind(tcx, kind),
96
97                    // Create a type variable (for now) to represent the closure kind.
98                    // It will be unified during the upvar inference phase (`upvar.rs`)
99                    None => self.next_ty_var(expr_span),
100                };
101
102                let closure_args = ty::ClosureArgs::new(
103                    tcx,
104                    ty::ClosureArgsParts {
105                        parent_args,
106                        closure_kind_ty,
107                        closure_sig_as_fn_ptr_ty: Ty::new_fn_ptr(tcx, sig),
108                        tupled_upvars_ty,
109                    },
110                );
111
112                (Ty::new_closure(tcx, expr_def_id.to_def_id(), closure_args.args), None)
113            }
114            hir::ClosureKind::Coroutine(kind) => {
115                let yield_ty = match kind {
116                    hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)
117                    | hir::CoroutineKind::Coroutine(_) => {
118                        let yield_ty = self.next_ty_var(expr_span);
119                        self.require_type_is_sized(
120                            yield_ty,
121                            expr_span,
122                            ObligationCauseCode::SizedYieldType,
123                        );
124                        yield_ty
125                    }
126                    // HACK(-Ztrait-solver=next): In the *old* trait solver, we must eagerly
127                    // guide inference on the yield type so that we can handle `AsyncIterator`
128                    // in this block in projection correctly. In the new trait solver, it is
129                    // not a problem.
130                    hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _) => {
131                        let yield_ty = self.next_ty_var(expr_span);
132                        self.require_type_is_sized(
133                            yield_ty,
134                            expr_span,
135                            ObligationCauseCode::SizedYieldType,
136                        );
137
138                        Ty::new_adt(
139                            tcx,
140                            tcx.adt_def(tcx.require_lang_item(LangItem::Poll, expr_span)),
141                            tcx.mk_args(&[Ty::new_adt(
142                                tcx,
143                                tcx.adt_def(tcx.require_lang_item(LangItem::Option, expr_span)),
144                                tcx.mk_args(&[yield_ty.into()]),
145                            )
146                            .into()]),
147                        )
148                    }
149                    hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _) => {
150                        tcx.types.unit
151                    }
152                };
153
154                // Resume type defaults to `()` if the coroutine has no argument.
155                let resume_ty = liberated_sig.inputs().get(0).copied().unwrap_or(tcx.types.unit);
156
157                // Coroutines that come from coroutine closures have not yet determined
158                // their kind ty, so make a fresh infer var which will be constrained
159                // later during upvar analysis. Regular coroutines always have the kind
160                // ty of `().`
161                let kind_ty = match kind {
162                    hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure) => {
163                        self.next_ty_var(expr_span)
164                    }
165                    _ => tcx.types.unit,
166                };
167
168                let coroutine_args = ty::CoroutineArgs::new(
169                    tcx,
170                    ty::CoroutineArgsParts {
171                        parent_args,
172                        kind_ty,
173                        resume_ty,
174                        yield_ty,
175                        return_ty: liberated_sig.output(),
176                        tupled_upvars_ty,
177                    },
178                );
179
180                (
181                    Ty::new_coroutine(tcx, expr_def_id.to_def_id(), coroutine_args.args),
182                    Some(CoroutineTypes { resume_ty, yield_ty }),
183                )
184            }
185            hir::ClosureKind::CoroutineClosure(kind) => {
186                let (bound_return_ty, bound_yield_ty) = match kind {
187                    hir::CoroutineDesugaring::Gen => {
188                        // `iter!` closures always return unit and yield the `Iterator::Item` type
189                        // that we have to infer.
190                        (tcx.types.unit, self.infcx.next_ty_var(expr_span))
191                    }
192                    hir::CoroutineDesugaring::Async => {
193                        // async closures always return the type ascribed after the `->` (if present),
194                        // and yield `()`.
195                        (bound_sig.skip_binder().output(), tcx.types.unit)
196                    }
197                    hir::CoroutineDesugaring::AsyncGen => {
198                        unimplemented!("`async gen` closures not supported yet")
199                    }
200                };
201                // Compute all of the variables that will be used to populate the coroutine.
202                let resume_ty = self.next_ty_var(expr_span);
203
204                let closure_kind_ty = match expected_kind {
205                    Some(kind) => Ty::from_closure_kind(tcx, kind),
206
207                    // Create a type variable (for now) to represent the closure kind.
208                    // It will be unified during the upvar inference phase (`upvar.rs`)
209                    None => self.next_ty_var(expr_span),
210                };
211
212                let coroutine_captures_by_ref_ty = self.next_ty_var(expr_span);
213                let closure_args = ty::CoroutineClosureArgs::new(
214                    tcx,
215                    ty::CoroutineClosureArgsParts {
216                        parent_args,
217                        closure_kind_ty,
218                        signature_parts_ty: Ty::new_fn_ptr(
219                            tcx,
220                            bound_sig.map_bound(|sig| {
221                                tcx.mk_fn_sig(
222                                    [
223                                        resume_ty,
224                                        Ty::new_tup_from_iter(tcx, sig.inputs().iter().copied()),
225                                    ],
226                                    Ty::new_tup(tcx, &[bound_yield_ty, bound_return_ty]),
227                                    sig.fn_sig_kind,
228                                )
229                            }),
230                        ),
231                        tupled_upvars_ty,
232                        coroutine_captures_by_ref_ty,
233                    },
234                );
235
236                let coroutine_kind_ty = match expected_kind {
237                    Some(kind) => Ty::from_coroutine_closure_kind(tcx, kind),
238
239                    // Create a type variable (for now) to represent the closure kind.
240                    // It will be unified during the upvar inference phase (`upvar.rs`)
241                    None => self.next_ty_var(expr_span),
242                };
243
244                let coroutine_upvars_ty = self.next_ty_var(expr_span);
245
246                // We need to turn the liberated signature that we got from HIR, which
247                // looks something like `|Args...| -> T`, into a signature that is suitable
248                // for type checking the inner body of the closure, which always returns a
249                // coroutine. To do so, we use the `CoroutineClosureSignature` to compute
250                // the coroutine type, filling in the tupled_upvars_ty and kind_ty with infer
251                // vars which will get constrained during upvar analysis.
252                let coroutine_output_ty = tcx.liberate_late_bound_regions(
253                    expr_def_id.to_def_id(),
254                    closure_args.coroutine_closure_sig().map_bound(|sig| {
255                        sig.to_coroutine(
256                            tcx,
257                            parent_args,
258                            coroutine_kind_ty,
259                            tcx.coroutine_for_closure(expr_def_id),
260                            coroutine_upvars_ty,
261                        )
262                    }),
263                );
264                liberated_sig = tcx.mk_fn_sig(
265                    liberated_sig.inputs().iter().copied(),
266                    coroutine_output_ty,
267                    liberated_sig.fn_sig_kind,
268                );
269
270                (Ty::new_coroutine_closure(tcx, expr_def_id.to_def_id(), closure_args.args), None)
271            }
272        };
273
274        check_fn(
275            &mut FnCtxt::new(self, self.param_env, closure.def_id),
276            liberated_sig,
277            coroutine_types,
278            closure.fn_decl,
279            expr_def_id,
280            body,
281            // Closure "rust-call" ABI doesn't support unsized params
282            false,
283        );
284
285        closure_ty
286    }
287
288    /// Given the expected type, figures out what it can about this closure we
289    /// are about to type check:
290    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("deduce_closure_signature",
                                "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                ::tracing_core::__macro_support::Option::Some(290u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("expected_ty")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("expected_ty");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("closure_kind")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("closure_kind");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_ty)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_kind)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return:
                                (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        match *expected_ty.kind() {
                            ty::Alias(_, ty::AliasTy {
                                kind: ty::Opaque { def_id }, args, .. }) =>
                                self.deduce_closure_signature_from_predicates(expected_ty,
                                    closure_kind,
                                    self.tcx.explicit_item_self_bounds(def_id).iter_instantiated_copied(self.tcx,
                                            args).map(Unnormalized::skip_norm_wip)),
                            ty::Dynamic(object_type, ..) => {
                                let sig =
                                    object_type.projection_bounds().find_map(|pb|
                                            {
                                                let pb =
                                                    pb.with_self_ty(self.tcx,
                                                        self.tcx.types.trait_object_dummy_self);
                                                self.deduce_sig_from_projection(None, closure_kind, pb)
                                            });
                                let kind =
                                    object_type.principal_def_id().and_then(|did|
                                            self.tcx.fn_trait_kind_from_def_id(did));
                                (sig, kind)
                            }
                            ty::Infer(ty::TyVar(vid)) =>
                                self.deduce_closure_signature_from_predicates(Ty::new_var(self.tcx,
                                        self.root_var(vid)), closure_kind,
                                    self.obligations_for_self_ty(vid,
                                                UseSubtyping::No).into_iter().filter_map(|obl|
                                            Some((obl.predicate.as_clause()?, obl.cause.span)))),
                            ty::FnPtr(sig_tys, hdr) =>
                                match closure_kind {
                                    hir::ClosureKind::Closure => {
                                        let expected_sig =
                                            ExpectedSig { cause_span: None, sig: sig_tys.with(hdr) };
                                        (Some(expected_sig), Some(ty::ClosureKind::Fn))
                                    }
                                    hir::ClosureKind::Coroutine(_) |
                                        hir::ClosureKind::CoroutineClosure(_) => {
                                        (None, None)
                                    }
                                },
                            _ => (None, None),
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:290",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(290u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(skip(self), level = "debug", ret)]
291    fn deduce_closure_signature(
292        &self,
293        expected_ty: Ty<'tcx>,
294        closure_kind: hir::ClosureKind,
295    ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
296        match *expected_ty.kind() {
297            ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => self
298                .deduce_closure_signature_from_predicates(
299                    expected_ty,
300                    closure_kind,
301                    self.tcx
302                        .explicit_item_self_bounds(def_id)
303                        .iter_instantiated_copied(self.tcx, args)
304                        .map(Unnormalized::skip_norm_wip),
305                ),
306            ty::Dynamic(object_type, ..) => {
307                let sig = object_type.projection_bounds().find_map(|pb| {
308                    let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self);
309                    self.deduce_sig_from_projection(None, closure_kind, pb)
310                });
311                let kind = object_type
312                    .principal_def_id()
313                    .and_then(|did| self.tcx.fn_trait_kind_from_def_id(did));
314                (sig, kind)
315            }
316            ty::Infer(ty::TyVar(vid)) => self.deduce_closure_signature_from_predicates(
317                Ty::new_var(self.tcx, self.root_var(vid)),
318                closure_kind,
319                self.obligations_for_self_ty(vid, UseSubtyping::No)
320                    .into_iter()
321                    .filter_map(|obl| Some((obl.predicate.as_clause()?, obl.cause.span))),
322            ),
323            ty::FnPtr(sig_tys, hdr) => match closure_kind {
324                hir::ClosureKind::Closure => {
325                    let expected_sig = ExpectedSig { cause_span: None, sig: sig_tys.with(hdr) };
326                    (Some(expected_sig), Some(ty::ClosureKind::Fn))
327                }
328                hir::ClosureKind::Coroutine(_) | hir::ClosureKind::CoroutineClosure(_) => {
329                    (None, None)
330                }
331            },
332            _ => (None, None),
333        }
334    }
335
336    fn deduce_closure_signature_from_predicates(
337        &self,
338        expected_ty: Ty<'tcx>,
339        closure_kind: hir::ClosureKind,
340        clauses: impl DoubleEndedIterator<Item = (ty::Clause<'tcx>, Span)>,
341    ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
342        let mut expected_sig = None;
343        let mut expected_kind = None;
344
345        for (clause, span) in traits::elaborate(
346            self.tcx,
347            // Reverse the obligations here, since `elaborate_*` uses a stack,
348            // and we want to keep inference generally in the same order of
349            // the registered obligations.
350            clauses.rev(),
351        )
352        // We only care about self bounds
353        .filter_only_self()
354        {
355            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:355",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(355u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("clause")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("clause");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&clause)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?clause);
356            let bound_clause = clause.kind();
357
358            // Given a Projection clause, we can potentially infer the complete signature.
359            if expected_sig.is_none()
360                && let ty::ClauseKind::Projection(proj_clause) = bound_clause.skip_binder()
361            {
362                let inferred_sig = self.normalize(
363                    span,
364                    Unnormalized::new_wip(self.deduce_sig_from_projection(
365                        Some(span),
366                        closure_kind,
367                        bound_clause.rebind(proj_clause),
368                    )),
369                );
370
371                // Make sure that we didn't infer a signature that mentions itself.
372                // This can happen when we elaborate certain supertrait bounds that
373                // mention projections containing the `Self` type. See #105401.
374                struct MentionsTy<'tcx> {
375                    expected_ty: Ty<'tcx>,
376                }
377                impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for MentionsTy<'tcx> {
378                    type Result = ControlFlow<()>;
379
380                    fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
381                        if t == self.expected_ty {
382                            ControlFlow::Break(())
383                        } else {
384                            t.super_visit_with(self)
385                        }
386                    }
387                }
388
389                // Don't infer a closure signature from a goal that names the closure type as this will
390                // (almost always) lead to occurs check errors later in type checking.
391                if self.next_trait_solver()
392                    && let Some(inferred_sig) = inferred_sig
393                {
394                    // In the new solver it is difficult to explicitly normalize the inferred signature as we
395                    // would have to manually handle universes and rewriting bound vars and placeholders back
396                    // and forth.
397                    //
398                    // Instead we take advantage of the fact that we relating an inference variable with an alias
399                    // will only instantiate the variable if the alias is rigid(*not quite). Concretely we:
400                    // - Create some new variable `?sig`
401                    // - Equate `?sig` with the unnormalized signature, e.g. `fn(<Foo<?x> as Trait>::Assoc)`
402                    // - Depending on whether `<Foo<?x> as Trait>::Assoc` is rigid, ambiguous or normalizeable,
403                    //   we will either wind up with `?sig=<Foo<?x> as Trait>::Assoc/?y/ConcreteTy` respectively.
404                    //
405                    // *: In cases where there are ambiguous aliases in the signature that make use of bound vars
406                    //    they will wind up present in `?sig` even though they are non-rigid.
407                    //
408                    //    This is a bit weird and means we may wind up discarding the goal due to it naming `expected_ty`
409                    //    even though the normalized form may not name `expected_ty`. However, this matches the existing
410                    //    behaviour of the old solver and would be technically a breaking change to fix.
411                    let generalized_fnptr_sig = self.next_ty_var(span);
412                    let inferred_fnptr_sig = Ty::new_fn_ptr(self.tcx, inferred_sig.sig);
413                    self.demand_eqtype(span, inferred_fnptr_sig, generalized_fnptr_sig);
414
415                    let resolved_sig = self.deeply_resolve_ignoring_regions(generalized_fnptr_sig);
416
417                    if resolved_sig.visit_with(&mut MentionsTy { expected_ty }).is_continue() {
418                        expected_sig = Some(ExpectedSig {
419                            cause_span: inferred_sig.cause_span,
420                            sig: resolved_sig.fn_sig(self.tcx),
421                        });
422                    }
423                } else {
424                    if inferred_sig.visit_with(&mut MentionsTy { expected_ty }).is_continue() {
425                        expected_sig = inferred_sig;
426                    }
427                }
428            }
429
430            // Even if we can't infer the full signature, we may be able to
431            // infer the kind. This can occur when we elaborate a predicate
432            // like `F : Fn<A>`. Note that due to subtyping we could encounter
433            // many viable options, so pick the most restrictive.
434            let trait_def_id = match bound_clause.skip_binder() {
435                ty::ClauseKind::Projection(data) => {
436                    Some(data.projection_term.trait_def_id(self.tcx))
437                }
438                ty::ClauseKind::Trait(data) => Some(data.def_id()),
439                _ => None,
440            };
441
442            if let Some(trait_def_id) = trait_def_id {
443                let found_kind = match closure_kind {
444                    hir::ClosureKind::Closure
445                    // FIXME(iter_macro): Someday we'll probably want iterator closures instead of
446                    // just using Fn* for iterators.
447                    | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => {
448                        self.tcx.fn_trait_kind_from_def_id(trait_def_id)
449                    }
450                    hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => self
451                        .tcx
452                        .async_fn_trait_kind_from_def_id(trait_def_id)
453                        .or_else(|| self.tcx.fn_trait_kind_from_def_id(trait_def_id)),
454                    _ => None,
455                };
456
457                if let Some(found_kind) = found_kind {
458                    // always use the closure kind that is more permissive.
459                    match (expected_kind, found_kind) {
460                        (None, _) => expected_kind = Some(found_kind),
461                        (Some(ClosureKind::FnMut), ClosureKind::Fn) => {
462                            expected_kind = Some(ClosureKind::Fn)
463                        }
464                        (Some(ClosureKind::FnOnce), ClosureKind::Fn | ClosureKind::FnMut) => {
465                            expected_kind = Some(found_kind)
466                        }
467                        _ => {}
468                    }
469                }
470            }
471        }
472
473        (expected_sig, expected_kind)
474    }
475
476    /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
477    /// everything we need to know about a closure or coroutine.
478    ///
479    /// The `cause_span` should be the span that caused us to
480    /// have this expected signature, or `None` if we can't readily
481    /// know that.
482    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("deduce_sig_from_projection",
                                "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                ::tracing_core::__macro_support::Option::Some(482u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("closure_kind")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("closure_kind");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("projection")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("projection");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_kind)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&projection)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: Option<ExpectedSig<'tcx>> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let def_id = projection.item_def_id();
                        match closure_kind {
                            hir::ClosureKind::Closure if
                                self.tcx.is_lang_item(def_id, LangItem::FnOnceOutput) => {
                                self.extract_sig_from_projection(cause_span, projection)
                            }
                            hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async)
                                if
                                self.tcx.is_lang_item(def_id, LangItem::AsyncFnOnceOutput)
                                => {
                                self.extract_sig_from_projection(cause_span, projection)
                            }
                            hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async)
                                if self.tcx.is_lang_item(def_id, LangItem::FnOnceOutput) =>
                                {
                                self.extract_sig_from_projection_and_future_bound(cause_span,
                                    projection)
                            }
                            _ => None,
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:482",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(482u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(self, cause_span), ret)]
483    fn deduce_sig_from_projection(
484        &self,
485        cause_span: Option<Span>,
486        closure_kind: hir::ClosureKind,
487        projection: ty::PolyProjectionClause<'tcx>,
488    ) -> Option<ExpectedSig<'tcx>> {
489        let def_id = projection.item_def_id();
490
491        // For now, we only do signature deduction based off of the `Fn` and `AsyncFn` traits,
492        // for closures and async closures, respectively.
493        match closure_kind {
494            hir::ClosureKind::Closure if self.tcx.is_lang_item(def_id, LangItem::FnOnceOutput) => {
495                self.extract_sig_from_projection(cause_span, projection)
496            }
497            hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async)
498                if self.tcx.is_lang_item(def_id, LangItem::AsyncFnOnceOutput) =>
499            {
500                self.extract_sig_from_projection(cause_span, projection)
501            }
502            // It's possible we've passed the closure to a (somewhat out-of-fashion)
503            // `F: FnOnce() -> Fut, Fut: Future<Output = T>` style bound. Let's still
504            // guide inference here, since it's beneficial for the user.
505            hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async)
506                if self.tcx.is_lang_item(def_id, LangItem::FnOnceOutput) =>
507            {
508                self.extract_sig_from_projection_and_future_bound(cause_span, projection)
509            }
510            _ => None,
511        }
512    }
513
514    /// Given an `FnOnce::Output` or `AsyncFn::Output` projection, extract the args
515    /// and return type to infer a [`ty::PolyFnSig`] for the closure.
516    fn extract_sig_from_projection(
517        &self,
518        cause_span: Option<Span>,
519        projection: ty::PolyProjectionClause<'tcx>,
520    ) -> Option<ExpectedSig<'tcx>> {
521        let projection = self.deeply_resolve_ignoring_regions(projection);
522
523        let arg_param_ty = projection.skip_binder().projection_term.args.type_at(1);
524        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:524",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(524u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("arg_param_ty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("arg_param_ty");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg_param_ty)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?arg_param_ty);
525
526        let ty::Tuple(input_tys) = *arg_param_ty.kind() else {
527            return None;
528        };
529
530        // Since this is a return parameter type it is safe to unwrap.
531        let ret_param_ty = projection.skip_binder().term.expect_type();
532        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:532",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(532u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("ret_param_ty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("ret_param_ty");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ret_param_ty)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?ret_param_ty);
533
534        let sig = projection.rebind(self.tcx.mk_fn_sig_safe_rust_abi(input_tys, ret_param_ty));
535
536        Some(ExpectedSig { cause_span, sig })
537    }
538
539    /// When an async closure is passed to a function that has a "two-part" `Fn`
540    /// and `Future` trait bound, like:
541    ///
542    /// ```rust
543    /// use std::future::Future;
544    ///
545    /// fn not_exactly_an_async_closure<F, Fut>(_f: F)
546    /// where
547    ///     F: FnOnce(String, u32) -> Fut,
548    ///     Fut: Future<Output = i32>,
549    /// {}
550    /// ```
551    ///
552    /// The we want to be able to extract the signature to guide inference in the async
553    /// closure. We will have two projection predicates registered in this case. First,
554    /// we identify the `FnOnce<Args, Output = ?Fut>` bound, and if the output type is
555    /// an inference variable `?Fut`, we check if that is bounded by a `Future<Output = Ty>`
556    /// projection.
557    ///
558    /// This function is actually best-effort with the return type; if we don't find a
559    /// `Future` projection, we still will return arguments that we extracted from the `FnOnce`
560    /// projection, and the output will be an unconstrained type variable instead.
561    fn extract_sig_from_projection_and_future_bound(
562        &self,
563        cause_span: Option<Span>,
564        projection: ty::PolyProjectionClause<'tcx>,
565    ) -> Option<ExpectedSig<'tcx>> {
566        let projection = self.deeply_resolve_ignoring_regions(projection);
567
568        let arg_param_ty = projection.skip_binder().projection_term.args.type_at(1);
569        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:569",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(569u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("arg_param_ty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("arg_param_ty");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg_param_ty)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?arg_param_ty);
570
571        let ty::Tuple(input_tys) = *arg_param_ty.kind() else {
572            return None;
573        };
574
575        // If the return type is a type variable, look for bounds on it.
576        // We could theoretically support other kinds of return types here,
577        // but none of them would be useful, since async closures return
578        // concrete anonymous future types, and their futures are not coerced
579        // into any other type within the body of the async closure.
580        let ty::Infer(ty::TyVar(return_vid)) = *projection.skip_binder().term.expect_type().kind()
581        else {
582            return None;
583        };
584
585        // FIXME: We may want to elaborate here, though I assume this will be exceedingly rare.
586        let mut return_ty = None;
587        for bound in self.obligations_for_self_ty(return_vid, UseSubtyping::No) {
588            if let Some(ret_projection) = bound.predicate.as_projection_clause()
589                && let Some(ret_projection) = ret_projection.no_bound_vars()
590                && self.tcx.is_lang_item(ret_projection.def_id(), LangItem::FutureOutput)
591            {
592                return_ty = Some(ret_projection.term.expect_type());
593                break;
594            }
595        }
596
597        // SUBTLE: If we didn't find a `Future<Output = ...>` bound for the return
598        // vid, we still want to attempt to provide inference guidance for the async
599        // closure's arguments. Instantiate a new vid to plug into the output type.
600        //
601        // You may be wondering, what if it's higher-ranked? Well, given that we
602        // found a type variable for the `FnOnce::Output` projection above, we know
603        // that the output can't mention any of the vars.
604        //
605        // Also note that we use a fresh var here for the signature since the signature
606        // records the output of the *future*, and `return_vid` above is the type
607        // variable of the future, not its output.
608        //
609        // FIXME: We probably should store this signature inference output in a way
610        // that does not misuse a `FnSig` type, but that can be done separately.
611        let return_ty =
612            return_ty.unwrap_or_else(|| self.next_ty_var(cause_span.unwrap_or(DUMMY_SP)));
613
614        let sig = projection.rebind(self.tcx.mk_fn_sig_safe_rust_abi(input_tys, return_ty));
615
616        Some(ExpectedSig { cause_span, sig })
617    }
618
619    fn sig_of_closure(
620        &self,
621        expr_def_id: LocalDefId,
622        decl: &hir::FnDecl<'tcx>,
623        closure_kind: hir::ClosureKind,
624        expected_sig: Option<ExpectedSig<'tcx>>,
625    ) -> ClosureSignatures<'tcx> {
626        if let Some(e) = expected_sig {
627            self.sig_of_closure_with_expectation(expr_def_id, decl, closure_kind, e)
628        } else {
629            self.sig_of_closure_no_expectation(expr_def_id, decl, closure_kind)
630        }
631    }
632
633    /// If there is no expected signature, then we will convert the
634    /// types that the user gave into a signature.
635    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("sig_of_closure_no_expectation",
                                    "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                    ::tracing_core::__macro_support::Option::Some(635u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_kind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_kind");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_kind)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ClosureSignatures<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let bound_sig =
                self.supplied_sig_of_closure(expr_def_id, decl, closure_kind);
            self.closure_sigs(expr_def_id, bound_sig)
        }
    }
}#[instrument(skip(self, expr_def_id, decl), level = "debug")]
636    fn sig_of_closure_no_expectation(
637        &self,
638        expr_def_id: LocalDefId,
639        decl: &hir::FnDecl<'tcx>,
640        closure_kind: hir::ClosureKind,
641    ) -> ClosureSignatures<'tcx> {
642        let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl, closure_kind);
643
644        self.closure_sigs(expr_def_id, bound_sig)
645    }
646
647    /// Invoked to compute the signature of a closure expression. This
648    /// combines any user-provided type annotations (e.g., `|x: u32|
649    /// -> u32 { .. }`) with the expected signature.
650    ///
651    /// The approach is as follows:
652    ///
653    /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
654    /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
655    ///   - If we have no expectation `E`, then the signature of the closure is `S`.
656    ///   - Otherwise, the signature of the closure is E. Moreover:
657    ///     - Skolemize the late-bound regions in `E`, yielding `E'`.
658    ///     - Instantiate all the late-bound regions bound in the closure within `S`
659    ///       with fresh (existential) variables, yielding `S'`
660    ///     - Require that `E' = S'`
661    ///       - We could use some kind of subtyping relationship here,
662    ///         I imagine, but equality is easier and works fine for
663    ///         our purposes.
664    ///
665    /// The key intuition here is that the user's types must be valid
666    /// from "the inside" of the closure, but the expectation
667    /// ultimately drives the overall signature.
668    ///
669    /// # Examples
670    ///
671    /// ```ignore (illustrative)
672    /// fn with_closure<F>(_: F)
673    ///   where F: Fn(&u32) -> &u32 { .. }
674    ///
675    /// with_closure(|x: &u32| { ... })
676    /// ```
677    ///
678    /// Here:
679    /// - E would be `fn(&u32) -> &u32`.
680    /// - S would be `fn(&u32) -> ?T`
681    /// - E' is `&'!0 u32 -> &'!0 u32`
682    /// - S' is `&'?0 u32 -> ?T`
683    ///
684    /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
685    ///
686    /// # Arguments
687    ///
688    /// - `expr_def_id`: the `LocalDefId` of the closure expression
689    /// - `decl`: the HIR declaration of the closure
690    /// - `body`: the body of the closure
691    /// - `expected_sig`: the expected signature (if any). Note that
692    ///   this is missing a binder: that is, there may be late-bound
693    ///   regions with depth 1, which are bound then by the closure.
694    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("sig_of_closure_with_expectation",
                                    "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                    ::tracing_core::__macro_support::Option::Some(694u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_kind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_kind");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expected_sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expected_sig");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_kind)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_sig)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ClosureSignatures<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if expected_sig.sig.c_variadic() != decl.c_variadic() {
                return self.sig_of_closure_no_expectation(expr_def_id, decl,
                        closure_kind);
            } else if expected_sig.sig.skip_binder().inputs_and_output.len()
                    != decl.inputs.len() + 1 {
                return self.sig_of_closure_with_mismatched_number_of_arguments(expr_def_id,
                        decl, expected_sig);
            }
            if !!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST)
                {
                ::core::panicking::panic("assertion failed: !expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST)")
            };
            let bound_sig =
                expected_sig.sig.map_bound(|sig|
                        {
                            let fn_sig_kind =
                                FnSigKind::default().set_abi(ExternAbi::RustCall).set_safety(hir::Safety::Safe).set_c_variadic(sig.c_variadic());
                            self.tcx.mk_fn_sig(sig.inputs().iter().cloned(),
                                sig.output(), fn_sig_kind)
                        });
            let bound_sig = self.tcx.anonymize_bound_vars(bound_sig);
            let closure_sigs = self.closure_sigs(expr_def_id, bound_sig);
            match self.merge_supplied_sig_with_expectation(expr_def_id, decl,
                    closure_kind, closure_sigs) {
                Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
                Err(_) =>
                    self.sig_of_closure_no_expectation(expr_def_id, decl,
                        closure_kind),
            }
        }
    }
}#[instrument(skip(self, expr_def_id, decl), level = "debug")]
695    fn sig_of_closure_with_expectation(
696        &self,
697        expr_def_id: LocalDefId,
698        decl: &hir::FnDecl<'tcx>,
699        closure_kind: hir::ClosureKind,
700        expected_sig: ExpectedSig<'tcx>,
701    ) -> ClosureSignatures<'tcx> {
702        // Watch out for some surprises and just ignore the
703        // expectation if things don't see to match up with what we
704        // expect.
705        if expected_sig.sig.c_variadic() != decl.c_variadic() {
706            return self.sig_of_closure_no_expectation(expr_def_id, decl, closure_kind);
707        } else if expected_sig.sig.skip_binder().inputs_and_output.len() != decl.inputs.len() + 1 {
708            return self.sig_of_closure_with_mismatched_number_of_arguments(
709                expr_def_id,
710                decl,
711                expected_sig,
712            );
713        }
714
715        // Create a `PolyFnSig`. Note the oddity that late bound
716        // regions appearing free in `expected_sig` are now bound up
717        // in this binder we are creating.
718        assert!(!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST));
719        let bound_sig = expected_sig.sig.map_bound(|sig| {
720            // Ignore splatting, it is unsupported on closures.
721            let fn_sig_kind = FnSigKind::default()
722                .set_abi(ExternAbi::RustCall)
723                .set_safety(hir::Safety::Safe)
724                .set_c_variadic(sig.c_variadic());
725            self.tcx.mk_fn_sig(sig.inputs().iter().cloned(), sig.output(), fn_sig_kind)
726        });
727
728        // `deduce_expectations_from_expected_type` introduces
729        // late-bound lifetimes defined elsewhere, which we now
730        // anonymize away, so as not to confuse the user.
731        let bound_sig = self.tcx.anonymize_bound_vars(bound_sig);
732
733        let closure_sigs = self.closure_sigs(expr_def_id, bound_sig);
734
735        // Up till this point, we have ignored the annotations that the user
736        // gave. This function will check that they unify successfully.
737        // Along the way, it also writes out entries for types that the user
738        // wrote into our typeck results, which are then later used by the privacy
739        // check.
740        match self.merge_supplied_sig_with_expectation(
741            expr_def_id,
742            decl,
743            closure_kind,
744            closure_sigs,
745        ) {
746            Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
747            Err(_) => self.sig_of_closure_no_expectation(expr_def_id, decl, closure_kind),
748        }
749    }
750
751    fn sig_of_closure_with_mismatched_number_of_arguments(
752        &self,
753        expr_def_id: LocalDefId,
754        decl: &hir::FnDecl<'tcx>,
755        expected_sig: ExpectedSig<'tcx>,
756    ) -> ClosureSignatures<'tcx> {
757        let expr_map_node = self.tcx.hir_node_by_def_id(expr_def_id);
758        let expected_args: Vec<_> = expected_sig
759            .sig
760            .skip_binder()
761            .inputs()
762            .iter()
763            .map(|ty| ArgKind::from_expected_ty(*ty, None))
764            .collect();
765        let (closure_span, closure_arg_span, found_args) =
766            match self.err_ctxt().get_fn_like_arguments(expr_map_node) {
767                Some((sp, arg_sp, args)) => (Some(sp), arg_sp, args),
768                None => (None, None, Vec::new()),
769            };
770        let expected_span =
771            expected_sig.cause_span.unwrap_or_else(|| self.tcx.def_span(expr_def_id));
772        let guar = self
773            .err_ctxt()
774            .report_arg_count_mismatch(
775                expected_span,
776                closure_span,
777                expected_args,
778                found_args,
779                true,
780                closure_arg_span,
781            )
782            .emit();
783
784        let error_sig = self.error_sig_of_closure(decl, guar);
785
786        self.closure_sigs(expr_def_id, error_sig)
787    }
788
789    /// Enforce the user's types against the expectation. See
790    /// `sig_of_closure_with_expectation` for details on the overall
791    /// strategy.
792    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("merge_supplied_sig_with_expectation",
                                    "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                    ::tracing_core::__macro_support::Option::Some(792u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_kind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_kind");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_kind)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    InferResult<'tcx, ClosureSignatures<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let supplied_sig =
                self.supplied_sig_of_closure(expr_def_id, decl, closure_kind);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:806",
                                    "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                    ::tracing_core::__macro_support::Option::Some(806u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("supplied_sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("supplied_sig");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&supplied_sig)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            self.commit_if_ok(|_|
                    {
                        let mut all_obligations = PredicateObligations::new();
                        let supplied_sig =
                            self.instantiate_binder_with_fresh_vars(self.tcx.def_span(expr_def_id),
                                BoundRegionConversionTime::FnCall, supplied_sig);
                        for ((hir_ty, &supplied_ty), expected_ty) in
                            iter::zip(iter::zip(decl.inputs, supplied_sig.inputs()),
                                expected_sigs.liberated_sig.inputs()) {
                            let cause = self.misc(hir_ty.span);
                            let InferOk { value: (), obligations } =
                                self.at(&cause,
                                            self.param_env).eq(DefineOpaqueTypes::Yes, *expected_ty,
                                        supplied_ty)?;
                            all_obligations.extend(obligations);
                        }
                        let supplied_output_ty = supplied_sig.output();
                        let cause = &self.misc(decl.output.span());
                        let InferOk { value: (), obligations } =
                            self.at(cause,
                                        self.param_env).eq(DefineOpaqueTypes::Yes,
                                    expected_sigs.liberated_sig.output(), supplied_output_ty)?;
                        all_obligations.extend(obligations);
                        let inputs =
                            supplied_sig.inputs().into_iter().map(|&ty|
                                    self.deeply_resolve_ignoring_regions(ty));
                        let fn_sig_kind =
                            FnSigKind::default().set_abi(ExternAbi::RustCall).set_safety(hir::Safety::Safe).set_c_variadic(expected_sigs.liberated_sig.c_variadic());
                        expected_sigs.liberated_sig =
                            self.tcx.mk_fn_sig(inputs, supplied_output_ty, fn_sig_kind);
                        Ok(InferOk {
                                value: expected_sigs,
                                obligations: all_obligations,
                            })
                    })
        }
    }
}#[instrument(level = "debug", skip(self, expr_def_id, decl, expected_sigs))]
793    fn merge_supplied_sig_with_expectation(
794        &self,
795        expr_def_id: LocalDefId,
796        decl: &hir::FnDecl<'tcx>,
797        closure_kind: hir::ClosureKind,
798        mut expected_sigs: ClosureSignatures<'tcx>,
799    ) -> InferResult<'tcx, ClosureSignatures<'tcx>> {
800        // Get the signature S that the user gave.
801        //
802        // (See comment on `sig_of_closure_with_expectation` for the
803        // meaning of these letters.)
804        let supplied_sig = self.supplied_sig_of_closure(expr_def_id, decl, closure_kind);
805
806        debug!(?supplied_sig);
807
808        // FIXME(#45727): As discussed in [this comment][c1], naively
809        // forcing equality here actually results in suboptimal error
810        // messages in some cases. For now, if there would have been
811        // an obvious error, we fallback to declaring the type of the
812        // closure to be the one the user gave, which allows other
813        // error message code to trigger.
814        //
815        // However, I think [there is potential to do even better
816        // here][c2], since in *this* code we have the precise span of
817        // the type parameter in question in hand when we report the
818        // error.
819        //
820        // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
821        // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
822        self.commit_if_ok(|_| {
823            let mut all_obligations = PredicateObligations::new();
824            let supplied_sig = self.instantiate_binder_with_fresh_vars(
825                self.tcx.def_span(expr_def_id),
826                BoundRegionConversionTime::FnCall,
827                supplied_sig,
828            );
829
830            // The liberated version of this signature should be a subtype
831            // of the liberated form of the expectation.
832            for ((hir_ty, &supplied_ty), expected_ty) in iter::zip(
833                iter::zip(decl.inputs, supplied_sig.inputs()),
834                expected_sigs.liberated_sig.inputs(), // `liberated_sig` is E'.
835            ) {
836                // Check that E' = S'.
837                let cause = self.misc(hir_ty.span);
838                let InferOk { value: (), obligations } = self.at(&cause, self.param_env).eq(
839                    DefineOpaqueTypes::Yes,
840                    *expected_ty,
841                    supplied_ty,
842                )?;
843                all_obligations.extend(obligations);
844            }
845
846            let supplied_output_ty = supplied_sig.output();
847            let cause = &self.misc(decl.output.span());
848            let InferOk { value: (), obligations } = self.at(cause, self.param_env).eq(
849                DefineOpaqueTypes::Yes,
850                expected_sigs.liberated_sig.output(),
851                supplied_output_ty,
852            )?;
853            all_obligations.extend(obligations);
854
855            let inputs = supplied_sig
856                .inputs()
857                .into_iter()
858                .map(|&ty| self.deeply_resolve_ignoring_regions(ty));
859
860            let fn_sig_kind = FnSigKind::default()
861                .set_abi(ExternAbi::RustCall)
862                .set_safety(hir::Safety::Safe)
863                .set_c_variadic(expected_sigs.liberated_sig.c_variadic());
864            expected_sigs.liberated_sig =
865                self.tcx.mk_fn_sig(inputs, supplied_output_ty, fn_sig_kind);
866
867            Ok(InferOk { value: expected_sigs, obligations: all_obligations })
868        })
869    }
870
871    /// If there is no expected signature, then we will convert the
872    /// types that the user gave into a signature.
873    ///
874    /// Also, record this closure signature for later.
875    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("supplied_sig_of_closure",
                                "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                ::tracing_core::__macro_support::Option::Some(875u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("expr_def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("expr_def_id");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("closure_kind")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("closure_kind");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr_def_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_kind)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: ty::PolyFnSig<'tcx> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let lowerer = self.lowerer();
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:884",
                                                "rustc_hir_typeck::closure", ::tracing::Level::TRACE,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                                ::tracing_core::__macro_support::Option::Some(884u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::TRACE <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::TRACE <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("decl = {0:#?}",
                                                                            decl) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:885",
                                                "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                                ::tracing_core::__macro_support::Option::Some(885u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("closure_kind")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("closure_kind");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_kind)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let hir_id = self.tcx.local_def_id_to_hir_id(expr_def_id);
                        let bound_vars = self.tcx.late_bound_vars(hir_id);
                        let supplied_arguments =
                            decl.inputs.iter().map(|a| lowerer.lower_ty(a));
                        let supplied_return =
                            match decl.output {
                                hir::FnRetTy::Return(ref output) =>
                                    lowerer.lower_ty(output),
                                hir::FnRetTy::DefaultReturn(_) =>
                                    match closure_kind {
                                        hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                                            hir::CoroutineSource::Fn)) => {
                                            {
                                                use ::tracing::__macro_support::Callsite as _;
                                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                                    {
                                                        static META: ::tracing::Metadata<'static> =
                                                            {
                                                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:902",
                                                                    "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                                                    ::tracing_core::__macro_support::Option::Some(902u32),
                                                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                                                    ::tracing_core::field::FieldSet::new(&["message"],
                                                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                                    ::tracing::metadata::Kind::EVENT)
                                                            };
                                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                                    };
                                                let enabled =
                                                    ::tracing::Level::DEBUG <=
                                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                            ::tracing::Level::DEBUG <=
                                                                ::tracing::level_filters::LevelFilter::current() &&
                                                        {
                                                            let interest = __CALLSITE.interest();
                                                            !interest.is_never() &&
                                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                                    interest)
                                                        };
                                                if enabled {
                                                    (|value_set: ::tracing::field::ValueSet|
                                                                {
                                                                    let meta = __CALLSITE.metadata();
                                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                                    ;
                                                                })({
                                                            #[allow(unused_imports)]
                                                            use ::tracing::field::{debug, display, Value};
                                                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("closure is async fn body")
                                                                                        as &dyn ::tracing::field::Value))])
                                                        });
                                                } else { ; }
                                            };
                                            self.deduce_future_output_from_obligations(expr_def_id).unwrap_or_else(||
                                                    { lowerer.ty_infer(None, decl.output.span()) })
                                        }
                                        hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen
                                            | hir::CoroutineDesugaring::AsyncGen, _)) =>
                                            self.tcx.types.unit,
                                        hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                                            _)) |
                                            hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_))
                                            | hir::ClosureKind::Closure |
                                            hir::ClosureKind::CoroutineClosure(_) => {
                                            lowerer.ty_infer(None, decl.output.span())
                                        }
                                    },
                            };
                        let fn_sig_kind =
                            FnSigKind::default().set_abi(ExternAbi::RustCall).set_safety(hir::Safety::Safe).set_c_variadic(decl.c_variadic());
                        let result =
                            ty::Binder::bind_with_vars(self.tcx.mk_fn_sig(supplied_arguments,
                                    supplied_return, fn_sig_kind), bound_vars);
                        let c_result = self.infcx.canonicalize_response(result);
                        self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id,
                            c_result);
                        self.normalize(self.tcx.def_span(expr_def_id),
                            Unnormalized::new_wip(result))
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:875",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(875u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(skip(self, decl), level = "debug", ret)]
876    fn supplied_sig_of_closure(
877        &self,
878        expr_def_id: LocalDefId,
879        decl: &hir::FnDecl<'tcx>,
880        closure_kind: hir::ClosureKind,
881    ) -> ty::PolyFnSig<'tcx> {
882        let lowerer = self.lowerer();
883
884        trace!("decl = {:#?}", decl);
885        debug!(?closure_kind);
886
887        let hir_id = self.tcx.local_def_id_to_hir_id(expr_def_id);
888        let bound_vars = self.tcx.late_bound_vars(hir_id);
889
890        // First, convert the types that the user supplied (if any).
891        let supplied_arguments = decl.inputs.iter().map(|a| lowerer.lower_ty(a));
892        let supplied_return = match decl.output {
893            hir::FnRetTy::Return(ref output) => lowerer.lower_ty(output),
894            hir::FnRetTy::DefaultReturn(_) => match closure_kind {
895                // In the case of the async block that we create for a function body,
896                // we expect the return type of the block to match that of the enclosing
897                // function.
898                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
899                    hir::CoroutineDesugaring::Async,
900                    hir::CoroutineSource::Fn,
901                )) => {
902                    debug!("closure is async fn body");
903                    self.deduce_future_output_from_obligations(expr_def_id).unwrap_or_else(|| {
904                        // AFAIK, deducing the future output
905                        // always succeeds *except* in error cases
906                        // like #65159. I'd like to return Error
907                        // here, but I can't because I can't
908                        // easily (and locally) prove that we
909                        // *have* reported an
910                        // error. --nikomatsakis
911                        lowerer.ty_infer(None, decl.output.span())
912                    })
913                }
914                // All `gen {}` and `async gen {}` must return unit.
915                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
916                    hir::CoroutineDesugaring::Gen | hir::CoroutineDesugaring::AsyncGen,
917                    _,
918                )) => self.tcx.types.unit,
919
920                // For async blocks, we just fall back to `_` here.
921                // For closures/coroutines, we know nothing about the return
922                // type unless it was supplied.
923                hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
924                    hir::CoroutineDesugaring::Async,
925                    _,
926                ))
927                | hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_))
928                | hir::ClosureKind::Closure
929                | hir::ClosureKind::CoroutineClosure(_) => {
930                    lowerer.ty_infer(None, decl.output.span())
931                }
932            },
933        };
934
935        let fn_sig_kind = FnSigKind::default()
936            .set_abi(ExternAbi::RustCall)
937            .set_safety(hir::Safety::Safe)
938            .set_c_variadic(decl.c_variadic());
939        let result = ty::Binder::bind_with_vars(
940            self.tcx.mk_fn_sig(supplied_arguments, supplied_return, fn_sig_kind),
941            bound_vars,
942        );
943
944        let c_result = self.infcx.canonicalize_response(result);
945        self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
946
947        // Normalize only after registering in `user_provided_sigs`.
948        self.normalize(self.tcx.def_span(expr_def_id), Unnormalized::new_wip(result))
949    }
950
951    /// Invoked when we are translating the coroutine that results
952    /// from desugaring an `async fn`. Returns the "sugared" return
953    /// type of the `async fn` -- that is, the return type that the
954    /// user specified. The "desugared" return type is an `impl
955    /// Future<Output = T>`, so we do this by searching through the
956    /// obligations to extract the `T`.
957    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("deduce_future_output_from_obligations",
                                "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                ::tracing_core::__macro_support::Option::Some(957u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("body_def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("body_def_id");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body_def_id)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: Option<Ty<'tcx>> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let ret_coercion =
                            self.ret_coercion.as_ref().unwrap_or_else(||
                                    {
                                        ::rustc_middle::util::bug::span_bug_fmt(self.tcx.def_span(body_def_id),
                                            format_args!("async fn coroutine outside of a fn"))
                                    });
                        let closure_span = self.tcx.def_span(body_def_id);
                        let ret_ty = ret_coercion.borrow().expected_ty();
                        let ret_ty =
                            self.deeply_resolve_ignoring_regions_with_obligations(ret_ty);
                        let get_future_output =
                            |clause: ty::Clause<'tcx>, span|
                                {
                                    let bound_clause = clause.kind();
                                    if let ty::ClauseKind::Projection(proj_clause) =
                                            bound_clause.skip_binder() {
                                        self.deduce_future_output_from_projection(span,
                                            bound_clause.rebind(proj_clause))
                                    } else { None }
                                };
                        let output_ty =
                            match *ret_ty.kind() {
                                ty::Infer(ty::TyVar(ret_vid)) =>
                                    self.obligations_for_self_ty(ret_vid,
                                                    UseSubtyping::No).into_iter().find_map(|obligation|
                                                {
                                                    obligation.predicate.as_clause().and_then(|clause|
                                                            get_future_output(clause, obligation.cause.span))
                                                })?,
                                ty::Alias(_, ty::AliasTy { kind: ty::Projection { .. }, ..
                                    }) => {
                                    return Some(Ty::new_error_with_message(self.tcx,
                                                closure_span,
                                                "this projection should have been projected to an opaque type"));
                                }
                                ty::Alias(_, ty::AliasTy {
                                    kind: ty::Opaque { def_id }, args, .. }) =>
                                    self.tcx.explicit_item_self_bounds(def_id).iter_instantiated_copied(self.tcx,
                                                    args).map(Unnormalized::skip_norm_wip).find_map(|(c, s)|
                                                get_future_output(c, s))?,
                                ty::Error(_) => return Some(ret_ty),
                                _ => {
                                    ::rustc_middle::util::bug::span_bug_fmt(closure_span,
                                        format_args!("invalid async fn coroutine return type: {0:?}",
                                            ret_ty))
                                }
                            };
                        let output_ty =
                            self.normalize(closure_span,
                                Unnormalized::new_wip(output_ty));
                        let InferOk { value: output_ty, obligations } =
                            self.replace_opaque_types_with_inference_vars(output_ty,
                                body_def_id, closure_span, self.param_env);
                        self.register_predicates(obligations);
                        Some(output_ty)
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:957",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(957u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(skip(self), level = "debug", ret)]
958    fn deduce_future_output_from_obligations(&self, body_def_id: LocalDefId) -> Option<Ty<'tcx>> {
959        let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
960            span_bug!(self.tcx.def_span(body_def_id), "async fn coroutine outside of a fn")
961        });
962
963        let closure_span = self.tcx.def_span(body_def_id);
964        let ret_ty = ret_coercion.borrow().expected_ty();
965        let ret_ty = self.deeply_resolve_ignoring_regions_with_obligations(ret_ty);
966
967        let get_future_output = |clause: ty::Clause<'tcx>, span| {
968            // Search for a pending obligation like
969            //
970            // `<R as Future>::Output = T`
971            //
972            // where R is the return type we are expecting. This type `T`
973            // will be our output.
974            let bound_clause = clause.kind();
975            if let ty::ClauseKind::Projection(proj_clause) = bound_clause.skip_binder() {
976                self.deduce_future_output_from_projection(span, bound_clause.rebind(proj_clause))
977            } else {
978                None
979            }
980        };
981
982        let output_ty = match *ret_ty.kind() {
983            ty::Infer(ty::TyVar(ret_vid)) => self
984                .obligations_for_self_ty(ret_vid, UseSubtyping::No)
985                .into_iter()
986                .find_map(|obligation| {
987                    obligation
988                        .predicate
989                        .as_clause()
990                        .and_then(|clause| get_future_output(clause, obligation.cause.span))
991                })?,
992            ty::Alias(_, ty::AliasTy { kind: ty::Projection { .. }, .. }) => {
993                return Some(Ty::new_error_with_message(
994                    self.tcx,
995                    closure_span,
996                    "this projection should have been projected to an opaque type",
997                ));
998            }
999            ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => self
1000                .tcx
1001                .explicit_item_self_bounds(def_id)
1002                .iter_instantiated_copied(self.tcx, args)
1003                .map(Unnormalized::skip_norm_wip)
1004                .find_map(|(c, s)| get_future_output(c, s))?,
1005            ty::Error(_) => return Some(ret_ty),
1006            _ => {
1007                span_bug!(closure_span, "invalid async fn coroutine return type: {ret_ty:?}")
1008            }
1009        };
1010
1011        let output_ty = self.normalize(closure_span, Unnormalized::new_wip(output_ty));
1012
1013        // async fn that have opaque types in their return type need to redo the conversion to inference variables
1014        // as they fetch the still opaque version from the signature.
1015        let InferOk { value: output_ty, obligations } = self
1016            .replace_opaque_types_with_inference_vars(
1017                output_ty,
1018                body_def_id,
1019                closure_span,
1020                self.param_env,
1021            );
1022        self.register_predicates(obligations);
1023
1024        Some(output_ty)
1025    }
1026
1027    /// Given a projection like
1028    ///
1029    /// `<X as Future>::Output = T`
1030    ///
1031    /// where `X` is some type that has no late-bound regions, returns
1032    /// `Some(T)`. If the projection is for some other trait, returns
1033    /// `None`.
1034    fn deduce_future_output_from_projection(
1035        &self,
1036        cause_span: Span,
1037        predicate: ty::PolyProjectionClause<'tcx>,
1038    ) -> Option<Ty<'tcx>> {
1039        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:1039",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(1039u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("deduce_future_output_from_projection(predicate={0:?})",
                                                    predicate) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
1040
1041        // We do not expect any bound regions in our predicate, so
1042        // skip past the bound vars.
1043        let Some(predicate) = predicate.no_bound_vars() else {
1044            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:1044",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(1044u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("deduce_future_output_from_projection: has late-bound regions")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("deduce_future_output_from_projection: has late-bound regions");
1045            return None;
1046        };
1047
1048        // Check that this is a projection from the `Future` trait.
1049        let trait_def_id = predicate.projection_term.trait_def_id(self.tcx);
1050        if !self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
1051            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:1051",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(1051u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("deduce_future_output_from_projection: not a future")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("deduce_future_output_from_projection: not a future");
1052            return None;
1053        }
1054
1055        // The `Future` trait has only one associated item, `Output`,
1056        // so check that this is what we see.
1057        let output_assoc_item = self.tcx.associated_item_def_ids(trait_def_id)[0];
1058        if output_assoc_item != predicate.def_id() {
1059            ::rustc_middle::util::bug::span_bug_fmt(cause_span,
    format_args!("projecting associated item `{0:?}` from future, which is not Output `{1:?}`",
        predicate.projection_term.kind, output_assoc_item));span_bug!(
1060                cause_span,
1061                "projecting associated item `{:?}` from future, which is not Output `{:?}`",
1062                predicate.projection_term.kind,
1063                output_assoc_item,
1064            );
1065        }
1066
1067        // Extract the type from the projection. Note that there can
1068        // be no bound variables in this type because the "self type"
1069        // does not have any regions in it.
1070        let output_ty = self.deeply_resolve_ignoring_regions(predicate.term);
1071        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:1071",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(1071u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("deduce_future_output_from_projection: output_ty={0:?}",
                                                    output_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
1072        // This is a projection on a Fn trait so will always be a type.
1073        Some(output_ty.expect_type())
1074    }
1075
1076    /// Converts the types that the user supplied, in case that doing
1077    /// so should yield an error, but returns back a signature where
1078    /// all parameters are of type `ty::Error`.
1079    fn error_sig_of_closure(
1080        &self,
1081        decl: &hir::FnDecl<'tcx>,
1082        guar: ErrorGuaranteed,
1083    ) -> ty::PolyFnSig<'tcx> {
1084        let lowerer = self.lowerer();
1085        let err_ty = Ty::new_error(self.tcx, guar);
1086
1087        let supplied_arguments = decl.inputs.iter().map(|a| {
1088            // Convert the types that the user supplied (if any), but ignore them.
1089            lowerer.lower_ty(a);
1090            err_ty
1091        });
1092
1093        if let hir::FnRetTy::Return(ref output) = decl.output {
1094            lowerer.lower_ty(output);
1095        }
1096
1097        let fn_sig_kind = FnSigKind::default()
1098            .set_abi(ExternAbi::RustCall)
1099            .set_safety(hir::Safety::Safe)
1100            .set_c_variadic(decl.c_variadic());
1101        let result = ty::Binder::dummy(self.tcx.mk_fn_sig(supplied_arguments, err_ty, fn_sig_kind));
1102
1103        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:1103",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(1103u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("supplied_sig_of_closure: result={0:?}",
                                                    result) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("supplied_sig_of_closure: result={:?}", result);
1104
1105        result
1106    }
1107
1108    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("closure_sigs",
                                "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                                ::tracing_core::__macro_support::Option::Some(1108u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("expr_def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("expr_def_id");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("bound_sig")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("bound_sig");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr_def_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_sig)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: ClosureSignatures<'tcx> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let liberated_sig =
                            self.tcx().liberate_late_bound_regions(expr_def_id.to_def_id(),
                                bound_sig);
                        let liberated_sig =
                            self.normalize(self.tcx.def_span(expr_def_id),
                                Unnormalized::new_wip(liberated_sig));
                        ClosureSignatures { bound_sig, liberated_sig }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs:1108",
                        "rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/closure.rs"),
                        ::tracing_core::__macro_support::Option::Some(1108u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
1109    fn closure_sigs(
1110        &self,
1111        expr_def_id: LocalDefId,
1112        bound_sig: ty::PolyFnSig<'tcx>,
1113    ) -> ClosureSignatures<'tcx> {
1114        let liberated_sig =
1115            self.tcx().liberate_late_bound_regions(expr_def_id.to_def_id(), bound_sig);
1116        let liberated_sig =
1117            self.normalize(self.tcx.def_span(expr_def_id), Unnormalized::new_wip(liberated_sig));
1118        ClosureSignatures { bound_sig, liberated_sig }
1119    }
1120}