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