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