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