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::RustTail
209            | CanonAbi::Swift
210            | CanonAbi::Arm(_)
211            | CanonAbi::X86(_) => {}
212        }
213    }
214
215    x;#[instrument(level = "debug", skip(self, call_expr, callee_expr, arg_exprs, autoderef), ret)]
216    fn try_overloaded_call_step(
217        &self,
218        call_expr: &'tcx hir::Expr<'tcx>,
219        callee_expr: &'tcx hir::Expr<'tcx>,
220        arg_exprs: &'tcx [hir::Expr<'tcx>],
221        autoderef: &Autoderef<'a, 'tcx>,
222    ) -> Option<CallStep<'tcx>> {
223        let adjusted_ty = self.resolve_vars_with_obligations(autoderef.final_ty());
224
225        // If the callee is a function pointer or a closure, then we're all set.
226        match *adjusted_ty.kind() {
227            ty::FnDef(..) | ty::FnPtr(..) => {
228                let adjustments = self.adjust_steps(autoderef);
229                self.apply_adjustments(callee_expr, adjustments);
230                return Some(CallStep::Builtin(adjusted_ty));
231            }
232
233            // Check whether this is a call to a closure where we
234            // haven't yet decided on whether the closure is fn vs
235            // fnmut vs fnonce. If so, we have to defer further processing.
236            ty::Closure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
237                let def_id = def_id.expect_local();
238                let closure_sig = args.as_closure().sig();
239                let closure_sig = self.instantiate_binder_with_fresh_vars(
240                    call_expr.span,
241                    BoundRegionConversionTime::FnCall,
242                    closure_sig,
243                );
244                let adjustments = self.adjust_steps(autoderef);
245                self.record_deferred_call_resolution(
246                    def_id,
247                    DeferredCallResolution {
248                        call_expr,
249                        callee_expr,
250                        closure_ty: adjusted_ty,
251                        adjustments,
252                        fn_sig: closure_sig,
253                    },
254                );
255                return Some(CallStep::DeferredClosure(def_id, closure_sig));
256            }
257
258            // When calling a `CoroutineClosure` that is local to the body, we will
259            // not know what its `closure_kind` is yet. Instead, just fill in the
260            // signature with an infer var for the `tupled_upvars_ty` of the coroutine,
261            // and record a deferred call resolution which will constrain that var
262            // as part of `AsyncFn*` trait confirmation.
263            ty::CoroutineClosure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
264                let def_id = def_id.expect_local();
265                let closure_args = args.as_coroutine_closure();
266                let coroutine_closure_sig = self.instantiate_binder_with_fresh_vars(
267                    call_expr.span,
268                    BoundRegionConversionTime::FnCall,
269                    closure_args.coroutine_closure_sig(),
270                );
271                let tupled_upvars_ty = self.next_ty_var(callee_expr.span);
272                // We may actually receive a coroutine back whose kind is different
273                // from the closure that this dispatched from. This is because when
274                // we have no captures, we automatically implement `FnOnce`. This
275                // impl forces the closure kind to `FnOnce` i.e. `u8`.
276                let kind_ty = self.next_ty_var(callee_expr.span);
277                let call_sig = self.tcx.mk_fn_sig(
278                    [coroutine_closure_sig.tupled_inputs_ty],
279                    coroutine_closure_sig.to_coroutine(
280                        self.tcx,
281                        closure_args.parent_args(),
282                        kind_ty,
283                        self.tcx.coroutine_for_closure(def_id),
284                        tupled_upvars_ty,
285                    ),
286                    coroutine_closure_sig.fn_sig_kind,
287                );
288                let adjustments = self.adjust_steps(autoderef);
289                self.record_deferred_call_resolution(
290                    def_id,
291                    DeferredCallResolution {
292                        call_expr,
293                        callee_expr,
294                        closure_ty: adjusted_ty,
295                        adjustments,
296                        fn_sig: call_sig,
297                    },
298                );
299                return Some(CallStep::DeferredClosure(def_id, call_sig));
300            }
301
302            // Hack: we know that there are traits implementing Fn for &F
303            // where F:Fn and so forth. In the particular case of types
304            // like `f: &mut FnMut()`, if there is a call `f()`, we would
305            // normally translate to `FnMut::call_mut(&mut f, ())`, but
306            // that winds up potentially requiring the user to mark their
307            // variable as `mut` which feels unnecessary and unexpected.
308            //
309            //     fn foo(f: &mut impl FnMut()) { f() }
310            //            ^ without this hack `f` would have to be declared as mutable
311            //
312            // The simplest fix by far is to just ignore this case and deref again,
313            // so we wind up with `FnMut::call_mut(&mut *f, ())`.
314            ty::Ref(..) if autoderef.step_count() == 0 => {
315                return None;
316            }
317
318            ty::Infer(ty::TyVar(vid)) => {
319                // If we end up with an inference variable which is not the hidden type of
320                // an opaque, emit an error.
321                if !self.has_opaques_with_sub_unified_hidden_type(vid) {
322                    self.type_must_be_known_at_this_point(autoderef.span(), adjusted_ty);
323                    return None;
324                }
325            }
326
327            ty::Error(_) => {
328                return None;
329            }
330
331            _ => {}
332        }
333
334        // Now, we look for the implementation of a Fn trait on the object's type.
335        // We first do it with the explicit instruction to look for an impl of
336        // `Fn<Tuple>`, with the tuple `Tuple` having an arity corresponding
337        // to the number of call parameters.
338        // If that fails (or_else branch), we try again without specifying the
339        // shape of the tuple (hence the None). This allows to detect an Fn trait
340        // is implemented, and use this information for diagnostic.
341        self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
342            .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
343            .map(|(autoref, method)| {
344                let mut adjustments = self.adjust_steps(autoderef);
345                adjustments.extend(autoref);
346                self.apply_adjustments(callee_expr, adjustments);
347                CallStep::Overloaded(method)
348            })
349    }
350
351    fn try_overloaded_call_traits(
352        &self,
353        call_expr: &hir::Expr<'_>,
354        adjusted_ty: Ty<'tcx>,
355        opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
356    ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
357        // HACK(async_closures): For async closures, prefer `AsyncFn*`
358        // over `Fn*`, since all async closures implement `FnOnce`, but
359        // choosing that over `AsyncFn`/`AsyncFnMut` would be more restrictive.
360        // For other callables, just prefer `Fn*` for perf reasons.
361        //
362        // The order of trait choices here is not that big of a deal,
363        // since it just guides inference (and our choice of autoref).
364        // Though in the future, I'd like typeck to choose:
365        // `Fn > AsyncFn > FnMut > AsyncFnMut > FnOnce > AsyncFnOnce`
366        // ...or *ideally*, we just have `LendingFn`/`LendingFnMut`, which
367        // would naturally unify these two trait hierarchies in the most
368        // general way.
369        let call_trait_choices = if self.shallow_resolve(adjusted_ty).is_coroutine_closure() {
370            [
371                (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
372                (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
373                (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
374                (self.tcx.lang_items().fn_trait(), sym::call, true),
375                (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
376                (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
377            ]
378        } else {
379            [
380                (self.tcx.lang_items().fn_trait(), sym::call, true),
381                (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
382                (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
383                (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
384                (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
385                (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
386            ]
387        };
388
389        // Try the options that are least restrictive on the caller first.
390        for (opt_trait_def_id, method_name, borrow) in call_trait_choices {
391            let Some(trait_def_id) = opt_trait_def_id else { continue };
392
393            let opt_input_type = opt_arg_exprs.map(|arg_exprs| {
394                Ty::new_tup_from_iter(self.tcx, arg_exprs.iter().map(|e| self.next_ty_var(e.span)))
395            });
396
397            // We use `TreatNotYetDefinedOpaques::AsRigid` here so that if the `adjusted_ty`
398            // is `Box<impl FnOnce()>` we choose  `FnOnce` instead of `Fn`.
399            //
400            // We try all the different call traits in order and choose the first
401            // one which may apply. So if we treat opaques as inference variables
402            // `Box<impl FnOnce()>: Fn` is considered ambiguous and chosen.
403            if let Some(ok) = self.lookup_method_for_operator(
404                self.misc(call_expr.span),
405                method_name,
406                trait_def_id,
407                adjusted_ty,
408                opt_input_type,
409                TreatNotYetDefinedOpaques::AsRigid,
410            ) {
411                let method = self.register_infer_ok_obligations(ok);
412                let mut autoref = None;
413                if borrow {
414                    // Check for &self vs &mut self in the method signature. Since this is either
415                    // the Fn or FnMut trait, it should be one of those.
416                    let ty::Ref(_, _, mutbl) = *method.sig.inputs()[0].kind() else {
417                        ::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")
418                    };
419
420                    // For initial two-phase borrow
421                    // deployment, conservatively omit
422                    // overloaded function call ops.
423                    let mutbl = AutoBorrowMutability::new(mutbl, AllowTwoPhase::No);
424
425                    autoref = Some(Adjustment {
426                        kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
427                        target: method.sig.inputs()[0],
428                    });
429                }
430
431                return Some((autoref, method));
432            }
433        }
434
435        None
436    }
437
438    fn is_scalable_vector_ctor(&self, callee_ty: Ty<'_>) -> bool {
439        if let ty::FnDef(def_id, _) = *callee_ty.kind()
440            && let def::DefKind::Ctor(def::CtorOf::Struct, _) = self.tcx.def_kind(def_id)
441        {
442            self.tcx
443                .opt_parent(def_id)
444                .and_then(|id| self.tcx.adt_def(id).repr().scalable)
445                .is_some()
446        } else {
447            false
448        }
449    }
450
451    /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
452    /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
453    fn identify_bad_closure_def_and_call(
454        &self,
455        err: &mut Diag<'_>,
456        hir_id: hir::HirId,
457        callee_node: &hir::ExprKind<'_>,
458        callee_span: Span,
459    ) {
460        let hir::ExprKind::Block(..) = callee_node else {
461            // Only calls on blocks suggested here.
462            return;
463        };
464
465        let fn_decl_span = if let hir::Node::Expr(&hir::Expr {
466            kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
467            ..
468        }) = self.tcx.parent_hir_node(hir_id)
469        {
470            fn_decl_span
471        } else if let Some((
472            _,
473            hir::Node::Expr(&hir::Expr {
474                hir_id: parent_hir_id,
475                kind:
476                    hir::ExprKind::Closure(&hir::Closure {
477                        kind:
478                            hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
479                                hir::CoroutineDesugaring::Async,
480                                hir::CoroutineSource::Closure,
481                            )),
482                        ..
483                    }),
484                ..
485            }),
486        )) = self.tcx.hir_parent_iter(hir_id).nth(3)
487        {
488            // Actually need to unwrap one more layer of HIR to get to
489            // the _real_ closure...
490            let hir::Node::Expr(&hir::Expr {
491                kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
492                ..
493            }) = self.tcx.parent_hir_node(parent_hir_id)
494            else {
495                return;
496            };
497            fn_decl_span
498        } else {
499            return;
500        };
501
502        let start = fn_decl_span.shrink_to_lo();
503        let end = callee_span.shrink_to_hi();
504        err.multipart_suggestion(
505            "if you meant to create this closure and immediately call it, surround the \
506                closure with parentheses",
507            ::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())],
508            Applicability::MaybeIncorrect,
509        );
510    }
511
512    /// Give appropriate suggestion when encountering `[("a", 0) ("b", 1)]`, where the
513    /// likely intention is to create an array containing tuples.
514    fn maybe_suggest_bad_array_definition(
515        &self,
516        err: &mut Diag<'_>,
517        call_expr: &'tcx hir::Expr<'tcx>,
518        callee_expr: &'tcx hir::Expr<'tcx>,
519    ) -> bool {
520        let parent_node = self.tcx.parent_hir_node(call_expr.hir_id);
521        if let (
522            hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
523            hir::ExprKind::Tup(exp),
524            hir::ExprKind::Call(_, args),
525        ) = (parent_node, &callee_expr.kind, &call_expr.kind)
526            && args.len() == exp.len()
527        {
528            let start = callee_expr.span.shrink_to_hi();
529            err.span_suggestion(
530                start,
531                "consider separating array elements with a comma",
532                ",",
533                Applicability::MaybeIncorrect,
534            );
535            return true;
536        }
537        false
538    }
539
540    fn confirm_builtin_call(
541        &self,
542        call_expr: &'tcx hir::Expr<'tcx>,
543        callee_expr: &'tcx hir::Expr<'tcx>,
544        callee_ty: Ty<'tcx>,
545        arg_exprs: &'tcx [hir::Expr<'tcx>],
546        expected: Expectation<'tcx>,
547    ) -> Ty<'tcx> {
548        let (fn_sig, def_id) = match *callee_ty.kind() {
549            ty::FnDef(def_id, args) => {
550                self.enforce_context_effects(Some(call_expr.hir_id), call_expr.span, def_id, args);
551                let fn_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args).skip_norm_wip();
552
553                // Unit testing: function items annotated with
554                // `#[rustc_evaluate_where_clauses]` trigger special output
555                // to let us test the trait evaluation system.
556                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) {
557                    let predicates = self.tcx.predicates_of(def_id);
558                    let predicates = predicates.instantiate(self.tcx, args);
559                    for (predicate, predicate_span) in predicates {
560                        let predicate = predicate.skip_norm_wip();
561                        let obligation = Obligation::new(
562                            self.tcx,
563                            ObligationCause::dummy_with_span(callee_expr.span),
564                            self.param_env,
565                            predicate,
566                        );
567                        let result = self.evaluate_obligation(&obligation);
568                        self.dcx()
569                            .struct_span_err(
570                                callee_expr.span,
571                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("evaluate({0:?}) = {1:?}",
                predicate, result))
    })format!("evaluate({predicate:?}) = {result:?}"),
572                            )
573                            .with_span_label(predicate_span, "predicate")
574                            .emit();
575                    }
576                }
577                (fn_sig, Some(def_id))
578            }
579
580            // FIXME(const_trait_impl): these arms should error because we can't enforce them
581            ty::FnPtr(sig_tys, hdr) => (sig_tys.with(hdr), None),
582
583            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
584        };
585
586        // Replace any late-bound regions that appear in the function
587        // signature with region variables. We also have to
588        // renormalize the associated types at this point, since they
589        // previously appeared within a `Binder<>` and hence would not
590        // have been normalized before.
591        let fn_sig = self.instantiate_binder_with_fresh_vars(
592            call_expr.span,
593            BoundRegionConversionTime::FnCall,
594            fn_sig,
595        );
596        let fn_sig = self.normalize(call_expr.span, Unnormalized::new_wip(fn_sig));
597
598        self.check_argument_types_maybe_method_like(
599            &fn_sig, call_expr, arg_exprs, expected, def_id,
600        );
601
602        if fn_sig.abi() == rustc_abi::ExternAbi::RustCall {
603            let sp = arg_exprs.last().map_or(call_expr.span, |expr| expr.span);
604            if let Some(ty) = fn_sig.inputs().last().copied() {
605                self.register_bound(
606                    ty,
607                    self.tcx.require_lang_item(hir::LangItem::Tuple, sp),
608                    self.cause(sp, ObligationCauseCode::RustCall),
609                );
610                self.require_type_is_sized(ty, sp, ObligationCauseCode::RustCall);
611            } else {
612                self.dcx().emit_err(errors::RustCallIncorrectArgs { span: sp });
613            }
614        }
615
616        fn_sig.output()
617    }
618
619    /// Performs arguments check with an additional routine of adjusting the first argument,
620    /// so it corresponds to the first parameter of the function. We reuse adjustments
621    /// that are obtained from `probe_for_name`, where the first argument pretends to be
622    /// a receiver like in a method call. At this point this routine is used for delegations,
623    /// as from this moment we always generate a call (earlier method calls were generated),
624    /// so we can both propagate parent generics and get benefits from adjustments from method call.
625    fn check_argument_types_maybe_method_like(
626        &self,
627        fn_sig: &FnSig<'tcx>,
628        call_expr: &'tcx hir::Expr<'tcx>,
629        arg_exprs: &'tcx [hir::Expr<'tcx>],
630        expected: Expectation<'tcx>,
631        def_id: Option<DefId>,
632    ) {
633        let do_check = || {
634            self.check_argument_types(
635                call_expr.span,
636                call_expr,
637                fn_sig.inputs(),
638                fn_sig.output(),
639                expected,
640                arg_exprs,
641                fn_sig.c_variadic(),
642                TupleArgumentsFlag::DontTupleArguments,
643                def_id,
644            );
645        };
646
647        let Some(scope) = self.get_scope_for_method_call_adjustments(call_expr, arg_exprs) else {
648            return do_check();
649        };
650
651        let first_expr = &arg_exprs[0];
652        let first_arg_type = self.check_expr(first_expr);
653
654        // Reuse method probing that is used during method call, as all this code pretends that
655        // we generated method call.
656        let pick = self.probe_for_name(
657            Mode::MethodCall,
658            Ident::dummy(),
659            None,
660            IsSuggestion(false),
661            first_arg_type,
662            call_expr.hir_id,
663            scope,
664        );
665
666        let Ok(ref pick) = pick else { return do_check() };
667
668        // Fool typechecker by placing an adjusted type of the first arg to avoid errors.
669        // We already wrote type of `first_expr` during `self.check_expr(first_expr)` above.
670        let first_arg_type = self
671            .typeck_results
672            .borrow_mut()
673            .node_types_mut()
674            .insert(first_expr.hir_id, pick.self_ty)
675            .expect("must be set");
676
677        do_check();
678
679        let mut results = self.typeck_results.borrow_mut();
680
681        // Remove any added adjustments for `first_expr` during `do_check` and replace them with ours.
682        let mut adjustments = results.adjustments_mut();
683        let adjustments = adjustments.entry(first_expr.hir_id).or_default();
684
685        let mut ctx = ConfirmContext::new(self, first_expr.span, first_expr, first_expr);
686        *adjustments = ctx.create_ty_adjustments_from_pick(first_arg_type, pick).1;
687
688        // Restore original first provided arg type.
689        results.node_types_mut().insert(first_expr.hir_id, first_arg_type);
690    }
691
692    /// Gets scope for method-call like adjustments for the first argument of the call.
693    /// Now only delegations are processed this way.
694    fn get_scope_for_method_call_adjustments(
695        &self,
696        call_expr: &'tcx hir::Expr<'tcx>,
697        arg_exprs: &'tcx [hir::Expr<'tcx>],
698    ) -> Option<ProbeScope> {
699        // Check that we are inside delegation and processing its call. First, we check that
700        // the parent of call expr. is delegation and then make sure that it is compiler-generated
701        // by comparing their hir ids (otherwise we will encounter errors in nested delegations,
702        // see tests\ui\delegation\impl-reuse-pass.rs:237).
703        let parent_def = self.tcx.hir_get_parent_item(call_expr.hir_id).def_id;
704        let Some(info) = opt_get_delegation_info(self.tcx, parent_def) else { return None };
705
706        if call_expr.hir_id != info.call_expr_id {
707            return None;
708        };
709
710        let Some(path_res_id) = info.call_path_res else { return None };
711
712        // Check that delegation has first provided arg and that the call path
713        // resolves to a trait method (inherent methods are not yet supported).
714        if arg_exprs.is_empty()
715            || !self.tcx.opt_associated_item(path_res_id).is_some_and(|i| i.is_method())
716        {
717            return None;
718        }
719
720        Some(ProbeScope::Single(path_res_id))
721    }
722
723    /// Attempts to reinterpret `method(rcvr, args...)` as `rcvr.method(args...)`
724    /// and suggesting the fix if the method probe is successful.
725    fn suggest_call_as_method(
726        &self,
727        diag: &mut Diag<'_>,
728        segment: &'tcx hir::PathSegment<'tcx>,
729        arg_exprs: &'tcx [hir::Expr<'tcx>],
730        call_expr: &'tcx hir::Expr<'tcx>,
731        expected: Expectation<'tcx>,
732    ) {
733        if let [callee_expr, rest @ ..] = arg_exprs {
734            let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)
735            else {
736                return;
737            };
738
739            // First, do a probe with `IsSuggestion(true)` to avoid emitting
740            // any strange errors. If it's successful, then we'll do a true
741            // method lookup.
742            let Ok(pick) = self.lookup_probe_for_diagnostic(
743                segment.ident,
744                callee_ty,
745                call_expr,
746                // We didn't record the in scope traits during late resolution
747                // so we need to probe AllTraits unfortunately
748                ProbeScope::AllTraits,
749                expected.only_has_type(self),
750            ) else {
751                return;
752            };
753
754            let pick = self.confirm_method_for_diagnostic(
755                call_expr.span,
756                callee_expr,
757                call_expr,
758                callee_ty,
759                &pick,
760                segment,
761            );
762            if pick.illegal_sized_bound.is_some() {
763                return;
764            }
765
766            let Some(callee_expr_span) = callee_expr.span.find_ancestor_inside(call_expr.span)
767            else {
768                return;
769            };
770            let up_to_rcvr_span = segment.ident.span.until(callee_expr_span);
771            let rest_span = callee_expr_span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
772            let rest_snippet = if let Some(first) = rest.first() {
773                self.tcx
774                    .sess
775                    .source_map()
776                    .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
777            } else {
778                Ok(")".to_string())
779            };
780
781            if let Ok(rest_snippet) = rest_snippet {
782                let sugg = if self.precedence(callee_expr) >= ExprPrecedence::Unambiguous {
783                    ::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![
784                        (up_to_rcvr_span, "".to_string()),
785                        (rest_span, format!(".{}({rest_snippet}", segment.ident)),
786                    ]
787                } else {
788                    ::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![
789                        (up_to_rcvr_span, "(".to_string()),
790                        (rest_span, format!(").{}({rest_snippet}", segment.ident)),
791                    ]
792                };
793                let self_ty = self.resolve_vars_if_possible(pick.callee.sig.inputs()[0]);
794                diag.multipart_suggestion(
795                    ::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!(
796                        "use the `.` operator to call the method `{}{}` on `{self_ty}`",
797                        self.tcx
798                            .associated_item(pick.callee.def_id)
799                            .trait_container(self.tcx)
800                            .map_or_else(
801                                || String::new(),
802                                |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
803                            ),
804                        segment.ident
805                    ),
806                    sugg,
807                    Applicability::MaybeIncorrect,
808                );
809            }
810        }
811    }
812
813    fn report_invalid_callee(
814        &self,
815        call_expr: &'tcx hir::Expr<'tcx>,
816        callee_expr: &'tcx hir::Expr<'tcx>,
817        callee_ty: Ty<'tcx>,
818        arg_exprs: &'tcx [hir::Expr<'tcx>],
819    ) -> ErrorGuaranteed {
820        // Callee probe fails when APIT references errors, so suppress those
821        // errors here.
822        if let Some((_, _, args)) = self.extract_callable_info(callee_ty)
823            && let Err(err) = args.error_reported()
824        {
825            return err;
826        }
827
828        let mut unit_variant = None;
829        if let hir::ExprKind::Path(qpath) = &callee_expr.kind
830            && let Res::Def(def::DefKind::Ctor(kind, CtorKind::Const), _)
831                = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
832            // Only suggest removing parens if there are no arguments
833            && arg_exprs.is_empty()
834            && call_expr.span.contains(callee_expr.span)
835        {
836            let descr = match kind {
837                def::CtorOf::Struct => "struct",
838                def::CtorOf::Variant => "enum variant",
839            };
840            let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
841            unit_variant =
842                Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(&self.tcx, qpath)));
843        }
844
845        let callee_ty = self.resolve_vars_if_possible(callee_ty);
846        let mut path = None;
847        let mut err = self.dcx().create_err(errors::InvalidCallee {
848            span: callee_expr.span,
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 label = match (unit_variant, inner_callee_path) {
953                (Some((_, kind, path)), _) => {
954                    err.arg("kind", kind);
955                    err.arg("path", path);
956                    Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$kind} `{$path}` defined here"))msg!("{$kind} `{$path}` defined here"))
957                }
958                (_, Some(hir::QPath::Resolved(_, path))) => {
959                    self.tcx.sess.source_map().span_to_snippet(path.span).ok().map(|p| {
960                        err.arg("func", p);
961                        err.arg("ty", callee_ty);
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                            err.arg("ty", callee_ty);
972                            Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$local_name}` has type `{$ty}`"))msg!("`{$local_name}` has type `{$ty}`"))
973                        }
974                        Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
975                            err.arg("path", self.tcx.def_path_str(def_id));
976                            Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
977                        }
978                        _ => {
979                            err.arg("path", callee_ty.to_string());
980                            Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
981                        }
982                    }
983                }
984            };
985            if let Some(label) = label {
986                err.span_label(span, label);
987            }
988        }
989        err.emit()
990    }
991
992    fn confirm_deferred_closure_call(
993        &self,
994        call_expr: &'tcx hir::Expr<'tcx>,
995        arg_exprs: &'tcx [hir::Expr<'tcx>],
996        expected: Expectation<'tcx>,
997        closure_def_id: LocalDefId,
998        fn_sig: ty::FnSig<'tcx>,
999    ) -> Ty<'tcx> {
1000        // `fn_sig` is the *signature* of the closure being called. We
1001        // don't know the full details yet (`Fn` vs `FnMut` etc), but we
1002        // do know the types expected for each argument and the return
1003        // type.
1004        self.check_argument_types(
1005            call_expr.span,
1006            call_expr,
1007            fn_sig.inputs(),
1008            fn_sig.output(),
1009            expected,
1010            arg_exprs,
1011            fn_sig.c_variadic(),
1012            TupleArgumentsFlag::TupleArguments,
1013            Some(closure_def_id.to_def_id()),
1014        );
1015
1016        fn_sig.output()
1017    }
1018
1019    #[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(1019u32),
                                    ::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))]
1020    pub(super) fn enforce_context_effects(
1021        &self,
1022        call_hir_id: Option<HirId>,
1023        span: Span,
1024        callee_did: DefId,
1025        callee_args: GenericArgsRef<'tcx>,
1026    ) {
1027        // FIXME(const_trait_impl): We should be enforcing these effects unconditionally.
1028        // This can be done as soon as we convert the standard library back to
1029        // using const traits, since if we were to enforce these conditions now,
1030        // we'd fail on basically every builtin trait call (i.e. `1 + 2`).
1031        if !self.tcx.features().const_trait_impl() {
1032            return;
1033        }
1034
1035        // If we have `rustc_do_not_const_check`, do not check `[const]` bounds.
1036        if self.has_rustc_attrs && find_attr!(self.tcx, self.body_id, RustcDoNotConstCheck) {
1037            return;
1038        }
1039
1040        let host = match self.tcx.hir_body_const_context(self.body_id) {
1041            Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
1042                ty::BoundConstness::Const
1043            }
1044            Some(hir::ConstContext::ConstFn) => ty::BoundConstness::Maybe,
1045            None => return,
1046        };
1047
1048        // FIXME(const_trait_impl): Should this be `is_const_fn_raw`? It depends on if we move
1049        // const stability checking here too, I guess.
1050        if self.tcx.is_conditionally_const(callee_did) {
1051            let q = self.tcx.const_conditions(callee_did);
1052            for (idx, (cond, pred_span)) in
1053                q.instantiate(self.tcx, callee_args).into_iter().enumerate()
1054            {
1055                let cause = self.cause(
1056                    span,
1057                    if let Some(hir_id) = call_hir_id {
1058                        ObligationCauseCode::HostEffectInExpr(callee_did, pred_span, hir_id, idx)
1059                    } else {
1060                        ObligationCauseCode::WhereClause(callee_did, pred_span)
1061                    },
1062                );
1063                self.register_predicate(Obligation::new(
1064                    self.tcx,
1065                    cause,
1066                    self.param_env,
1067                    cond.to_host_effect_clause(self.tcx, host).skip_norm_wip(),
1068                ));
1069            }
1070        } else {
1071            // FIXME(const_trait_impl): This should eventually be caught here.
1072            // For now, though, we defer some const checking to MIR.
1073        }
1074    }
1075
1076    fn confirm_overloaded_call(
1077        &self,
1078        call_expr: &'tcx hir::Expr<'tcx>,
1079        arg_exprs: &'tcx [hir::Expr<'tcx>],
1080        expected: Expectation<'tcx>,
1081        method: MethodCallee<'tcx>,
1082    ) -> Ty<'tcx> {
1083        self.check_argument_types(
1084            call_expr.span,
1085            call_expr,
1086            &method.sig.inputs()[1..],
1087            method.sig.output(),
1088            expected,
1089            arg_exprs,
1090            method.sig.c_variadic(),
1091            TupleArgumentsFlag::TupleArguments,
1092            Some(method.def_id),
1093        );
1094
1095        self.write_method_call_and_enforce_effects(call_expr.hir_id, call_expr.span, method);
1096
1097        method.sig.output()
1098    }
1099}
1100
1101#[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)]
1102pub(crate) struct DeferredCallResolution<'tcx> {
1103    call_expr: &'tcx hir::Expr<'tcx>,
1104    callee_expr: &'tcx hir::Expr<'tcx>,
1105    closure_ty: Ty<'tcx>,
1106    adjustments: Vec<Adjustment<'tcx>>,
1107    fn_sig: ty::FnSig<'tcx>,
1108}
1109
1110impl<'a, 'tcx> DeferredCallResolution<'tcx> {
1111    pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
1112        {
    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:1112",
                        "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(1112u32),
                        ::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);
1113
1114        // we should not be invoked until the closure kind has been
1115        // determined by upvar inference
1116        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());
1117
1118        // We may now know enough to figure out fn vs fnmut etc.
1119        match fcx.try_overloaded_call_traits(self.call_expr, self.closure_ty, None) {
1120            Some((autoref, method_callee)) => {
1121                // One problem is that when we get here, we are going
1122                // to have a newly instantiated function signature
1123                // from the call trait. This has to be reconciled with
1124                // the older function signature we had before. In
1125                // principle we *should* be able to fn_sigs(), but we
1126                // can't because of the annoying need for a TypeTrace.
1127                // (This always bites me, should find a way to
1128                // refactor it.)
1129                let method_sig = method_callee.sig;
1130
1131                {
    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:1131",
                        "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(1131u32),
                        ::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);
1132
1133                for (method_arg_ty, self_arg_ty) in
1134                    iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
1135                {
1136                    fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
1137                }
1138
1139                fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
1140
1141                let mut adjustments = self.adjustments;
1142                adjustments.extend(autoref);
1143                fcx.apply_adjustments(self.callee_expr, adjustments);
1144
1145                fcx.write_method_call_and_enforce_effects(
1146                    self.call_expr.hir_id,
1147                    self.call_expr.span,
1148                    method_callee,
1149                );
1150            }
1151            None => {
1152                ::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!(
1153                    self.call_expr.span,
1154                    "Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{}`",
1155                    self.closure_ty
1156                )
1157            }
1158        }
1159    }
1160}