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_data_structures::fx::{FxHashMap, FxIndexSet};
6use rustc_errors::{Applicability, Diag, ErrorGuaranteed, StashKey, msg};
7use rustc_hir::def::{self, CtorKind, Namespace, Res};
8use rustc_hir::def_id::DefId;
9use rustc_hir::{self as hir, HirId, LangItem, find_attr};
10use rustc_hir_analysis::autoderef::Autoderef;
11use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes};
12use rustc_infer::traits::{Obligation, ObligationCause, ObligationCauseCode};
13use rustc_middle::bug;
14use rustc_middle::ty::adjustment::{
15    Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
16};
17use rustc_middle::ty::{self, FnSig, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
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::diagnostics;
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_def_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_def_id), LangItem::Drop)
48    {
49        let sugg = if let Some(receiver) = receiver.filter(|s| !s.is_empty()) {
50            diagnostics::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            diagnostics::ExplicitDestructorCallSugg::Empty(span)
56        };
57        return Err(tcx.dcx().emit_err(diagnostics::ExplicitDestructorCall { span, sugg }));
58    }
59    tcx.ensure_result().coherent_trait(trait_id)
60}
61
62/// State machine for typechecking a call, based on the callee type.
63#[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)]
64enum CallStep<'tcx> {
65    /// Typecheck a call to a function definition or pointer.
66    /// Includes functions with splatted arguments.
67    Builtin(Ty<'tcx>),
68    /// Deferred closure Fn* trait typechecking, when the callee is a closure.
69    DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
70    /// Call overloading when callee implements one of the Fn* traits.
71    Overloaded(MethodCallee<'tcx>),
72}
73
74impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
75    #[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(75u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("call_expr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("call_expr");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("callee_expr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("callee_expr");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("arg_exprs")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("arg_exprs");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expected")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expected");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&call_expr)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_expr)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg_exprs)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let const_context =
                self.tcx.hir_body_const_context(self.body_def_id);
            if let hir::Constness::Const { always: true } =
                    self.tcx.constness(callee_did) {
                match const_context {
                    Some(hir::ConstContext::Const { .. } |
                        hir::ConstContext::Static(_)) => {}
                    Some(hir::ConstContext::ConstFn) | None => {
                        self.dcx().span_err(span,
                            "comptime fns can only be called at compile time");
                    }
                }
            }
            if !self.tcx.features().const_trait_impl() { return; }
            if self.has_rustc_attrs &&
                    {
                            {
                                'done:
                                    {
                                    for i in
                                        ::rustc_hir::attrs::HasAttrs::get_attrs(self.body_def_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))]
1085    pub(super) fn enforce_context_effects(
1086        &self,
1087        call_hir_id: Option<HirId>,
1088        span: Span,
1089        callee_did: DefId,
1090        callee_args: GenericArgsRef<'tcx>,
1091    ) {
1092        let const_context = self.tcx.hir_body_const_context(self.body_def_id);
1093
1094        if let hir::Constness::Const { always: true } = self.tcx.constness(callee_did) {
1095            match const_context {
1096                Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {}
1097                Some(hir::ConstContext::ConstFn) | None => {
1098                    self.dcx().span_err(span, "comptime fns can only be called at compile time");
1099                }
1100            }
1101        }
1102
1103        // FIXME(const_trait_impl): We should be enforcing these effects unconditionally.
1104        // This can be done as soon as we convert the standard library back to
1105        // using const traits, since if we were to enforce these conditions now,
1106        // we'd fail on basically every builtin trait call (i.e. `1 + 2`).
1107        if !self.tcx.features().const_trait_impl() {
1108            return;
1109        }
1110
1111        // If we have `rustc_do_not_const_check`, do not check `[const]` bounds.
1112        if self.has_rustc_attrs && find_attr!(self.tcx, self.body_def_id, RustcDoNotConstCheck) {
1113            return;
1114        }
1115
1116        let host = match const_context {
1117            Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
1118                ty::BoundConstness::Const
1119            }
1120            Some(hir::ConstContext::ConstFn) => ty::BoundConstness::Maybe,
1121            None => return,
1122        };
1123
1124        // FIXME(const_trait_impl): Should this be `is_const_fn_raw`? It depends on if we move
1125        // const stability checking here too, I guess.
1126        if self.tcx.is_conditionally_const(callee_did) {
1127            let q = self.tcx.const_conditions(callee_did);
1128            for (idx, (cond, pred_span)) in
1129                q.instantiate(self.tcx, callee_args).into_iter().enumerate()
1130            {
1131                let cause = self.cause(
1132                    span,
1133                    if let Some(hir_id) = call_hir_id {
1134                        ObligationCauseCode::HostEffectInExpr(callee_did, pred_span, hir_id, idx)
1135                    } else {
1136                        ObligationCauseCode::WhereClause(callee_did, pred_span)
1137                    },
1138                );
1139                self.register_predicate(Obligation::new(
1140                    self.tcx,
1141                    cause,
1142                    self.param_env,
1143                    cond.to_host_effect_clause(self.tcx, host).skip_norm_wip(),
1144                ));
1145            }
1146        } else {
1147            // FIXME(const_trait_impl): This should eventually be caught here.
1148            // For now, though, we defer some const checking to MIR.
1149        }
1150    }
1151
1152    fn confirm_overloaded_call(
1153        &self,
1154        call_expr: &'tcx hir::Expr<'tcx>,
1155        arg_exprs: &'tcx [hir::Expr<'tcx>],
1156        expected: Expectation<'tcx>,
1157        method: MethodCallee<'tcx>,
1158    ) -> Ty<'tcx> {
1159        // FIXME(splat): if we ever support splatting here, decrement the splatted index, because
1160        // the receiver argument is removed below.
1161        {
    match (&method.sig.fn_sig_kind.splatted(), &None) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("splatting is not supported on RustCall tuples")));
            }
        }
    }
};assert_eq!(
1162            method.sig.fn_sig_kind.splatted(),
1163            None,
1164            "splatting is not supported on RustCall tuples",
1165        );
1166        self.check_argument_types(
1167            call_expr.span,
1168            call_expr,
1169            &method.sig.inputs()[1..],
1170            method.sig.output(),
1171            expected,
1172            arg_exprs,
1173            method.sig.fn_sig_kind.c_variadic(),
1174            TupleArgumentsFlag::rust_fn_trait_call(),
1175            Some(method.def_id),
1176            None,
1177        );
1178
1179        self.write_method_call_and_enforce_effects(call_expr.hir_id, call_expr.span, method);
1180
1181        method.sig.output()
1182    }
1183}
1184
1185#[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)]
1186pub(crate) struct DeferredCallResolution<'tcx> {
1187    call_expr: &'tcx hir::Expr<'tcx>,
1188    callee_expr: &'tcx hir::Expr<'tcx>,
1189    closure_ty: Ty<'tcx>,
1190    adjustments: Vec<Adjustment<'tcx>>,
1191    fn_sig: ty::FnSig<'tcx>,
1192}
1193
1194impl<'a, 'tcx> DeferredCallResolution<'tcx> {
1195    pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
1196        {
    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:1196",
                        "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(1196u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("DeferredCallResolution::resolve() {0:?}",
                                                    self) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("DeferredCallResolution::resolve() {:?}", self);
1197
1198        // we should not be invoked until the closure kind has been
1199        // determined by upvar inference
1200        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());
1201
1202        // We may now know enough to figure out fn vs fnmut etc.
1203        match fcx.try_overloaded_call_traits(self.call_expr, self.closure_ty, None) {
1204            Some((autoref, method_callee)) => {
1205                // One problem is that when we get here, we are going
1206                // to have a newly instantiated function signature
1207                // from the call trait. This has to be reconciled with
1208                // the older function signature we had before. In
1209                // principle we *should* be able to fn_sigs(), but we
1210                // can't because of the annoying need for a TypeTrace.
1211                // (This always bites me, should find a way to
1212                // refactor it.)
1213                let method_sig = method_callee.sig;
1214
1215                {
    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:1215",
                        "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(1215u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("attempt_resolution: method_callee={0:?}",
                                                    method_callee) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("attempt_resolution: method_callee={:?}", method_callee);
1216
1217                for (method_arg_ty, self_arg_ty) in
1218                    iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
1219                {
1220                    fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
1221                }
1222
1223                fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
1224
1225                let mut adjustments = self.adjustments;
1226                adjustments.extend(autoref);
1227                fcx.apply_adjustments(self.callee_expr, adjustments);
1228
1229                fcx.write_method_call_and_enforce_effects(
1230                    self.call_expr.hir_id,
1231                    self.call_expr.span,
1232                    method_callee,
1233                );
1234            }
1235            None => {
1236                let guar = fcx.tainted_by_errors().unwrap_or_else(|| {
1237                    fcx.dcx().span_delayed_bug(
1238                        self.call_expr.span,
1239                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{0}`",
                self.closure_ty))
    })format!(
1240                            "Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{}`",
1241                            self.closure_ty
1242                        ),
1243                    )
1244                });
1245                fcx.write_resolution(self.call_expr.hir_id, Err(guar));
1246            }
1247        }
1248    }
1249}