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