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