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_infer::infer::BoundRegionConversionTime;
11use rustc_infer::traits::{Obligation, ObligationCause, ObligationCauseCode};
12use rustc_middle::ty::adjustment::{
13    Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
14};
15use rustc_middle::ty::{self, FnSig, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
16use rustc_middle::{bug, span_bug};
17use rustc_span::def_id::LocalDefId;
18use rustc_span::{Ident, Span, sym};
19use rustc_target::spec::{AbiMap, AbiMapping};
20use rustc_trait_selection::error_reporting::traits::DefIdOrName;
21use rustc_trait_selection::infer::InferCtxtExt as _;
22use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
23use tracing::{debug, instrument};
24
25use super::method::MethodCallee;
26use super::method::probe::ProbeScope;
27use super::{Expectation, FnCtxt, TupleArgumentsFlag};
28use crate::diagnostics;
29use crate::method::TreatNotYetDefinedOpaques;
30use crate::method::confirm::ConfirmContext;
31use crate::method::probe::{IsSuggestion, Mode};
32
33/// Checks that it is legal to call methods of the trait corresponding
34/// to `trait_id` (this only cares about the trait, not the specific
35/// method that is called).
36pub(crate) fn check_legal_trait_for_method_call(
37    tcx: TyCtxt<'_>,
38    span: Span,
39    receiver: Option<Span>,
40    expr_span: Span,
41    trait_id: DefId,
42    body_id: DefId,
43) -> Result<(), ErrorGuaranteed> {
44    if tcx.is_lang_item(trait_id, LangItem::Drop)
45        // Allow calling `Drop::pin_drop` in `Drop::drop`
46        && !tcx.is_lang_item(tcx.parent(body_id), LangItem::Drop)
47    {
48        let sugg = if let Some(receiver) = receiver.filter(|s| !s.is_empty()) {
49            diagnostics::ExplicitDestructorCallSugg::Snippet {
50                lo: expr_span.shrink_to_lo().to(receiver.shrink_to_lo()),
51                hi: receiver.shrink_to_hi().to(expr_span.shrink_to_hi()),
52            }
53        } else {
54            diagnostics::ExplicitDestructorCallSugg::Empty(span)
55        };
56        return Err(tcx.dcx().emit_err(diagnostics::ExplicitDestructorCall { span, sugg }));
57    }
58    tcx.ensure_result().coherent_trait(trait_id)
59}
60
61#[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)]
62enum CallStep<'tcx> {
63    Builtin(Ty<'tcx>),
64    DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
65    /// Call overloading when callee implements one of the Fn* traits.
66    Overloaded(MethodCallee<'tcx>),
67}
68
69impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
70    #[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(70u32),
                                    ::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(diagnostics::ScalableVectorCtor {
                            span: callee_expr.span,
                            ty: autoderef.final_ty(),
                        });
                err.span_label(callee_expr.span,
                    "you can create scalable vectors using intrinsics");
                Ty::new_error(self.tcx, err.emit());
            }
            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))]
71    pub(crate) fn check_expr_call(
72        &self,
73        call_expr: &'tcx hir::Expr<'tcx>,
74        callee_expr: &'tcx hir::Expr<'tcx>,
75        arg_exprs: &'tcx [hir::Expr<'tcx>],
76        expected: Expectation<'tcx>,
77    ) -> Ty<'tcx> {
78        let original_callee_ty = match &callee_expr.kind {
79            hir::ExprKind::Path(hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)) => self
80                .check_expr_with_expectation_and_args(
81                    callee_expr,
82                    Expectation::NoExpectation,
83                    Some((call_expr, arg_exprs)),
84                ),
85            _ => self.check_expr(callee_expr),
86        };
87
88        let expr_ty = self.resolve_vars_with_obligations(original_callee_ty);
89
90        let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
91        let mut result = None;
92        while result.is_none() && autoderef.next().is_some() {
93            result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
94        }
95
96        match *autoderef.final_ty().kind() {
97            ty::FnDef(def_id, _) => {
98                let abi = self.tcx.fn_sig(def_id).skip_binder().skip_binder().abi();
99                self.check_call_abi(abi, call_expr.span);
100            }
101            ty::FnPtr(_, header) => {
102                self.check_call_abi(header.abi(), call_expr.span);
103            }
104            _ => { /* cannot have a non-rust abi */ }
105        }
106
107        if self.is_scalable_vector_ctor(autoderef.final_ty()) {
108            let mut err = self.dcx().create_err(diagnostics::ScalableVectorCtor {
109                span: callee_expr.span,
110                ty: autoderef.final_ty(),
111            });
112            err.span_label(callee_expr.span, "you can create scalable vectors using intrinsics");
113            Ty::new_error(self.tcx, err.emit());
114        }
115
116        self.register_predicates(autoderef.into_obligations());
117
118        let output = match result {
119            None => {
120                // Check all of the arg expressions, but with no expectations
121                // since we don't have a signature to compare them to.
122                for arg in arg_exprs {
123                    self.check_expr(arg);
124                }
125
126                if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &callee_expr.kind
127                    && let [segment] = path.segments
128                {
129                    self.dcx().try_steal_modify_and_emit_err(
130                        segment.ident.span,
131                        StashKey::CallIntoMethod,
132                        |err| {
133                            // Try suggesting `foo(a)` -> `a.foo()` if possible.
134                            self.suggest_call_as_method(
135                                err, segment, arg_exprs, call_expr, expected,
136                            );
137                        },
138                    );
139                }
140
141                let guar = self.report_invalid_callee(call_expr, callee_expr, expr_ty, arg_exprs);
142                Ty::new_error(self.tcx, guar)
143            }
144
145            Some(CallStep::Builtin(callee_ty)) => {
146                self.confirm_builtin_call(call_expr, callee_expr, callee_ty, arg_exprs, expected)
147            }
148
149            Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
150                self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, def_id, fn_sig)
151            }
152
153            Some(CallStep::Overloaded(method_callee)) => {
154                self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
155            }
156        };
157
158        // we must check that return type of called functions is WF:
159        self.register_wf_obligation(
160            output.into(),
161            call_expr.span,
162            ObligationCauseCode::WellFormed(None),
163        );
164
165        output
166    }
167
168    /// Can a function with this ABI be called with a rust call expression?
169    ///
170    /// Some ABIs cannot be called from rust, either because rust does not know how to generate
171    /// code for the call, or because a call does not semantically make sense.
172    pub(crate) fn check_call_abi(&self, abi: ExternAbi, span: Span) {
173        let canon_abi = match AbiMap::from_target(&self.sess().target).canonize_abi(abi, false) {
174            AbiMapping::Direct(canon_abi) | AbiMapping::Deprecated(canon_abi) => canon_abi,
175            AbiMapping::Invalid => {
176                // This should be reported elsewhere, but we want to taint this body
177                // so that we don't try to evaluate calls to ABIs that are invalid.
178                let guar = self.dcx().span_delayed_bug(
179                    span,
180                    ::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}"),
181                );
182                self.set_tainted_by_errors(guar);
183                return;
184            }
185        };
186
187        match canon_abi {
188            // Rust doesn't know how to call functions with this ABI.
189            CanonAbi::Custom
190            // The interrupt ABIs should only be called by the CPU. They have complex
191            // pre- and postconditions, and can use non-standard instructions like `iret` on x86.
192            | CanonAbi::Interrupt(_) => {
193                let err = crate::diagnostics::AbiCannotBeCalled { span, abi };
194                self.tcx.dcx().emit_err(err);
195            }
196
197            // This is an entry point for the host, and cannot be called directly.
198            CanonAbi::GpuKernel => {
199                let err = crate::diagnostics::GpuKernelAbiCannotBeCalled { span };
200                self.tcx.dcx().emit_err(err);
201            }
202
203            CanonAbi::C
204            | CanonAbi::Rust
205            | CanonAbi::RustCold
206            | CanonAbi::RustPreserveNone
207            | CanonAbi::RustTail
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(diagnostics::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) = self.tcx.hir_opt_delegation_info(parent_def) else {
704            return None;
705        };
706
707        if call_expr.hir_id != info.call_expr_id {
708            return None;
709        };
710
711        let Some(path_res_id) = info.call_path_res else { return None };
712
713        // Check that delegation has first provided arg and that the call path
714        // resolves to a trait method (inherent methods are not yet supported).
715        if arg_exprs.is_empty()
716            || !self.tcx.opt_associated_item(path_res_id).is_some_and(|i| i.is_method())
717        {
718            return None;
719        }
720
721        Some(ProbeScope::Single(path_res_id))
722    }
723
724    /// Attempts to reinterpret `method(rcvr, args...)` as `rcvr.method(args...)`
725    /// and suggesting the fix if the method probe is successful.
726    fn suggest_call_as_method(
727        &self,
728        diag: &mut Diag<'_>,
729        segment: &'tcx hir::PathSegment<'tcx>,
730        arg_exprs: &'tcx [hir::Expr<'tcx>],
731        call_expr: &'tcx hir::Expr<'tcx>,
732        expected: Expectation<'tcx>,
733    ) {
734        if let [callee_expr, rest @ ..] = arg_exprs {
735            let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)
736            else {
737                return;
738            };
739
740            // First, do a probe with `IsSuggestion(true)` to avoid emitting
741            // any strange errors. If it's successful, then we'll do a true
742            // method lookup.
743            let Ok(pick) = self.lookup_probe_for_diagnostic(
744                segment.ident,
745                callee_ty,
746                call_expr,
747                // We didn't record the in scope traits during late resolution
748                // so we need to probe AllTraits unfortunately
749                ProbeScope::AllTraits,
750                expected.only_has_type(self),
751            ) else {
752                return;
753            };
754
755            let pick = self.confirm_method_for_diagnostic(
756                call_expr.span,
757                callee_expr,
758                call_expr,
759                callee_ty,
760                &pick,
761                segment,
762            );
763            if pick.illegal_sized_bound.is_some() {
764                return;
765            }
766
767            let Some(callee_expr_span) = callee_expr.span.find_ancestor_inside(call_expr.span)
768            else {
769                return;
770            };
771            let up_to_rcvr_span = segment.ident.span.until(callee_expr_span);
772            let rest_span = callee_expr_span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
773            let rest_snippet = if let Some(first) = rest.first() {
774                self.tcx
775                    .sess
776                    .source_map()
777                    .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
778            } else {
779                Ok(")".to_string())
780            };
781
782            if let Ok(rest_snippet) = rest_snippet {
783                let sugg = if self.precedence(callee_expr) >= ExprPrecedence::Unambiguous {
784                    ::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![
785                        (up_to_rcvr_span, "".to_string()),
786                        (rest_span, format!(".{}({rest_snippet}", segment.ident)),
787                    ]
788                } else {
789                    ::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![
790                        (up_to_rcvr_span, "(".to_string()),
791                        (rest_span, format!(").{}({rest_snippet}", segment.ident)),
792                    ]
793                };
794                let self_ty = self.resolve_vars_if_possible(pick.callee.sig.inputs()[0]);
795                diag.multipart_suggestion(
796                    ::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!(
797                        "use the `.` operator to call the method `{}{}` on `{self_ty}`",
798                        self.tcx
799                            .associated_item(pick.callee.def_id)
800                            .trait_container(self.tcx)
801                            .map_or_else(
802                                || String::new(),
803                                |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
804                            ),
805                        segment.ident
806                    ),
807                    sugg,
808                    Applicability::MaybeIncorrect,
809                );
810            }
811        }
812    }
813
814    fn report_invalid_callee(
815        &self,
816        call_expr: &'tcx hir::Expr<'tcx>,
817        callee_expr: &'tcx hir::Expr<'tcx>,
818        callee_ty: Ty<'tcx>,
819        arg_exprs: &'tcx [hir::Expr<'tcx>],
820    ) -> ErrorGuaranteed {
821        // Callee probe fails when APIT references errors, so suppress those
822        // errors here.
823        if let Some((_, _, args)) = self.extract_callable_info(callee_ty)
824            && let Err(err) = args.error_reported()
825        {
826            return err;
827        }
828
829        let mut unit_variant = None;
830        if let hir::ExprKind::Path(qpath) = &callee_expr.kind
831            && let Res::Def(def::DefKind::Ctor(kind, CtorKind::Const), _)
832                = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
833            // Only suggest removing parens if there are no arguments
834            && arg_exprs.is_empty()
835            && call_expr.span.contains(callee_expr.span)
836        {
837            let descr = match kind {
838                def::CtorOf::Struct => "struct",
839                def::CtorOf::Variant => "enum variant",
840            };
841            let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
842            unit_variant =
843                Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(&self.tcx, qpath)));
844        }
845
846        let callee_ty = self.resolve_vars_if_possible(callee_ty);
847        let mut path = None;
848        let mut err = self.dcx().create_err(diagnostics::InvalidCallee {
849            span: callee_expr.span,
850            found: match &unit_variant {
851                Some((_, kind, path)) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}`", kind, path))
    })format!("{kind} `{path}`"),
852                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)),
853            },
854        });
855        *err.long_ty_path() = path;
856        if callee_ty.references_error() {
857            err.downgrade_to_delayed_bug();
858        }
859
860        self.identify_bad_closure_def_and_call(
861            &mut err,
862            call_expr.hir_id,
863            &callee_expr.kind,
864            callee_expr.span,
865        );
866
867        if let Some((removal_span, kind, path)) = &unit_variant {
868            err.span_suggestion_verbose(
869                *removal_span,
870                ::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!(
871                    "`{path}` is a unit {kind}, and does not take parentheses to be constructed",
872                ),
873                "",
874                Applicability::MachineApplicable,
875            );
876        }
877
878        if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = callee_expr.kind
879            && let Res::Local(_) = path.res
880            && let [segment] = &path.segments
881        {
882            for id in self.tcx.hir_free_items() {
883                if let Some(node) = self.tcx.hir_get_if_local(id.owner_id.into())
884                    && let hir::Node::Item(item) = node
885                    && let hir::ItemKind::Fn { ident, .. } = item.kind
886                    && ident.name == segment.ident.name
887                {
888                    err.span_label(
889                        self.tcx.def_span(id.owner_id),
890                        "this function of the same name is available here, but it's shadowed by \
891                         the local binding",
892                    );
893                }
894            }
895        }
896
897        let mut inner_callee_path = None;
898        let def = match callee_expr.kind {
899            hir::ExprKind::Path(ref qpath) => {
900                self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
901            }
902            hir::ExprKind::Call(inner_callee, _) => {
903                if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
904                    inner_callee_path = Some(inner_qpath);
905                    self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
906                } else {
907                    Res::Err
908                }
909            }
910            _ => Res::Err,
911        };
912
913        if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
914            // If the call spans more than one line and the callee kind is
915            // itself another `ExprCall`, that's a clue that we might just be
916            // missing a semicolon (#51055, #106515).
917            let call_is_multiline = self
918                .tcx
919                .sess
920                .source_map()
921                .is_multiline(call_expr.span.with_lo(callee_expr.span.hi()))
922                && call_expr.span.eq_ctxt(callee_expr.span);
923            if call_is_multiline {
924                err.span_suggestion(
925                    callee_expr.span.shrink_to_hi(),
926                    "consider using a semicolon here to finish the statement",
927                    ";",
928                    Applicability::MaybeIncorrect,
929                );
930            }
931            if let Some((maybe_def, output_ty, _)) = self.extract_callable_info(callee_ty)
932                && !self.type_is_sized_modulo_regions(self.param_env, output_ty)
933            {
934                let descr = match maybe_def {
935                    DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
936                    DefIdOrName::Name(name) => name,
937                };
938                err.span_label(
939                    callee_expr.span,
940                    ::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")
941                );
942                if let DefIdOrName::DefId(def_id) = maybe_def
943                    && let Some(def_span) = self.tcx.hir_span_if_local(def_id)
944                {
945                    err.span_label(def_span, "the callable type is defined here");
946                }
947            } else {
948                err.span_label(call_expr.span, "call expression requires function");
949            }
950        }
951
952        if let Some(span) = self.tcx.hir_res_span(def) {
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                        err.arg("ty", callee_ty);
963                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$func}` defined here returns `{$ty}`"))msg!("`{$func}` defined here returns `{$ty}`")
964                    })
965                }
966                _ => {
967                    match def {
968                        // Emit a different diagnostic for local variables, as they are not
969                        // type definitions themselves, but rather variables *of* that type.
970                        Res::Local(hir_id) => {
971                            err.arg("local_name", self.tcx.hir_name(hir_id));
972                            err.arg("ty", callee_ty);
973                            Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$local_name}` has type `{$ty}`"))msg!("`{$local_name}` has type `{$ty}`"))
974                        }
975                        Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
976                            err.arg("path", self.tcx.def_path_str(def_id));
977                            Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
978                        }
979                        _ => {
980                            err.arg("path", callee_ty.to_string());
981                            Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
982                        }
983                    }
984                }
985            };
986            if let Some(label) = label {
987                err.span_label(span, label);
988            }
989        }
990        err.emit()
991    }
992
993    fn confirm_deferred_closure_call(
994        &self,
995        call_expr: &'tcx hir::Expr<'tcx>,
996        arg_exprs: &'tcx [hir::Expr<'tcx>],
997        expected: Expectation<'tcx>,
998        closure_def_id: LocalDefId,
999        fn_sig: ty::FnSig<'tcx>,
1000    ) -> Ty<'tcx> {
1001        // `fn_sig` is the *signature* of the closure being called. We
1002        // don't know the full details yet (`Fn` vs `FnMut` etc), but we
1003        // do know the types expected for each argument and the return
1004        // type.
1005        self.check_argument_types(
1006            call_expr.span,
1007            call_expr,
1008            fn_sig.inputs(),
1009            fn_sig.output(),
1010            expected,
1011            arg_exprs,
1012            fn_sig.c_variadic(),
1013            TupleArgumentsFlag::TupleArguments,
1014            Some(closure_def_id.to_def_id()),
1015        );
1016
1017        fn_sig.output()
1018    }
1019
1020    #[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(1020u32),
                                    ::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;
        }
        {
            let const_context = self.tcx.hir_body_const_context(self.body_id);
            if let hir::Constness::Const { always: true } =
                    self.tcx.constness(callee_did) {
                match const_context {
                    Some(hir::ConstContext::Const { .. } |
                        hir::ConstContext::Static(_)) => {}
                    Some(hir::ConstContext::ConstFn) | None => {
                        self.dcx().span_err(span,
                            "comptime fns can only be called at compile time");
                    }
                }
            }
            if !self.tcx.features().const_trait_impl() { return; }
            if self.has_rustc_attrs &&
                    {
                            {
                                'done:
                                    {
                                    for i in
                                        ::rustc_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 const_context {
                    Some(hir::ConstContext::Const { .. } |
                        hir::ConstContext::Static(_)) => {
                        ty::BoundConstness::Const
                    }
                    Some(hir::ConstContext::ConstFn) =>
                        ty::BoundConstness::Maybe,
                    None => return,
                };
            if self.tcx.is_conditionally_const(callee_did) {
                let q = self.tcx.const_conditions(callee_did);
                for (idx, (cond, pred_span)) in
                    q.instantiate(self.tcx, callee_args).into_iter().enumerate()
                    {
                    let cause =
                        self.cause(span,
                            if let Some(hir_id) = call_hir_id {
                                ObligationCauseCode::HostEffectInExpr(callee_did, pred_span,
                                    hir_id, idx)
                            } else {
                                ObligationCauseCode::WhereClause(callee_did, pred_span)
                            });
                    self.register_predicate(Obligation::new(self.tcx, cause,
                            self.param_env,
                            cond.to_host_effect_clause(self.tcx,
                                    host).skip_norm_wip()));
                }
            } else {}
        }
    }
}#[tracing::instrument(level = "debug", skip(self, span))]
1021    pub(super) fn enforce_context_effects(
1022        &self,
1023        call_hir_id: Option<HirId>,
1024        span: Span,
1025        callee_did: DefId,
1026        callee_args: GenericArgsRef<'tcx>,
1027    ) {
1028        let const_context = self.tcx.hir_body_const_context(self.body_id);
1029
1030        if let hir::Constness::Const { always: true } = self.tcx.constness(callee_did) {
1031            match const_context {
1032                Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {}
1033                Some(hir::ConstContext::ConstFn) | None => {
1034                    self.dcx().span_err(span, "comptime fns can only be called at compile time");
1035                }
1036            }
1037        }
1038
1039        // FIXME(const_trait_impl): We should be enforcing these effects unconditionally.
1040        // This can be done as soon as we convert the standard library back to
1041        // using const traits, since if we were to enforce these conditions now,
1042        // we'd fail on basically every builtin trait call (i.e. `1 + 2`).
1043        if !self.tcx.features().const_trait_impl() {
1044            return;
1045        }
1046
1047        // If we have `rustc_do_not_const_check`, do not check `[const]` bounds.
1048        if self.has_rustc_attrs && find_attr!(self.tcx, self.body_id, RustcDoNotConstCheck) {
1049            return;
1050        }
1051
1052        let host = match const_context {
1053            Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
1054                ty::BoundConstness::Const
1055            }
1056            Some(hir::ConstContext::ConstFn) => ty::BoundConstness::Maybe,
1057            None => return,
1058        };
1059
1060        // FIXME(const_trait_impl): Should this be `is_const_fn_raw`? It depends on if we move
1061        // const stability checking here too, I guess.
1062        if self.tcx.is_conditionally_const(callee_did) {
1063            let q = self.tcx.const_conditions(callee_did);
1064            for (idx, (cond, pred_span)) in
1065                q.instantiate(self.tcx, callee_args).into_iter().enumerate()
1066            {
1067                let cause = self.cause(
1068                    span,
1069                    if let Some(hir_id) = call_hir_id {
1070                        ObligationCauseCode::HostEffectInExpr(callee_did, pred_span, hir_id, idx)
1071                    } else {
1072                        ObligationCauseCode::WhereClause(callee_did, pred_span)
1073                    },
1074                );
1075                self.register_predicate(Obligation::new(
1076                    self.tcx,
1077                    cause,
1078                    self.param_env,
1079                    cond.to_host_effect_clause(self.tcx, host).skip_norm_wip(),
1080                ));
1081            }
1082        } else {
1083            // FIXME(const_trait_impl): This should eventually be caught here.
1084            // For now, though, we defer some const checking to MIR.
1085        }
1086    }
1087
1088    fn confirm_overloaded_call(
1089        &self,
1090        call_expr: &'tcx hir::Expr<'tcx>,
1091        arg_exprs: &'tcx [hir::Expr<'tcx>],
1092        expected: Expectation<'tcx>,
1093        method: MethodCallee<'tcx>,
1094    ) -> Ty<'tcx> {
1095        self.check_argument_types(
1096            call_expr.span,
1097            call_expr,
1098            &method.sig.inputs()[1..],
1099            method.sig.output(),
1100            expected,
1101            arg_exprs,
1102            method.sig.c_variadic(),
1103            TupleArgumentsFlag::TupleArguments,
1104            Some(method.def_id),
1105        );
1106
1107        self.write_method_call_and_enforce_effects(call_expr.hir_id, call_expr.span, method);
1108
1109        method.sig.output()
1110    }
1111}
1112
1113#[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)]
1114pub(crate) struct DeferredCallResolution<'tcx> {
1115    call_expr: &'tcx hir::Expr<'tcx>,
1116    callee_expr: &'tcx hir::Expr<'tcx>,
1117    closure_ty: Ty<'tcx>,
1118    adjustments: Vec<Adjustment<'tcx>>,
1119    fn_sig: ty::FnSig<'tcx>,
1120}
1121
1122impl<'a, 'tcx> DeferredCallResolution<'tcx> {
1123    pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
1124        {
    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:1124",
                        "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(1124u32),
                        ::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);
1125
1126        // we should not be invoked until the closure kind has been
1127        // determined by upvar inference
1128        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());
1129
1130        // We may now know enough to figure out fn vs fnmut etc.
1131        match fcx.try_overloaded_call_traits(self.call_expr, self.closure_ty, None) {
1132            Some((autoref, method_callee)) => {
1133                // One problem is that when we get here, we are going
1134                // to have a newly instantiated function signature
1135                // from the call trait. This has to be reconciled with
1136                // the older function signature we had before. In
1137                // principle we *should* be able to fn_sigs(), but we
1138                // can't because of the annoying need for a TypeTrace.
1139                // (This always bites me, should find a way to
1140                // refactor it.)
1141                let method_sig = method_callee.sig;
1142
1143                {
    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:1143",
                        "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(1143u32),
                        ::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);
1144
1145                for (method_arg_ty, self_arg_ty) in
1146                    iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
1147                {
1148                    fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
1149                }
1150
1151                fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
1152
1153                let mut adjustments = self.adjustments;
1154                adjustments.extend(autoref);
1155                fcx.apply_adjustments(self.callee_expr, adjustments);
1156
1157                fcx.write_method_call_and_enforce_effects(
1158                    self.call_expr.hir_id,
1159                    self.call_expr.span,
1160                    method_callee,
1161                );
1162            }
1163            None => {
1164                ::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!(
1165                    self.call_expr.span,
1166                    "Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{}`",
1167                    self.closure_ty
1168                )
1169            }
1170        }
1171    }
1172}