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            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            else {
466                return;
467            };
468            fn_decl_span
469        } else {
470            return;
471        };
472
473        let start = fn_decl_span.shrink_to_lo();
474        let end = callee_span.shrink_to_hi();
475        err.multipart_suggestion(
476            "if you meant to create this closure and immediately call it, surround the \
477                closure with parentheses",
478            vec![(start, "(".to_string()), (end, ")".to_string())],
479            Applicability::MaybeIncorrect,
480        );
481    }
482
483    /// Give appropriate suggestion when encountering `[("a", 0) ("b", 1)]`, where the
484    /// likely intention is to create an array containing tuples.
485    fn maybe_suggest_bad_array_definition(
486        &self,
487        err: &mut Diag<'_>,
488        call_expr: &'tcx hir::Expr<'tcx>,
489        callee_expr: &'tcx hir::Expr<'tcx>,
490    ) -> bool {
491        let parent_node = self.tcx.parent_hir_node(call_expr.hir_id);
492        if let (
493            hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
494            hir::ExprKind::Tup(exp),
495            hir::ExprKind::Call(_, args),
496        ) = (parent_node, &callee_expr.kind, &call_expr.kind)
497            && args.len() == exp.len()
498        {
499            let start = callee_expr.span.shrink_to_hi();
500            err.span_suggestion(
501                start,
502                "consider separating array elements with a comma",
503                ",",
504                Applicability::MaybeIncorrect,
505            );
506            return true;
507        }
508        false
509    }
510
511    fn confirm_builtin_call(
512        &self,
513        call_expr: &'tcx hir::Expr<'tcx>,
514        callee_expr: &'tcx hir::Expr<'tcx>,
515        callee_ty: Ty<'tcx>,
516        arg_exprs: &'tcx [hir::Expr<'tcx>],
517        expected: Expectation<'tcx>,
518    ) -> Ty<'tcx> {
519        let (fn_sig, def_id) = match *callee_ty.kind() {
520            ty::FnDef(def_id, args) => {
521                self.enforce_context_effects(Some(call_expr.hir_id), call_expr.span, def_id, args);
522                let fn_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args);
523
524                // Unit testing: function items annotated with
525                // `#[rustc_evaluate_where_clauses]` trigger special output
526                // to let us test the trait evaluation system.
527                // Untranslatable diagnostics are okay for rustc internals
528                #[allow(rustc::untranslatable_diagnostic)]
529                #[allow(rustc::diagnostic_outside_of_impl)]
530                if self.has_rustc_attrs
531                    && self.tcx.has_attr(def_id, sym::rustc_evaluate_where_clauses)
532                {
533                    let predicates = self.tcx.predicates_of(def_id);
534                    let predicates = predicates.instantiate(self.tcx, args);
535                    for (predicate, predicate_span) in predicates {
536                        let obligation = Obligation::new(
537                            self.tcx,
538                            ObligationCause::dummy_with_span(callee_expr.span),
539                            self.param_env,
540                            predicate,
541                        );
542                        let result = self.evaluate_obligation(&obligation);
543                        self.dcx()
544                            .struct_span_err(
545                                callee_expr.span,
546                                format!("evaluate({predicate:?}) = {result:?}"),
547                            )
548                            .with_span_label(predicate_span, "predicate")
549                            .emit();
550                    }
551                }
552                (fn_sig, Some(def_id))
553            }
554
555            // FIXME(const_trait_impl): these arms should error because we can't enforce them
556            ty::FnPtr(sig_tys, hdr) => (sig_tys.with(hdr), None),
557
558            _ => unreachable!(),
559        };
560
561        // Replace any late-bound regions that appear in the function
562        // signature with region variables. We also have to
563        // renormalize the associated types at this point, since they
564        // previously appeared within a `Binder<>` and hence would not
565        // have been normalized before.
566        let fn_sig = self.instantiate_binder_with_fresh_vars(
567            call_expr.span,
568            BoundRegionConversionTime::FnCall,
569            fn_sig,
570        );
571        let fn_sig = self.normalize(call_expr.span, fn_sig);
572
573        self.check_argument_types(
574            call_expr.span,
575            call_expr,
576            fn_sig.inputs(),
577            fn_sig.output(),
578            expected,
579            arg_exprs,
580            fn_sig.c_variadic,
581            TupleArgumentsFlag::DontTupleArguments,
582            def_id,
583        );
584
585        if fn_sig.abi == rustc_abi::ExternAbi::RustCall {
586            let sp = arg_exprs.last().map_or(call_expr.span, |expr| expr.span);
587            if let Some(ty) = fn_sig.inputs().last().copied() {
588                self.register_bound(
589                    ty,
590                    self.tcx.require_lang_item(hir::LangItem::Tuple, sp),
591                    self.cause(sp, ObligationCauseCode::RustCall),
592                );
593                self.require_type_is_sized(ty, sp, ObligationCauseCode::RustCall);
594            } else {
595                self.dcx().emit_err(errors::RustCallIncorrectArgs { span: sp });
596            }
597        }
598
599        fn_sig.output()
600    }
601
602    /// Attempts to reinterpret `method(rcvr, args...)` as `rcvr.method(args...)`
603    /// and suggesting the fix if the method probe is successful.
604    fn suggest_call_as_method(
605        &self,
606        diag: &mut Diag<'_>,
607        segment: &'tcx hir::PathSegment<'tcx>,
608        arg_exprs: &'tcx [hir::Expr<'tcx>],
609        call_expr: &'tcx hir::Expr<'tcx>,
610        expected: Expectation<'tcx>,
611    ) {
612        if let [callee_expr, rest @ ..] = arg_exprs {
613            let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)
614            else {
615                return;
616            };
617
618            // First, do a probe with `IsSuggestion(true)` to avoid emitting
619            // any strange errors. If it's successful, then we'll do a true
620            // method lookup.
621            let Ok(pick) = self.lookup_probe_for_diagnostic(
622                segment.ident,
623                callee_ty,
624                call_expr,
625                // We didn't record the in scope traits during late resolution
626                // so we need to probe AllTraits unfortunately
627                ProbeScope::AllTraits,
628                expected.only_has_type(self),
629            ) else {
630                return;
631            };
632
633            let pick = self.confirm_method_for_diagnostic(
634                call_expr.span,
635                callee_expr,
636                call_expr,
637                callee_ty,
638                &pick,
639                segment,
640            );
641            if pick.illegal_sized_bound.is_some() {
642                return;
643            }
644
645            let Some(callee_expr_span) = callee_expr.span.find_ancestor_inside(call_expr.span)
646            else {
647                return;
648            };
649            let up_to_rcvr_span = segment.ident.span.until(callee_expr_span);
650            let rest_span = callee_expr_span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
651            let rest_snippet = if let Some(first) = rest.first() {
652                self.tcx
653                    .sess
654                    .source_map()
655                    .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
656            } else {
657                Ok(")".to_string())
658            };
659
660            if let Ok(rest_snippet) = rest_snippet {
661                let sugg = if self.precedence(callee_expr) >= ExprPrecedence::Unambiguous {
662                    vec![
663                        (up_to_rcvr_span, "".to_string()),
664                        (rest_span, format!(".{}({rest_snippet}", segment.ident)),
665                    ]
666                } else {
667                    vec![
668                        (up_to_rcvr_span, "(".to_string()),
669                        (rest_span, format!(").{}({rest_snippet}", segment.ident)),
670                    ]
671                };
672                let self_ty = self.resolve_vars_if_possible(pick.callee.sig.inputs()[0]);
673                diag.multipart_suggestion(
674                    format!(
675                        "use the `.` operator to call the method `{}{}` on `{self_ty}`",
676                        self.tcx
677                            .associated_item(pick.callee.def_id)
678                            .trait_container(self.tcx)
679                            .map_or_else(
680                                || String::new(),
681                                |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
682                            ),
683                        segment.ident
684                    ),
685                    sugg,
686                    Applicability::MaybeIncorrect,
687                );
688            }
689        }
690    }
691
692    fn report_invalid_callee(
693        &self,
694        call_expr: &'tcx hir::Expr<'tcx>,
695        callee_expr: &'tcx hir::Expr<'tcx>,
696        callee_ty: Ty<'tcx>,
697        arg_exprs: &'tcx [hir::Expr<'tcx>],
698    ) -> ErrorGuaranteed {
699        // Callee probe fails when APIT references errors, so suppress those
700        // errors here.
701        if let Some((_, _, args)) = self.extract_callable_info(callee_ty)
702            && let Err(err) = args.error_reported()
703        {
704            return err;
705        }
706
707        let mut unit_variant = None;
708        if let hir::ExprKind::Path(qpath) = &callee_expr.kind
709            && let Res::Def(def::DefKind::Ctor(kind, CtorKind::Const), _)
710                = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
711            // Only suggest removing parens if there are no arguments
712            && arg_exprs.is_empty()
713            && call_expr.span.contains(callee_expr.span)
714        {
715            let descr = match kind {
716                def::CtorOf::Struct => "struct",
717                def::CtorOf::Variant => "enum variant",
718            };
719            let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
720            unit_variant =
721                Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(&self.tcx, qpath)));
722        }
723
724        let callee_ty = self.resolve_vars_if_possible(callee_ty);
725        let mut path = None;
726        let mut err = self.dcx().create_err(errors::InvalidCallee {
727            span: callee_expr.span,
728            ty: callee_ty,
729            found: match &unit_variant {
730                Some((_, kind, path)) => format!("{kind} `{path}`"),
731                None => format!("`{}`", self.tcx.short_string(callee_ty, &mut path)),
732            },
733        });
734        *err.long_ty_path() = path;
735        if callee_ty.references_error() {
736            err.downgrade_to_delayed_bug();
737        }
738
739        self.identify_bad_closure_def_and_call(
740            &mut err,
741            call_expr.hir_id,
742            &callee_expr.kind,
743            callee_expr.span,
744        );
745
746        if let Some((removal_span, kind, path)) = &unit_variant {
747            err.span_suggestion_verbose(
748                *removal_span,
749                format!(
750                    "`{path}` is a unit {kind}, and does not take parentheses to be constructed",
751                ),
752                "",
753                Applicability::MachineApplicable,
754            );
755        }
756
757        if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = callee_expr.kind
758            && let Res::Local(_) = path.res
759            && let [segment] = &path.segments
760        {
761            for id in self.tcx.hir_free_items() {
762                if let Some(node) = self.tcx.hir_get_if_local(id.owner_id.into())
763                    && let hir::Node::Item(item) = node
764                    && let hir::ItemKind::Fn { ident, .. } = item.kind
765                    && ident.name == segment.ident.name
766                {
767                    err.span_label(
768                        self.tcx.def_span(id.owner_id),
769                        "this function of the same name is available here, but it's shadowed by \
770                         the local binding",
771                    );
772                }
773            }
774        }
775
776        let mut inner_callee_path = None;
777        let def = match callee_expr.kind {
778            hir::ExprKind::Path(ref qpath) => {
779                self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
780            }
781            hir::ExprKind::Call(inner_callee, _) => {
782                if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
783                    inner_callee_path = Some(inner_qpath);
784                    self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
785                } else {
786                    Res::Err
787                }
788            }
789            _ => Res::Err,
790        };
791
792        if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
793            // If the call spans more than one line and the callee kind is
794            // itself another `ExprCall`, that's a clue that we might just be
795            // missing a semicolon (#51055, #106515).
796            let call_is_multiline = self
797                .tcx
798                .sess
799                .source_map()
800                .is_multiline(call_expr.span.with_lo(callee_expr.span.hi()))
801                && call_expr.span.eq_ctxt(callee_expr.span);
802            if call_is_multiline {
803                err.span_suggestion(
804                    callee_expr.span.shrink_to_hi(),
805                    "consider using a semicolon here to finish the statement",
806                    ";",
807                    Applicability::MaybeIncorrect,
808                );
809            }
810            if let Some((maybe_def, output_ty, _)) = self.extract_callable_info(callee_ty)
811                && !self.type_is_sized_modulo_regions(self.param_env, output_ty)
812            {
813                let descr = match maybe_def {
814                    DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
815                    DefIdOrName::Name(name) => name,
816                };
817                err.span_label(
818                    callee_expr.span,
819                    format!("this {descr} returns an unsized value `{output_ty}`, so it cannot be called")
820                );
821                if let DefIdOrName::DefId(def_id) = maybe_def
822                    && let Some(def_span) = self.tcx.hir_span_if_local(def_id)
823                {
824                    err.span_label(def_span, "the callable type is defined here");
825                }
826            } else {
827                err.span_label(call_expr.span, "call expression requires function");
828            }
829        }
830
831        if let Some(span) = self.tcx.hir_res_span(def) {
832            let callee_ty = callee_ty.to_string();
833            let label = match (unit_variant, inner_callee_path) {
834                (Some((_, kind, path)), _) => {
835                    err.arg("kind", kind);
836                    err.arg("path", path);
837                    Some(fluent_generated::hir_typeck_invalid_defined_kind)
838                }
839                (_, Some(hir::QPath::Resolved(_, path))) => {
840                    self.tcx.sess.source_map().span_to_snippet(path.span).ok().map(|p| {
841                        err.arg("func", p);
842                        fluent_generated::hir_typeck_invalid_fn_defined
843                    })
844                }
845                _ => {
846                    match def {
847                        // Emit a different diagnostic for local variables, as they are not
848                        // type definitions themselves, but rather variables *of* that type.
849                        Res::Local(hir_id) => {
850                            err.arg("local_name", self.tcx.hir_name(hir_id));
851                            Some(fluent_generated::hir_typeck_invalid_local)
852                        }
853                        Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
854                            err.arg("path", self.tcx.def_path_str(def_id));
855                            Some(fluent_generated::hir_typeck_invalid_defined)
856                        }
857                        _ => {
858                            err.arg("path", callee_ty);
859                            Some(fluent_generated::hir_typeck_invalid_defined)
860                        }
861                    }
862                }
863            };
864            if let Some(label) = label {
865                err.span_label(span, label);
866            }
867        }
868        err.emit()
869    }
870
871    fn confirm_deferred_closure_call(
872        &self,
873        call_expr: &'tcx hir::Expr<'tcx>,
874        arg_exprs: &'tcx [hir::Expr<'tcx>],
875        expected: Expectation<'tcx>,
876        closure_def_id: LocalDefId,
877        fn_sig: ty::FnSig<'tcx>,
878    ) -> Ty<'tcx> {
879        // `fn_sig` is the *signature* of the closure being called. We
880        // don't know the full details yet (`Fn` vs `FnMut` etc), but we
881        // do know the types expected for each argument and the return
882        // type.
883        self.check_argument_types(
884            call_expr.span,
885            call_expr,
886            fn_sig.inputs(),
887            fn_sig.output(),
888            expected,
889            arg_exprs,
890            fn_sig.c_variadic,
891            TupleArgumentsFlag::TupleArguments,
892            Some(closure_def_id.to_def_id()),
893        );
894
895        fn_sig.output()
896    }
897
898    #[tracing::instrument(level = "debug", skip(self, span))]
899    pub(super) fn enforce_context_effects(
900        &self,
901        call_hir_id: Option<HirId>,
902        span: Span,
903        callee_did: DefId,
904        callee_args: GenericArgsRef<'tcx>,
905    ) {
906        // FIXME(const_trait_impl): We should be enforcing these effects unconditionally.
907        // This can be done as soon as we convert the standard library back to
908        // using const traits, since if we were to enforce these conditions now,
909        // we'd fail on basically every builtin trait call (i.e. `1 + 2`).
910        if !self.tcx.features().const_trait_impl() {
911            return;
912        }
913
914        // If we have `rustc_do_not_const_check`, do not check `[const]` bounds.
915        if self.has_rustc_attrs && self.tcx.has_attr(self.body_id, sym::rustc_do_not_const_check) {
916            return;
917        }
918
919        let host = match self.tcx.hir_body_const_context(self.body_id) {
920            Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
921                ty::BoundConstness::Const
922            }
923            Some(hir::ConstContext::ConstFn) => ty::BoundConstness::Maybe,
924            None => return,
925        };
926
927        // FIXME(const_trait_impl): Should this be `is_const_fn_raw`? It depends on if we move
928        // const stability checking here too, I guess.
929        if self.tcx.is_conditionally_const(callee_did) {
930            let q = self.tcx.const_conditions(callee_did);
931            for (idx, (cond, pred_span)) in
932                q.instantiate(self.tcx, callee_args).into_iter().enumerate()
933            {
934                let cause = self.cause(
935                    span,
936                    if let Some(hir_id) = call_hir_id {
937                        ObligationCauseCode::HostEffectInExpr(callee_did, pred_span, hir_id, idx)
938                    } else {
939                        ObligationCauseCode::WhereClause(callee_did, pred_span)
940                    },
941                );
942                self.register_predicate(Obligation::new(
943                    self.tcx,
944                    cause,
945                    self.param_env,
946                    cond.to_host_effect_clause(self.tcx, host),
947                ));
948            }
949        } else {
950            // FIXME(const_trait_impl): This should eventually be caught here.
951            // For now, though, we defer some const checking to MIR.
952        }
953    }
954
955    fn confirm_overloaded_call(
956        &self,
957        call_expr: &'tcx hir::Expr<'tcx>,
958        arg_exprs: &'tcx [hir::Expr<'tcx>],
959        expected: Expectation<'tcx>,
960        method: MethodCallee<'tcx>,
961    ) -> Ty<'tcx> {
962        self.check_argument_types(
963            call_expr.span,
964            call_expr,
965            &method.sig.inputs()[1..],
966            method.sig.output(),
967            expected,
968            arg_exprs,
969            method.sig.c_variadic,
970            TupleArgumentsFlag::TupleArguments,
971            Some(method.def_id),
972        );
973
974        self.write_method_call_and_enforce_effects(call_expr.hir_id, call_expr.span, method);
975
976        method.sig.output()
977    }
978}
979
980#[derive(Debug)]
981pub(crate) struct DeferredCallResolution<'tcx> {
982    call_expr: &'tcx hir::Expr<'tcx>,
983    callee_expr: &'tcx hir::Expr<'tcx>,
984    closure_ty: Ty<'tcx>,
985    adjustments: Vec<Adjustment<'tcx>>,
986    fn_sig: ty::FnSig<'tcx>,
987}
988
989impl<'a, 'tcx> DeferredCallResolution<'tcx> {
990    pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
991        debug!("DeferredCallResolution::resolve() {:?}", self);
992
993        // we should not be invoked until the closure kind has been
994        // determined by upvar inference
995        assert!(fcx.closure_kind(self.closure_ty).is_some());
996
997        // We may now know enough to figure out fn vs fnmut etc.
998        match fcx.try_overloaded_call_traits(self.call_expr, self.closure_ty, None) {
999            Some((autoref, method_callee)) => {
1000                // One problem is that when we get here, we are going
1001                // to have a newly instantiated function signature
1002                // from the call trait. This has to be reconciled with
1003                // the older function signature we had before. In
1004                // principle we *should* be able to fn_sigs(), but we
1005                // can't because of the annoying need for a TypeTrace.
1006                // (This always bites me, should find a way to
1007                // refactor it.)
1008                let method_sig = method_callee.sig;
1009
1010                debug!("attempt_resolution: method_callee={:?}", method_callee);
1011
1012                for (method_arg_ty, self_arg_ty) in
1013                    iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
1014                {
1015                    fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
1016                }
1017
1018                fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
1019
1020                let mut adjustments = self.adjustments;
1021                adjustments.extend(autoref);
1022                fcx.apply_adjustments(self.callee_expr, adjustments);
1023
1024                fcx.write_method_call_and_enforce_effects(
1025                    self.call_expr.hir_id,
1026                    self.call_expr.span,
1027                    method_callee,
1028                );
1029            }
1030            None => {
1031                span_bug!(
1032                    self.call_expr.span,
1033                    "Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{}`",
1034                    self.closure_ty
1035                )
1036            }
1037        }
1038    }
1039}