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