Skip to main content

rustc_hir_typeck/
callee.rs

1use std::iter;
2
3use rustc_abi::{CanonAbi, ExternAbi};
4use rustc_ast::util::parser::ExprPrecedence;
5use rustc_attr_ir::find_attr;
6use rustc_attr_ir::lang_items::LangItem;
7use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
8use rustc_errors::{Applicability, Diag, ErrorGuaranteed, StashKey, msg};
9use rustc_hir::def::{self, CtorKind, Namespace, Res};
10use rustc_hir::def_id::DefId;
11use rustc_hir::{self as hir, HirId};
12use rustc_hir_analysis::autoderef::Autoderef;
13use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes};
14use rustc_infer::traits::{Obligation, ObligationCause, ObligationCauseCode};
15use rustc_middle::ty::adjustment::{
16    Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
17};
18use rustc_middle::ty::{self, FnSig, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
19use rustc_span::def_id::LocalDefId;
20use rustc_span::{Ident, Span, bug, sym};
21use rustc_target::spec::{AbiMap, AbiMapping};
22use rustc_trait_selection::error_reporting::traits::DefIdOrName;
23use rustc_trait_selection::infer::InferCtxtExt as _;
24use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
25use tracing::{debug, instrument};
26
27use super::method::MethodCallee;
28use super::method::probe::ProbeScope;
29use super::{Expectation, FnCtxt, TupleArgumentsFlag};
30use crate::diagnostics;
31use crate::method::TreatNotYetDefinedOpaques;
32use crate::method::confirm::ConfirmContext;
33use crate::method::probe::{IsSuggestion, Mode};
34
35/// Side-table info for lowering splatted function arguments.
36#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for SplatLoweringInfo<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::FnDef(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "FnDef",
                    &__self_0),
            Self::FnPtr(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "FnPtr",
                    &__self_0),
            Self::Error(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Error",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for SplatLoweringInfo<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for SplatLoweringInfo<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for SplatLoweringInfo<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<ErrorGuaranteed>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for SplatLoweringInfo<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DefId>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<ErrorGuaranteed>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for SplatLoweringInfo<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for SplatLoweringInfo<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::FnDef(__self_0), Self::FnDef(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::FnPtr(__self_0), Self::FnPtr(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Error(__self_0), Self::Error(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq)]
37pub(crate) enum SplatLoweringInfo<'tcx> {
38    /// The DefId of the FnDef being called, used to look up the function type.
39    /// Also used during argument suggestion for non-splatted function calls.
40    FnDef(DefId),
41    /// The type of the FnPtr being called.
42    FnPtr(Ty<'tcx>),
43    /// Type resolution errored.
44    Error(ErrorGuaranteed),
45}
46
47/// Checks that it is legal to call methods of the trait corresponding
48/// to `trait_id` (this only cares about the trait, not the specific
49/// method that is called).
50pub(crate) fn check_legal_trait_for_method_call(
51    tcx: TyCtxt<'_>,
52    span: Span,
53    receiver: Option<Span>,
54    expr_span: Span,
55    trait_id: DefId,
56    body_def_id: DefId,
57) -> Result<(), ErrorGuaranteed> {
58    if tcx.is_lang_item(trait_id, LangItem::Drop)
59        // Allow calling `Drop::pin_drop` in `Drop::drop`
60        && !tcx.is_lang_item(tcx.parent(body_def_id), LangItem::Drop)
61    {
62        let sugg = if let Some(receiver) = receiver.filter(|s| !s.is_empty()) {
63            diagnostics::ExplicitDestructorCallSugg::Snippet {
64                lo: expr_span.shrink_to_lo().to(receiver.shrink_to_lo()),
65                hi: receiver.shrink_to_hi().to(expr_span.shrink_to_hi()),
66            }
67        } else {
68            diagnostics::ExplicitDestructorCallSugg::Empty(span)
69        };
70        return Err(tcx.dcx().emit_err(diagnostics::ExplicitDestructorCall { span, sugg }));
71    }
72    tcx.ensure_result().coherent_trait(trait_id)
73}
74
75/// State machine for typechecking a call, based on the callee type.
76#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CallStep<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Builtin(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Builtin", &__self_0),
            Self::DeferredClosure(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "DeferredClosure", __self_0, &__self_1),
            Self::Overloaded(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Overloaded", &__self_0),
        }
    }
}Debug)]
77enum CallStep<'tcx> {
78    /// Typecheck a call to a function definition or pointer.
79    /// Includes functions with splatted arguments.
80    Builtin(Ty<'tcx>),
81    /// Deferred closure Fn* trait typechecking, when the callee is a closure.
82    DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
83    /// Call overloading when callee implements one of the Fn* traits.
84    Overloaded(MethodCallee<'tcx>),
85}
86
87impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
88    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::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_call",
                                    "rustc_hir_typeck::callee", ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_hir_typeck/src/callee.rs"),
                                    ::tracing_core::__macro_support::Option::Some(88u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("call_expr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("call_expr");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("callee_expr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("callee_expr");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("arg_exprs")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("arg_exprs");
                                                        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::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::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(&call_expr)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_expr)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg_exprs)
                                                            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 original_callee_ty =
                match &callee_expr.kind {
                    hir::ExprKind::Path(hir::QPath::Resolved(..) |
                        hir::QPath::TypeRelative(..)) =>
                        self.check_expr_with_expectation_and_args(callee_expr,
                            Expectation::NoExpectation, Some((call_expr, arg_exprs))),
                    _ => self.check_expr(callee_expr),
                };
            let expr_ty =
                self.deeply_resolve_ignoring_regions_with_obligations(original_callee_ty);
            let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
            let mut result = None;
            while result.is_none() && autoderef.next().is_some() {
                result =
                    self.try_overloaded_call_step(call_expr, callee_expr,
                        arg_exprs, &autoderef);
            }
            match *autoderef.final_ty().kind() {
                ty::FnDef(def_id, _) => {
                    let abi =
                        self.tcx.fn_sig(def_id).skip_binder().skip_binder().abi();
                    self.check_call_abi(abi, call_expr.span);
                }
                ty::FnPtr(_, header) => {
                    self.check_call_abi(header.abi(), call_expr.span);
                }
                _ => {}
            }
            if self.is_scalable_vector_ctor(autoderef.final_ty()) {
                let mut err =
                    self.dcx().create_err(diagnostics::ScalableVectorCtor {
                            span: callee_expr.span,
                            ty: autoderef.final_ty(),
                        });
                err.span_label(callee_expr.span,
                    "you can create scalable vectors using intrinsics");
                Ty::new_error(self.tcx, err.emit_err());
            }
            self.register_predicates(autoderef.into_obligations());
            let output =
                match result {
                    None => {
                        for arg in arg_exprs { self.check_expr(arg); }
                        if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) =
                                    &callee_expr.kind && let [segment] = path.segments {
                            self.dcx().try_steal_modify_and_emit_err(segment.ident.span,
                                StashKey::CallIntoMethod,
                                |err|
                                    {
                                        self.suggest_call_as_method(err, segment, arg_exprs,
                                            call_expr, expected);
                                    });
                        }
                        let guar =
                            self.report_invalid_callee(call_expr, callee_expr, expr_ty,
                                arg_exprs);
                        Ty::new_error(self.tcx, guar)
                    }
                    Some(CallStep::Builtin(callee_ty)) => {
                        self.confirm_builtin_call(call_expr, callee_expr, callee_ty,
                            arg_exprs, expected)
                    }
                    Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
                        self.confirm_deferred_closure_call(call_expr, arg_exprs,
                            expected, def_id, fn_sig)
                    }
                    Some(CallStep::Overloaded(method_callee)) => {
                        self.confirm_overloaded_call(call_expr, arg_exprs, expected,
                            method_callee)
                    }
                };
            self.register_wf_obligation(output.into(), call_expr.span,
                ObligationCauseCode::WellFormed(None));
            output
        }
    }
}#[tracing::instrument(skip(self))]
89    pub(crate) fn check_expr_call(
90        &self,
91        call_expr: &'tcx hir::Expr<'tcx>,
92        callee_expr: &'tcx hir::Expr<'tcx>,
93        arg_exprs: &'tcx [hir::Expr<'tcx>],
94        expected: Expectation<'tcx>,
95    ) -> Ty<'tcx> {
96        let original_callee_ty = match &callee_expr.kind {
97            hir::ExprKind::Path(hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)) => self
98                .check_expr_with_expectation_and_args(
99                    callee_expr,
100                    Expectation::NoExpectation,
101                    Some((call_expr, arg_exprs)),
102                ),
103            _ => self.check_expr(callee_expr),
104        };
105
106        let expr_ty = self.deeply_resolve_ignoring_regions_with_obligations(original_callee_ty);
107
108        let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
109        let mut result = None;
110        while result.is_none() && autoderef.next().is_some() {
111            result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
112        }
113
114        match *autoderef.final_ty().kind() {
115            ty::FnDef(def_id, _) => {
116                let abi = self.tcx.fn_sig(def_id).skip_binder().skip_binder().abi();
117                self.check_call_abi(abi, call_expr.span);
118            }
119            ty::FnPtr(_, header) => {
120                self.check_call_abi(header.abi(), call_expr.span);
121            }
122            _ => { /* cannot have a non-rust abi */ }
123        }
124
125        if self.is_scalable_vector_ctor(autoderef.final_ty()) {
126            let mut err = self.dcx().create_err(diagnostics::ScalableVectorCtor {
127                span: callee_expr.span,
128                ty: autoderef.final_ty(),
129            });
130            err.span_label(callee_expr.span, "you can create scalable vectors using intrinsics");
131            Ty::new_error(self.tcx, err.emit_err());
132        }
133
134        self.register_predicates(autoderef.into_obligations());
135
136        let output = match result {
137            None => {
138                // Check all of the arg expressions, but with no expectations
139                // since we don't have a signature to compare them to.
140                for arg in arg_exprs {
141                    self.check_expr(arg);
142                }
143
144                if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &callee_expr.kind
145                    && let [segment] = path.segments
146                {
147                    self.dcx().try_steal_modify_and_emit_err(
148                        segment.ident.span,
149                        StashKey::CallIntoMethod,
150                        |err| {
151                            // Try suggesting `foo(a)` -> `a.foo()` if possible.
152                            self.suggest_call_as_method(
153                                err, segment, arg_exprs, call_expr, expected,
154                            );
155                        },
156                    );
157                }
158
159                let guar = self.report_invalid_callee(call_expr, callee_expr, expr_ty, arg_exprs);
160                Ty::new_error(self.tcx, guar)
161            }
162
163            Some(CallStep::Builtin(callee_ty)) => {
164                self.confirm_builtin_call(call_expr, callee_expr, callee_ty, arg_exprs, expected)
165            }
166
167            Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
168                self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, def_id, fn_sig)
169            }
170
171            Some(CallStep::Overloaded(method_callee)) => {
172                self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
173            }
174        };
175
176        // we must check that return type of called functions is WF:
177        self.register_wf_obligation(
178            output.into(),
179            call_expr.span,
180            ObligationCauseCode::WellFormed(None),
181        );
182
183        output
184    }
185
186    /// Can a function with this ABI be called with a rust call expression?
187    ///
188    /// Some ABIs cannot be called from rust, either because rust does not know how to generate
189    /// code for the call, or because a call does not semantically make sense.
190    pub(crate) fn check_call_abi(&self, abi: ExternAbi, span: Span) {
191        let canon_abi = match AbiMap::from_target(&self.sess().target).canonize_abi(abi, false) {
192            AbiMapping::Direct(canon_abi) | AbiMapping::Deprecated(canon_abi) => canon_abi,
193            AbiMapping::Invalid => {
194                // This should be reported elsewhere, but we want to taint this body
195                // so that we don't try to evaluate calls to ABIs that are invalid.
196                let guar = self.dcx().span_delayed_bug(
197                    span,
198                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invalid abi for platform should have reported an error: {0}",
                abi))
    })format!("invalid abi for platform should have reported an error: {abi}"),
199                );
200                self.set_tainted_by_errors(guar);
201                return;
202            }
203        };
204
205        match canon_abi {
206            // Rust doesn't know how to call functions with this ABI.
207            CanonAbi::Custom
208            // The interrupt ABIs should only be called by the CPU. They have complex
209            // pre- and postconditions, and can use non-standard instructions like `iret` on x86.
210            | CanonAbi::Interrupt(_) => {
211                let err = crate::diagnostics::AbiCannotBeCalled { span, abi };
212                self.tcx.dcx().emit_err(err);
213            }
214
215            // This is an entry point for the host, and cannot be called directly.
216            CanonAbi::GpuKernel => {
217                let err = crate::diagnostics::GpuKernelAbiCannotBeCalled { span };
218                self.tcx.dcx().emit_err(err);
219            }
220
221            CanonAbi::C
222            | CanonAbi::Rust
223            | CanonAbi::RustCold
224            | CanonAbi::RustPreserveNone
225            | CanonAbi::RustTail
226            | CanonAbi::Swift
227            | CanonAbi::Arm(_)
228            | CanonAbi::X86(_) => {}
229        }
230    }
231
232    {}
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("try_overloaded_call_step",
                                "rustc_hir_typeck::callee", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_hir_typeck/src/callee.rs"),
                                ::tracing_core::__macro_support::Option::Some(232u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
                                ::tracing_core::field::FieldSet::new(&[],
                                    ::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,
                    &{ meta.fields().value_set_all(&[]) })
            } 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<CallStep<'tcx>> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let adjusted_ty =
                            self.deeply_resolve_ignoring_regions_with_obligations(autoderef.final_ty());
                        match *adjusted_ty.kind() {
                            ty::FnDef(..) | ty::FnPtr(..) => {
                                let adjustments = self.adjust_steps(autoderef);
                                self.apply_adjustments(callee_expr, adjustments);
                                return Some(CallStep::Builtin(adjusted_ty));
                            }
                            ty::Closure(def_id, args) if
                                self.closure_kind(adjusted_ty).is_none() => {
                                let def_id = def_id.expect_local();
                                let closure_sig = args.as_closure().sig();
                                let closure_sig =
                                    self.instantiate_binder_with_fresh_vars(call_expr.span,
                                        BoundRegionConversionTime::FnCall, closure_sig);
                                let adjustments = self.adjust_steps(autoderef);
                                self.record_deferred_call_resolution(def_id,
                                    DeferredCallResolution {
                                        call_expr,
                                        callee_expr,
                                        closure_ty: adjusted_ty,
                                        adjustments,
                                        fn_sig: closure_sig,
                                    });
                                return Some(CallStep::DeferredClosure(def_id, closure_sig));
                            }
                            ty::CoroutineClosure(def_id, args) if
                                self.closure_kind(adjusted_ty).is_none() => {
                                let def_id = def_id.expect_local();
                                let closure_args = args.as_coroutine_closure();
                                let coroutine_closure_sig =
                                    self.instantiate_binder_with_fresh_vars(call_expr.span,
                                        BoundRegionConversionTime::FnCall,
                                        closure_args.coroutine_closure_sig());
                                let tupled_upvars_ty = self.next_ty_var(callee_expr.span);
                                let kind_ty = self.next_ty_var(callee_expr.span);
                                let call_sig =
                                    self.tcx.mk_fn_sig([coroutine_closure_sig.tupled_inputs_ty],
                                        coroutine_closure_sig.to_coroutine(self.tcx,
                                            closure_args.parent_args(), kind_ty,
                                            self.tcx.coroutine_for_closure(def_id), tupled_upvars_ty),
                                        coroutine_closure_sig.fn_sig_kind);
                                let adjustments = self.adjust_steps(autoderef);
                                self.record_deferred_call_resolution(def_id,
                                    DeferredCallResolution {
                                        call_expr,
                                        callee_expr,
                                        closure_ty: adjusted_ty,
                                        adjustments,
                                        fn_sig: call_sig,
                                    });
                                return Some(CallStep::DeferredClosure(def_id, call_sig));
                            }
                            ty::Ref(..) if autoderef.step_count() == 0 => {
                                return None;
                            }
                            ty::Infer(ty::TyVar(vid)) => {
                                if !self.has_opaques_with_sub_unified_hidden_type(vid) {
                                    self.type_must_be_known_at_this_point(autoderef.span(),
                                        adjusted_ty);
                                    return None;
                                }
                            }
                            ty::Error(_) => { return None; }
                            _ => {}
                        }
                        self.try_overloaded_call_traits(call_expr, adjusted_ty,
                                    Some(arg_exprs)).or_else(||
                                    self.try_overloaded_call_traits(call_expr, adjusted_ty,
                                        None)).map(|(autoref, method)|
                                {
                                    let mut adjustments = self.adjust_steps(autoderef);
                                    adjustments.extend(autoref);
                                    self.apply_adjustments(callee_expr, adjustments);
                                    CallStep::Overloaded(method)
                                })
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_hir_typeck/src/callee.rs:232",
                        "rustc_hir_typeck::callee", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_hir_typeck/src/callee.rs"),
                        ::tracing_core::__macro_support::Option::Some(232u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
                        ::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, call_expr, callee_expr, arg_exprs, autoderef), ret)]
233    fn try_overloaded_call_step(
234        &self,
235        call_expr: &'tcx hir::Expr<'tcx>,
236        callee_expr: &'tcx hir::Expr<'tcx>,
237        arg_exprs: &'tcx [hir::Expr<'tcx>],
238        autoderef: &Autoderef<'a, 'tcx>,
239    ) -> Option<CallStep<'tcx>> {
240        let adjusted_ty =
241            self.deeply_resolve_ignoring_regions_with_obligations(autoderef.final_ty());
242
243        // If the callee is a function pointer or a closure, then we're all set.
244        match *adjusted_ty.kind() {
245            ty::FnDef(..) | ty::FnPtr(..) => {
246                let adjustments = self.adjust_steps(autoderef);
247                self.apply_adjustments(callee_expr, adjustments);
248                return Some(CallStep::Builtin(adjusted_ty));
249            }
250
251            // Check whether this is a call to a closure where we
252            // haven't yet decided on whether the closure is fn vs
253            // fnmut vs fnonce. If so, we have to defer further processing.
254            ty::Closure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
255                let def_id = def_id.expect_local();
256                let closure_sig = args.as_closure().sig();
257                let closure_sig = self.instantiate_binder_with_fresh_vars(
258                    call_expr.span,
259                    BoundRegionConversionTime::FnCall,
260                    closure_sig,
261                );
262                let adjustments = self.adjust_steps(autoderef);
263                self.record_deferred_call_resolution(
264                    def_id,
265                    DeferredCallResolution {
266                        call_expr,
267                        callee_expr,
268                        closure_ty: adjusted_ty,
269                        adjustments,
270                        fn_sig: closure_sig,
271                    },
272                );
273                return Some(CallStep::DeferredClosure(def_id, closure_sig));
274            }
275
276            // When calling a `CoroutineClosure` that is local to the body, we will
277            // not know what its `closure_kind` is yet. Instead, just fill in the
278            // signature with an infer var for the `tupled_upvars_ty` of the coroutine,
279            // and record a deferred call resolution which will constrain that var
280            // as part of `AsyncFn*` trait confirmation.
281            ty::CoroutineClosure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
282                let def_id = def_id.expect_local();
283                let closure_args = args.as_coroutine_closure();
284                let coroutine_closure_sig = self.instantiate_binder_with_fresh_vars(
285                    call_expr.span,
286                    BoundRegionConversionTime::FnCall,
287                    closure_args.coroutine_closure_sig(),
288                );
289                let tupled_upvars_ty = self.next_ty_var(callee_expr.span);
290                // We may actually receive a coroutine back whose kind is different
291                // from the closure that this dispatched from. This is because when
292                // we have no captures, we automatically implement `FnOnce`. This
293                // impl forces the closure kind to `FnOnce` i.e. `u8`.
294                let kind_ty = self.next_ty_var(callee_expr.span);
295                let call_sig = self.tcx.mk_fn_sig(
296                    [coroutine_closure_sig.tupled_inputs_ty],
297                    coroutine_closure_sig.to_coroutine(
298                        self.tcx,
299                        closure_args.parent_args(),
300                        kind_ty,
301                        self.tcx.coroutine_for_closure(def_id),
302                        tupled_upvars_ty,
303                    ),
304                    coroutine_closure_sig.fn_sig_kind,
305                );
306                let adjustments = self.adjust_steps(autoderef);
307                self.record_deferred_call_resolution(
308                    def_id,
309                    DeferredCallResolution {
310                        call_expr,
311                        callee_expr,
312                        closure_ty: adjusted_ty,
313                        adjustments,
314                        fn_sig: call_sig,
315                    },
316                );
317                return Some(CallStep::DeferredClosure(def_id, call_sig));
318            }
319
320            // Hack: we know that there are traits implementing Fn for &F
321            // where F:Fn and so forth. In the particular case of types
322            // like `f: &mut FnMut()`, if there is a call `f()`, we would
323            // normally translate to `FnMut::call_mut(&mut f, ())`, but
324            // that winds up potentially requiring the user to mark their
325            // variable as `mut` which feels unnecessary and unexpected.
326            //
327            //     fn foo(f: &mut impl FnMut()) { f() }
328            //            ^ without this hack `f` would have to be declared as mutable
329            //
330            // The simplest fix by far is to just ignore this case and deref again,
331            // so we wind up with `FnMut::call_mut(&mut *f, ())`.
332            ty::Ref(..) if autoderef.step_count() == 0 => {
333                return None;
334            }
335
336            ty::Infer(ty::TyVar(vid)) => {
337                // If we end up with an inference variable which is not the hidden type of
338                // an opaque, emit an error.
339                if !self.has_opaques_with_sub_unified_hidden_type(vid) {
340                    self.type_must_be_known_at_this_point(autoderef.span(), adjusted_ty);
341                    return None;
342                }
343            }
344
345            ty::Error(_) => {
346                return None;
347            }
348
349            _ => {}
350        }
351
352        // Now, we look for the implementation of a Fn trait on the object's type.
353        // We first do it with the explicit instruction to look for an impl of
354        // `Fn<Tuple>`, with the tuple `Tuple` having an arity corresponding
355        // to the number of call parameters.
356        // If that fails (or_else branch), we try again without specifying the
357        // shape of the tuple (hence the None). This allows to detect an Fn trait
358        // is implemented, and use this information for diagnostic.
359        self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
360            .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
361            .map(|(autoref, method)| {
362                let mut adjustments = self.adjust_steps(autoderef);
363                adjustments.extend(autoref);
364                self.apply_adjustments(callee_expr, adjustments);
365                CallStep::Overloaded(method)
366            })
367    }
368
369    fn try_overloaded_call_traits(
370        &self,
371        call_expr: &hir::Expr<'_>,
372        adjusted_ty: Ty<'tcx>,
373        opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
374    ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
375        // HACK(async_closures): For async closures, prefer `AsyncFn*`
376        // over `Fn*`, since all async closures implement `FnOnce`, but
377        // choosing that over `AsyncFn`/`AsyncFnMut` would be more restrictive.
378        // For other callables, just prefer `Fn*` for perf reasons.
379        //
380        // The order of trait choices here is not that big of a deal,
381        // since it just guides inference (and our choice of autoref).
382        // Though in the future, I'd like typeck to choose:
383        // `Fn > AsyncFn > FnMut > AsyncFnMut > FnOnce > AsyncFnOnce`
384        // ...or *ideally*, we just have `LendingFn`/`LendingFnMut`, which
385        // would naturally unify these two trait hierarchies in the most
386        // general way.
387        let call_trait_choices = if self.shallow_resolve(adjusted_ty).is_coroutine_closure() {
388            [
389                (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
390                (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
391                (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
392                (self.tcx.lang_items().fn_trait(), sym::call, true),
393                (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
394                (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
395            ]
396        } else {
397            [
398                (self.tcx.lang_items().fn_trait(), sym::call, true),
399                (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
400                (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
401                (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
402                (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
403                (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
404            ]
405        };
406
407        // Try the options that are least restrictive on the caller first.
408        for (opt_trait_def_id, method_name, borrow) in call_trait_choices {
409            let Some(trait_def_id) = opt_trait_def_id else { continue };
410
411            let opt_input_type = opt_arg_exprs.map(|arg_exprs| {
412                Ty::new_tup_from_iter(self.tcx, arg_exprs.iter().map(|e| self.next_ty_var(e.span)))
413            });
414
415            // We use `TreatNotYetDefinedOpaques::AsRigid` here so that if the `adjusted_ty`
416            // is `Box<impl FnOnce()>` we choose  `FnOnce` instead of `Fn`.
417            //
418            // We try all the different call traits in order and choose the first
419            // one which may apply. So if we treat opaques as inference variables
420            // `Box<impl FnOnce()>: Fn` is considered ambiguous and chosen.
421            if let Some(ok) = self.lookup_method_for_operator(
422                self.misc(call_expr.span),
423                method_name,
424                trait_def_id,
425                adjusted_ty,
426                opt_input_type,
427                TreatNotYetDefinedOpaques::AsRigid,
428            ) {
429                let method = self.register_infer_ok_obligations(ok);
430                let mut autoref = None;
431                if borrow {
432                    // Check for &self vs &mut self in the method signature. Since this is either
433                    // the Fn or FnMut trait, it should be one of those.
434                    let ty::Ref(_, _, mutbl) = *method.sig.inputs()[0].kind() else {
435                        ::rustc_span::macros::bug_impl(None,
    format_args!("Expected `FnMut`/`Fn` to take receiver by-ref/by-mut"),
    Location::caller())bug!("Expected `FnMut`/`Fn` to take receiver by-ref/by-mut")
436                    };
437
438                    // For initial two-phase borrow
439                    // deployment, conservatively omit
440                    // overloaded function call ops.
441                    let mutbl = AutoBorrowMutability::new(mutbl, AllowTwoPhase::No);
442
443                    autoref = Some(Adjustment {
444                        kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
445                        target: method.sig.inputs()[0],
446                    });
447                }
448
449                return Some((autoref, method));
450            }
451        }
452
453        None
454    }
455
456    fn is_scalable_vector_ctor(&self, callee_ty: Ty<'_>) -> bool {
457        if let ty::FnDef(def_id, _) = *callee_ty.kind()
458            && let def::DefKind::Ctor(def::CtorOf::Struct, _) = self.tcx.def_kind(def_id)
459        {
460            self.tcx
461                .opt_parent(def_id)
462                .and_then(|id| self.tcx.adt_def(id).repr().scalable)
463                .is_some()
464        } else {
465            false
466        }
467    }
468
469    /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
470    /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
471    fn identify_bad_closure_def_and_call(
472        &self,
473        err: &mut Diag<'_>,
474        hir_id: hir::HirId,
475        callee_node: &hir::ExprKind<'_>,
476        callee_span: Span,
477    ) {
478        let hir::ExprKind::Block(..) = callee_node else {
479            // Only calls on blocks suggested here.
480            return;
481        };
482
483        let fn_decl_span = if let hir::Node::Expr(&hir::Expr {
484            kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
485            ..
486        }) = self.tcx.parent_hir_node(hir_id)
487        {
488            fn_decl_span
489        } else if let Some((
490            _,
491            hir::Node::Expr(&hir::Expr {
492                hir_id: parent_hir_id,
493                kind:
494                    hir::ExprKind::Closure(&hir::Closure {
495                        kind:
496                            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
497                                hir::CoroutineDesugaring::Async,
498                                hir::CoroutineSource::Closure,
499                            )),
500                        ..
501                    }),
502                ..
503            }),
504        )) = self.tcx.hir_parent_iter(hir_id).nth(3)
505        {
506            // Actually need to unwrap one more layer of HIR to get to
507            // the _real_ closure...
508            let hir::Node::Expr(&hir::Expr {
509                kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
510                ..
511            }) = self.tcx.parent_hir_node(parent_hir_id)
512            else {
513                return;
514            };
515            fn_decl_span
516        } else {
517            return;
518        };
519
520        let start = fn_decl_span.shrink_to_lo();
521        let end = callee_span.shrink_to_hi();
522        err.multipart_suggestion(
523            "if you meant to create this closure and immediately call it, surround the \
524                closure with parentheses",
525            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(start, "(".to_string()), (end, ")".to_string())]))vec![(start, "(".to_string()), (end, ")".to_string())],
526            Applicability::MaybeIncorrect,
527        );
528    }
529
530    /// Give appropriate suggestion when encountering `[("a", 0) ("b", 1)]`, where the
531    /// likely intention is to create an array containing tuples.
532    fn maybe_suggest_bad_array_definition(
533        &self,
534        err: &mut Diag<'_>,
535        call_expr: &'tcx hir::Expr<'tcx>,
536        callee_expr: &'tcx hir::Expr<'tcx>,
537    ) -> bool {
538        let parent_node = self.tcx.parent_hir_node(call_expr.hir_id);
539        if let (
540            hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
541            hir::ExprKind::Tup(exp),
542            hir::ExprKind::Call(_, args),
543        ) = (parent_node, &callee_expr.kind, &call_expr.kind)
544            && args.len() == exp.len()
545        {
546            let start = callee_expr.span.shrink_to_hi();
547            err.span_suggestion(
548                start,
549                "consider separating array elements with a comma",
550                ",",
551                Applicability::MaybeIncorrect,
552            );
553            return true;
554        }
555        false
556    }
557
558    fn confirm_builtin_call(
559        &self,
560        call_expr: &'tcx hir::Expr<'tcx>,
561        callee_expr: &'tcx hir::Expr<'tcx>,
562        callee_ty: Ty<'tcx>,
563        arg_exprs: &'tcx [hir::Expr<'tcx>],
564        expected: Expectation<'tcx>,
565    ) -> Ty<'tcx> {
566        let (fn_sig, def_id, callee_generic_args) = match *callee_ty.kind() {
567            ty::FnDef(def_id, args) => {
568                let args = args.no_bound_vars().unwrap();
569                self.enforce_context_effects(Some(call_expr.hir_id), call_expr.span, def_id, args);
570                let fn_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args).skip_norm_wip();
571
572                // Unit testing: function items annotated with
573                // `#[rustc_evaluate_where_clauses]` trigger special output
574                // to let us test the trait evaluation system.
575                if self.has_rustc_attrs && {
        {
            'done:
                {
                for i in
                    ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &self.tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcEvaluateWhereClauses)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self.tcx, def_id, RustcEvaluateWhereClauses) {
576                    let clauses = self.tcx.clauses_of(def_id);
577                    let clauses = clauses.instantiate(self.tcx, args);
578                    for (clause, clause_span) in clauses {
579                        let clause = clause.skip_norm_wip();
580                        let obligation = Obligation::new(
581                            self.tcx,
582                            ObligationCause::dummy_with_span(callee_expr.span),
583                            self.param_env,
584                            clause,
585                        );
586                        let result = self.evaluate_obligation(&obligation);
587                        self.dcx()
588                            .struct_span_err(
589                                callee_expr.span,
590                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("evaluate({0:?}) = {1:?}", clause,
                result))
    })format!("evaluate({clause:?}) = {result:?}"),
591                            )
592                            .with_span_label(clause_span, "predicate")
593                            .emit();
594                    }
595                }
596                (fn_sig, Some(def_id), Some(args))
597            }
598
599            // FIXME(const_trait_impl): these arms should error because we can't enforce them
600            ty::FnPtr(sig_tys, hdr) => (sig_tys.with(hdr), None, None),
601
602            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
603        };
604
605        // Replace any late-bound regions that appear in the function
606        // signature with region variables. We also have to
607        // renormalize the associated types at this point, since they
608        // previously appeared within a `Binder<>` and hence would not
609        // have been normalized before.
610        let fn_sig = self.instantiate_binder_with_fresh_vars(
611            call_expr.span,
612            BoundRegionConversionTime::FnCall,
613            fn_sig,
614        );
615        let fn_sig = self.normalize(call_expr.span, Unnormalized::new_wip(fn_sig));
616
617        // Splatted FnDefs use the DefId to look up the type, FnPtrs need it directly
618        let fn_id = match def_id {
619            Some(x) => SplatLoweringInfo::FnDef(x),
620            None => SplatLoweringInfo::FnPtr(callee_ty),
621        };
622
623        self.check_argument_types_maybe_method_like(
624            &fn_sig,
625            call_expr,
626            arg_exprs,
627            expected,
628            TupleArgumentsFlag::with_fn_sig_kind(fn_sig.fn_sig_kind, false),
629            fn_id,
630            callee_generic_args,
631        );
632
633        // Splatting is currently incompatible with RustCall.
634        if fn_sig.abi() == rustc_abi::ExternAbi::RustCall {
635            let sp = arg_exprs.last().map_or(call_expr.span, |expr| expr.span);
636            if let Some(ty) = fn_sig.inputs().last().copied()
637                && fn_sig.splatted().is_none()
638            {
639                self.register_bound(
640                    ty,
641                    self.tcx.require_lang_item(LangItem::Tuple, sp),
642                    self.cause(sp, ObligationCauseCode::RustCall),
643                );
644                self.require_type_is_sized(ty, sp, ObligationCauseCode::RustCall);
645            } else {
646                self.dcx().emit_err(diagnostics::RustCallIncorrectArgs { span: sp });
647            }
648        }
649
650        fn_sig.output()
651    }
652
653    /// Performs arguments check with an additional routine of adjusting the first argument,
654    /// (and possibly other arguments) so it corresponds to the first parameter of the function.
655    /// We reuse adjustments that are obtained from `probe_for_name`, where the first argument pretends to be
656    /// a receiver like in a method call. At this point this routine is used for delegations,
657    /// as from this moment we always generate a call (earlier method calls were generated),
658    /// so we can both propagate parent generics and get benefits from adjustments from method call.
659    fn check_argument_types_maybe_method_like(
660        &self,
661        fn_sig: &FnSig<'tcx>,
662        call_expr: &'tcx hir::Expr<'tcx>,
663        arg_exprs: &'tcx [hir::Expr<'tcx>],
664        expected: Expectation<'tcx>,
665        tuple_arguments_flag: TupleArgumentsFlag,
666        fn_id: SplatLoweringInfo<'tcx>,
667        callee_generic_args: Option<GenericArgsRef<'tcx>>,
668    ) {
669        let do_check = || {
670            self.check_argument_types(
671                call_expr.span,
672                call_expr,
673                fn_sig.inputs(),
674                fn_sig.output(),
675                expected,
676                arg_exprs,
677                fn_sig.c_variadic(),
678                tuple_arguments_flag,
679                fn_id,
680                callee_generic_args,
681            );
682        };
683
684        let Some((candidate_res, args_to_map)) =
685            self.get_info_for_method_call_adjustments(call_expr, arg_exprs)
686        else {
687            return do_check();
688        };
689
690        // After we found pick for first argument we need to resolve inference variables
691        // in order to find adjustments for other mapped arguments.
692        let mut resolved_inputs = ::alloc::vec::Vec::new()vec![];
693        let mut prev_types = FxHashMap::default();
694        let formal_input_tys = fn_sig.inputs();
695
696        let args_to_map = arg_exprs
697            .iter()
698            .enumerate()
699            .filter(|(idx, _)| args_to_map.contains(idx))
700            .collect::<Vec<_>>();
701
702        for &(idx, arg) in &args_to_map {
703            let is_first_arg = idx == 0;
704            let self_ty_override = if is_first_arg { None } else { Some(resolved_inputs[idx]) };
705            let scope = ProbeScope::Single(candidate_res, self_ty_override);
706            let arg_type = self.check_expr(arg);
707
708            // Reuse method probing that is used during method call, as all this code pretends that
709            // we generated method call.
710            let pick = self.probe_for_name(
711                Mode::MethodCall,
712                Ident::dummy(),
713                None,
714                IsSuggestion(false),
715                arg_type,
716                call_expr.hir_id,
717                scope,
718            );
719
720            let Ok(ref pick) = pick else { return do_check() };
721
722            let mut ctx = ConfirmContext::new(self, arg.span, arg, arg);
723            let (adjusted_arg_type, method_adjustments) =
724                ctx.create_ty_adjustments_from_pick(arg_type, pick);
725
726            if is_first_arg && args_to_map.len() > 1 {
727                // We successfully found a pick and adjustments for first argument,
728                // now we have to unify it with signature input in order to resolve
729                // all inference variables. After that we update input signature for
730                // adjustments search for mapped arguments.
731                let cause = self.cause(call_expr.span, ObligationCauseCode::Misc);
732                if self
733                    .at(&cause, self.param_env)
734                    .sup(DefineOpaqueTypes::Yes, formal_input_tys[0], adjusted_arg_type)
735                    .is_err()
736                {
737                    return do_check();
738                }
739
740                resolved_inputs = self.deeply_resolve_ignoring_regions(formal_input_tys.to_vec());
741            }
742
743            // Fool typechecker by placing an adjusted type of the first arg to avoid errors.
744            // We already wrote type of `first_expr` during `self.check_expr(first_expr)` above.
745            prev_types.insert(
746                arg.hir_id,
747                (
748                    self.typeck_results
749                        .borrow_mut()
750                        .node_types_mut()
751                        .insert(arg.hir_id, adjusted_arg_type)
752                        .expect("must be set"),
753                    method_adjustments,
754                ),
755            );
756        }
757
758        do_check();
759
760        for (_, arg) in args_to_map {
761            let mut results = self.typeck_results.borrow_mut();
762            let mut adjustments = results.adjustments_mut();
763
764            let (prev_type, method_adjustments) =
765                prev_types.remove(&arg.hir_id).expect("must be in a map");
766
767            // Remove any added adjustments for arg expression during `do_check` and replace them with ours.
768            let adjustments = adjustments.entry(arg.hir_id).or_default();
769            *adjustments = method_adjustments;
770
771            // Restore original first provided arg type.
772            results.node_types_mut().insert(arg.hir_id, prev_type);
773        }
774    }
775
776    /// Gets scope for method-call like adjustments for the first argument of the call.
777    /// Now only delegations are processed this way.
778    fn get_info_for_method_call_adjustments(
779        &self,
780        call_expr: &'tcx hir::Expr<'tcx>,
781        arg_exprs: &'tcx [hir::Expr<'tcx>],
782    ) -> Option<(DefId, &FxIndexSet<usize>)> {
783        // Check that we are inside delegation and processing its call. First, we check that
784        // the parent of call expr. is delegation and then make sure that it is compiler-generated
785        // by comparing their hir ids (otherwise we will encounter errors in nested delegations,
786        // see tests\ui\delegation\impl-reuse-pass.rs:237).
787        let parent_def = self.tcx.hir_get_parent_item(call_expr.hir_id).def_id;
788        let Some(info) = self.tcx.hir_opt_delegation_info(parent_def) else {
789            return None;
790        };
791
792        if call_expr.hir_id != info.call_expr_id {
793            return None;
794        };
795
796        // Check that delegation has first provided arg and that the call path
797        // resolves to a trait method (inherent methods are not yet supported).
798        if arg_exprs.is_empty()
799            || !self.tcx.opt_associated_item(info.call_path_res).is_some_and(|i| i.is_method())
800        {
801            return None;
802        }
803
804        Some((info.call_path_res, &info.arguments_to_map))
805    }
806
807    /// Attempts to reinterpret `method(rcvr, args...)` as `rcvr.method(args...)`
808    /// and suggesting the fix if the method probe is successful.
809    fn suggest_call_as_method(
810        &self,
811        diag: &mut Diag<'_>,
812        segment: &'tcx hir::PathSegment<'tcx>,
813        arg_exprs: &'tcx [hir::Expr<'tcx>],
814        call_expr: &'tcx hir::Expr<'tcx>,
815        expected: Expectation<'tcx>,
816    ) {
817        if let [callee_expr, rest @ ..] = arg_exprs {
818            let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)
819            else {
820                return;
821            };
822
823            // First, do a probe with `IsSuggestion(true)` to avoid emitting
824            // any strange errors. If it's successful, then we'll do a true
825            // method lookup.
826            let Ok(pick) = self.lookup_probe_for_diagnostic(
827                segment.ident,
828                callee_ty,
829                call_expr,
830                // We didn't record the in scope traits during late resolution
831                // so we need to probe AllTraits unfortunately
832                ProbeScope::AllTraits,
833                expected.only_has_type(self),
834            ) else {
835                return;
836            };
837
838            let pick = self.confirm_method_for_diagnostic(
839                call_expr.span,
840                callee_expr,
841                call_expr,
842                callee_ty,
843                &pick,
844                segment,
845            );
846            if pick.illegal_sized_bound.is_some() {
847                return;
848            }
849
850            let Some(callee_expr_span) = callee_expr.span.find_ancestor_inside(call_expr.span)
851            else {
852                return;
853            };
854            let up_to_rcvr_span = segment.ident.span.until(callee_expr_span);
855            let rest_span = callee_expr_span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
856            let rest_snippet = if let Some(first) = rest.first() {
857                self.tcx
858                    .sess
859                    .source_map()
860                    .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
861            } else {
862                Ok(")".to_string())
863            };
864
865            if let Ok(rest_snippet) = rest_snippet {
866                let sugg = if self.precedence(callee_expr) >= ExprPrecedence::Unambiguous {
867                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(up_to_rcvr_span, "".to_string()),
                (rest_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(".{0}({1}", segment.ident,
                                    rest_snippet))
                        }))]))vec![
868                        (up_to_rcvr_span, "".to_string()),
869                        (rest_span, format!(".{}({rest_snippet}", segment.ident)),
870                    ]
871                } else {
872                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(up_to_rcvr_span, "(".to_string()),
                (rest_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(").{0}({1}",
                                    segment.ident, rest_snippet))
                        }))]))vec![
873                        (up_to_rcvr_span, "(".to_string()),
874                        (rest_span, format!(").{}({rest_snippet}", segment.ident)),
875                    ]
876                };
877                let self_ty = self.deeply_resolve_ignoring_regions(pick.callee.sig.inputs()[0]);
878                diag.multipart_suggestion(
879                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use the `.` operator to call the method `{0}{1}` on `{2}`",
                self.tcx.associated_item(pick.callee.def_id).trait_container(self.tcx).map_or_else(||
                        String::new(),
                    |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"),
                segment.ident, self_ty))
    })format!(
880                        "use the `.` operator to call the method `{}{}` on `{self_ty}`",
881                        self.tcx
882                            .associated_item(pick.callee.def_id)
883                            .trait_container(self.tcx)
884                            .map_or_else(
885                                || String::new(),
886                                |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
887                            ),
888                        segment.ident
889                    ),
890                    sugg,
891                    Applicability::MaybeIncorrect,
892                );
893            }
894        }
895    }
896
897    fn report_invalid_callee(
898        &self,
899        call_expr: &'tcx hir::Expr<'tcx>,
900        callee_expr: &'tcx hir::Expr<'tcx>,
901        callee_ty: Ty<'tcx>,
902        arg_exprs: &'tcx [hir::Expr<'tcx>],
903    ) -> ErrorGuaranteed {
904        // Callee probe fails when APIT references errors, so suppress those
905        // errors here.
906        if let Some((_, _, args)) = self.extract_callable_info(callee_ty)
907            && let Err(err) = args.error_reported()
908        {
909            return err;
910        }
911
912        let mut unit_variant = None;
913        if let hir::ExprKind::Path(qpath) = &callee_expr.kind
914            && let Res::Def(def::DefKind::Ctor(kind, CtorKind::Const), _)
915                = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
916            // Only suggest removing parens if there are no arguments
917            && arg_exprs.is_empty()
918            && call_expr.span.contains(callee_expr.span)
919        {
920            let descr = match kind {
921                def::CtorOf::Struct => "struct",
922                def::CtorOf::Variant => "enum variant",
923            };
924            let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
925            unit_variant =
926                Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(self, qpath)));
927        }
928
929        let callee_ty = self.deeply_resolve_ignoring_regions(callee_ty);
930        let mut path = None;
931        let mut err = self.dcx().create_err(diagnostics::InvalidCallee {
932            span: callee_expr.span,
933            found: match &unit_variant {
934                Some((_, kind, path)) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}`", kind, path))
    })format!("{kind} `{path}`"),
935                None => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`",
                self.tcx.short_string(callee_ty, &mut path)))
    })format!("`{}`", self.tcx.short_string(callee_ty, &mut path)),
936            },
937        });
938        *err.long_ty_path() = path;
939        if callee_ty.references_error() {
940            err.downgrade_to_delayed_bug();
941        }
942
943        self.identify_bad_closure_def_and_call(
944            &mut err,
945            call_expr.hir_id,
946            &callee_expr.kind,
947            callee_expr.span,
948        );
949
950        if let Some((removal_span, kind, path)) = &unit_variant {
951            err.span_suggestion_verbose(
952                *removal_span,
953                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is a unit {1}, and does not take parentheses to be constructed",
                path, kind))
    })format!(
954                    "`{path}` is a unit {kind}, and does not take parentheses to be constructed",
955                ),
956                "",
957                Applicability::MachineApplicable,
958            );
959        }
960
961        if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = callee_expr.kind
962            && let Res::Local(_) = path.res
963            && let [segment] = &path.segments
964        {
965            for id in self.tcx.hir_free_items() {
966                if let Some(node) = self.tcx.hir_get_if_local(id.owner_id.into())
967                    && let hir::Node::Item(item) = node
968                    && let hir::ItemKind::Fn { ident, .. } = item.kind
969                    && ident.name == segment.ident.name
970                {
971                    err.span_label(
972                        self.tcx.def_span(id.owner_id),
973                        "this function of the same name is available here, but it's shadowed by \
974                         the local binding",
975                    );
976                }
977            }
978        }
979
980        let mut inner_callee_path = None;
981        let def = match callee_expr.kind {
982            hir::ExprKind::Path(ref qpath) => {
983                self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
984            }
985            hir::ExprKind::Call(inner_callee, _) => {
986                if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
987                    inner_callee_path = Some(inner_qpath);
988                    self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
989                } else {
990                    Res::Err
991                }
992            }
993            _ => Res::Err,
994        };
995
996        if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
997            // If the call spans more than one line and the callee kind is
998            // itself another `ExprCall`, that's a clue that we might just be
999            // missing a semicolon (#51055, #106515).
1000            let call_is_multiline = self
1001                .tcx
1002                .sess
1003                .source_map()
1004                .is_multiline(call_expr.span.with_lo(callee_expr.span.hi()))
1005                && call_expr.span.eq_ctxt(callee_expr.span);
1006            if call_is_multiline {
1007                err.span_suggestion(
1008                    callee_expr.span.shrink_to_hi(),
1009                    "consider using a semicolon here to finish the statement",
1010                    ";",
1011                    Applicability::MaybeIncorrect,
1012                );
1013            }
1014            if let Some((maybe_def, output_ty, _)) = self.extract_callable_info(callee_ty)
1015                && !self.type_is_sized_modulo_regions(self.param_env, output_ty)
1016            {
1017                let descr = match maybe_def {
1018                    DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
1019                    DefIdOrName::Name(name) => name,
1020                };
1021                err.span_label(
1022                    callee_expr.span,
1023                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this {0} returns an unsized value `{1}`, so it cannot be called",
                descr, output_ty))
    })format!("this {descr} returns an unsized value `{output_ty}`, so it cannot be called")
1024                );
1025                if let DefIdOrName::DefId(def_id) = maybe_def
1026                    && let Some(def_span) = self.tcx.hir_span_if_local(def_id)
1027                {
1028                    err.span_label(def_span, "the callable type is defined here");
1029                }
1030            } else {
1031                err.span_label(call_expr.span, "call expression requires function");
1032            }
1033        }
1034
1035        if let Some(span) = self.tcx.hir_res_span(def) {
1036            let label = match (unit_variant, inner_callee_path) {
1037                (Some((_, kind, path)), _) => {
1038                    err.arg("kind", kind);
1039                    err.arg("path", path);
1040                    Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$kind} `{$path}` defined here"))msg!("{$kind} `{$path}` defined here"))
1041                }
1042                (_, Some(hir::QPath::Resolved(_, path))) => {
1043                    self.tcx.sess.source_map().span_to_snippet(path.span).ok().map(|p| {
1044                        err.arg("func", p);
1045                        err.arg("ty", callee_ty);
1046                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$func}` defined here returns `{$ty}`"))msg!("`{$func}` defined here returns `{$ty}`")
1047                    })
1048                }
1049                _ => {
1050                    match def {
1051                        // Emit a different diagnostic for local variables, as they are not
1052                        // type definitions themselves, but rather variables *of* that type.
1053                        Res::Local(hir_id) => {
1054                            err.arg("local_name", self.tcx.hir_name(hir_id));
1055                            err.arg("ty", callee_ty);
1056                            Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$local_name}` has type `{$ty}`"))msg!("`{$local_name}` has type `{$ty}`"))
1057                        }
1058                        Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
1059                            err.arg("path", self.tcx.def_path_str(def_id));
1060                            Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
1061                        }
1062                        _ => {
1063                            err.arg("path", callee_ty.to_string());
1064                            Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
1065                        }
1066                    }
1067                }
1068            };
1069            if let Some(label) = label {
1070                err.span_label(span, label);
1071            }
1072        }
1073        err.emit_err()
1074    }
1075
1076    fn confirm_deferred_closure_call(
1077        &self,
1078        call_expr: &'tcx hir::Expr<'tcx>,
1079        arg_exprs: &'tcx [hir::Expr<'tcx>],
1080        expected: Expectation<'tcx>,
1081        closure_def_id: LocalDefId,
1082        fn_sig: ty::FnSig<'tcx>,
1083    ) -> Ty<'tcx> {
1084        // `fn_sig` is the *signature* of the closure being called. We
1085        // don't know the full details yet (`Fn` vs `FnMut` etc), but we
1086        // do know the types expected for each argument and the return
1087        // type.
1088        self.check_argument_types(
1089            call_expr.span,
1090            call_expr,
1091            fn_sig.inputs(),
1092            fn_sig.output(),
1093            expected,
1094            arg_exprs,
1095            fn_sig.fn_sig_kind.c_variadic(),
1096            TupleArgumentsFlag::rust_fn_trait_call(),
1097            SplatLoweringInfo::FnDef(closure_def_id.to_def_id()),
1098            None,
1099        );
1100
1101        fn_sig.output()
1102    }
1103
1104    {}
#[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("enforce_context_effects",
                                    "rustc_hir_typeck::callee", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_hir_typeck/src/callee.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1104u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("call_hir_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("call_hir_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("callee_did")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("callee_did");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("callee_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("callee_args");
                                                        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(&call_hir_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_did)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_args)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let const_context =
                self.tcx.hir_body_const_context(self.body_def_id);
            if let hir::Constness::Const { always: true } =
                    self.tcx.constness(callee_did) {
                match const_context {
                    Some(hir::ConstContext::Const { .. } |
                        hir::ConstContext::Static(_)) => {}
                    Some(hir::ConstContext::ConstFn) | None => {
                        self.dcx().span_err(span,
                            "comptime fns can only be called at compile time");
                    }
                }
            }
            if !self.tcx.features().const_trait_impl() { return; }
            if self.has_rustc_attrs &&
                    {
                            {
                                'done:
                                    {
                                    for i in
                                        ::rustc_attr_ir::HasAttrs::get_attrs(self.body_def_id,
                                            &self.tcx) {
                                        #[allow(unused_imports)]
                                        use ::rustc_attr_ir::AttributeKind::*;
                                        let i: &::rustc_attr_ir::Attribute = i;
                                        match i {
                                            ::rustc_attr_ir::Attribute::Parsed(RustcDoNotConstCheck) =>
                                                {
                                                break 'done Some(());
                                            }
                                            ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                {}
                                                #[deny(unreachable_patterns)]
                                                _ => {}
                                        }
                                    }
                                    None
                                }
                            }
                        }.is_some() {
                return;
            }
            let host =
                match const_context {
                    Some(hir::ConstContext::Const { .. } |
                        hir::ConstContext::Static(_)) => {
                        ty::BoundConstness::Const
                    }
                    Some(hir::ConstContext::ConstFn) =>
                        ty::BoundConstness::Maybe,
                    None => return,
                };
            if self.tcx.is_conditionally_const(callee_did) {
                let q = self.tcx.const_conditions(callee_did);
                for (idx, (cond, pred_span)) in
                    q.instantiate(self.tcx, callee_args).into_iter().enumerate()
                    {
                    let cause =
                        self.cause(span,
                            if let Some(hir_id) = call_hir_id {
                                ObligationCauseCode::HostEffectInExpr(callee_did, pred_span,
                                    hir_id, idx)
                            } else {
                                ObligationCauseCode::WhereClause(callee_did, pred_span)
                            });
                    self.register_predicate(Obligation::new(self.tcx, cause,
                            self.param_env,
                            cond.to_host_effect_clause(self.tcx,
                                    host).skip_norm_wip()));
                }
            } else {}
        }
    }
}#[tracing::instrument(level = "debug", skip(self, span))]
1105    pub(super) fn enforce_context_effects(
1106        &self,
1107        call_hir_id: Option<HirId>,
1108        span: Span,
1109        callee_did: DefId,
1110        callee_args: GenericArgsRef<'tcx>,
1111    ) {
1112        let const_context = self.tcx.hir_body_const_context(self.body_def_id);
1113
1114        if let hir::Constness::Const { always: true } = self.tcx.constness(callee_did) {
1115            match const_context {
1116                Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {}
1117                Some(hir::ConstContext::ConstFn) | None => {
1118                    self.dcx().span_err(span, "comptime fns can only be called at compile time");
1119                }
1120            }
1121        }
1122
1123        // FIXME(const_trait_impl): We should be enforcing these effects unconditionally.
1124        // This can be done as soon as we convert the standard library back to
1125        // using const traits, since if we were to enforce these conditions now,
1126        // we'd fail on basically every builtin trait call (i.e. `1 + 2`).
1127        if !self.tcx.features().const_trait_impl() {
1128            return;
1129        }
1130
1131        // If we have `rustc_do_not_const_check`, do not check `[const]` bounds.
1132        if self.has_rustc_attrs && find_attr!(self.tcx, self.body_def_id, RustcDoNotConstCheck) {
1133            return;
1134        }
1135
1136        let host = match const_context {
1137            Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
1138                ty::BoundConstness::Const
1139            }
1140            Some(hir::ConstContext::ConstFn) => ty::BoundConstness::Maybe,
1141            None => return,
1142        };
1143
1144        // FIXME(const_trait_impl): Should this be `is_const_fn_raw`? It depends on if we move
1145        // const stability checking here too, I guess.
1146        if self.tcx.is_conditionally_const(callee_did) {
1147            let q = self.tcx.const_conditions(callee_did);
1148            for (idx, (cond, pred_span)) in
1149                q.instantiate(self.tcx, callee_args).into_iter().enumerate()
1150            {
1151                let cause = self.cause(
1152                    span,
1153                    if let Some(hir_id) = call_hir_id {
1154                        ObligationCauseCode::HostEffectInExpr(callee_did, pred_span, hir_id, idx)
1155                    } else {
1156                        ObligationCauseCode::WhereClause(callee_did, pred_span)
1157                    },
1158                );
1159                self.register_predicate(Obligation::new(
1160                    self.tcx,
1161                    cause,
1162                    self.param_env,
1163                    cond.to_host_effect_clause(self.tcx, host).skip_norm_wip(),
1164                ));
1165            }
1166        } else {
1167            // FIXME(const_trait_impl): This should eventually be caught here.
1168            // For now, though, we defer some const checking to MIR.
1169        }
1170    }
1171
1172    fn confirm_overloaded_call(
1173        &self,
1174        call_expr: &'tcx hir::Expr<'tcx>,
1175        arg_exprs: &'tcx [hir::Expr<'tcx>],
1176        expected: Expectation<'tcx>,
1177        method: MethodCallee<'tcx>,
1178    ) -> Ty<'tcx> {
1179        // FIXME(splat): if we ever support splatting here, decrement the splatted index, because
1180        // the receiver argument is removed below.
1181        {
    match (&method.sig.fn_sig_kind.splatted(), &None) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("splatting is not supported on RustCall tuples")));
            }
        }
    }
};assert_eq!(
1182            method.sig.fn_sig_kind.splatted(),
1183            None,
1184            "splatting is not supported on RustCall tuples",
1185        );
1186        self.check_argument_types(
1187            call_expr.span,
1188            call_expr,
1189            &method.sig.inputs()[1..],
1190            method.sig.output(),
1191            expected,
1192            arg_exprs,
1193            method.sig.fn_sig_kind.c_variadic(),
1194            TupleArgumentsFlag::rust_fn_trait_call(),
1195            SplatLoweringInfo::FnDef(method.def_id),
1196            None,
1197        );
1198
1199        self.write_method_call_and_enforce_effects(call_expr.hir_id, call_expr.span, method);
1200
1201        method.sig.output()
1202    }
1203}
1204
1205#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for DeferredCallResolution<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "DeferredCallResolution", "call_expr", &self.call_expr,
            "callee_expr", &self.callee_expr, "closure_ty", &self.closure_ty,
            "adjustments", &self.adjustments, "fn_sig", &&self.fn_sig)
    }
}Debug)]
1206pub(crate) struct DeferredCallResolution<'tcx> {
1207    call_expr: &'tcx hir::Expr<'tcx>,
1208    callee_expr: &'tcx hir::Expr<'tcx>,
1209    closure_ty: Ty<'tcx>,
1210    adjustments: Vec<Adjustment<'tcx>>,
1211    fn_sig: ty::FnSig<'tcx>,
1212}
1213
1214impl<'a, 'tcx> DeferredCallResolution<'tcx> {
1215    pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
1216        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_hir_typeck/src/callee.rs:1216",
                        "rustc_hir_typeck::callee", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_hir_typeck/src/callee.rs"),
                        ::tracing_core::__macro_support::Option::Some(1216u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
                        ::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!("DeferredCallResolution::resolve() {0:?}",
                                                    self) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("DeferredCallResolution::resolve() {:?}", self);
1217
1218        // we should not be invoked until the closure kind has been
1219        // determined by upvar inference
1220        if !fcx.closure_kind(self.closure_ty).is_some() {
    ::core::panicking::panic("assertion failed: fcx.closure_kind(self.closure_ty).is_some()")
};assert!(fcx.closure_kind(self.closure_ty).is_some());
1221
1222        // We may now know enough to figure out fn vs fnmut etc.
1223        match fcx.try_overloaded_call_traits(self.call_expr, self.closure_ty, None) {
1224            Some((autoref, method_callee)) => {
1225                // One problem is that when we get here, we are going
1226                // to have a newly instantiated function signature
1227                // from the call trait. This has to be reconciled with
1228                // the older function signature we had before. In
1229                // principle we *should* be able to fn_sigs(), but we
1230                // can't because of the annoying need for a TypeTrace.
1231                // (This always bites me, should find a way to
1232                // refactor it.)
1233                let method_sig = method_callee.sig;
1234
1235                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_hir_typeck/src/callee.rs:1235",
                        "rustc_hir_typeck::callee", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_hir_typeck/src/callee.rs"),
                        ::tracing_core::__macro_support::Option::Some(1235u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
                        ::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!("attempt_resolution: method_callee={0:?}",
                                                    method_callee) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("attempt_resolution: method_callee={:?}", method_callee);
1236
1237                for (method_arg_ty, self_arg_ty) in
1238                    iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
1239                {
1240                    fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
1241                }
1242
1243                fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
1244
1245                let mut adjustments = self.adjustments;
1246                adjustments.extend(autoref);
1247                fcx.apply_adjustments(self.callee_expr, adjustments);
1248
1249                fcx.write_method_call_and_enforce_effects(
1250                    self.call_expr.hir_id,
1251                    self.call_expr.span,
1252                    method_callee,
1253                );
1254            }
1255            None => {
1256                let guar = fcx.tainted_by_errors().unwrap_or_else(|| {
1257                    fcx.dcx().span_delayed_bug(
1258                        self.call_expr.span,
1259                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{0}`",
                self.closure_ty))
    })format!(
1260                            "Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{}`",
1261                            self.closure_ty
1262                        ),
1263                    )
1264                });
1265                fcx.write_resolution(self.call_expr.hir_id, Err(guar));
1266            }
1267        }
1268    }
1269}