rustc_hir_typeck/
callee.rs

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