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