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