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