]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/fn_ctxt/checks.rs
Auto merge of #99495 - oli-obk:revert_98582, r=oli-obk
[rust.git] / compiler / rustc_typeck / src / check / fn_ctxt / checks.rs
1 use crate::astconv::AstConv;
2 use crate::check::coercion::CoerceMany;
3 use crate::check::fn_ctxt::arg_matrix::{
4     ArgMatrix, Compatibility, Error, ExpectedIdx, ProvidedIdx,
5 };
6 use crate::check::gather_locals::Declaration;
7 use crate::check::intrinsicck::InlineAsmCtxt;
8 use crate::check::method::MethodCallee;
9 use crate::check::Expectation::*;
10 use crate::check::TupleArgumentsFlag::*;
11 use crate::check::{
12     potentially_plural_count, struct_span_err, BreakableCtxt, Diverges, Expectation, FnCtxt,
13     LocalTy, Needs, TupleArgumentsFlag,
14 };
15 use crate::structured_errors::StructuredDiagnostic;
16
17 use rustc_ast as ast;
18 use rustc_errors::{Applicability, Diagnostic, DiagnosticId, MultiSpan};
19 use rustc_hir as hir;
20 use rustc_hir::def::{CtorOf, DefKind, Res};
21 use rustc_hir::def_id::DefId;
22 use rustc_hir::{ExprKind, Node, QPath};
23 use rustc_index::vec::IndexVec;
24 use rustc_infer::infer::error_reporting::{FailureCode, ObligationCauseExt};
25 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
26 use rustc_infer::infer::InferOk;
27 use rustc_infer::infer::TypeTrace;
28 use rustc_middle::ty::adjustment::AllowTwoPhase;
29 use rustc_middle::ty::visit::TypeVisitable;
30 use rustc_middle::ty::{self, DefIdTree, IsSuggestable, Ty};
31 use rustc_session::Session;
32 use rustc_span::symbol::Ident;
33 use rustc_span::{self, Span};
34 use rustc_trait_selection::traits::{self, ObligationCauseCode, SelectionContext};
35
36 use std::iter;
37 use std::slice;
38
39 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
40     pub(in super::super) fn check_casts(&self) {
41         let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
42         debug!("FnCtxt::check_casts: {} deferred checks", deferred_cast_checks.len());
43         for cast in deferred_cast_checks.drain(..) {
44             cast.check(self);
45         }
46     }
47
48     pub(in super::super) fn check_transmutes(&self) {
49         let mut deferred_transmute_checks = self.deferred_transmute_checks.borrow_mut();
50         debug!("FnCtxt::check_transmutes: {} deferred checks", deferred_transmute_checks.len());
51         for (from, to, span) in deferred_transmute_checks.drain(..) {
52             self.check_transmute(span, from, to);
53         }
54     }
55
56     pub(in super::super) fn check_asms(&self) {
57         let mut deferred_asm_checks = self.deferred_asm_checks.borrow_mut();
58         debug!("FnCtxt::check_asm: {} deferred checks", deferred_asm_checks.len());
59         for (asm, hir_id) in deferred_asm_checks.drain(..) {
60             let enclosing_id = self.tcx.hir().enclosing_body_owner(hir_id);
61             InlineAsmCtxt::new_in_fn(self).check_asm(asm, enclosing_id);
62         }
63     }
64
65     pub(in super::super) fn check_method_argument_types(
66         &self,
67         sp: Span,
68         expr: &'tcx hir::Expr<'tcx>,
69         method: Result<MethodCallee<'tcx>, ()>,
70         args_no_rcvr: &'tcx [hir::Expr<'tcx>],
71         tuple_arguments: TupleArgumentsFlag,
72         expected: Expectation<'tcx>,
73     ) -> Ty<'tcx> {
74         let has_error = match method {
75             Ok(method) => method.substs.references_error() || method.sig.references_error(),
76             Err(_) => true,
77         };
78         if has_error {
79             let err_inputs = self.err_args(args_no_rcvr.len());
80
81             let err_inputs = match tuple_arguments {
82                 DontTupleArguments => err_inputs,
83                 TupleArguments => vec![self.tcx.intern_tup(&err_inputs)],
84             };
85
86             self.check_argument_types(
87                 sp,
88                 expr,
89                 &err_inputs,
90                 None,
91                 args_no_rcvr,
92                 false,
93                 tuple_arguments,
94                 method.ok().map(|method| method.def_id),
95             );
96             return self.tcx.ty_error();
97         }
98
99         let method = method.unwrap();
100         // HACK(eddyb) ignore self in the definition (see above).
101         let expected_input_tys = self.expected_inputs_for_expected_output(
102             sp,
103             expected,
104             method.sig.output(),
105             &method.sig.inputs()[1..],
106         );
107         self.check_argument_types(
108             sp,
109             expr,
110             &method.sig.inputs()[1..],
111             expected_input_tys,
112             args_no_rcvr,
113             method.sig.c_variadic,
114             tuple_arguments,
115             Some(method.def_id),
116         );
117         method.sig.output()
118     }
119
120     /// Generic function that factors out common logic from function calls,
121     /// method calls and overloaded operators.
122     pub(in super::super) fn check_argument_types(
123         &self,
124         // Span enclosing the call site
125         call_span: Span,
126         // Expression of the call site
127         call_expr: &'tcx hir::Expr<'tcx>,
128         // Types (as defined in the *signature* of the target function)
129         formal_input_tys: &[Ty<'tcx>],
130         // More specific expected types, after unifying with caller output types
131         expected_input_tys: Option<Vec<Ty<'tcx>>>,
132         // The expressions for each provided argument
133         provided_args: &'tcx [hir::Expr<'tcx>],
134         // Whether the function is variadic, for example when imported from C
135         c_variadic: bool,
136         // Whether the arguments have been bundled in a tuple (ex: closures)
137         tuple_arguments: TupleArgumentsFlag,
138         // The DefId for the function being called, for better error messages
139         fn_def_id: Option<DefId>,
140     ) {
141         let tcx = self.tcx;
142
143         // Conceptually, we've got some number of expected inputs, and some number of provided aguments
144         // and we can form a grid of whether each argument could satisfy a given input:
145         //      in1 | in2 | in3 | ...
146         // arg1  ?  |     |     |
147         // arg2     |  ?  |     |
148         // arg3     |     |  ?  |
149         // ...
150         // Initially, we just check the diagonal, because in the case of correct code
151         // these are the only checks that matter
152         // However, in the unhappy path, we'll fill in this whole grid to attempt to provide
153         // better error messages about invalid method calls.
154
155         // All the input types from the fn signature must outlive the call
156         // so as to validate implied bounds.
157         for (&fn_input_ty, arg_expr) in iter::zip(formal_input_tys, provided_args) {
158             self.register_wf_obligation(fn_input_ty.into(), arg_expr.span, traits::MiscObligation);
159         }
160
161         let mut err_code = "E0061";
162
163         // If the arguments should be wrapped in a tuple (ex: closures), unwrap them here
164         let (formal_input_tys, expected_input_tys) = if tuple_arguments == TupleArguments {
165             let tuple_type = self.structurally_resolved_type(call_span, formal_input_tys[0]);
166             match tuple_type.kind() {
167                 // We expected a tuple and got a tuple
168                 ty::Tuple(arg_types) => {
169                     // Argument length differs
170                     if arg_types.len() != provided_args.len() {
171                         err_code = "E0057";
172                     }
173                     let expected_input_tys = match expected_input_tys {
174                         Some(expected_input_tys) => match expected_input_tys.get(0) {
175                             Some(ty) => match ty.kind() {
176                                 ty::Tuple(tys) => Some(tys.iter().collect()),
177                                 _ => None,
178                             },
179                             None => None,
180                         },
181                         None => None,
182                     };
183                     (arg_types.iter().collect(), expected_input_tys)
184                 }
185                 _ => {
186                     // Otherwise, there's a mismatch, so clear out what we're expecting, and set
187                     // our input types to err_args so we don't blow up the error messages
188                     struct_span_err!(
189                         tcx.sess,
190                         call_span,
191                         E0059,
192                         "cannot use call notation; the first type parameter \
193                          for the function trait is neither a tuple nor unit"
194                     )
195                     .emit();
196                     (self.err_args(provided_args.len()), None)
197                 }
198             }
199         } else {
200             (formal_input_tys.to_vec(), expected_input_tys)
201         };
202
203         // If there are no external expectations at the call site, just use the types from the function defn
204         let expected_input_tys = if let Some(expected_input_tys) = expected_input_tys {
205             assert_eq!(expected_input_tys.len(), formal_input_tys.len());
206             expected_input_tys
207         } else {
208             formal_input_tys.clone()
209         };
210
211         let minimum_input_count = expected_input_tys.len();
212         let provided_arg_count = provided_args.len();
213
214         // We introduce a helper function to demand that a given argument satisfy a given input
215         // This is more complicated than just checking type equality, as arguments could be coerced
216         // This version writes those types back so further type checking uses the narrowed types
217         let demand_compatible = |idx| {
218             let formal_input_ty: Ty<'tcx> = formal_input_tys[idx];
219             let expected_input_ty: Ty<'tcx> = expected_input_tys[idx];
220             let provided_arg = &provided_args[idx];
221
222             debug!("checking argument {}: {:?} = {:?}", idx, provided_arg, formal_input_ty);
223
224             // We're on the happy path here, so we'll do a more involved check and write back types
225             // To check compatibility, we'll do 3 things:
226             // 1. Unify the provided argument with the expected type
227             let expectation = Expectation::rvalue_hint(self, expected_input_ty);
228
229             let checked_ty = self.check_expr_with_expectation(provided_arg, expectation);
230
231             // 2. Coerce to the most detailed type that could be coerced
232             //    to, which is `expected_ty` if `rvalue_hint` returns an
233             //    `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
234             let coerced_ty = expectation.only_has_type(self).unwrap_or(formal_input_ty);
235
236             // Cause selection errors caused by resolving a single argument to point at the
237             // argument and not the call. This lets us customize the span pointed to in the
238             // fulfillment error to be more accurate.
239             let coerced_ty =
240                 self.resolve_vars_with_obligations_and_mutate_fulfillment(coerced_ty, |errors| {
241                     self.point_at_type_arg_instead_of_call_if_possible(errors, call_expr);
242                     self.point_at_arg_instead_of_call_if_possible(
243                         errors,
244                         call_expr,
245                         call_span,
246                         provided_args,
247                         &expected_input_tys,
248                     );
249                 });
250
251             let coerce_error = self
252                 .try_coerce(provided_arg, checked_ty, coerced_ty, AllowTwoPhase::Yes, None)
253                 .err();
254
255             if coerce_error.is_some() {
256                 return Compatibility::Incompatible(coerce_error);
257             }
258
259             // 3. Check if the formal type is a supertype of the checked one
260             //    and register any such obligations for future type checks
261             let supertype_error = self
262                 .at(&self.misc(provided_arg.span), self.param_env)
263                 .sup(formal_input_ty, coerced_ty);
264             let subtyping_error = match supertype_error {
265                 Ok(InferOk { obligations, value: () }) => {
266                     self.register_predicates(obligations);
267                     None
268                 }
269                 Err(err) => Some(err),
270             };
271
272             // If neither check failed, the types are compatible
273             match subtyping_error {
274                 None => Compatibility::Compatible,
275                 Some(_) => Compatibility::Incompatible(subtyping_error),
276             }
277         };
278
279         // To start, we only care "along the diagonal", where we expect every
280         // provided arg to be in the right spot
281         let mut compatibility_diagonal =
282             vec![Compatibility::Incompatible(None); provided_args.len()];
283
284         // Keep track of whether we *could possibly* be satisfied, i.e. whether we're on the happy path
285         // if the wrong number of arguments were supplied, we CAN'T be satisfied,
286         // and if we're c_variadic, the supplied arguments must be >= the minimum count from the function
287         // otherwise, they need to be identical, because rust doesn't currently support variadic functions
288         let mut call_appears_satisfied = if c_variadic {
289             provided_arg_count >= minimum_input_count
290         } else {
291             provided_arg_count == minimum_input_count
292         };
293
294         // Check the arguments.
295         // We do this in a pretty awful way: first we type-check any arguments
296         // that are not closures, then we type-check the closures. This is so
297         // that we have more information about the types of arguments when we
298         // type-check the functions. This isn't really the right way to do this.
299         for check_closures in [false, true] {
300             // More awful hacks: before we check argument types, try to do
301             // an "opportunistic" trait resolution of any trait bounds on
302             // the call. This helps coercions.
303             if check_closures {
304                 self.select_obligations_where_possible(false, |errors| {
305                     self.point_at_type_arg_instead_of_call_if_possible(errors, call_expr);
306                     self.point_at_arg_instead_of_call_if_possible(
307                         errors,
308                         call_expr,
309                         call_span,
310                         &provided_args,
311                         &expected_input_tys,
312                     );
313                 })
314             }
315
316             // Check each argument, to satisfy the input it was provided for
317             // Visually, we're traveling down the diagonal of the compatibility matrix
318             for (idx, arg) in provided_args.iter().enumerate() {
319                 // Warn only for the first loop (the "no closures" one).
320                 // Closure arguments themselves can't be diverging, but
321                 // a previous argument can, e.g., `foo(panic!(), || {})`.
322                 if !check_closures {
323                     self.warn_if_unreachable(arg.hir_id, arg.span, "expression");
324                 }
325
326                 // For C-variadic functions, we don't have a declared type for all of
327                 // the arguments hence we only do our usual type checking with
328                 // the arguments who's types we do know. However, we *can* check
329                 // for unreachable expressions (see above).
330                 // FIXME: unreachable warning current isn't emitted
331                 if idx >= minimum_input_count {
332                     continue;
333                 }
334
335                 let is_closure = matches!(arg.kind, ExprKind::Closure { .. });
336                 if is_closure != check_closures {
337                     continue;
338                 }
339
340                 let compatible = demand_compatible(idx);
341                 let is_compatible = matches!(compatible, Compatibility::Compatible);
342                 compatibility_diagonal[idx] = compatible;
343
344                 if !is_compatible {
345                     call_appears_satisfied = false;
346                 }
347             }
348         }
349
350         if c_variadic && provided_arg_count < minimum_input_count {
351             err_code = "E0060";
352         }
353
354         for arg in provided_args.iter().skip(minimum_input_count) {
355             // Make sure we've checked this expr at least once.
356             let arg_ty = self.check_expr(&arg);
357
358             // If the function is c-style variadic, we skipped a bunch of arguments
359             // so we need to check those, and write out the types
360             // Ideally this would be folded into the above, for uniform style
361             // but c-variadic is already a corner case
362             if c_variadic {
363                 fn variadic_error<'tcx>(
364                     sess: &'tcx Session,
365                     span: Span,
366                     ty: Ty<'tcx>,
367                     cast_ty: &str,
368                 ) {
369                     use crate::structured_errors::MissingCastForVariadicArg;
370
371                     MissingCastForVariadicArg { sess, span, ty, cast_ty }.diagnostic().emit();
372                 }
373
374                 // There are a few types which get autopromoted when passed via varargs
375                 // in C but we just error out instead and require explicit casts.
376                 let arg_ty = self.structurally_resolved_type(arg.span, arg_ty);
377                 match arg_ty.kind() {
378                     ty::Float(ty::FloatTy::F32) => {
379                         variadic_error(tcx.sess, arg.span, arg_ty, "c_double");
380                     }
381                     ty::Int(ty::IntTy::I8 | ty::IntTy::I16) | ty::Bool => {
382                         variadic_error(tcx.sess, arg.span, arg_ty, "c_int");
383                     }
384                     ty::Uint(ty::UintTy::U8 | ty::UintTy::U16) => {
385                         variadic_error(tcx.sess, arg.span, arg_ty, "c_uint");
386                     }
387                     ty::FnDef(..) => {
388                         let ptr_ty = self.tcx.mk_fn_ptr(arg_ty.fn_sig(self.tcx));
389                         let ptr_ty = self.resolve_vars_if_possible(ptr_ty);
390                         variadic_error(tcx.sess, arg.span, arg_ty, &ptr_ty.to_string());
391                     }
392                     _ => {}
393                 }
394             }
395         }
396
397         if !call_appears_satisfied {
398             let compatibility_diagonal = IndexVec::from_raw(compatibility_diagonal);
399             let provided_args = IndexVec::from_iter(provided_args.iter().take(if c_variadic {
400                 minimum_input_count
401             } else {
402                 provided_arg_count
403             }));
404             debug_assert_eq!(
405                 formal_input_tys.len(),
406                 expected_input_tys.len(),
407                 "expected formal_input_tys to be the same size as expected_input_tys"
408             );
409             let formal_and_expected_inputs = IndexVec::from_iter(
410                 formal_input_tys
411                     .iter()
412                     .copied()
413                     .zip(expected_input_tys.iter().copied())
414                     .map(|vars| self.resolve_vars_if_possible(vars)),
415             );
416
417             self.report_arg_errors(
418                 compatibility_diagonal,
419                 formal_and_expected_inputs,
420                 provided_args,
421                 c_variadic,
422                 err_code,
423                 fn_def_id,
424                 call_span,
425                 call_expr,
426             );
427         }
428     }
429
430     fn report_arg_errors(
431         &self,
432         compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
433         formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
434         provided_args: IndexVec<ProvidedIdx, &'tcx hir::Expr<'tcx>>,
435         c_variadic: bool,
436         err_code: &str,
437         fn_def_id: Option<DefId>,
438         call_span: Span,
439         call_expr: &hir::Expr<'tcx>,
440     ) {
441         // Next, let's construct the error
442         let (error_span, full_call_span, ctor_of) = match &call_expr.kind {
443             hir::ExprKind::Call(
444                 hir::Expr { hir_id, span, kind: hir::ExprKind::Path(qpath), .. },
445                 _,
446             ) => {
447                 if let Res::Def(DefKind::Ctor(of, _), _) =
448                     self.typeck_results.borrow().qpath_res(qpath, *hir_id)
449                 {
450                     (call_span, *span, Some(of))
451                 } else {
452                     (call_span, *span, None)
453                 }
454             }
455             hir::ExprKind::Call(hir::Expr { span, .. }, _) => (call_span, *span, None),
456             hir::ExprKind::MethodCall(path_segment, _, span) => {
457                 let ident_span = path_segment.ident.span;
458                 let ident_span = if let Some(args) = path_segment.args {
459                     ident_span.with_hi(args.span_ext.hi())
460                 } else {
461                     ident_span
462                 };
463                 (
464                     *span, ident_span, None, // methods are never ctors
465                 )
466             }
467             k => span_bug!(call_span, "checking argument types on a non-call: `{:?}`", k),
468         };
469         let args_span = error_span.trim_start(full_call_span).unwrap_or(error_span);
470         let call_name = match ctor_of {
471             Some(CtorOf::Struct) => "struct",
472             Some(CtorOf::Variant) => "enum variant",
473             None => "function",
474         };
475
476         // Don't print if it has error types or is just plain `_`
477         fn has_error_or_infer<'tcx>(tys: impl IntoIterator<Item = Ty<'tcx>>) -> bool {
478             tys.into_iter().any(|ty| ty.references_error() || ty.is_ty_var())
479         }
480
481         self.set_tainted_by_errors();
482         let tcx = self.tcx;
483
484         // Precompute the provided types and spans, since that's all we typically need for below
485         let provided_arg_tys: IndexVec<ProvidedIdx, (Ty<'tcx>, Span)> = provided_args
486             .iter()
487             .map(|expr| {
488                 let ty = self
489                     .typeck_results
490                     .borrow()
491                     .expr_ty_adjusted_opt(*expr)
492                     .unwrap_or_else(|| tcx.ty_error());
493                 (self.resolve_vars_if_possible(ty), expr.span)
494             })
495             .collect();
496         let callee_expr = match &call_expr.peel_blocks().kind {
497             hir::ExprKind::Call(callee, _) => Some(*callee),
498             hir::ExprKind::MethodCall(_, callee, _) => {
499                 if let Some((DefKind::AssocFn, def_id)) =
500                     self.typeck_results.borrow().type_dependent_def(call_expr.hir_id)
501                     && let Some(assoc) = tcx.opt_associated_item(def_id)
502                     && assoc.fn_has_self_parameter
503                 {
504                     Some(&callee[0])
505                 } else {
506                     None
507                 }
508             }
509             _ => None,
510         };
511         let callee_ty = callee_expr
512             .and_then(|callee_expr| self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr));
513
514         // A "softer" version of the `demand_compatible`, which checks types without persisting them,
515         // and treats error types differently
516         // This will allow us to "probe" for other argument orders that would likely have been correct
517         let check_compatible = |provided_idx: ProvidedIdx, expected_idx: ExpectedIdx| {
518             if provided_idx.as_usize() == expected_idx.as_usize() {
519                 return compatibility_diagonal[provided_idx].clone();
520             }
521
522             let (formal_input_ty, expected_input_ty) = formal_and_expected_inputs[expected_idx];
523             // If either is an error type, we defy the usual convention and consider them to *not* be
524             // coercible. This prevents our error message heuristic from trying to pass errors into
525             // every argument.
526             if (formal_input_ty, expected_input_ty).references_error() {
527                 return Compatibility::Incompatible(None);
528             }
529
530             let (arg_ty, arg_span) = provided_arg_tys[provided_idx];
531
532             let expectation = Expectation::rvalue_hint(self, expected_input_ty);
533             let coerced_ty = expectation.only_has_type(self).unwrap_or(formal_input_ty);
534             let can_coerce = self.can_coerce(arg_ty, coerced_ty);
535             if !can_coerce {
536                 return Compatibility::Incompatible(None);
537             }
538
539             // Using probe here, since we don't want this subtyping to affect inference.
540             let subtyping_error = self.probe(|_| {
541                 self.at(&self.misc(arg_span), self.param_env).sup(formal_input_ty, coerced_ty).err()
542             });
543
544             // Same as above: if either the coerce type or the checked type is an error type,
545             // consider them *not* compatible.
546             let references_error = (coerced_ty, arg_ty).references_error();
547             match (references_error, subtyping_error) {
548                 (false, None) => Compatibility::Compatible,
549                 (_, subtyping_error) => Compatibility::Incompatible(subtyping_error),
550             }
551         };
552
553         // The algorithm here is inspired by levenshtein distance and longest common subsequence.
554         // We'll try to detect 4 different types of mistakes:
555         // - An extra parameter has been provided that doesn't satisfy *any* of the other inputs
556         // - An input is missing, which isn't satisfied by *any* of the other arguments
557         // - Some number of arguments have been provided in the wrong order
558         // - A type is straight up invalid
559
560         // First, let's find the errors
561         let (mut errors, matched_inputs) =
562             ArgMatrix::new(provided_args.len(), formal_and_expected_inputs.len(), check_compatible)
563                 .find_errors();
564
565         // First, check if we just need to wrap some arguments in a tuple.
566         if let Some((mismatch_idx, terr)) =
567             compatibility_diagonal.iter().enumerate().find_map(|(i, c)| {
568                 if let Compatibility::Incompatible(Some(terr)) = c { Some((i, terr)) } else { None }
569             })
570         {
571             // Is the first bad expected argument a tuple?
572             // Do we have as many extra provided arguments as the tuple's length?
573             // If so, we might have just forgotten to wrap some args in a tuple.
574             if let Some(ty::Tuple(tys)) =
575                 formal_and_expected_inputs.get(mismatch_idx.into()).map(|tys| tys.1.kind())
576                 && provided_arg_tys.len() == formal_and_expected_inputs.len() - 1 + tys.len()
577             {
578                 // Wrap up the N provided arguments starting at this position in a tuple.
579                 let provided_as_tuple = tcx.mk_tup(
580                     provided_arg_tys.iter().map(|(ty, _)| *ty).skip(mismatch_idx).take(tys.len()),
581                 );
582
583                 let mut satisfied = true;
584                 // Check if the newly wrapped tuple + rest of the arguments are compatible.
585                 for ((_, expected_ty), provided_ty) in std::iter::zip(
586                     formal_and_expected_inputs.iter().skip(mismatch_idx),
587                     [provided_as_tuple].into_iter().chain(
588                         provided_arg_tys.iter().map(|(ty, _)| *ty).skip(mismatch_idx + tys.len()),
589                     ),
590                 ) {
591                     if !self.can_coerce(provided_ty, *expected_ty) {
592                         satisfied = false;
593                         break;
594                     }
595                 }
596
597                 // If they're compatible, suggest wrapping in an arg, and we're done!
598                 // Take some care with spans, so we don't suggest wrapping a macro's
599                 // innards in parenthesis, for example.
600                 if satisfied
601                     && let Some(lo) =
602                         provided_args[mismatch_idx.into()].span.find_ancestor_inside(error_span)
603                     && let Some(hi) = provided_args[(mismatch_idx + tys.len() - 1).into()]
604                         .span
605                         .find_ancestor_inside(error_span)
606                 {
607                     let mut err;
608                     if tys.len() == 1 {
609                         // A tuple wrap suggestion actually occurs within,
610                         // so don't do anything special here.
611                         err = self.report_and_explain_type_error(
612                             TypeTrace::types(
613                                 &self.misc(lo),
614                                 true,
615                                 formal_and_expected_inputs[mismatch_idx.into()].1,
616                                 provided_arg_tys[mismatch_idx.into()].0,
617                             ),
618                             terr,
619                         );
620                         err.span_label(
621                             full_call_span,
622                             format!("arguments to this {} are incorrect", call_name),
623                         );
624                     } else {
625                         err = tcx.sess.struct_span_err_with_code(
626                             full_call_span,
627                             &format!(
628                                 "this {} takes {}{} but {} {} supplied",
629                                 call_name,
630                                 if c_variadic { "at least " } else { "" },
631                                 potentially_plural_count(
632                                     formal_and_expected_inputs.len(),
633                                     "argument"
634                                 ),
635                                 potentially_plural_count(provided_args.len(), "argument"),
636                                 if provided_args.len() == 1 { "was" } else { "were" }
637                             ),
638                             DiagnosticId::Error(err_code.to_owned()),
639                         );
640                         err.multipart_suggestion_verbose(
641                             "wrap these arguments in parentheses to construct a tuple",
642                             vec![
643                                 (lo.shrink_to_lo(), "(".to_string()),
644                                 (hi.shrink_to_hi(), ")".to_string()),
645                             ],
646                             Applicability::MachineApplicable,
647                         );
648                     };
649                     self.label_fn_like(&mut err, fn_def_id, callee_ty);
650                     err.emit();
651                     return;
652                 }
653             }
654         }
655
656         // Okay, so here's where it gets complicated in regards to what errors
657         // we emit and how.
658         // There are 3 different "types" of errors we might encounter.
659         //   1) Missing/extra/swapped arguments
660         //   2) Valid but incorrect arguments
661         //   3) Invalid arguments
662         //      - Currently I think this only comes up with `CyclicTy`
663         //
664         // We first need to go through, remove those from (3) and emit those
665         // as their own error, particularly since they're error code and
666         // message is special. From what I can tell, we *must* emit these
667         // here (vs somewhere prior to this function) since the arguments
668         // become invalid *because* of how they get used in the function.
669         // It is what it is.
670
671         if errors.is_empty() {
672             if cfg!(debug_assertions) {
673                 span_bug!(error_span, "expected errors from argument matrix");
674             } else {
675                 tcx.sess
676                     .struct_span_err(
677                         error_span,
678                         "argument type mismatch was detected, \
679                         but rustc had trouble determining where",
680                     )
681                     .note(
682                         "we would appreciate a bug report: \
683                         https://github.com/rust-lang/rust/issues/new",
684                     )
685                     .emit();
686             }
687             return;
688         }
689
690         errors.drain_filter(|error| {
691                 let Error::Invalid(provided_idx, expected_idx, Compatibility::Incompatible(error)) = error else { return false };
692                 let (provided_ty, provided_span) = provided_arg_tys[*provided_idx];
693                 let (expected_ty, _) = formal_and_expected_inputs[*expected_idx];
694                 let cause = &self.misc(provided_span);
695                 let trace = TypeTrace::types(cause, true, expected_ty, provided_ty);
696                 if let Some(e) = error {
697                     if !matches!(trace.cause.as_failure_code(e), FailureCode::Error0308(_)) {
698                         self.report_and_explain_type_error(trace, e).emit();
699                         return true;
700                     }
701                 }
702                 false
703             });
704
705         // We're done if we found errors, but we already emitted them.
706         if errors.is_empty() {
707             return;
708         }
709
710         // Okay, now that we've emitted the special errors separately, we
711         // are only left missing/extra/swapped and mismatched arguments, both
712         // can be collated pretty easily if needed.
713
714         // Next special case: if there is only one "Incompatible" error, just emit that
715         if let [
716             Error::Invalid(provided_idx, expected_idx, Compatibility::Incompatible(Some(err))),
717         ] = &errors[..]
718         {
719             let (formal_ty, expected_ty) = formal_and_expected_inputs[*expected_idx];
720             let (provided_ty, provided_arg_span) = provided_arg_tys[*provided_idx];
721             let cause = &self.misc(provided_arg_span);
722             let trace = TypeTrace::types(cause, true, expected_ty, provided_ty);
723             let mut err = self.report_and_explain_type_error(trace, err);
724             self.emit_coerce_suggestions(
725                 &mut err,
726                 &provided_args[*provided_idx],
727                 provided_ty,
728                 Expectation::rvalue_hint(self, expected_ty)
729                     .only_has_type(self)
730                     .unwrap_or(formal_ty),
731                 None,
732                 None,
733             );
734             err.span_label(
735                 full_call_span,
736                 format!("arguments to this {} are incorrect", call_name),
737             );
738             // Call out where the function is defined
739             self.label_fn_like(&mut err, fn_def_id, callee_ty);
740             err.emit();
741             return;
742         }
743
744         let mut err = if formal_and_expected_inputs.len() == provided_args.len() {
745             struct_span_err!(
746                 tcx.sess,
747                 full_call_span,
748                 E0308,
749                 "arguments to this {} are incorrect",
750                 call_name,
751             )
752         } else {
753             tcx.sess.struct_span_err_with_code(
754                 full_call_span,
755                 &format!(
756                     "this {} takes {}{} but {} {} supplied",
757                     call_name,
758                     if c_variadic { "at least " } else { "" },
759                     potentially_plural_count(formal_and_expected_inputs.len(), "argument"),
760                     potentially_plural_count(provided_args.len(), "argument"),
761                     if provided_args.len() == 1 { "was" } else { "were" }
762                 ),
763                 DiagnosticId::Error(err_code.to_owned()),
764             )
765         };
766
767         // As we encounter issues, keep track of what we want to provide for the suggestion
768         let mut labels = vec![];
769         // If there is a single error, we give a specific suggestion; otherwise, we change to
770         // "did you mean" with the suggested function call
771         enum SuggestionText {
772             None,
773             Provide(bool),
774             Remove(bool),
775             Swap,
776             Reorder,
777             DidYouMean,
778         }
779         let mut suggestion_text = SuggestionText::None;
780
781         let mut errors = errors.into_iter().peekable();
782         while let Some(error) = errors.next() {
783             match error {
784                 Error::Invalid(provided_idx, expected_idx, compatibility) => {
785                     let (formal_ty, expected_ty) = formal_and_expected_inputs[expected_idx];
786                     let (provided_ty, provided_span) = provided_arg_tys[provided_idx];
787                     if let Compatibility::Incompatible(error) = &compatibility {
788                         let cause = &self.misc(provided_span);
789                         let trace = TypeTrace::types(cause, true, expected_ty, provided_ty);
790                         if let Some(e) = error {
791                             self.note_type_err(
792                                 &mut err,
793                                 &trace.cause,
794                                 None,
795                                 Some(trace.values),
796                                 e,
797                                 false,
798                                 true,
799                             );
800                         }
801                     }
802
803                     self.emit_coerce_suggestions(
804                         &mut err,
805                         &provided_args[provided_idx],
806                         provided_ty,
807                         Expectation::rvalue_hint(self, expected_ty)
808                             .only_has_type(self)
809                             .unwrap_or(formal_ty),
810                         None,
811                         None,
812                     );
813                 }
814                 Error::Extra(arg_idx) => {
815                     let (provided_ty, provided_span) = provided_arg_tys[arg_idx];
816                     let provided_ty_name = if !has_error_or_infer([provided_ty]) {
817                         // FIXME: not suggestable, use something else
818                         format!(" of type `{}`", provided_ty)
819                     } else {
820                         "".to_string()
821                     };
822                     labels
823                         .push((provided_span, format!("argument{} unexpected", provided_ty_name)));
824                     suggestion_text = match suggestion_text {
825                         SuggestionText::None => SuggestionText::Remove(false),
826                         SuggestionText::Remove(_) => SuggestionText::Remove(true),
827                         _ => SuggestionText::DidYouMean,
828                     };
829                 }
830                 Error::Missing(expected_idx) => {
831                     // If there are multiple missing arguments adjacent to each other,
832                     // then we can provide a single error.
833
834                     let mut missing_idxs = vec![expected_idx];
835                     while let Some(e) = errors.next_if(|e| {
836                         matches!(e, Error::Missing(next_expected_idx)
837                             if *next_expected_idx == *missing_idxs.last().unwrap() + 1)
838                     }) {
839                         match e {
840                             Error::Missing(expected_idx) => missing_idxs.push(expected_idx),
841                             _ => unreachable!(),
842                         }
843                     }
844
845                     // NOTE: Because we might be re-arranging arguments, might have extra
846                     // arguments, etc. it's hard to *really* know where we should provide
847                     // this error label, so as a heuristic, we point to the provided arg, or
848                     // to the call if the missing inputs pass the provided args.
849                     match &missing_idxs[..] {
850                         &[expected_idx] => {
851                             let (_, input_ty) = formal_and_expected_inputs[expected_idx];
852                             let span = if let Some((_, arg_span)) =
853                                 provided_arg_tys.get(expected_idx.to_provided_idx())
854                             {
855                                 *arg_span
856                             } else {
857                                 args_span
858                             };
859                             let rendered = if !has_error_or_infer([input_ty]) {
860                                 format!(" of type `{}`", input_ty)
861                             } else {
862                                 "".to_string()
863                             };
864                             labels.push((span, format!("an argument{} is missing", rendered)));
865                             suggestion_text = match suggestion_text {
866                                 SuggestionText::None => SuggestionText::Provide(false),
867                                 SuggestionText::Provide(_) => SuggestionText::Provide(true),
868                                 _ => SuggestionText::DidYouMean,
869                             };
870                         }
871                         &[first_idx, second_idx] => {
872                             let (_, first_expected_ty) = formal_and_expected_inputs[first_idx];
873                             let (_, second_expected_ty) = formal_and_expected_inputs[second_idx];
874                             let span = if let (Some((_, first_span)), Some((_, second_span))) = (
875                                 provided_arg_tys.get(first_idx.to_provided_idx()),
876                                 provided_arg_tys.get(second_idx.to_provided_idx()),
877                             ) {
878                                 first_span.to(*second_span)
879                             } else {
880                                 args_span
881                             };
882                             let rendered =
883                                 if !has_error_or_infer([first_expected_ty, second_expected_ty]) {
884                                     format!(
885                                         " of type `{}` and `{}`",
886                                         first_expected_ty, second_expected_ty
887                                     )
888                                 } else {
889                                     "".to_string()
890                                 };
891                             labels.push((span, format!("two arguments{} are missing", rendered)));
892                             suggestion_text = match suggestion_text {
893                                 SuggestionText::None | SuggestionText::Provide(_) => {
894                                     SuggestionText::Provide(true)
895                                 }
896                                 _ => SuggestionText::DidYouMean,
897                             };
898                         }
899                         &[first_idx, second_idx, third_idx] => {
900                             let (_, first_expected_ty) = formal_and_expected_inputs[first_idx];
901                             let (_, second_expected_ty) = formal_and_expected_inputs[second_idx];
902                             let (_, third_expected_ty) = formal_and_expected_inputs[third_idx];
903                             let span = if let (Some((_, first_span)), Some((_, third_span))) = (
904                                 provided_arg_tys.get(first_idx.to_provided_idx()),
905                                 provided_arg_tys.get(third_idx.to_provided_idx()),
906                             ) {
907                                 first_span.to(*third_span)
908                             } else {
909                                 args_span
910                             };
911                             let rendered = if !has_error_or_infer([
912                                 first_expected_ty,
913                                 second_expected_ty,
914                                 third_expected_ty,
915                             ]) {
916                                 format!(
917                                     " of type `{}`, `{}`, and `{}`",
918                                     first_expected_ty, second_expected_ty, third_expected_ty
919                                 )
920                             } else {
921                                 "".to_string()
922                             };
923                             labels.push((span, format!("three arguments{} are missing", rendered)));
924                             suggestion_text = match suggestion_text {
925                                 SuggestionText::None | SuggestionText::Provide(_) => {
926                                     SuggestionText::Provide(true)
927                                 }
928                                 _ => SuggestionText::DidYouMean,
929                             };
930                         }
931                         missing_idxs => {
932                             let first_idx = *missing_idxs.first().unwrap();
933                             let last_idx = *missing_idxs.last().unwrap();
934                             // NOTE: Because we might be re-arranging arguments, might have extra arguments, etc.
935                             // It's hard to *really* know where we should provide this error label, so this is a
936                             // decent heuristic
937                             let span = if let (Some((_, first_span)), Some((_, last_span))) = (
938                                 provided_arg_tys.get(first_idx.to_provided_idx()),
939                                 provided_arg_tys.get(last_idx.to_provided_idx()),
940                             ) {
941                                 first_span.to(*last_span)
942                             } else {
943                                 args_span
944                             };
945                             labels.push((span, format!("multiple arguments are missing")));
946                             suggestion_text = match suggestion_text {
947                                 SuggestionText::None | SuggestionText::Provide(_) => {
948                                     SuggestionText::Provide(true)
949                                 }
950                                 _ => SuggestionText::DidYouMean,
951                             };
952                         }
953                     }
954                 }
955                 Error::Swap(
956                     first_provided_idx,
957                     second_provided_idx,
958                     first_expected_idx,
959                     second_expected_idx,
960                 ) => {
961                     let (first_provided_ty, first_span) = provided_arg_tys[first_provided_idx];
962                     let (_, first_expected_ty) = formal_and_expected_inputs[first_expected_idx];
963                     let first_provided_ty_name = if !has_error_or_infer([first_provided_ty]) {
964                         format!(", found `{}`", first_provided_ty)
965                     } else {
966                         String::new()
967                     };
968                     labels.push((
969                         first_span,
970                         format!("expected `{}`{}", first_expected_ty, first_provided_ty_name),
971                     ));
972
973                     let (second_provided_ty, second_span) = provided_arg_tys[second_provided_idx];
974                     let (_, second_expected_ty) = formal_and_expected_inputs[second_expected_idx];
975                     let second_provided_ty_name = if !has_error_or_infer([second_provided_ty]) {
976                         format!(", found `{}`", second_provided_ty)
977                     } else {
978                         String::new()
979                     };
980                     labels.push((
981                         second_span,
982                         format!("expected `{}`{}", second_expected_ty, second_provided_ty_name),
983                     ));
984
985                     suggestion_text = match suggestion_text {
986                         SuggestionText::None => SuggestionText::Swap,
987                         _ => SuggestionText::DidYouMean,
988                     };
989                 }
990                 Error::Permutation(args) => {
991                     for (dst_arg, dest_input) in args {
992                         let (_, expected_ty) = formal_and_expected_inputs[dst_arg];
993                         let (provided_ty, provided_span) = provided_arg_tys[dest_input];
994                         let provided_ty_name = if !has_error_or_infer([provided_ty]) {
995                             format!(", found `{}`", provided_ty)
996                         } else {
997                             String::new()
998                         };
999                         labels.push((
1000                             provided_span,
1001                             format!("expected `{}`{}", expected_ty, provided_ty_name),
1002                         ));
1003                     }
1004
1005                     suggestion_text = match suggestion_text {
1006                         SuggestionText::None => SuggestionText::Reorder,
1007                         _ => SuggestionText::DidYouMean,
1008                     };
1009                 }
1010             }
1011         }
1012
1013         // If we have less than 5 things to say, it would be useful to call out exactly what's wrong
1014         if labels.len() <= 5 {
1015             for (span, label) in labels {
1016                 err.span_label(span, label);
1017             }
1018         }
1019
1020         // Call out where the function is defined
1021         self.label_fn_like(&mut err, fn_def_id, callee_ty);
1022
1023         // And add a suggestion block for all of the parameters
1024         let suggestion_text = match suggestion_text {
1025             SuggestionText::None => None,
1026             SuggestionText::Provide(plural) => {
1027                 Some(format!("provide the argument{}", if plural { "s" } else { "" }))
1028             }
1029             SuggestionText::Remove(plural) => {
1030                 Some(format!("remove the extra argument{}", if plural { "s" } else { "" }))
1031             }
1032             SuggestionText::Swap => Some("swap these arguments".to_string()),
1033             SuggestionText::Reorder => Some("reorder these arguments".to_string()),
1034             SuggestionText::DidYouMean => Some("did you mean".to_string()),
1035         };
1036         if let Some(suggestion_text) = suggestion_text {
1037             let source_map = self.sess().source_map();
1038             let mut suggestion = format!(
1039                 "{}(",
1040                 source_map.span_to_snippet(full_call_span).unwrap_or_else(|_| fn_def_id
1041                     .map_or("".to_string(), |fn_def_id| tcx.item_name(fn_def_id).to_string()))
1042             );
1043             let mut needs_comma = false;
1044             for (expected_idx, provided_idx) in matched_inputs.iter_enumerated() {
1045                 if needs_comma {
1046                     suggestion += ", ";
1047                 } else {
1048                     needs_comma = true;
1049                 }
1050                 let suggestion_text = if let Some(provided_idx) = provided_idx
1051                     && let (_, provided_span) = provided_arg_tys[*provided_idx]
1052                     && let Ok(arg_text) =
1053                         source_map.span_to_snippet(provided_span.source_callsite())
1054                 {
1055                     arg_text
1056                 } else {
1057                     // Propose a placeholder of the correct type
1058                     let (_, expected_ty) = formal_and_expected_inputs[expected_idx];
1059                     if expected_ty.is_unit() {
1060                         "()".to_string()
1061                     } else if expected_ty.is_suggestable(tcx) {
1062                         format!("/* {} */", expected_ty)
1063                     } else {
1064                         "/* value */".to_string()
1065                     }
1066                 };
1067                 suggestion += &suggestion_text;
1068             }
1069             suggestion += ")";
1070             err.span_suggestion_verbose(
1071                 error_span,
1072                 &suggestion_text,
1073                 suggestion,
1074                 Applicability::HasPlaceholders,
1075             );
1076         }
1077
1078         err.emit();
1079     }
1080
1081     // AST fragment checking
1082     pub(in super::super) fn check_lit(
1083         &self,
1084         lit: &hir::Lit,
1085         expected: Expectation<'tcx>,
1086     ) -> Ty<'tcx> {
1087         let tcx = self.tcx;
1088
1089         match lit.node {
1090             ast::LitKind::Str(..) => tcx.mk_static_str(),
1091             ast::LitKind::ByteStr(ref v) => {
1092                 tcx.mk_imm_ref(tcx.lifetimes.re_static, tcx.mk_array(tcx.types.u8, v.len() as u64))
1093             }
1094             ast::LitKind::Byte(_) => tcx.types.u8,
1095             ast::LitKind::Char(_) => tcx.types.char,
1096             ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(ty::int_ty(t)),
1097             ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(ty::uint_ty(t)),
1098             ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
1099                 let opt_ty = expected.to_option(self).and_then(|ty| match ty.kind() {
1100                     ty::Int(_) | ty::Uint(_) => Some(ty),
1101                     ty::Char => Some(tcx.types.u8),
1102                     ty::RawPtr(..) => Some(tcx.types.usize),
1103                     ty::FnDef(..) | ty::FnPtr(_) => Some(tcx.types.usize),
1104                     _ => None,
1105                 });
1106                 opt_ty.unwrap_or_else(|| self.next_int_var())
1107             }
1108             ast::LitKind::Float(_, ast::LitFloatType::Suffixed(t)) => {
1109                 tcx.mk_mach_float(ty::float_ty(t))
1110             }
1111             ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
1112                 let opt_ty = expected.to_option(self).and_then(|ty| match ty.kind() {
1113                     ty::Float(_) => Some(ty),
1114                     _ => None,
1115                 });
1116                 opt_ty.unwrap_or_else(|| self.next_float_var())
1117             }
1118             ast::LitKind::Bool(_) => tcx.types.bool,
1119             ast::LitKind::Err(_) => tcx.ty_error(),
1120         }
1121     }
1122
1123     pub fn check_struct_path(
1124         &self,
1125         qpath: &QPath<'_>,
1126         hir_id: hir::HirId,
1127     ) -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> {
1128         let path_span = qpath.span();
1129         let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, hir_id);
1130         let variant = match def {
1131             Res::Err => {
1132                 self.set_tainted_by_errors();
1133                 return None;
1134             }
1135             Res::Def(DefKind::Variant, _) => match ty.kind() {
1136                 ty::Adt(adt, substs) => Some((adt.variant_of_res(def), adt.did(), substs)),
1137                 _ => bug!("unexpected type: {:?}", ty),
1138             },
1139             Res::Def(DefKind::Struct | DefKind::Union | DefKind::TyAlias | DefKind::AssocTy, _)
1140             | Res::SelfTy { .. } => match ty.kind() {
1141                 ty::Adt(adt, substs) if !adt.is_enum() => {
1142                     Some((adt.non_enum_variant(), adt.did(), substs))
1143                 }
1144                 _ => None,
1145             },
1146             _ => bug!("unexpected definition: {:?}", def),
1147         };
1148
1149         if let Some((variant, did, substs)) = variant {
1150             debug!("check_struct_path: did={:?} substs={:?}", did, substs);
1151             self.write_user_type_annotation_from_substs(hir_id, did, substs, None);
1152
1153             // Check bounds on type arguments used in the path.
1154             self.add_required_obligations(path_span, did, substs);
1155
1156             Some((variant, ty))
1157         } else {
1158             match ty.kind() {
1159                 ty::Error(_) => {
1160                     // E0071 might be caused by a spelling error, which will have
1161                     // already caused an error message and probably a suggestion
1162                     // elsewhere. Refrain from emitting more unhelpful errors here
1163                     // (issue #88844).
1164                 }
1165                 _ => {
1166                     struct_span_err!(
1167                         self.tcx.sess,
1168                         path_span,
1169                         E0071,
1170                         "expected struct, variant or union type, found {}",
1171                         ty.sort_string(self.tcx)
1172                     )
1173                     .span_label(path_span, "not a struct")
1174                     .emit();
1175                 }
1176             }
1177             None
1178         }
1179     }
1180
1181     pub fn check_decl_initializer(
1182         &self,
1183         hir_id: hir::HirId,
1184         pat: &'tcx hir::Pat<'tcx>,
1185         init: &'tcx hir::Expr<'tcx>,
1186     ) -> Ty<'tcx> {
1187         // FIXME(tschottdorf): `contains_explicit_ref_binding()` must be removed
1188         // for #42640 (default match binding modes).
1189         //
1190         // See #44848.
1191         let ref_bindings = pat.contains_explicit_ref_binding();
1192
1193         let local_ty = self.local_ty(init.span, hir_id).revealed_ty;
1194         if let Some(m) = ref_bindings {
1195             // Somewhat subtle: if we have a `ref` binding in the pattern,
1196             // we want to avoid introducing coercions for the RHS. This is
1197             // both because it helps preserve sanity and, in the case of
1198             // ref mut, for soundness (issue #23116). In particular, in
1199             // the latter case, we need to be clear that the type of the
1200             // referent for the reference that results is *equal to* the
1201             // type of the place it is referencing, and not some
1202             // supertype thereof.
1203             let init_ty = self.check_expr_with_needs(init, Needs::maybe_mut_place(m));
1204             self.demand_eqtype(init.span, local_ty, init_ty);
1205             init_ty
1206         } else {
1207             self.check_expr_coercable_to_type(init, local_ty, None)
1208         }
1209     }
1210
1211     pub(in super::super) fn check_decl(&self, decl: Declaration<'tcx>) {
1212         // Determine and write the type which we'll check the pattern against.
1213         let decl_ty = self.local_ty(decl.span, decl.hir_id).decl_ty;
1214         self.write_ty(decl.hir_id, decl_ty);
1215
1216         // Type check the initializer.
1217         if let Some(ref init) = decl.init {
1218             let init_ty = self.check_decl_initializer(decl.hir_id, decl.pat, &init);
1219             self.overwrite_local_ty_if_err(decl.hir_id, decl.pat, decl_ty, init_ty);
1220         }
1221
1222         // Does the expected pattern type originate from an expression and what is the span?
1223         let (origin_expr, ty_span) = match (decl.ty, decl.init) {
1224             (Some(ty), _) => (false, Some(ty.span)), // Bias towards the explicit user type.
1225             (_, Some(init)) => (true, Some(init.span)), // No explicit type; so use the scrutinee.
1226             _ => (false, None), // We have `let $pat;`, so the expected type is unconstrained.
1227         };
1228
1229         // Type check the pattern. Override if necessary to avoid knock-on errors.
1230         self.check_pat_top(&decl.pat, decl_ty, ty_span, origin_expr);
1231         let pat_ty = self.node_ty(decl.pat.hir_id);
1232         self.overwrite_local_ty_if_err(decl.hir_id, decl.pat, decl_ty, pat_ty);
1233
1234         if let Some(blk) = decl.els {
1235             let previous_diverges = self.diverges.get();
1236             let else_ty = self.check_block_with_expected(blk, NoExpectation);
1237             let cause = self.cause(blk.span, ObligationCauseCode::LetElse);
1238             if let Some(mut err) =
1239                 self.demand_eqtype_with_origin(&cause, self.tcx.types.never, else_ty)
1240             {
1241                 err.emit();
1242             }
1243             self.diverges.set(previous_diverges);
1244         }
1245     }
1246
1247     /// Type check a `let` statement.
1248     pub fn check_decl_local(&self, local: &'tcx hir::Local<'tcx>) {
1249         self.check_decl(local.into());
1250     }
1251
1252     pub fn check_stmt(&self, stmt: &'tcx hir::Stmt<'tcx>, is_last: bool) {
1253         // Don't do all the complex logic below for `DeclItem`.
1254         match stmt.kind {
1255             hir::StmtKind::Item(..) => return,
1256             hir::StmtKind::Local(..) | hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => {}
1257         }
1258
1259         self.warn_if_unreachable(stmt.hir_id, stmt.span, "statement");
1260
1261         // Hide the outer diverging and `has_errors` flags.
1262         let old_diverges = self.diverges.replace(Diverges::Maybe);
1263         let old_has_errors = self.has_errors.replace(false);
1264
1265         match stmt.kind {
1266             hir::StmtKind::Local(l) => {
1267                 self.check_decl_local(l);
1268             }
1269             // Ignore for now.
1270             hir::StmtKind::Item(_) => {}
1271             hir::StmtKind::Expr(ref expr) => {
1272                 // Check with expected type of `()`.
1273                 self.check_expr_has_type_or_error(&expr, self.tcx.mk_unit(), |err| {
1274                     if expr.can_have_side_effects() {
1275                         self.suggest_semicolon_at_end(expr.span, err);
1276                     }
1277                 });
1278             }
1279             hir::StmtKind::Semi(ref expr) => {
1280                 // All of this is equivalent to calling `check_expr`, but it is inlined out here
1281                 // in order to capture the fact that this `match` is the last statement in its
1282                 // function. This is done for better suggestions to remove the `;`.
1283                 let expectation = match expr.kind {
1284                     hir::ExprKind::Match(..) if is_last => IsLast(stmt.span),
1285                     _ => NoExpectation,
1286                 };
1287                 self.check_expr_with_expectation(expr, expectation);
1288             }
1289         }
1290
1291         // Combine the diverging and `has_error` flags.
1292         self.diverges.set(self.diverges.get() | old_diverges);
1293         self.has_errors.set(self.has_errors.get() | old_has_errors);
1294     }
1295
1296     pub fn check_block_no_value(&self, blk: &'tcx hir::Block<'tcx>) {
1297         let unit = self.tcx.mk_unit();
1298         let ty = self.check_block_with_expected(blk, ExpectHasType(unit));
1299
1300         // if the block produces a `!` value, that can always be
1301         // (effectively) coerced to unit.
1302         if !ty.is_never() {
1303             self.demand_suptype(blk.span, unit, ty);
1304         }
1305     }
1306
1307     pub(in super::super) fn check_block_with_expected(
1308         &self,
1309         blk: &'tcx hir::Block<'tcx>,
1310         expected: Expectation<'tcx>,
1311     ) -> Ty<'tcx> {
1312         let prev = self.ps.replace(self.ps.get().recurse(blk));
1313
1314         // In some cases, blocks have just one exit, but other blocks
1315         // can be targeted by multiple breaks. This can happen both
1316         // with labeled blocks as well as when we desugar
1317         // a `try { ... }` expression.
1318         //
1319         // Example 1:
1320         //
1321         //    'a: { if true { break 'a Err(()); } Ok(()) }
1322         //
1323         // Here we would wind up with two coercions, one from
1324         // `Err(())` and the other from the tail expression
1325         // `Ok(())`. If the tail expression is omitted, that's a
1326         // "forced unit" -- unless the block diverges, in which
1327         // case we can ignore the tail expression (e.g., `'a: {
1328         // break 'a 22; }` would not force the type of the block
1329         // to be `()`).
1330         let tail_expr = blk.expr.as_ref();
1331         let coerce_to_ty = expected.coercion_target_type(self, blk.span);
1332         let coerce = if blk.targeted_by_break {
1333             CoerceMany::new(coerce_to_ty)
1334         } else {
1335             let tail_expr: &[&hir::Expr<'_>] = match tail_expr {
1336                 Some(e) => slice::from_ref(e),
1337                 None => &[],
1338             };
1339             CoerceMany::with_coercion_sites(coerce_to_ty, tail_expr)
1340         };
1341
1342         let prev_diverges = self.diverges.get();
1343         let ctxt = BreakableCtxt { coerce: Some(coerce), may_break: false };
1344
1345         let (ctxt, ()) = self.with_breakable_ctxt(blk.hir_id, ctxt, || {
1346             for (pos, s) in blk.stmts.iter().enumerate() {
1347                 self.check_stmt(s, blk.stmts.len() - 1 == pos);
1348             }
1349
1350             // check the tail expression **without** holding the
1351             // `enclosing_breakables` lock below.
1352             let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected));
1353
1354             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1355             let ctxt = enclosing_breakables.find_breakable(blk.hir_id);
1356             let coerce = ctxt.coerce.as_mut().unwrap();
1357             if let Some(tail_expr_ty) = tail_expr_ty {
1358                 let tail_expr = tail_expr.unwrap();
1359                 let span = self.get_expr_coercion_span(tail_expr);
1360                 let cause = self.cause(span, ObligationCauseCode::BlockTailExpression(blk.hir_id));
1361                 let ty_for_diagnostic = coerce.merged_ty();
1362                 // We use coerce_inner here because we want to augment the error
1363                 // suggesting to wrap the block in square brackets if it might've
1364                 // been mistaken array syntax
1365                 coerce.coerce_inner(
1366                     self,
1367                     &cause,
1368                     Some(tail_expr),
1369                     tail_expr_ty,
1370                     Some(&mut |diag: &mut Diagnostic| {
1371                         self.suggest_block_to_brackets(diag, blk, tail_expr_ty, ty_for_diagnostic);
1372                     }),
1373                     false,
1374                 );
1375             } else {
1376                 // Subtle: if there is no explicit tail expression,
1377                 // that is typically equivalent to a tail expression
1378                 // of `()` -- except if the block diverges. In that
1379                 // case, there is no value supplied from the tail
1380                 // expression (assuming there are no other breaks,
1381                 // this implies that the type of the block will be
1382                 // `!`).
1383                 //
1384                 // #41425 -- label the implicit `()` as being the
1385                 // "found type" here, rather than the "expected type".
1386                 if !self.diverges.get().is_always() {
1387                     // #50009 -- Do not point at the entire fn block span, point at the return type
1388                     // span, as it is the cause of the requirement, and
1389                     // `consider_hint_about_removing_semicolon` will point at the last expression
1390                     // if it were a relevant part of the error. This improves usability in editors
1391                     // that highlight errors inline.
1392                     let mut sp = blk.span;
1393                     let mut fn_span = None;
1394                     if let Some((decl, ident)) = self.get_parent_fn_decl(blk.hir_id) {
1395                         let ret_sp = decl.output.span();
1396                         if let Some(block_sp) = self.parent_item_span(blk.hir_id) {
1397                             // HACK: on some cases (`ui/liveness/liveness-issue-2163.rs`) the
1398                             // output would otherwise be incorrect and even misleading. Make sure
1399                             // the span we're aiming at correspond to a `fn` body.
1400                             if block_sp == blk.span {
1401                                 sp = ret_sp;
1402                                 fn_span = Some(ident.span);
1403                             }
1404                         }
1405                     }
1406                     coerce.coerce_forced_unit(
1407                         self,
1408                         &self.misc(sp),
1409                         &mut |err| {
1410                             if let Some(expected_ty) = expected.only_has_type(self) {
1411                                 if !self.consider_removing_semicolon(blk, expected_ty, err) {
1412                                     self.consider_returning_binding(blk, expected_ty, err);
1413                                 }
1414                                 if expected_ty == self.tcx.types.bool {
1415                                     // If this is caused by a missing `let` in a `while let`,
1416                                     // silence this redundant error, as we already emit E0070.
1417
1418                                     // Our block must be a `assign desugar local; assignment`
1419                                     if let Some(hir::Node::Block(hir::Block {
1420                                         stmts:
1421                                             [
1422                                                 hir::Stmt {
1423                                                     kind:
1424                                                         hir::StmtKind::Local(hir::Local {
1425                                                             source:
1426                                                                 hir::LocalSource::AssignDesugar(_),
1427                                                             ..
1428                                                         }),
1429                                                     ..
1430                                                 },
1431                                                 hir::Stmt {
1432                                                     kind:
1433                                                         hir::StmtKind::Expr(hir::Expr {
1434                                                             kind: hir::ExprKind::Assign(..),
1435                                                             ..
1436                                                         }),
1437                                                     ..
1438                                                 },
1439                                             ],
1440                                         ..
1441                                     })) = self.tcx.hir().find(blk.hir_id)
1442                                     {
1443                                         self.comes_from_while_condition(blk.hir_id, |_| {
1444                                             err.downgrade_to_delayed_bug();
1445                                         })
1446                                     }
1447                                 }
1448                             }
1449                             if let Some(fn_span) = fn_span {
1450                                 err.span_label(
1451                                     fn_span,
1452                                     "implicitly returns `()` as its body has no tail or `return` \
1453                                      expression",
1454                                 );
1455                             }
1456                         },
1457                         false,
1458                     );
1459                 }
1460             }
1461         });
1462
1463         if ctxt.may_break {
1464             // If we can break from the block, then the block's exit is always reachable
1465             // (... as long as the entry is reachable) - regardless of the tail of the block.
1466             self.diverges.set(prev_diverges);
1467         }
1468
1469         let mut ty = ctxt.coerce.unwrap().complete(self);
1470
1471         if self.has_errors.get() || ty.references_error() {
1472             ty = self.tcx.ty_error()
1473         }
1474
1475         self.write_ty(blk.hir_id, ty);
1476
1477         self.ps.set(prev);
1478         ty
1479     }
1480
1481     fn parent_item_span(&self, id: hir::HirId) -> Option<Span> {
1482         let node = self.tcx.hir().get_by_def_id(self.tcx.hir().get_parent_item(id));
1483         match node {
1484             Node::Item(&hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })
1485             | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body_id), .. }) => {
1486                 let body = self.tcx.hir().body(body_id);
1487                 if let ExprKind::Block(block, _) = &body.value.kind {
1488                     return Some(block.span);
1489                 }
1490             }
1491             _ => {}
1492         }
1493         None
1494     }
1495
1496     /// Given a function block's `HirId`, returns its `FnDecl` if it exists, or `None` otherwise.
1497     fn get_parent_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl<'tcx>, Ident)> {
1498         let parent = self.tcx.hir().get_by_def_id(self.tcx.hir().get_parent_item(blk_id));
1499         self.get_node_fn_decl(parent).map(|(fn_decl, ident, _)| (fn_decl, ident))
1500     }
1501
1502     /// If `expr` is a `match` expression that has only one non-`!` arm, use that arm's tail
1503     /// expression's `Span`, otherwise return `expr.span`. This is done to give better errors
1504     /// when given code like the following:
1505     /// ```text
1506     /// if false { return 0i32; } else { 1u32 }
1507     /// //                               ^^^^ point at this instead of the whole `if` expression
1508     /// ```
1509     fn get_expr_coercion_span(&self, expr: &hir::Expr<'_>) -> rustc_span::Span {
1510         let check_in_progress = |elem: &hir::Expr<'_>| {
1511             self.in_progress_typeck_results
1512                 .and_then(|typeck_results| typeck_results.borrow().node_type_opt(elem.hir_id))
1513                 .and_then(|ty| {
1514                     if ty.is_never() {
1515                         None
1516                     } else {
1517                         Some(match elem.kind {
1518                             // Point at the tail expression when possible.
1519                             hir::ExprKind::Block(block, _) => {
1520                                 block.expr.map_or(block.span, |e| e.span)
1521                             }
1522                             _ => elem.span,
1523                         })
1524                     }
1525                 })
1526         };
1527
1528         if let hir::ExprKind::If(_, _, Some(el)) = expr.kind {
1529             if let Some(rslt) = check_in_progress(el) {
1530                 return rslt;
1531             }
1532         }
1533
1534         if let hir::ExprKind::Match(_, arms, _) = expr.kind {
1535             let mut iter = arms.iter().filter_map(|arm| check_in_progress(arm.body));
1536             if let Some(span) = iter.next() {
1537                 if iter.next().is_none() {
1538                     return span;
1539                 }
1540             }
1541         }
1542
1543         expr.span
1544     }
1545
1546     fn overwrite_local_ty_if_err(
1547         &self,
1548         hir_id: hir::HirId,
1549         pat: &'tcx hir::Pat<'tcx>,
1550         decl_ty: Ty<'tcx>,
1551         ty: Ty<'tcx>,
1552     ) {
1553         if ty.references_error() {
1554             // Override the types everywhere with `err()` to avoid knock on errors.
1555             self.write_ty(hir_id, ty);
1556             self.write_ty(pat.hir_id, ty);
1557             let local_ty = LocalTy { decl_ty, revealed_ty: ty };
1558             self.locals.borrow_mut().insert(hir_id, local_ty);
1559             self.locals.borrow_mut().insert(pat.hir_id, local_ty);
1560         }
1561     }
1562
1563     // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
1564     // The newly resolved definition is written into `type_dependent_defs`.
1565     fn finish_resolving_struct_path(
1566         &self,
1567         qpath: &QPath<'_>,
1568         path_span: Span,
1569         hir_id: hir::HirId,
1570     ) -> (Res, Ty<'tcx>) {
1571         match *qpath {
1572             QPath::Resolved(ref maybe_qself, ref path) => {
1573                 let self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself));
1574                 let ty = <dyn AstConv<'_>>::res_to_ty(self, self_ty, path, true);
1575                 (path.res, ty)
1576             }
1577             QPath::TypeRelative(ref qself, ref segment) => {
1578                 let ty = self.to_ty(qself);
1579
1580                 let result = <dyn AstConv<'_>>::associated_path_to_ty(
1581                     self, hir_id, path_span, ty, qself, segment, true,
1582                 );
1583                 let ty = result.map(|(ty, _, _)| ty).unwrap_or_else(|_| self.tcx().ty_error());
1584                 let result = result.map(|(_, kind, def_id)| (kind, def_id));
1585
1586                 // Write back the new resolution.
1587                 self.write_resolution(hir_id, result);
1588
1589                 (result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), ty)
1590             }
1591             QPath::LangItem(lang_item, span, id) => {
1592                 self.resolve_lang_item_path(lang_item, span, hir_id, id)
1593             }
1594         }
1595     }
1596
1597     /// Given a vec of evaluated `FulfillmentError`s and an `fn` call argument expressions, we walk
1598     /// the checked and coerced types for each argument to see if any of the `FulfillmentError`s
1599     /// reference a type argument. The reason to walk also the checked type is that the coerced type
1600     /// can be not easily comparable with predicate type (because of coercion). If the types match
1601     /// for either checked or coerced type, and there's only *one* argument that does, we point at
1602     /// the corresponding argument's expression span instead of the `fn` call path span.
1603     fn point_at_arg_instead_of_call_if_possible(
1604         &self,
1605         errors: &mut Vec<traits::FulfillmentError<'tcx>>,
1606         expr: &'tcx hir::Expr<'tcx>,
1607         call_sp: Span,
1608         args: &'tcx [hir::Expr<'tcx>],
1609         expected_tys: &[Ty<'tcx>],
1610     ) {
1611         // We *do not* do this for desugared call spans to keep good diagnostics when involving
1612         // the `?` operator.
1613         if call_sp.desugaring_kind().is_some() {
1614             return;
1615         }
1616
1617         'outer: for error in errors {
1618             // Only if the cause is somewhere inside the expression we want try to point at arg.
1619             // Otherwise, it means that the cause is somewhere else and we should not change
1620             // anything because we can break the correct span.
1621             if !call_sp.contains(error.obligation.cause.span) {
1622                 continue;
1623             }
1624
1625             // Peel derived obligation, because it's the type that originally
1626             // started this inference chain that matters, not the one we wound
1627             // up with at the end.
1628             fn unpeel_to_top<'a, 'tcx>(
1629                 mut code: &'a ObligationCauseCode<'tcx>,
1630             ) -> &'a ObligationCauseCode<'tcx> {
1631                 let mut result_code = code;
1632                 loop {
1633                     let parent = match code {
1634                         ObligationCauseCode::ImplDerivedObligation(c) => &c.derived.parent_code,
1635                         ObligationCauseCode::BuiltinDerivedObligation(c)
1636                         | ObligationCauseCode::DerivedObligation(c) => &c.parent_code,
1637                         _ => break result_code,
1638                     };
1639                     (result_code, code) = (code, parent);
1640                 }
1641             }
1642             let self_: ty::subst::GenericArg<'_> =
1643                 match unpeel_to_top(error.obligation.cause.code()) {
1644                     ObligationCauseCode::BuiltinDerivedObligation(code)
1645                     | ObligationCauseCode::DerivedObligation(code) => {
1646                         code.parent_trait_pred.self_ty().skip_binder().into()
1647                     }
1648                     ObligationCauseCode::ImplDerivedObligation(code) => {
1649                         code.derived.parent_trait_pred.self_ty().skip_binder().into()
1650                     }
1651                     _ if let ty::PredicateKind::Trait(predicate) =
1652                         error.obligation.predicate.kind().skip_binder() =>
1653                     {
1654                         predicate.self_ty().into()
1655                     }
1656                     _ => continue,
1657                 };
1658             let self_ = self.resolve_vars_if_possible(self_);
1659             let ty_matches_self = |ty: Ty<'tcx>| ty.walk().any(|arg| arg == self_);
1660
1661             let typeck_results = self.typeck_results.borrow();
1662
1663             for (idx, arg) in args.iter().enumerate() {
1664                 // Don't adjust the span if we already have a more precise span
1665                 // within one of the args.
1666                 if arg.span.contains(error.obligation.cause.span) {
1667                     let references_arg =
1668                         typeck_results.expr_ty_opt(arg).map_or(false, &ty_matches_self)
1669                             || expected_tys.get(idx).copied().map_or(false, &ty_matches_self);
1670                     if references_arg && !arg.span.from_expansion() {
1671                         error.obligation.cause.map_code(|parent_code| {
1672                             ObligationCauseCode::FunctionArgumentObligation {
1673                                 arg_hir_id: args[idx].hir_id,
1674                                 call_hir_id: expr.hir_id,
1675                                 parent_code,
1676                             }
1677                         })
1678                     }
1679                     continue 'outer;
1680                 }
1681             }
1682
1683             // Collect the argument position for all arguments that could have caused this
1684             // `FulfillmentError`.
1685             let mut referenced_in: Vec<_> = std::iter::zip(expected_tys, args)
1686                 .enumerate()
1687                 .flat_map(|(idx, (expected_ty, arg))| {
1688                     if let Some(arg_ty) = typeck_results.expr_ty_opt(arg) {
1689                         vec![(idx, arg_ty), (idx, *expected_ty)]
1690                     } else {
1691                         vec![]
1692                     }
1693                 })
1694                 .filter_map(|(i, ty)| {
1695                     let ty = self.resolve_vars_if_possible(ty);
1696                     // We walk the argument type because the argument's type could have
1697                     // been `Option<T>`, but the `FulfillmentError` references `T`.
1698                     if ty_matches_self(ty) { Some(i) } else { None }
1699                 })
1700                 .collect();
1701
1702             // Both checked and coerced types could have matched, thus we need to remove
1703             // duplicates.
1704
1705             // We sort primitive type usize here and can use unstable sort
1706             referenced_in.sort_unstable();
1707             referenced_in.dedup();
1708
1709             if let &[idx] = &referenced_in[..] {
1710                 // Do not point at the inside of a macro.
1711                 // That would often result in poor error messages.
1712                 if args[idx].span.from_expansion() {
1713                     continue;
1714                 }
1715                 // We make sure that only *one* argument matches the obligation failure
1716                 // and we assign the obligation's span to its expression's.
1717                 error.obligation.cause.span = args[idx].span;
1718                 error.obligation.cause.map_code(|parent_code| {
1719                     ObligationCauseCode::FunctionArgumentObligation {
1720                         arg_hir_id: args[idx].hir_id,
1721                         call_hir_id: expr.hir_id,
1722                         parent_code,
1723                     }
1724                 });
1725             } else if error.obligation.cause.span == call_sp {
1726                 // Make function calls point at the callee, not the whole thing.
1727                 if let hir::ExprKind::Call(callee, _) = expr.kind {
1728                     error.obligation.cause.span = callee.span;
1729                 }
1730             }
1731         }
1732     }
1733
1734     /// Given a vec of evaluated `FulfillmentError`s and an `fn` call expression, we walk the
1735     /// `PathSegment`s and resolve their type parameters to see if any of the `FulfillmentError`s
1736     /// were caused by them. If they were, we point at the corresponding type argument's span
1737     /// instead of the `fn` call path span.
1738     fn point_at_type_arg_instead_of_call_if_possible(
1739         &self,
1740         errors: &mut Vec<traits::FulfillmentError<'tcx>>,
1741         call_expr: &'tcx hir::Expr<'tcx>,
1742     ) {
1743         if let hir::ExprKind::Call(path, _) = &call_expr.kind {
1744             if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &path.kind {
1745                 for error in errors {
1746                     if let ty::PredicateKind::Trait(predicate) =
1747                         error.obligation.predicate.kind().skip_binder()
1748                     {
1749                         // If any of the type arguments in this path segment caused the
1750                         // `FulfillmentError`, point at its span (#61860).
1751                         for arg in path
1752                             .segments
1753                             .iter()
1754                             .filter_map(|seg| seg.args.as_ref())
1755                             .flat_map(|a| a.args.iter())
1756                         {
1757                             if let hir::GenericArg::Type(hir_ty) = &arg {
1758                                 if let hir::TyKind::Path(hir::QPath::TypeRelative(..)) =
1759                                     &hir_ty.kind
1760                                 {
1761                                     // Avoid ICE with associated types. As this is best
1762                                     // effort only, it's ok to ignore the case. It
1763                                     // would trigger in `is_send::<T::AssocType>();`
1764                                     // from `typeck-default-trait-impl-assoc-type.rs`.
1765                                 } else {
1766                                     let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, hir_ty);
1767                                     let ty = self.resolve_vars_if_possible(ty);
1768                                     if ty == predicate.self_ty() {
1769                                         error.obligation.cause.span = hir_ty.span;
1770                                     }
1771                                 }
1772                             }
1773                         }
1774                     }
1775                 }
1776             }
1777         }
1778     }
1779
1780     fn label_fn_like(
1781         &self,
1782         err: &mut rustc_errors::DiagnosticBuilder<'tcx, rustc_errors::ErrorGuaranteed>,
1783         callable_def_id: Option<DefId>,
1784         callee_ty: Option<Ty<'tcx>>,
1785     ) {
1786         let Some(mut def_id) = callable_def_id else {
1787             return;
1788         };
1789
1790         if let Some(assoc_item) = self.tcx.opt_associated_item(def_id)
1791             // Possibly points at either impl or trait item, so try to get it
1792             // to point to trait item, then get the parent.
1793             // This parent might be an impl in the case of an inherent function,
1794             // but the next check will fail.
1795             && let maybe_trait_item_def_id = assoc_item.trait_item_def_id.unwrap_or(def_id)
1796             && let maybe_trait_def_id = self.tcx.parent(maybe_trait_item_def_id)
1797             // Just an easy way to check "trait_def_id == Fn/FnMut/FnOnce"
1798             && let Some(call_kind) = ty::ClosureKind::from_def_id(self.tcx, maybe_trait_def_id)
1799             && let Some(callee_ty) = callee_ty
1800         {
1801             let callee_ty = callee_ty.peel_refs();
1802             match *callee_ty.kind() {
1803                 ty::Param(param) => {
1804                     let param =
1805                         self.tcx.generics_of(self.body_id.owner).type_param(&param, self.tcx);
1806                     if param.kind.is_synthetic() {
1807                         // if it's `impl Fn() -> ..` then just fall down to the def-id based logic
1808                         def_id = param.def_id;
1809                     } else {
1810                         // Otherwise, find the predicate that makes this generic callable,
1811                         // and point at that.
1812                         let instantiated = self
1813                             .tcx
1814                             .explicit_predicates_of(self.body_id.owner)
1815                             .instantiate_identity(self.tcx);
1816                         // FIXME(compiler-errors): This could be problematic if something has two
1817                         // fn-like predicates with different args, but callable types really never
1818                         // do that, so it's OK.
1819                         for (predicate, span) in
1820                             std::iter::zip(instantiated.predicates, instantiated.spans)
1821                         {
1822                             if let ty::PredicateKind::Trait(pred) = predicate.kind().skip_binder()
1823                                 && pred.self_ty().peel_refs() == callee_ty
1824                                 && ty::ClosureKind::from_def_id(self.tcx, pred.def_id()).is_some()
1825                             {
1826                                 err.span_note(span, "callable defined here");
1827                                 return;
1828                             }
1829                         }
1830                     }
1831                 }
1832                 ty::Opaque(new_def_id, _)
1833                 | ty::Closure(new_def_id, _)
1834                 | ty::FnDef(new_def_id, _) => {
1835                     def_id = new_def_id;
1836                 }
1837                 _ => {
1838                     // Look for a user-provided impl of a `Fn` trait, and point to it.
1839                     let new_def_id = self.probe(|_| {
1840                         let trait_ref = ty::TraitRef::new(
1841                             call_kind.to_def_id(self.tcx),
1842                             self.tcx.mk_substs([
1843                                 ty::GenericArg::from(callee_ty),
1844                                 self.next_ty_var(TypeVariableOrigin {
1845                                     kind: TypeVariableOriginKind::MiscVariable,
1846                                     span: rustc_span::DUMMY_SP,
1847                                 })
1848                                 .into(),
1849                             ].into_iter()),
1850                         );
1851                         let obligation = traits::Obligation::new(
1852                             traits::ObligationCause::dummy(),
1853                             self.param_env,
1854                             ty::Binder::dummy(ty::TraitPredicate {
1855                                 trait_ref,
1856                                 constness: ty::BoundConstness::NotConst,
1857                                 polarity: ty::ImplPolarity::Positive,
1858                             }),
1859                         );
1860                         match SelectionContext::new(&self).select(&obligation) {
1861                             Ok(Some(traits::ImplSource::UserDefined(impl_source))) => {
1862                                 Some(impl_source.impl_def_id)
1863                             }
1864                             _ => None
1865                         }
1866                     });
1867                     if let Some(new_def_id) = new_def_id {
1868                         def_id = new_def_id;
1869                     } else {
1870                         return;
1871                     }
1872                 }
1873             }
1874         }
1875
1876         if let Some(def_span) = self.tcx.def_ident_span(def_id) && !def_span.is_dummy() {
1877             let mut spans: MultiSpan = def_span.into();
1878
1879             let params = self
1880                 .tcx
1881                 .hir()
1882                 .get_if_local(def_id)
1883                 .and_then(|node| node.body_id())
1884                 .into_iter()
1885                 .flat_map(|id| self.tcx.hir().body(id).params);
1886
1887             for param in params {
1888                 spans.push_span_label(param.span, "");
1889             }
1890
1891             let def_kind = self.tcx.def_kind(def_id);
1892             err.span_note(spans, &format!("{} defined here", def_kind.descr(def_id)));
1893         } else {
1894             let def_kind = self.tcx.def_kind(def_id);
1895             err.span_note(
1896                 self.tcx.def_span(def_id),
1897                 &format!("{} defined here", def_kind.descr(def_id)),
1898             );
1899         }
1900     }
1901 }