]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/callee.rs
Rollup merge of #104921 - compiler-errors:no-binder-on-fut-ty, r=cjgillot
[rust.git] / compiler / rustc_hir_typeck / src / callee.rs
1 use super::method::probe::{IsSuggestion, Mode, ProbeScope};
2 use super::method::MethodCallee;
3 use super::{Expectation, FnCtxt, TupleArgumentsFlag};
4
5 use crate::type_error_struct;
6 use rustc_ast::util::parser::PREC_POSTFIX;
7 use rustc_errors::{struct_span_err, Applicability, Diagnostic, StashKey};
8 use rustc_hir as hir;
9 use rustc_hir::def::{self, CtorKind, Namespace, Res};
10 use rustc_hir::def_id::DefId;
11 use rustc_infer::{
12     infer,
13     traits::{self, Obligation},
14 };
15 use rustc_infer::{
16     infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind},
17     traits::ObligationCause,
18 };
19 use rustc_middle::ty::adjustment::{
20     Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
21 };
22 use rustc_middle::ty::SubstsRef;
23 use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable};
24 use rustc_span::def_id::LocalDefId;
25 use rustc_span::symbol::{sym, Ident};
26 use rustc_span::Span;
27 use rustc_target::spec::abi;
28 use rustc_trait_selection::autoderef::Autoderef;
29 use rustc_trait_selection::infer::InferCtxtExt as _;
30 use rustc_trait_selection::traits::error_reporting::DefIdOrName;
31 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
32
33 use std::{iter, slice};
34
35 /// Checks that it is legal to call methods of the trait corresponding
36 /// to `trait_id` (this only cares about the trait, not the specific
37 /// method that is called).
38 pub fn check_legal_trait_for_method_call(
39     tcx: TyCtxt<'_>,
40     span: Span,
41     receiver: Option<Span>,
42     expr_span: Span,
43     trait_id: DefId,
44 ) {
45     if tcx.lang_items().drop_trait() == Some(trait_id) {
46         let mut err = struct_span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
47         err.span_label(span, "explicit destructor calls not allowed");
48
49         let (sp, suggestion) = receiver
50             .and_then(|s| tcx.sess.source_map().span_to_snippet(s).ok())
51             .filter(|snippet| !snippet.is_empty())
52             .map(|snippet| (expr_span, format!("drop({snippet})")))
53             .unwrap_or_else(|| (span, "drop".to_string()));
54
55         err.span_suggestion(
56             sp,
57             "consider using `drop` function",
58             suggestion,
59             Applicability::MaybeIncorrect,
60         );
61
62         err.emit();
63     }
64 }
65
66 #[derive(Debug)]
67 enum CallStep<'tcx> {
68     Builtin(Ty<'tcx>),
69     DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
70     /// E.g., enum variant constructors.
71     Overloaded(MethodCallee<'tcx>),
72 }
73
74 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
75     pub fn check_call(
76         &self,
77         call_expr: &'tcx hir::Expr<'tcx>,
78         callee_expr: &'tcx hir::Expr<'tcx>,
79         arg_exprs: &'tcx [hir::Expr<'tcx>],
80         expected: Expectation<'tcx>,
81     ) -> Ty<'tcx> {
82         let original_callee_ty = match &callee_expr.kind {
83             hir::ExprKind::Path(hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)) => self
84                 .check_expr_with_expectation_and_args(
85                     callee_expr,
86                     Expectation::NoExpectation,
87                     arg_exprs,
88                 ),
89             _ => self.check_expr(callee_expr),
90         };
91
92         let expr_ty = self.structurally_resolved_type(call_expr.span, original_callee_ty);
93
94         let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
95         let mut result = None;
96         while result.is_none() && autoderef.next().is_some() {
97             result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
98         }
99         self.register_predicates(autoderef.into_obligations());
100
101         let output = match result {
102             None => {
103                 // this will report an error since original_callee_ty is not a fn
104                 self.confirm_builtin_call(
105                     call_expr,
106                     callee_expr,
107                     original_callee_ty,
108                     arg_exprs,
109                     expected,
110                 )
111             }
112
113             Some(CallStep::Builtin(callee_ty)) => {
114                 self.confirm_builtin_call(call_expr, callee_expr, callee_ty, arg_exprs, expected)
115             }
116
117             Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
118                 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, def_id, fn_sig)
119             }
120
121             Some(CallStep::Overloaded(method_callee)) => {
122                 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
123             }
124         };
125
126         // we must check that return type of called functions is WF:
127         self.register_wf_obligation(output.into(), call_expr.span, traits::WellFormed(None));
128
129         output
130     }
131
132     #[instrument(level = "debug", skip(self, call_expr, callee_expr, arg_exprs, autoderef), ret)]
133     fn try_overloaded_call_step(
134         &self,
135         call_expr: &'tcx hir::Expr<'tcx>,
136         callee_expr: &'tcx hir::Expr<'tcx>,
137         arg_exprs: &'tcx [hir::Expr<'tcx>],
138         autoderef: &Autoderef<'a, 'tcx>,
139     ) -> Option<CallStep<'tcx>> {
140         let adjusted_ty =
141             self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false));
142
143         // If the callee is a bare function or a closure, then we're all set.
144         match *adjusted_ty.kind() {
145             ty::FnDef(..) | ty::FnPtr(_) => {
146                 let adjustments = self.adjust_steps(autoderef);
147                 self.apply_adjustments(callee_expr, adjustments);
148                 return Some(CallStep::Builtin(adjusted_ty));
149             }
150
151             ty::Closure(def_id, substs) => {
152                 let def_id = def_id.expect_local();
153
154                 // Check whether this is a call to a closure where we
155                 // haven't yet decided on whether the closure is fn vs
156                 // fnmut vs fnonce. If so, we have to defer further processing.
157                 if self.closure_kind(substs).is_none() {
158                     let closure_sig = substs.as_closure().sig();
159                     let closure_sig = self.replace_bound_vars_with_fresh_vars(
160                         call_expr.span,
161                         infer::FnCall,
162                         closure_sig,
163                     );
164                     let adjustments = self.adjust_steps(autoderef);
165                     self.record_deferred_call_resolution(
166                         def_id,
167                         DeferredCallResolution {
168                             call_expr,
169                             callee_expr,
170                             adjusted_ty,
171                             adjustments,
172                             fn_sig: closure_sig,
173                             closure_substs: substs,
174                         },
175                     );
176                     return Some(CallStep::DeferredClosure(def_id, closure_sig));
177                 }
178             }
179
180             // Hack: we know that there are traits implementing Fn for &F
181             // where F:Fn and so forth. In the particular case of types
182             // like `x: &mut FnMut()`, if there is a call `x()`, we would
183             // normally translate to `FnMut::call_mut(&mut x, ())`, but
184             // that winds up requiring `mut x: &mut FnMut()`. A little
185             // over the top. The simplest fix by far is to just ignore
186             // this case and deref again, so we wind up with
187             // `FnMut::call_mut(&mut *x, ())`.
188             ty::Ref(..) if autoderef.step_count() == 0 => {
189                 return None;
190             }
191
192             ty::Error(_) => {
193                 return None;
194             }
195
196             _ => {}
197         }
198
199         // Now, we look for the implementation of a Fn trait on the object's type.
200         // We first do it with the explicit instruction to look for an impl of
201         // `Fn<Tuple>`, with the tuple `Tuple` having an arity corresponding
202         // to the number of call parameters.
203         // If that fails (or_else branch), we try again without specifying the
204         // shape of the tuple (hence the None). This allows to detect an Fn trait
205         // is implemented, and use this information for diagnostic.
206         self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
207             .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
208             .map(|(autoref, method)| {
209                 let mut adjustments = self.adjust_steps(autoderef);
210                 adjustments.extend(autoref);
211                 self.apply_adjustments(callee_expr, adjustments);
212                 CallStep::Overloaded(method)
213             })
214     }
215
216     fn try_overloaded_call_traits(
217         &self,
218         call_expr: &hir::Expr<'_>,
219         adjusted_ty: Ty<'tcx>,
220         opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
221     ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
222         // Try the options that are least restrictive on the caller first.
223         for (opt_trait_def_id, method_name, borrow) in [
224             (self.tcx.lang_items().fn_trait(), Ident::with_dummy_span(sym::call), true),
225             (self.tcx.lang_items().fn_mut_trait(), Ident::with_dummy_span(sym::call_mut), true),
226             (self.tcx.lang_items().fn_once_trait(), Ident::with_dummy_span(sym::call_once), false),
227         ] {
228             let Some(trait_def_id) = opt_trait_def_id else { continue };
229
230             let opt_input_type = opt_arg_exprs.map(|arg_exprs| {
231                 self.tcx.mk_tup(arg_exprs.iter().map(|e| {
232                     self.next_ty_var(TypeVariableOrigin {
233                         kind: TypeVariableOriginKind::TypeInference,
234                         span: e.span,
235                     })
236                 }))
237             });
238
239             if let Some(ok) = self.lookup_method_in_trait(
240                 call_expr.span,
241                 method_name,
242                 trait_def_id,
243                 adjusted_ty,
244                 opt_input_type.as_ref().map(slice::from_ref),
245             ) {
246                 let method = self.register_infer_ok_obligations(ok);
247                 let mut autoref = None;
248                 if borrow {
249                     // Check for &self vs &mut self in the method signature. Since this is either
250                     // the Fn or FnMut trait, it should be one of those.
251                     let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind() else {
252                         // The `fn`/`fn_mut` lang item is ill-formed, which should have
253                         // caused an error elsewhere.
254                         self.tcx
255                             .sess
256                             .delay_span_bug(call_expr.span, "input to call/call_mut is not a ref?");
257                         return None;
258                     };
259
260                     // For initial two-phase borrow
261                     // deployment, conservatively omit
262                     // overloaded function call ops.
263                     let mutbl = AutoBorrowMutability::new(*mutbl, AllowTwoPhase::No);
264
265                     autoref = Some(Adjustment {
266                         kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
267                         target: method.sig.inputs()[0],
268                     });
269                 }
270                 return Some((autoref, method));
271             }
272         }
273
274         None
275     }
276
277     /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
278     /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
279     fn identify_bad_closure_def_and_call(
280         &self,
281         err: &mut Diagnostic,
282         hir_id: hir::HirId,
283         callee_node: &hir::ExprKind<'_>,
284         callee_span: Span,
285     ) {
286         let hir = self.tcx.hir();
287         let parent_hir_id = hir.get_parent_node(hir_id);
288         let parent_node = hir.get(parent_hir_id);
289         if let (
290             hir::Node::Expr(hir::Expr {
291                 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, body, .. }),
292                 ..
293             }),
294             hir::ExprKind::Block(..),
295         ) = (parent_node, callee_node)
296         {
297             let fn_decl_span = if hir.body(body).generator_kind
298                 == Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure))
299             {
300                 // Actually need to unwrap a few more layers of HIR to get to
301                 // the _real_ closure...
302                 let async_closure = hir.get_parent_node(hir.get_parent_node(parent_hir_id));
303                 if let hir::Node::Expr(hir::Expr {
304                     kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
305                     ..
306                 }) = hir.get(async_closure)
307                 {
308                     fn_decl_span
309                 } else {
310                     return;
311                 }
312             } else {
313                 fn_decl_span
314             };
315
316             let start = fn_decl_span.shrink_to_lo();
317             let end = callee_span.shrink_to_hi();
318             err.multipart_suggestion(
319                 "if you meant to create this closure and immediately call it, surround the \
320                 closure with parentheses",
321                 vec![(start, "(".to_string()), (end, ")".to_string())],
322                 Applicability::MaybeIncorrect,
323             );
324         }
325     }
326
327     /// Give appropriate suggestion when encountering `[("a", 0) ("b", 1)]`, where the
328     /// likely intention is to create an array containing tuples.
329     fn maybe_suggest_bad_array_definition(
330         &self,
331         err: &mut Diagnostic,
332         call_expr: &'tcx hir::Expr<'tcx>,
333         callee_expr: &'tcx hir::Expr<'tcx>,
334     ) -> bool {
335         let hir_id = self.tcx.hir().get_parent_node(call_expr.hir_id);
336         let parent_node = self.tcx.hir().get(hir_id);
337         if let (
338             hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
339             hir::ExprKind::Tup(exp),
340             hir::ExprKind::Call(_, args),
341         ) = (parent_node, &callee_expr.kind, &call_expr.kind)
342             && args.len() == exp.len()
343         {
344             let start = callee_expr.span.shrink_to_hi();
345             err.span_suggestion(
346                 start,
347                 "consider separating array elements with a comma",
348                 ",",
349                 Applicability::MaybeIncorrect,
350             );
351             return true;
352         }
353         false
354     }
355
356     fn confirm_builtin_call(
357         &self,
358         call_expr: &'tcx hir::Expr<'tcx>,
359         callee_expr: &'tcx hir::Expr<'tcx>,
360         callee_ty: Ty<'tcx>,
361         arg_exprs: &'tcx [hir::Expr<'tcx>],
362         expected: Expectation<'tcx>,
363     ) -> Ty<'tcx> {
364         let (fn_sig, def_id) = match *callee_ty.kind() {
365             ty::FnDef(def_id, subst) => {
366                 let fn_sig = self.tcx.bound_fn_sig(def_id).subst(self.tcx, subst);
367
368                 // Unit testing: function items annotated with
369                 // `#[rustc_evaluate_where_clauses]` trigger special output
370                 // to let us test the trait evaluation system.
371                 if self.tcx.has_attr(def_id, sym::rustc_evaluate_where_clauses) {
372                     let predicates = self.tcx.predicates_of(def_id);
373                     let predicates = predicates.instantiate(self.tcx, subst);
374                     for (predicate, predicate_span) in
375                         predicates.predicates.iter().zip(&predicates.spans)
376                     {
377                         let obligation = Obligation::new(
378                             self.tcx,
379                             ObligationCause::dummy_with_span(callee_expr.span),
380                             self.param_env,
381                             *predicate,
382                         );
383                         let result = self.evaluate_obligation(&obligation);
384                         self.tcx
385                             .sess
386                             .struct_span_err(
387                                 callee_expr.span,
388                                 &format!("evaluate({:?}) = {:?}", predicate, result),
389                             )
390                             .span_label(*predicate_span, "predicate")
391                             .emit();
392                     }
393                 }
394                 (fn_sig, Some(def_id))
395             }
396             ty::FnPtr(sig) => (sig, None),
397             _ => {
398                 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &callee_expr.kind
399                     && let [segment] = path.segments
400                     && let Some(mut diag) = self
401                         .tcx
402                         .sess
403                         .diagnostic()
404                         .steal_diagnostic(segment.ident.span, StashKey::CallIntoMethod)
405                 {
406                     // Try suggesting `foo(a)` -> `a.foo()` if possible.
407                     if let Some(ty) =
408                         self.suggest_call_as_method(
409                             &mut diag,
410                             segment,
411                             arg_exprs,
412                             call_expr,
413                             expected
414                         )
415                     {
416                         diag.emit();
417                         return ty;
418                     } else {
419                         diag.emit();
420                     }
421                 }
422
423                 self.report_invalid_callee(call_expr, callee_expr, callee_ty, arg_exprs);
424
425                 // This is the "default" function signature, used in case of error.
426                 // In that case, we check each argument against "error" in order to
427                 // set up all the node type bindings.
428                 (
429                     ty::Binder::dummy(self.tcx.mk_fn_sig(
430                         self.err_args(arg_exprs.len()).into_iter(),
431                         self.tcx.ty_error(),
432                         false,
433                         hir::Unsafety::Normal,
434                         abi::Abi::Rust,
435                     )),
436                     None,
437                 )
438             }
439         };
440
441         // Replace any late-bound regions that appear in the function
442         // signature with region variables. We also have to
443         // renormalize the associated types at this point, since they
444         // previously appeared within a `Binder<>` and hence would not
445         // have been normalized before.
446         let fn_sig = self.replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, fn_sig);
447         let fn_sig = self.normalize_associated_types_in(call_expr.span, fn_sig);
448
449         // Call the generic checker.
450         let expected_arg_tys = self.expected_inputs_for_expected_output(
451             call_expr.span,
452             expected,
453             fn_sig.output(),
454             fn_sig.inputs(),
455         );
456         self.check_argument_types(
457             call_expr.span,
458             call_expr,
459             fn_sig.inputs(),
460             expected_arg_tys,
461             arg_exprs,
462             fn_sig.c_variadic,
463             TupleArgumentsFlag::DontTupleArguments,
464             def_id,
465         );
466
467         if fn_sig.abi == abi::Abi::RustCall {
468             let sp = arg_exprs.last().map_or(call_expr.span, |expr| expr.span);
469             if let Some(ty) = fn_sig.inputs().last().copied() {
470                 self.register_bound(
471                     ty,
472                     self.tcx.require_lang_item(hir::LangItem::Tuple, Some(sp)),
473                     traits::ObligationCause::new(sp, self.body_id, traits::RustCall),
474                 );
475             } else {
476                 self.tcx.sess.span_err(
477                         sp,
478                         "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
479                     );
480             }
481         }
482
483         fn_sig.output()
484     }
485
486     /// Attempts to reinterpret `method(rcvr, args...)` as `rcvr.method(args...)`
487     /// and suggesting the fix if the method probe is successful.
488     fn suggest_call_as_method(
489         &self,
490         diag: &mut Diagnostic,
491         segment: &'tcx hir::PathSegment<'tcx>,
492         arg_exprs: &'tcx [hir::Expr<'tcx>],
493         call_expr: &'tcx hir::Expr<'tcx>,
494         expected: Expectation<'tcx>,
495     ) -> Option<Ty<'tcx>> {
496         if let [callee_expr, rest @ ..] = arg_exprs {
497             let callee_ty = self.check_expr(callee_expr);
498             // First, do a probe with `IsSuggestion(true)` to avoid emitting
499             // any strange errors. If it's successful, then we'll do a true
500             // method lookup.
501             let Ok(pick) = self
502             .probe_for_name(
503                 Mode::MethodCall,
504                 segment.ident,
505                 IsSuggestion(true),
506                 callee_ty,
507                 call_expr.hir_id,
508                 // We didn't record the in scope traits during late resolution
509                 // so we need to probe AllTraits unfortunately
510                 ProbeScope::AllTraits,
511             ) else {
512                 return None;
513             };
514
515             let pick = self.confirm_method(
516                 call_expr.span,
517                 callee_expr,
518                 call_expr,
519                 callee_ty,
520                 pick,
521                 segment,
522             );
523             if pick.illegal_sized_bound.is_some() {
524                 return None;
525             }
526
527             let up_to_rcvr_span = segment.ident.span.until(callee_expr.span);
528             let rest_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
529             let rest_snippet = if let Some(first) = rest.first() {
530                 self.tcx
531                     .sess
532                     .source_map()
533                     .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
534             } else {
535                 Ok(")".to_string())
536             };
537
538             if let Ok(rest_snippet) = rest_snippet {
539                 let sugg = if callee_expr.precedence().order() >= PREC_POSTFIX {
540                     vec![
541                         (up_to_rcvr_span, "".to_string()),
542                         (rest_span, format!(".{}({rest_snippet}", segment.ident)),
543                     ]
544                 } else {
545                     vec![
546                         (up_to_rcvr_span, "(".to_string()),
547                         (rest_span, format!(").{}({rest_snippet}", segment.ident)),
548                     ]
549                 };
550                 let self_ty = self.resolve_vars_if_possible(pick.callee.sig.inputs()[0]);
551                 diag.multipart_suggestion(
552                     format!(
553                         "use the `.` operator to call the method `{}{}` on `{self_ty}`",
554                         self.tcx
555                             .associated_item(pick.callee.def_id)
556                             .trait_container(self.tcx)
557                             .map_or_else(
558                                 || String::new(),
559                                 |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
560                             ),
561                         segment.ident
562                     ),
563                     sugg,
564                     Applicability::MaybeIncorrect,
565                 );
566
567                 // Let's check the method fully now
568                 let return_ty = self.check_method_argument_types(
569                     segment.ident.span,
570                     call_expr,
571                     Ok(pick.callee),
572                     rest,
573                     TupleArgumentsFlag::DontTupleArguments,
574                     expected,
575                 );
576
577                 return Some(return_ty);
578             }
579         }
580
581         None
582     }
583
584     fn report_invalid_callee(
585         &self,
586         call_expr: &'tcx hir::Expr<'tcx>,
587         callee_expr: &'tcx hir::Expr<'tcx>,
588         callee_ty: Ty<'tcx>,
589         arg_exprs: &'tcx [hir::Expr<'tcx>],
590     ) {
591         let mut unit_variant = None;
592         if let hir::ExprKind::Path(qpath) = &callee_expr.kind
593             && let Res::Def(def::DefKind::Ctor(kind, CtorKind::Const), _)
594                 = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
595             // Only suggest removing parens if there are no arguments
596             && arg_exprs.is_empty()
597         {
598             let descr = match kind {
599                 def::CtorOf::Struct => "struct",
600                 def::CtorOf::Variant => "enum variant",
601             };
602             let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
603             unit_variant = Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(qpath)));
604         }
605
606         let callee_ty = self.resolve_vars_if_possible(callee_ty);
607         let mut err = type_error_struct!(
608             self.tcx.sess,
609             callee_expr.span,
610             callee_ty,
611             E0618,
612             "expected function, found {}",
613             match &unit_variant {
614                 Some((_, kind, path)) => format!("{kind} `{path}`"),
615                 None => format!("`{callee_ty}`"),
616             }
617         );
618
619         self.identify_bad_closure_def_and_call(
620             &mut err,
621             call_expr.hir_id,
622             &callee_expr.kind,
623             callee_expr.span,
624         );
625
626         if let Some((removal_span, kind, path)) = &unit_variant {
627             err.span_suggestion_verbose(
628                 *removal_span,
629                 &format!(
630                     "`{path}` is a unit {kind}, and does not take parentheses to be constructed",
631                 ),
632                 "",
633                 Applicability::MachineApplicable,
634             );
635         }
636
637         let mut inner_callee_path = None;
638         let def = match callee_expr.kind {
639             hir::ExprKind::Path(ref qpath) => {
640                 self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
641             }
642             hir::ExprKind::Call(ref inner_callee, _) => {
643                 // If the call spans more than one line and the callee kind is
644                 // itself another `ExprCall`, that's a clue that we might just be
645                 // missing a semicolon (Issue #51055)
646                 let call_is_multiline = self.tcx.sess.source_map().is_multiline(call_expr.span);
647                 if call_is_multiline {
648                     err.span_suggestion(
649                         callee_expr.span.shrink_to_hi(),
650                         "consider using a semicolon here",
651                         ";",
652                         Applicability::MaybeIncorrect,
653                     );
654                 }
655                 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
656                     inner_callee_path = Some(inner_qpath);
657                     self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
658                 } else {
659                     Res::Err
660                 }
661             }
662             _ => Res::Err,
663         };
664
665         if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
666             if let Some((maybe_def, output_ty, _)) =
667                 self.extract_callable_info(callee_expr, callee_ty)
668                 && !self.type_is_sized_modulo_regions(self.param_env, output_ty, callee_expr.span)
669             {
670                 let descr = match maybe_def {
671                     DefIdOrName::DefId(def_id) => self.tcx.def_kind(def_id).descr(def_id),
672                     DefIdOrName::Name(name) => name,
673                 };
674                 err.span_label(
675                     callee_expr.span,
676                     format!("this {descr} returns an unsized value `{output_ty}`, so it cannot be called")
677                 );
678                 if let DefIdOrName::DefId(def_id) = maybe_def
679                     && let Some(def_span) = self.tcx.hir().span_if_local(def_id)
680                 {
681                     err.span_label(def_span, "the callable type is defined here");
682                 }
683             } else {
684                 err.span_label(call_expr.span, "call expression requires function");
685             }
686         }
687
688         if let Some(span) = self.tcx.hir().res_span(def) {
689             let callee_ty = callee_ty.to_string();
690             let label = match (unit_variant, inner_callee_path) {
691                 (Some((_, kind, path)), _) => Some(format!("{kind} `{path}` defined here")),
692                 (_, Some(hir::QPath::Resolved(_, path))) => self
693                     .tcx
694                     .sess
695                     .source_map()
696                     .span_to_snippet(path.span)
697                     .ok()
698                     .map(|p| format!("`{p}` defined here returns `{callee_ty}`")),
699                 _ => {
700                     match def {
701                         // Emit a different diagnostic for local variables, as they are not
702                         // type definitions themselves, but rather variables *of* that type.
703                         Res::Local(hir_id) => Some(format!(
704                             "`{}` has type `{}`",
705                             self.tcx.hir().name(hir_id),
706                             callee_ty
707                         )),
708                         Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
709                             Some(format!("`{}` defined here", self.tcx.def_path_str(def_id),))
710                         }
711                         _ => Some(format!("`{callee_ty}` defined here")),
712                     }
713                 }
714             };
715             if let Some(label) = label {
716                 err.span_label(span, label);
717             }
718         }
719         err.emit();
720     }
721
722     fn confirm_deferred_closure_call(
723         &self,
724         call_expr: &'tcx hir::Expr<'tcx>,
725         arg_exprs: &'tcx [hir::Expr<'tcx>],
726         expected: Expectation<'tcx>,
727         closure_def_id: LocalDefId,
728         fn_sig: ty::FnSig<'tcx>,
729     ) -> Ty<'tcx> {
730         // `fn_sig` is the *signature* of the closure being called. We
731         // don't know the full details yet (`Fn` vs `FnMut` etc), but we
732         // do know the types expected for each argument and the return
733         // type.
734
735         let expected_arg_tys = self.expected_inputs_for_expected_output(
736             call_expr.span,
737             expected,
738             fn_sig.output(),
739             fn_sig.inputs(),
740         );
741
742         self.check_argument_types(
743             call_expr.span,
744             call_expr,
745             fn_sig.inputs(),
746             expected_arg_tys,
747             arg_exprs,
748             fn_sig.c_variadic,
749             TupleArgumentsFlag::TupleArguments,
750             Some(closure_def_id.to_def_id()),
751         );
752
753         fn_sig.output()
754     }
755
756     fn confirm_overloaded_call(
757         &self,
758         call_expr: &'tcx hir::Expr<'tcx>,
759         arg_exprs: &'tcx [hir::Expr<'tcx>],
760         expected: Expectation<'tcx>,
761         method_callee: MethodCallee<'tcx>,
762     ) -> Ty<'tcx> {
763         let output_type = self.check_method_argument_types(
764             call_expr.span,
765             call_expr,
766             Ok(method_callee),
767             arg_exprs,
768             TupleArgumentsFlag::TupleArguments,
769             expected,
770         );
771
772         self.write_method_call(call_expr.hir_id, method_callee);
773         output_type
774     }
775 }
776
777 #[derive(Debug)]
778 pub struct DeferredCallResolution<'tcx> {
779     call_expr: &'tcx hir::Expr<'tcx>,
780     callee_expr: &'tcx hir::Expr<'tcx>,
781     adjusted_ty: Ty<'tcx>,
782     adjustments: Vec<Adjustment<'tcx>>,
783     fn_sig: ty::FnSig<'tcx>,
784     closure_substs: SubstsRef<'tcx>,
785 }
786
787 impl<'a, 'tcx> DeferredCallResolution<'tcx> {
788     pub fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
789         debug!("DeferredCallResolution::resolve() {:?}", self);
790
791         // we should not be invoked until the closure kind has been
792         // determined by upvar inference
793         assert!(fcx.closure_kind(self.closure_substs).is_some());
794
795         // We may now know enough to figure out fn vs fnmut etc.
796         match fcx.try_overloaded_call_traits(self.call_expr, self.adjusted_ty, None) {
797             Some((autoref, method_callee)) => {
798                 // One problem is that when we get here, we are going
799                 // to have a newly instantiated function signature
800                 // from the call trait. This has to be reconciled with
801                 // the older function signature we had before. In
802                 // principle we *should* be able to fn_sigs(), but we
803                 // can't because of the annoying need for a TypeTrace.
804                 // (This always bites me, should find a way to
805                 // refactor it.)
806                 let method_sig = method_callee.sig;
807
808                 debug!("attempt_resolution: method_callee={:?}", method_callee);
809
810                 for (method_arg_ty, self_arg_ty) in
811                     iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
812                 {
813                     fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
814                 }
815
816                 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
817
818                 let mut adjustments = self.adjustments;
819                 adjustments.extend(autoref);
820                 fcx.apply_adjustments(self.callee_expr, adjustments);
821
822                 fcx.write_method_call(self.call_expr.hir_id, method_callee);
823             }
824             None => {
825                 // This can happen if `#![no_core]` is used and the `fn/fn_mut/fn_once`
826                 // lang items are not defined (issue #86238).
827                 let mut err = fcx.inh.tcx.sess.struct_span_err(
828                     self.call_expr.span,
829                     "failed to find an overloaded call trait for closure call",
830                 );
831                 err.help(
832                     "make sure the `fn`/`fn_mut`/`fn_once` lang items are defined \
833                      and have associated `call`/`call_mut`/`call_once` functions",
834                 );
835                 err.emit();
836             }
837         }
838     }
839 }