rustc_hir_typeck/fn_ctxt/
checks.rs

1use std::ops::Deref;
2use std::{fmt, iter};
3
4use itertools::Itertools;
5use rustc_data_structures::fx::FxIndexSet;
6use rustc_errors::codes::*;
7use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, a_or_an, listify, pluralize};
8use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
9use rustc_hir::def_id::DefId;
10use rustc_hir::intravisit::Visitor;
11use rustc_hir::{Expr, ExprKind, HirId, LangItem, Node, QPath, is_range_literal};
12use rustc_hir_analysis::check::potentially_plural_count;
13use rustc_hir_analysis::hir_ty_lowering::{HirTyLowerer, PermitVariants};
14use rustc_index::IndexVec;
15use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk, TypeTrace};
16use rustc_middle::ty::adjustment::AllowTwoPhase;
17use rustc_middle::ty::error::TypeError;
18use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt, TypeVisitableExt};
19use rustc_middle::{bug, span_bug};
20use rustc_session::Session;
21use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
22use rustc_trait_selection::error_reporting::infer::{FailureCode, ObligationCauseExt};
23use rustc_trait_selection::infer::InferCtxtExt;
24use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt, SelectionContext};
25use smallvec::SmallVec;
26use tracing::debug;
27use {rustc_ast as ast, rustc_hir as hir};
28
29use crate::Expectation::*;
30use crate::TupleArgumentsFlag::*;
31use crate::coercion::CoerceMany;
32use crate::errors::SuggestPtrNullMut;
33use crate::fn_ctxt::arg_matrix::{ArgMatrix, Compatibility, Error, ExpectedIdx, ProvidedIdx};
34use crate::gather_locals::Declaration;
35use crate::inline_asm::InlineAsmCtxt;
36use crate::method::probe::IsSuggestion;
37use crate::method::probe::Mode::MethodCall;
38use crate::method::probe::ProbeScope::TraitsInScope;
39use crate::{
40    BreakableCtxt, Diverges, Expectation, FnCtxt, GatherLocalsVisitor, LoweredTy, Needs,
41    TupleArgumentsFlag, errors, struct_span_code_err,
42};
43
44rustc_index::newtype_index! {
45    #[orderable]
46    #[debug_format = "GenericIdx({})"]
47    pub(crate) struct GenericIdx {}
48}
49
50#[derive(Clone, Copy, Default)]
51pub(crate) enum DivergingBlockBehavior {
52    /// This is the current stable behavior:
53    ///
54    /// ```rust
55    /// {
56    ///     return;
57    /// } // block has type = !, even though we are supposedly dropping it with `;`
58    /// ```
59    #[default]
60    Never,
61
62    /// Alternative behavior:
63    ///
64    /// ```ignore (very-unstable-new-attribute)
65    /// #![rustc_never_type_options(diverging_block_default = "unit")]
66    /// {
67    ///     return;
68    /// } // block has type = (), since we are dropping `!` from `return` with `;`
69    /// ```
70    Unit,
71}
72
73impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
74    pub(in super::super) fn check_casts(&mut self) {
75        let mut deferred_cast_checks = self.root_ctxt.deferred_cast_checks.borrow_mut();
76        debug!("FnCtxt::check_casts: {} deferred checks", deferred_cast_checks.len());
77        for cast in deferred_cast_checks.drain(..) {
78            let body_id = std::mem::replace(&mut self.body_id, cast.body_id);
79            cast.check(self);
80            self.body_id = body_id;
81        }
82    }
83
84    pub(in super::super) fn check_asms(&self) {
85        let mut deferred_asm_checks = self.deferred_asm_checks.borrow_mut();
86        debug!("FnCtxt::check_asm: {} deferred checks", deferred_asm_checks.len());
87        for (asm, hir_id) in deferred_asm_checks.drain(..) {
88            let enclosing_id = self.tcx.hir_enclosing_body_owner(hir_id);
89            InlineAsmCtxt::new(self, enclosing_id).check_asm(asm);
90        }
91    }
92
93    pub(in super::super) fn check_repeat_exprs(&self) {
94        let mut deferred_repeat_expr_checks = self.deferred_repeat_expr_checks.borrow_mut();
95        debug!("FnCtxt::check_repeat_exprs: {} deferred checks", deferred_repeat_expr_checks.len());
96
97        let deferred_repeat_expr_checks = deferred_repeat_expr_checks
98            .drain(..)
99            .flat_map(|(element, element_ty, count)| {
100                // Actual constants as the repeat element are inserted repeatedly instead
101                // of being copied via `Copy`, so we don't need to attempt to structurally
102                // resolve the repeat count which may unnecessarily error.
103                match &element.kind {
104                    hir::ExprKind::ConstBlock(..) => return None,
105                    hir::ExprKind::Path(qpath) => {
106                        let res = self.typeck_results.borrow().qpath_res(qpath, element.hir_id);
107                        if let Res::Def(DefKind::Const | DefKind::AssocConst, _) = res {
108                            return None;
109                        }
110                    }
111                    _ => {}
112                }
113
114                // We want to emit an error if the const is not structurally resolvable
115                // as otherwise we can wind up conservatively proving `Copy` which may
116                // infer the repeat expr count to something that never required `Copy` in
117                // the first place.
118                let count = self
119                    .structurally_resolve_const(element.span, self.normalize(element.span, count));
120
121                // Avoid run on "`NotCopy: Copy` is not implemented" errors when the
122                // repeat expr count is erroneous/unknown. The user might wind up
123                // specifying a repeat count of 0/1.
124                if count.references_error() {
125                    return None;
126                }
127
128                Some((element, element_ty, count))
129            })
130            // We collect to force the side effects of structurally resolving the repeat
131            // count to happen in one go, to avoid side effects from proving `Copy`
132            // affecting whether repeat counts are known or not. If we did not do this we
133            // would get results that depend on the order that we evaluate each repeat
134            // expr's `Copy` check.
135            .collect::<Vec<_>>();
136
137        let enforce_copy_bound = |element: &hir::Expr<'_>, element_ty| {
138            // If someone calls a const fn or constructs a const value, they can extract that
139            // out into a separate constant (or a const block in the future), so we check that
140            // to tell them that in the diagnostic. Does not affect typeck.
141            let is_constable = match element.kind {
142                hir::ExprKind::Call(func, _args) => match *self.node_ty(func.hir_id).kind() {
143                    ty::FnDef(def_id, _) if self.tcx.is_stable_const_fn(def_id) => {
144                        traits::IsConstable::Fn
145                    }
146                    _ => traits::IsConstable::No,
147                },
148                hir::ExprKind::Path(qpath) => {
149                    match self.typeck_results.borrow().qpath_res(&qpath, element.hir_id) {
150                        Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => traits::IsConstable::Ctor,
151                        _ => traits::IsConstable::No,
152                    }
153                }
154                _ => traits::IsConstable::No,
155            };
156
157            let lang_item = self.tcx.require_lang_item(LangItem::Copy, element.span);
158            let code = traits::ObligationCauseCode::RepeatElementCopy {
159                is_constable,
160                elt_span: element.span,
161            };
162            self.require_type_meets(element_ty, element.span, code, lang_item);
163        };
164
165        for (element, element_ty, count) in deferred_repeat_expr_checks {
166            match count.kind() {
167                ty::ConstKind::Value(val) => {
168                    if val.try_to_target_usize(self.tcx).is_none_or(|count| count > 1) {
169                        enforce_copy_bound(element, element_ty)
170                    } else {
171                        // If the length is 0 or 1 we don't actually copy the element, we either don't create it
172                        // or we just use the one value.
173                    }
174                }
175
176                // If the length is a generic parameter or some rigid alias then conservatively
177                // require `element_ty: Copy` as it may wind up being `>1` after monomorphization.
178                ty::ConstKind::Param(_)
179                | ty::ConstKind::Expr(_)
180                | ty::ConstKind::Placeholder(_)
181                | ty::ConstKind::Unevaluated(_) => enforce_copy_bound(element, element_ty),
182
183                ty::ConstKind::Bound(_, _) | ty::ConstKind::Infer(_) | ty::ConstKind::Error(_) => {
184                    unreachable!()
185                }
186            }
187        }
188    }
189
190    /// Generic function that factors out common logic from function calls,
191    /// method calls and overloaded operators.
192    pub(in super::super) fn check_argument_types(
193        &self,
194        // Span enclosing the call site
195        call_span: Span,
196        // Expression of the call site
197        call_expr: &'tcx hir::Expr<'tcx>,
198        // Types (as defined in the *signature* of the target function)
199        formal_input_tys: &[Ty<'tcx>],
200        formal_output: Ty<'tcx>,
201        // Expected output from the parent expression or statement
202        expectation: Expectation<'tcx>,
203        // The expressions for each provided argument
204        provided_args: &'tcx [hir::Expr<'tcx>],
205        // Whether the function is variadic, for example when imported from C
206        c_variadic: bool,
207        // Whether the arguments have been bundled in a tuple (ex: closures)
208        tuple_arguments: TupleArgumentsFlag,
209        // The DefId for the function being called, for better error messages
210        fn_def_id: Option<DefId>,
211    ) {
212        let tcx = self.tcx;
213
214        // Conceptually, we've got some number of expected inputs, and some number of provided arguments
215        // and we can form a grid of whether each argument could satisfy a given input:
216        //      in1 | in2 | in3 | ...
217        // arg1  ?  |     |     |
218        // arg2     |  ?  |     |
219        // arg3     |     |  ?  |
220        // ...
221        // Initially, we just check the diagonal, because in the case of correct code
222        // these are the only checks that matter
223        // However, in the unhappy path, we'll fill in this whole grid to attempt to provide
224        // better error messages about invalid method calls.
225
226        // All the input types from the fn signature must outlive the call
227        // so as to validate implied bounds.
228        for (&fn_input_ty, arg_expr) in iter::zip(formal_input_tys, provided_args) {
229            self.register_wf_obligation(
230                fn_input_ty.into(),
231                arg_expr.span,
232                ObligationCauseCode::WellFormed(None),
233            );
234
235            self.check_place_expr_if_unsized(fn_input_ty, arg_expr);
236        }
237
238        // First, let's unify the formal method signature with the expectation eagerly.
239        // We use this to guide coercion inference; it's output is "fudged" which means
240        // any remaining type variables are assigned to new, unrelated variables. This
241        // is because the inference guidance here is only speculative.
242        let formal_output = self.resolve_vars_with_obligations(formal_output);
243        let expected_input_tys: Option<Vec<_>> = expectation
244            .only_has_type(self)
245            .and_then(|expected_output| {
246                // FIXME(#149379): This operation results in expected input
247                // types which are potentially not well-formed or for whom the
248                // function where-bounds don't actually hold. This results
249                // in weird bugs when later treating these expectations as if
250                // they were actually correct.
251                self.fudge_inference_if_ok(|| {
252                    let ocx = ObligationCtxt::new(self);
253
254                    // Attempt to apply a subtyping relationship between the formal
255                    // return type (likely containing type variables if the function
256                    // is polymorphic) and the expected return type.
257                    // No argument expectations are produced if unification fails.
258                    let origin = self.misc(call_span);
259                    ocx.sup(&origin, self.param_env, expected_output, formal_output)?;
260
261                    let formal_input_tys_ns;
262                    let formal_input_tys = if self.next_trait_solver() {
263                        // In the new solver, the normalizations are done lazily.
264                        // Because of this, if we encounter unnormalized alias types inside this
265                        // fudge scope, we might lose the relationships between them and other vars
266                        // when fudging inference variables created here.
267                        // So, we utilize generalization to normalize aliases by adding a new
268                        // inference var and equating it with the type we want to pull out of the
269                        // fudge scope.
270                        formal_input_tys_ns = formal_input_tys
271                            .iter()
272                            .map(|&ty| {
273                                // If we replace a (unresolved) inference var with a new inference
274                                // var, it will be eventually resolved to itself and this will
275                                // weaken type inferences as the new inference var will be fudged
276                                // out and lose all relationships with other vars while the former
277                                // will not be fudged.
278                                if ty.is_ty_var() {
279                                    return ty;
280                                }
281
282                                let generalized_ty = self.next_ty_var(call_span);
283                                ocx.eq(&origin, self.param_env, ty, generalized_ty).unwrap();
284                                generalized_ty
285                            })
286                            .collect_vec();
287
288                        formal_input_tys_ns.as_slice()
289                    } else {
290                        formal_input_tys
291                    };
292
293                    if !ocx.try_evaluate_obligations().is_empty() {
294                        return Err(TypeError::Mismatch);
295                    }
296
297                    // Record all the argument types, with the args
298                    // produced from the above subtyping unification.
299                    Ok(Some(
300                        formal_input_tys
301                            .iter()
302                            .map(|&ty| self.resolve_vars_if_possible(ty))
303                            .collect(),
304                    ))
305                })
306                .ok()
307            })
308            .unwrap_or_default();
309
310        let mut err_code = E0061;
311
312        // If the arguments should be wrapped in a tuple (ex: closures), unwrap them here
313        let (formal_input_tys, expected_input_tys) = if tuple_arguments == TupleArguments {
314            let tuple_type = self.structurally_resolve_type(call_span, formal_input_tys[0]);
315            match tuple_type.kind() {
316                // We expected a tuple and got a tuple
317                ty::Tuple(arg_types) => {
318                    // Argument length differs
319                    if arg_types.len() != provided_args.len() {
320                        err_code = E0057;
321                    }
322                    let expected_input_tys = match expected_input_tys {
323                        Some(expected_input_tys) => match expected_input_tys.get(0) {
324                            Some(ty) => match ty.kind() {
325                                ty::Tuple(tys) => Some(tys.iter().collect()),
326                                _ => None,
327                            },
328                            None => None,
329                        },
330                        None => None,
331                    };
332                    (arg_types.iter().collect(), expected_input_tys)
333                }
334                _ => {
335                    // Otherwise, there's a mismatch, so clear out what we're expecting, and set
336                    // our input types to err_args so we don't blow up the error messages
337                    let guar = struct_span_code_err!(
338                        self.dcx(),
339                        call_span,
340                        E0059,
341                        "cannot use call notation; the first type parameter \
342                         for the function trait is neither a tuple nor unit"
343                    )
344                    .emit();
345                    (self.err_args(provided_args.len(), guar), None)
346                }
347            }
348        } else {
349            (formal_input_tys.to_vec(), expected_input_tys)
350        };
351
352        // If there are no external expectations at the call site, just use the types from the function defn
353        let expected_input_tys = if let Some(expected_input_tys) = expected_input_tys {
354            assert_eq!(expected_input_tys.len(), formal_input_tys.len());
355            expected_input_tys
356        } else {
357            formal_input_tys.clone()
358        };
359
360        let minimum_input_count = expected_input_tys.len();
361        let provided_arg_count = provided_args.len();
362
363        // We introduce a helper function to demand that a given argument satisfy a given input
364        // This is more complicated than just checking type equality, as arguments could be coerced
365        // This version writes those types back so further type checking uses the narrowed types
366        let demand_compatible = |idx| {
367            let formal_input_ty: Ty<'tcx> = formal_input_tys[idx];
368            let expected_input_ty: Ty<'tcx> = expected_input_tys[idx];
369            let provided_arg = &provided_args[idx];
370
371            debug!("checking argument {}: {:?} = {:?}", idx, provided_arg, formal_input_ty);
372
373            // We're on the happy path here, so we'll do a more involved check and write back types
374            // To check compatibility, we'll do 3 things:
375            // 1. Unify the provided argument with the expected type
376            let expectation = Expectation::rvalue_hint(self, expected_input_ty);
377
378            let checked_ty = self.check_expr_with_expectation(provided_arg, expectation);
379
380            // 2. Coerce to the most detailed type that could be coerced
381            //    to, which is `expected_ty` if `rvalue_hint` returns an
382            //    `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
383            let coerced_ty = expectation.only_has_type(self).unwrap_or(formal_input_ty);
384
385            // Cause selection errors caused by resolving a single argument to point at the
386            // argument and not the call. This lets us customize the span pointed to in the
387            // fulfillment error to be more accurate.
388            let coerced_ty = self.resolve_vars_with_obligations(coerced_ty);
389
390            let coerce_error =
391                self.coerce(provided_arg, checked_ty, coerced_ty, AllowTwoPhase::Yes, None).err();
392            if coerce_error.is_some() {
393                return Compatibility::Incompatible(coerce_error);
394            }
395
396            // 3. Check if the formal type is actually equal to the checked one
397            //    and register any such obligations for future type checks.
398            let formal_ty_error = self.at(&self.misc(provided_arg.span), self.param_env).eq(
399                DefineOpaqueTypes::Yes,
400                formal_input_ty,
401                coerced_ty,
402            );
403
404            // If neither check failed, the types are compatible
405            match formal_ty_error {
406                Ok(InferOk { obligations, value: () }) => {
407                    self.register_predicates(obligations);
408                    Compatibility::Compatible
409                }
410                Err(err) => Compatibility::Incompatible(Some(err)),
411            }
412        };
413
414        // To start, we only care "along the diagonal", where we expect every
415        // provided arg to be in the right spot
416        let mut compatibility_diagonal =
417            vec![Compatibility::Incompatible(None); provided_args.len()];
418
419        // Keep track of whether we *could possibly* be satisfied, i.e. whether we're on the happy path
420        // if the wrong number of arguments were supplied, we CAN'T be satisfied,
421        // and if we're c_variadic, the supplied arguments must be >= the minimum count from the function
422        // otherwise, they need to be identical, because rust doesn't currently support variadic functions
423        let mut call_appears_satisfied = if c_variadic {
424            provided_arg_count >= minimum_input_count
425        } else {
426            provided_arg_count == minimum_input_count
427        };
428
429        // Check the arguments.
430        // We do this in a pretty awful way: first we type-check any arguments
431        // that are not closures, then we type-check the closures. This is so
432        // that we have more information about the types of arguments when we
433        // type-check the functions. This isn't really the right way to do this.
434        for check_closures in [false, true] {
435            // More awful hacks: before we check argument types, try to do
436            // an "opportunistic" trait resolution of any trait bounds on
437            // the call. This helps coercions.
438            if check_closures {
439                self.select_obligations_where_possible(|_| {})
440            }
441
442            // Check each argument, to satisfy the input it was provided for
443            // Visually, we're traveling down the diagonal of the compatibility matrix
444            for (idx, arg) in provided_args.iter().enumerate() {
445                // Warn only for the first loop (the "no closures" one).
446                // Closure arguments themselves can't be diverging, but
447                // a previous argument can, e.g., `foo(panic!(), || {})`.
448                if !check_closures {
449                    self.warn_if_unreachable(arg.hir_id, arg.span, "expression");
450                }
451
452                // For C-variadic functions, we don't have a declared type for all of
453                // the arguments hence we only do our usual type checking with
454                // the arguments who's types we do know. However, we *can* check
455                // for unreachable expressions (see above).
456                // FIXME: unreachable warning current isn't emitted
457                if idx >= minimum_input_count {
458                    continue;
459                }
460
461                // For this check, we do *not* want to treat async coroutine closures (async blocks)
462                // as proper closures. Doing so would regress type inference when feeding
463                // the return value of an argument-position async block to an argument-position
464                // closure wrapped in a block.
465                // See <https://github.com/rust-lang/rust/issues/112225>.
466                let is_closure = if let ExprKind::Closure(closure) = arg.kind {
467                    !tcx.coroutine_is_async(closure.def_id.to_def_id())
468                } else {
469                    false
470                };
471                if is_closure != check_closures {
472                    continue;
473                }
474
475                let compatible = demand_compatible(idx);
476                let is_compatible = matches!(compatible, Compatibility::Compatible);
477                compatibility_diagonal[idx] = compatible;
478
479                if !is_compatible {
480                    call_appears_satisfied = false;
481                }
482            }
483        }
484
485        if c_variadic && provided_arg_count < minimum_input_count {
486            err_code = E0060;
487        }
488
489        for arg in provided_args.iter().skip(minimum_input_count) {
490            // Make sure we've checked this expr at least once.
491            let arg_ty = self.check_expr(arg);
492
493            // If the function is c-style variadic, we skipped a bunch of arguments
494            // so we need to check those, and write out the types
495            // Ideally this would be folded into the above, for uniform style
496            // but c-variadic is already a corner case
497            if c_variadic {
498                fn variadic_error<'tcx>(
499                    sess: &'tcx Session,
500                    span: Span,
501                    ty: Ty<'tcx>,
502                    cast_ty: &str,
503                ) {
504                    sess.dcx().emit_err(errors::PassToVariadicFunction {
505                        span,
506                        ty,
507                        cast_ty,
508                        sugg_span: span.shrink_to_hi(),
509                        teach: sess.teach(E0617),
510                    });
511                }
512
513                // There are a few types which get autopromoted when passed via varargs
514                // in C but we just error out instead and require explicit casts.
515                let arg_ty = self.structurally_resolve_type(arg.span, arg_ty);
516                match arg_ty.kind() {
517                    ty::Float(ty::FloatTy::F32) => {
518                        variadic_error(tcx.sess, arg.span, arg_ty, "c_double");
519                    }
520                    ty::Int(ty::IntTy::I8 | ty::IntTy::I16) | ty::Bool => {
521                        variadic_error(tcx.sess, arg.span, arg_ty, "c_int");
522                    }
523                    ty::Uint(ty::UintTy::U8 | ty::UintTy::U16) => {
524                        variadic_error(tcx.sess, arg.span, arg_ty, "c_uint");
525                    }
526                    ty::FnDef(..) => {
527                        let fn_ptr = Ty::new_fn_ptr(self.tcx, arg_ty.fn_sig(self.tcx));
528                        let fn_ptr = self.resolve_vars_if_possible(fn_ptr).to_string();
529
530                        let fn_item_spa = arg.span;
531                        tcx.sess.dcx().emit_err(errors::PassFnItemToVariadicFunction {
532                            span: fn_item_spa,
533                            sugg_span: fn_item_spa.shrink_to_hi(),
534                            replace: fn_ptr,
535                        });
536                    }
537                    _ => {}
538                }
539            }
540        }
541
542        if !call_appears_satisfied {
543            let compatibility_diagonal = IndexVec::from_raw(compatibility_diagonal);
544            let provided_args = IndexVec::from_iter(provided_args.iter().take(if c_variadic {
545                minimum_input_count
546            } else {
547                provided_arg_count
548            }));
549            debug_assert_eq!(
550                formal_input_tys.len(),
551                expected_input_tys.len(),
552                "expected formal_input_tys to be the same size as expected_input_tys"
553            );
554            let formal_and_expected_inputs = IndexVec::from_iter(
555                formal_input_tys
556                    .iter()
557                    .copied()
558                    .zip_eq(expected_input_tys.iter().copied())
559                    .map(|vars| self.resolve_vars_if_possible(vars)),
560            );
561
562            self.report_arg_errors(
563                compatibility_diagonal,
564                formal_and_expected_inputs,
565                provided_args,
566                c_variadic,
567                err_code,
568                fn_def_id,
569                call_span,
570                call_expr,
571                tuple_arguments,
572            );
573        }
574    }
575
576    /// If `unsized_fn_params` is active, check that unsized values are place expressions. Since
577    /// the removal of `unsized_locals` in <https://github.com/rust-lang/rust/pull/142911> we can't
578    /// store them in MIR locals as temporaries.
579    ///
580    /// If `unsized_fn_params` is inactive, this will be checked in borrowck instead.
581    fn check_place_expr_if_unsized(&self, ty: Ty<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
582        if self.tcx.features().unsized_fn_params() && !expr.is_syntactic_place_expr() {
583            self.require_type_is_sized(
584                ty,
585                expr.span,
586                ObligationCauseCode::UnsizedNonPlaceExpr(expr.span),
587            );
588        }
589    }
590
591    fn report_arg_errors(
592        &self,
593        compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
594        formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
595        provided_args: IndexVec<ProvidedIdx, &'tcx hir::Expr<'tcx>>,
596        c_variadic: bool,
597        err_code: ErrCode,
598        fn_def_id: Option<DefId>,
599        call_span: Span,
600        call_expr: &'tcx hir::Expr<'tcx>,
601        tuple_arguments: TupleArgumentsFlag,
602    ) -> ErrorGuaranteed {
603        // Next, let's construct the error
604
605        let mut fn_call_diag_ctxt = FnCallDiagCtxt::new(
606            self,
607            compatibility_diagonal,
608            formal_and_expected_inputs,
609            provided_args,
610            c_variadic,
611            err_code,
612            fn_def_id,
613            call_span,
614            call_expr,
615            tuple_arguments,
616        );
617
618        // First, check if we just need to wrap some arguments in a tuple.
619        if let Some(err) = fn_call_diag_ctxt.check_wrap_args_in_tuple() {
620            return err;
621        }
622
623        if let Some(fallback_error) = fn_call_diag_ctxt.ensure_has_errors() {
624            return fallback_error;
625        }
626
627        // Okay, so here's where it gets complicated in regards to what errors
628        // we emit and how.
629        // There are 3 different "types" of errors we might encounter.
630        //   1) Missing/extra/swapped arguments
631        //   2) Valid but incorrect arguments
632        //   3) Invalid arguments
633        //      - Currently I think this only comes up with `CyclicTy`
634
635        // We first need to go through, remove those from (3) and emit those
636        // as their own error, particularly since they're error code and
637        // message is special. From what I can tell, we *must* emit these
638        // here (vs somewhere prior to this function) since the arguments
639        // become invalid *because* of how they get used in the function.
640        // It is what it is.
641        if let Some(err) = fn_call_diag_ctxt.filter_out_invalid_arguments()
642            && fn_call_diag_ctxt.errors.is_empty()
643        {
644            // We're done if we found errors, but we already emitted them.
645            return err;
646        }
647
648        assert!(!fn_call_diag_ctxt.errors.is_empty());
649
650        // Last special case: if there is only one "Incompatible" error, just emit that
651        if let Some(err) = fn_call_diag_ctxt.check_single_incompatible() {
652            return err;
653        }
654
655        // Okay, now that we've emitted the special errors separately, we
656        // are only left missing/extra/swapped and mismatched arguments, both
657        // can be collated pretty easily if needed.
658
659        // Special case, we found an extra argument is provided, which is very common in practice.
660        // but there is a obviously better removing suggestion compared to the current one,
661        // try to find the argument with Error type, if we removed it all the types will become good,
662        // then we will replace the current suggestion.
663        fn_call_diag_ctxt.maybe_optimize_extra_arg_suggestion();
664
665        let mut err = fn_call_diag_ctxt.initial_final_diagnostic();
666        fn_call_diag_ctxt.suggest_confusable(&mut err);
667
668        // As we encounter issues, keep track of what we want to provide for the suggestion.
669
670        let (mut suggestions, labels, suggestion_text) =
671            fn_call_diag_ctxt.labels_and_suggestion_text(&mut err);
672
673        fn_call_diag_ctxt.label_generic_mismatches(&mut err);
674        fn_call_diag_ctxt.append_arguments_changes(&mut suggestions);
675
676        // If we have less than 5 things to say, it would be useful to call out exactly what's wrong
677        if labels.len() <= 5 {
678            for (span, label) in labels {
679                err.span_label(span, label);
680            }
681        }
682
683        // Call out where the function is defined
684        fn_call_diag_ctxt.label_fn_like(
685            &mut err,
686            fn_def_id,
687            fn_call_diag_ctxt.callee_ty,
688            call_expr,
689            None,
690            None,
691            &fn_call_diag_ctxt.matched_inputs,
692            &fn_call_diag_ctxt.formal_and_expected_inputs,
693            fn_call_diag_ctxt.call_metadata.is_method,
694            tuple_arguments,
695        );
696
697        // And add a suggestion block for all of the parameters
698        if let Some(suggestion_message) =
699            FnCallDiagCtxt::format_suggestion_text(&mut err, suggestions, suggestion_text)
700            && !fn_call_diag_ctxt.call_is_in_macro()
701        {
702            let (suggestion_span, suggestion_code) = fn_call_diag_ctxt.suggestion_code();
703
704            err.span_suggestion_verbose(
705                suggestion_span,
706                suggestion_message,
707                suggestion_code,
708                Applicability::HasPlaceholders,
709            );
710        }
711
712        err.emit()
713    }
714
715    fn suggest_ptr_null_mut(
716        &self,
717        expected_ty: Ty<'tcx>,
718        provided_ty: Ty<'tcx>,
719        arg: &hir::Expr<'tcx>,
720        err: &mut Diag<'_>,
721    ) {
722        if let ty::RawPtr(_, hir::Mutability::Mut) = expected_ty.kind()
723            && let ty::RawPtr(_, hir::Mutability::Not) = provided_ty.kind()
724            && let hir::ExprKind::Call(callee, _) = arg.kind
725            && let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = callee.kind
726            && let Res::Def(_, def_id) = path.res
727            && self.tcx.get_diagnostic_item(sym::ptr_null) == Some(def_id)
728        {
729            // The user provided `ptr::null()`, but the function expects
730            // `ptr::null_mut()`.
731            err.subdiagnostic(SuggestPtrNullMut { span: arg.span });
732        }
733    }
734
735    // AST fragment checking
736    pub(in super::super) fn check_expr_lit(
737        &self,
738        lit: &hir::Lit,
739        expected: Expectation<'tcx>,
740    ) -> Ty<'tcx> {
741        let tcx = self.tcx;
742
743        match lit.node {
744            ast::LitKind::Str(..) => Ty::new_static_str(tcx),
745            ast::LitKind::ByteStr(ref v, _) => Ty::new_imm_ref(
746                tcx,
747                tcx.lifetimes.re_static,
748                Ty::new_array(tcx, tcx.types.u8, v.as_byte_str().len() as u64),
749            ),
750            ast::LitKind::Byte(_) => tcx.types.u8,
751            ast::LitKind::Char(_) => tcx.types.char,
752            ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => Ty::new_int(tcx, t),
753            ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => Ty::new_uint(tcx, t),
754            ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) => {
755                let opt_ty = expected.to_option(self).and_then(|ty| match ty.kind() {
756                    ty::Int(_) | ty::Uint(_) => Some(ty),
757                    // These exist to direct casts like `0x61 as char` to use
758                    // the right integer type to cast from, instead of falling back to
759                    // i32 due to no further constraints.
760                    ty::Char => Some(tcx.types.u8),
761                    ty::RawPtr(..) => Some(tcx.types.usize),
762                    ty::FnDef(..) | ty::FnPtr(..) => Some(tcx.types.usize),
763                    &ty::Pat(base, _) if base.is_integral() => {
764                        let layout = tcx
765                            .layout_of(self.typing_env(self.param_env).as_query_input(ty))
766                            .ok()?;
767                        assert!(!layout.uninhabited);
768
769                        match layout.backend_repr {
770                            rustc_abi::BackendRepr::Scalar(scalar) => {
771                                scalar.valid_range(&tcx).contains(u128::from(i.get())).then_some(ty)
772                            }
773                            _ => unreachable!(),
774                        }
775                    }
776                    _ => None,
777                });
778                opt_ty.unwrap_or_else(|| self.next_int_var())
779            }
780            ast::LitKind::Float(_, ast::LitFloatType::Suffixed(t)) => Ty::new_float(tcx, t),
781            ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
782                let opt_ty = expected.to_option(self).and_then(|ty| match ty.kind() {
783                    ty::Float(_) => Some(ty),
784                    _ => None,
785                });
786                opt_ty.unwrap_or_else(|| self.next_float_var())
787            }
788            ast::LitKind::Bool(_) => tcx.types.bool,
789            ast::LitKind::CStr(_, _) => Ty::new_imm_ref(
790                tcx,
791                tcx.lifetimes.re_static,
792                tcx.type_of(tcx.require_lang_item(hir::LangItem::CStr, lit.span)).skip_binder(),
793            ),
794            ast::LitKind::Err(guar) => Ty::new_error(tcx, guar),
795        }
796    }
797
798    pub(crate) fn check_struct_path(
799        &self,
800        qpath: &QPath<'tcx>,
801        hir_id: HirId,
802    ) -> Result<(&'tcx ty::VariantDef, Ty<'tcx>), ErrorGuaranteed> {
803        let path_span = qpath.span();
804        let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, hir_id);
805        let variant = match def {
806            Res::Err => {
807                let guar =
808                    self.dcx().span_delayed_bug(path_span, "`Res::Err` but no error emitted");
809                self.set_tainted_by_errors(guar);
810                return Err(guar);
811            }
812            Res::Def(DefKind::Variant, _) => match ty.normalized.ty_adt_def() {
813                Some(adt) => {
814                    Some((adt.variant_of_res(def), adt.did(), Self::user_args_for_adt(ty)))
815                }
816                _ => bug!("unexpected type: {:?}", ty.normalized),
817            },
818            Res::Def(DefKind::Struct | DefKind::Union | DefKind::TyAlias | DefKind::AssocTy, _)
819            | Res::SelfTyParam { .. }
820            | Res::SelfTyAlias { .. } => match ty.normalized.ty_adt_def() {
821                Some(adt) if !adt.is_enum() => {
822                    Some((adt.non_enum_variant(), adt.did(), Self::user_args_for_adt(ty)))
823                }
824                _ => None,
825            },
826            _ => bug!("unexpected definition: {:?}", def),
827        };
828
829        if let Some((variant, did, ty::UserArgs { args, user_self_ty })) = variant {
830            debug!("check_struct_path: did={:?} args={:?}", did, args);
831
832            // Register type annotation.
833            self.write_user_type_annotation_from_args(hir_id, did, args, user_self_ty);
834
835            // Check bounds on type arguments used in the path.
836            self.add_required_obligations_for_hir(path_span, did, args, hir_id);
837
838            Ok((variant, ty.normalized))
839        } else {
840            Err(match *ty.normalized.kind() {
841                ty::Error(guar) => {
842                    // E0071 might be caused by a spelling error, which will have
843                    // already caused an error message and probably a suggestion
844                    // elsewhere. Refrain from emitting more unhelpful errors here
845                    // (issue #88844).
846                    guar
847                }
848                _ => struct_span_code_err!(
849                    self.dcx(),
850                    path_span,
851                    E0071,
852                    "expected struct, variant or union type, found {}",
853                    ty.normalized.sort_string(self.tcx)
854                )
855                .with_span_label(path_span, "not a struct")
856                .emit(),
857            })
858        }
859    }
860
861    fn check_decl_initializer(
862        &self,
863        hir_id: HirId,
864        pat: &'tcx hir::Pat<'tcx>,
865        init: &'tcx hir::Expr<'tcx>,
866    ) -> Ty<'tcx> {
867        // FIXME(tschottdorf): `contains_explicit_ref_binding()` must be removed
868        // for #42640 (default match binding modes).
869        //
870        // See #44848.
871        let ref_bindings = pat.contains_explicit_ref_binding();
872
873        let local_ty = self.local_ty(init.span, hir_id);
874        if let Some(m) = ref_bindings {
875            // Somewhat subtle: if we have a `ref` binding in the pattern,
876            // we want to avoid introducing coercions for the RHS. This is
877            // both because it helps preserve sanity and, in the case of
878            // ref mut, for soundness (issue #23116). In particular, in
879            // the latter case, we need to be clear that the type of the
880            // referent for the reference that results is *equal to* the
881            // type of the place it is referencing, and not some
882            // supertype thereof.
883            let init_ty = self.check_expr_with_needs(init, Needs::maybe_mut_place(m));
884            if let Err(mut diag) = self.demand_eqtype_diag(init.span, local_ty, init_ty) {
885                self.emit_type_mismatch_suggestions(
886                    &mut diag,
887                    init.peel_drop_temps(),
888                    init_ty,
889                    local_ty,
890                    None,
891                    None,
892                );
893                diag.emit();
894            }
895            init_ty
896        } else {
897            self.check_expr_coercible_to_type(init, local_ty, None)
898        }
899    }
900
901    pub(in super::super) fn check_decl(&self, decl: Declaration<'tcx>) -> Ty<'tcx> {
902        // Determine and write the type which we'll check the pattern against.
903        let decl_ty = self.local_ty(decl.span, decl.hir_id);
904
905        // Type check the initializer.
906        if let Some(init) = decl.init {
907            let init_ty = self.check_decl_initializer(decl.hir_id, decl.pat, init);
908            self.overwrite_local_ty_if_err(decl.hir_id, decl.pat, init_ty);
909        }
910
911        // Does the expected pattern type originate from an expression and what is the span?
912        let (origin_expr, ty_span) = match (decl.ty, decl.init) {
913            (Some(ty), _) => (None, Some(ty.span)), // Bias towards the explicit user type.
914            (_, Some(init)) => {
915                (Some(init), Some(init.span.find_ancestor_inside(decl.span).unwrap_or(init.span)))
916            } // No explicit type; so use the scrutinee.
917            _ => (None, None), // We have `let $pat;`, so the expected type is unconstrained.
918        };
919
920        // Type check the pattern. Override if necessary to avoid knock-on errors.
921        self.check_pat_top(decl.pat, decl_ty, ty_span, origin_expr, Some(decl.origin));
922        let pat_ty = self.node_ty(decl.pat.hir_id);
923        self.overwrite_local_ty_if_err(decl.hir_id, decl.pat, pat_ty);
924
925        if let Some(blk) = decl.origin.try_get_else() {
926            let previous_diverges = self.diverges.get();
927            let else_ty = self.check_expr_block(blk, NoExpectation);
928            let cause = self.cause(blk.span, ObligationCauseCode::LetElse);
929            if let Err(err) = self.demand_eqtype_with_origin(&cause, self.tcx.types.never, else_ty)
930            {
931                err.emit();
932            }
933            self.diverges.set(previous_diverges);
934        }
935        decl_ty
936    }
937
938    /// Type check a `let` statement.
939    fn check_decl_local(&self, local: &'tcx hir::LetStmt<'tcx>) {
940        GatherLocalsVisitor::gather_from_local(self, local);
941
942        let ty = self.check_decl(local.into());
943        self.write_ty(local.hir_id, ty);
944        if local.pat.is_never_pattern() {
945            self.diverges.set(Diverges::Always {
946                span: local.pat.span,
947                custom_note: Some("any code following a never pattern is unreachable"),
948            });
949        }
950    }
951
952    fn check_stmt(&self, stmt: &'tcx hir::Stmt<'tcx>) {
953        // Don't do all the complex logic below for `DeclItem`.
954        match stmt.kind {
955            hir::StmtKind::Item(..) => return,
956            hir::StmtKind::Let(..) | hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => {}
957        }
958
959        self.warn_if_unreachable(stmt.hir_id, stmt.span, "statement");
960
961        // Hide the outer diverging flags.
962        let old_diverges = self.diverges.replace(Diverges::Maybe);
963
964        match stmt.kind {
965            hir::StmtKind::Let(l) => {
966                self.check_decl_local(l);
967            }
968            // Ignore for now.
969            hir::StmtKind::Item(_) => {}
970            hir::StmtKind::Expr(expr) => {
971                // Check with expected type of `()`.
972                self.check_expr_has_type_or_error(expr, self.tcx.types.unit, |err| {
973                    if self.is_next_stmt_expr_continuation(stmt.hir_id)
974                        && let hir::ExprKind::Match(..) | hir::ExprKind::If(..) = expr.kind
975                    {
976                        // We have something like `match () { _ => true } && true`. Suggest
977                        // wrapping in parentheses. We find the statement or expression
978                        // following the `match` (`&& true`) and see if it is something that
979                        // can reasonably be interpreted as a binop following an expression.
980                        err.multipart_suggestion(
981                            "parentheses are required to parse this as an expression",
982                            vec![
983                                (expr.span.shrink_to_lo(), "(".to_string()),
984                                (expr.span.shrink_to_hi(), ")".to_string()),
985                            ],
986                            Applicability::MachineApplicable,
987                        );
988                    } else if expr.can_have_side_effects() {
989                        self.suggest_semicolon_at_end(expr.span, err);
990                    }
991                });
992            }
993            hir::StmtKind::Semi(expr) => {
994                let ty = self.check_expr(expr);
995                self.check_place_expr_if_unsized(ty, expr);
996            }
997        }
998
999        // Combine the diverging and `has_error` flags.
1000        self.diverges.set(self.diverges.get() | old_diverges);
1001    }
1002
1003    pub(crate) fn check_block_no_value(&self, blk: &'tcx hir::Block<'tcx>) {
1004        let unit = self.tcx.types.unit;
1005        let ty = self.check_expr_block(blk, ExpectHasType(unit));
1006
1007        // if the block produces a `!` value, that can always be
1008        // (effectively) coerced to unit.
1009        if !ty.is_never() {
1010            self.demand_suptype(blk.span, unit, ty);
1011        }
1012    }
1013
1014    pub(in super::super) fn check_expr_block(
1015        &self,
1016        blk: &'tcx hir::Block<'tcx>,
1017        expected: Expectation<'tcx>,
1018    ) -> Ty<'tcx> {
1019        // In some cases, blocks have just one exit, but other blocks
1020        // can be targeted by multiple breaks. This can happen both
1021        // with labeled blocks as well as when we desugar
1022        // a `try { ... }` expression.
1023        //
1024        // Example 1:
1025        //
1026        //    'a: { if true { break 'a Err(()); } Ok(()) }
1027        //
1028        // Here we would wind up with two coercions, one from
1029        // `Err(())` and the other from the tail expression
1030        // `Ok(())`. If the tail expression is omitted, that's a
1031        // "forced unit" -- unless the block diverges, in which
1032        // case we can ignore the tail expression (e.g., `'a: {
1033        // break 'a 22; }` would not force the type of the block
1034        // to be `()`).
1035        let coerce_to_ty = expected.coercion_target_type(self, blk.span);
1036        let coerce = CoerceMany::new(coerce_to_ty);
1037
1038        let prev_diverges = self.diverges.get();
1039        let ctxt = BreakableCtxt { coerce: Some(coerce), may_break: false };
1040
1041        let (ctxt, ()) = self.with_breakable_ctxt(blk.hir_id, ctxt, || {
1042            for s in blk.stmts {
1043                self.check_stmt(s);
1044            }
1045
1046            // check the tail expression **without** holding the
1047            // `enclosing_breakables` lock below.
1048            let tail_expr_ty =
1049                blk.expr.map(|expr| (expr, self.check_expr_with_expectation(expr, expected)));
1050
1051            let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1052            let ctxt = enclosing_breakables.find_breakable(blk.hir_id);
1053            let coerce = ctxt.coerce.as_mut().unwrap();
1054            if let Some((tail_expr, tail_expr_ty)) = tail_expr_ty {
1055                let span = self.get_expr_coercion_span(tail_expr);
1056                let cause = self.cause(
1057                    span,
1058                    ObligationCauseCode::BlockTailExpression(blk.hir_id, hir::MatchSource::Normal),
1059                );
1060                let ty_for_diagnostic = coerce.merged_ty();
1061                // We use coerce_inner here because we want to augment the error
1062                // suggesting to wrap the block in square brackets if it might've
1063                // been mistaken array syntax
1064                coerce.coerce_inner(
1065                    self,
1066                    &cause,
1067                    Some(tail_expr),
1068                    tail_expr_ty,
1069                    |diag| {
1070                        self.suggest_block_to_brackets(diag, blk, tail_expr_ty, ty_for_diagnostic);
1071                    },
1072                    false,
1073                );
1074            } else {
1075                // Subtle: if there is no explicit tail expression,
1076                // that is typically equivalent to a tail expression
1077                // of `()` -- except if the block diverges. In that
1078                // case, there is no value supplied from the tail
1079                // expression (assuming there are no other breaks,
1080                // this implies that the type of the block will be
1081                // `!`).
1082                //
1083                // #41425 -- label the implicit `()` as being the
1084                // "found type" here, rather than the "expected type".
1085                if !self.diverges.get().is_always()
1086                    || matches!(self.diverging_block_behavior, DivergingBlockBehavior::Unit)
1087                {
1088                    // #50009 -- Do not point at the entire fn block span, point at the return type
1089                    // span, as it is the cause of the requirement, and
1090                    // `consider_hint_about_removing_semicolon` will point at the last expression
1091                    // if it were a relevant part of the error. This improves usability in editors
1092                    // that highlight errors inline.
1093                    let mut sp = blk.span;
1094                    let mut fn_span = None;
1095                    if let Some((fn_def_id, decl)) = self.get_fn_decl(blk.hir_id) {
1096                        let ret_sp = decl.output.span();
1097                        if let Some(block_sp) = self.parent_item_span(blk.hir_id) {
1098                            // HACK: on some cases (`ui/liveness/liveness-issue-2163.rs`) the
1099                            // output would otherwise be incorrect and even misleading. Make sure
1100                            // the span we're aiming at correspond to a `fn` body.
1101                            if block_sp == blk.span {
1102                                sp = ret_sp;
1103                                fn_span = self.tcx.def_ident_span(fn_def_id);
1104                            }
1105                        }
1106                    }
1107                    coerce.coerce_forced_unit(
1108                        self,
1109                        &self.misc(sp),
1110                        |err| {
1111                            if let Some(expected_ty) = expected.only_has_type(self) {
1112                                if blk.stmts.is_empty() && blk.expr.is_none() {
1113                                    self.suggest_boxing_when_appropriate(
1114                                        err,
1115                                        blk.span,
1116                                        blk.hir_id,
1117                                        expected_ty,
1118                                        self.tcx.types.unit,
1119                                    );
1120                                }
1121                                if !self.err_ctxt().consider_removing_semicolon(
1122                                    blk,
1123                                    expected_ty,
1124                                    err,
1125                                ) {
1126                                    self.err_ctxt().consider_returning_binding(
1127                                        blk,
1128                                        expected_ty,
1129                                        err,
1130                                    );
1131                                }
1132                                if expected_ty == self.tcx.types.bool {
1133                                    // If this is caused by a missing `let` in a `while let`,
1134                                    // silence this redundant error, as we already emit E0070.
1135
1136                                    // Our block must be a `assign desugar local; assignment`
1137                                    if let hir::Block {
1138                                        stmts:
1139                                            [
1140                                                hir::Stmt {
1141                                                    kind:
1142                                                        hir::StmtKind::Let(hir::LetStmt {
1143                                                            source: hir::LocalSource::AssignDesugar,
1144                                                            ..
1145                                                        }),
1146                                                    ..
1147                                                },
1148                                                hir::Stmt {
1149                                                    kind:
1150                                                        hir::StmtKind::Expr(hir::Expr {
1151                                                            kind: hir::ExprKind::Assign(lhs, ..),
1152                                                            ..
1153                                                        }),
1154                                                    ..
1155                                                },
1156                                            ],
1157                                        ..
1158                                    } = blk
1159                                    {
1160                                        self.comes_from_while_condition(blk.hir_id, |_| {
1161                                            // We cannot suppress the error if the LHS of assignment
1162                                            // is a syntactic place expression because E0070 would
1163                                            // not be emitted by `check_lhs_assignable`.
1164                                            let res = self.typeck_results.borrow().expr_ty_opt(lhs);
1165
1166                                            if !lhs.is_syntactic_place_expr()
1167                                                || res.references_error()
1168                                            {
1169                                                err.downgrade_to_delayed_bug();
1170                                            }
1171                                        })
1172                                    }
1173                                }
1174                            }
1175                            if let Some(fn_span) = fn_span {
1176                                err.span_label(
1177                                    fn_span,
1178                                    "implicitly returns `()` as its body has no tail or `return` \
1179                                     expression",
1180                                );
1181                            }
1182                        },
1183                        false,
1184                    );
1185                }
1186            }
1187        });
1188
1189        if ctxt.may_break {
1190            // If we can break from the block, then the block's exit is always reachable
1191            // (... as long as the entry is reachable) - regardless of the tail of the block.
1192            self.diverges.set(prev_diverges);
1193        }
1194
1195        let ty = ctxt.coerce.unwrap().complete(self);
1196
1197        self.write_ty(blk.hir_id, ty);
1198
1199        ty
1200    }
1201
1202    fn parent_item_span(&self, id: HirId) -> Option<Span> {
1203        let node = self.tcx.hir_node_by_def_id(self.tcx.hir_get_parent_item(id).def_id);
1204        match node {
1205            Node::Item(&hir::Item { kind: hir::ItemKind::Fn { body: body_id, .. }, .. })
1206            | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body_id), .. }) => {
1207                let body = self.tcx.hir_body(body_id);
1208                if let ExprKind::Block(block, _) = &body.value.kind {
1209                    return Some(block.span);
1210                }
1211            }
1212            _ => {}
1213        }
1214        None
1215    }
1216
1217    /// If `expr` is a `match` expression that has only one non-`!` arm, use that arm's tail
1218    /// expression's `Span`, otherwise return `expr.span`. This is done to give better errors
1219    /// when given code like the following:
1220    /// ```text
1221    /// if false { return 0i32; } else { 1u32 }
1222    /// //                               ^^^^ point at this instead of the whole `if` expression
1223    /// ```
1224    fn get_expr_coercion_span(&self, expr: &hir::Expr<'_>) -> rustc_span::Span {
1225        let check_in_progress = |elem: &hir::Expr<'_>| {
1226            self.typeck_results.borrow().node_type_opt(elem.hir_id).filter(|ty| !ty.is_never()).map(
1227                |_| match elem.kind {
1228                    // Point at the tail expression when possible.
1229                    hir::ExprKind::Block(block, _) => block.expr.map_or(block.span, |e| e.span),
1230                    _ => elem.span,
1231                },
1232            )
1233        };
1234
1235        if let hir::ExprKind::If(_, _, Some(el)) = expr.kind
1236            && let Some(rslt) = check_in_progress(el)
1237        {
1238            return rslt;
1239        }
1240
1241        if let hir::ExprKind::Match(_, arms, _) = expr.kind {
1242            let mut iter = arms.iter().filter_map(|arm| check_in_progress(arm.body));
1243            if let Some(span) = iter.next() {
1244                if iter.next().is_none() {
1245                    return span;
1246                }
1247            }
1248        }
1249
1250        expr.span
1251    }
1252
1253    fn overwrite_local_ty_if_err(&self, hir_id: HirId, pat: &'tcx hir::Pat<'tcx>, ty: Ty<'tcx>) {
1254        if let Err(guar) = ty.error_reported() {
1255            struct OverwritePatternsWithError {
1256                pat_hir_ids: Vec<hir::HirId>,
1257            }
1258            impl<'tcx> Visitor<'tcx> for OverwritePatternsWithError {
1259                fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
1260                    self.pat_hir_ids.push(p.hir_id);
1261                    hir::intravisit::walk_pat(self, p);
1262                }
1263            }
1264            // Override the types everywhere with `err()` to avoid knock on errors.
1265            let err = Ty::new_error(self.tcx, guar);
1266            self.write_ty(hir_id, err);
1267            self.write_ty(pat.hir_id, err);
1268            let mut visitor = OverwritePatternsWithError { pat_hir_ids: vec![] };
1269            hir::intravisit::walk_pat(&mut visitor, pat);
1270            // Mark all the subpatterns as `{type error}` as well. This allows errors for specific
1271            // subpatterns to be silenced.
1272            for hir_id in visitor.pat_hir_ids {
1273                self.write_ty(hir_id, err);
1274            }
1275            self.locals.borrow_mut().insert(hir_id, err);
1276            self.locals.borrow_mut().insert(pat.hir_id, err);
1277        }
1278    }
1279
1280    // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
1281    // The newly resolved definition is written into `type_dependent_defs`.
1282    fn finish_resolving_struct_path(
1283        &self,
1284        qpath: &QPath<'tcx>,
1285        path_span: Span,
1286        hir_id: HirId,
1287    ) -> (Res, LoweredTy<'tcx>) {
1288        match *qpath {
1289            QPath::Resolved(ref maybe_qself, path) => {
1290                let self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself).raw);
1291                let ty = self.lowerer().lower_resolved_ty_path(
1292                    self_ty,
1293                    path,
1294                    hir_id,
1295                    PermitVariants::Yes,
1296                );
1297                (path.res, LoweredTy::from_raw(self, path_span, ty))
1298            }
1299            QPath::TypeRelative(hir_self_ty, segment) => {
1300                let self_ty = self.lower_ty(hir_self_ty);
1301
1302                let result = self.lowerer().lower_type_relative_ty_path(
1303                    self_ty.raw,
1304                    hir_self_ty,
1305                    segment,
1306                    hir_id,
1307                    path_span,
1308                    PermitVariants::Yes,
1309                );
1310                let ty = result
1311                    .map(|(ty, _, _)| ty)
1312                    .unwrap_or_else(|guar| Ty::new_error(self.tcx(), guar));
1313                let ty = LoweredTy::from_raw(self, path_span, ty);
1314                let result = result.map(|(_, kind, def_id)| (kind, def_id));
1315
1316                // Write back the new resolution.
1317                self.write_resolution(hir_id, result);
1318
1319                (result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), ty)
1320            }
1321        }
1322    }
1323
1324    /// Given a vector of fulfillment errors, try to adjust the spans of the
1325    /// errors to more accurately point at the cause of the failure.
1326    ///
1327    /// This applies to calls, methods, and struct expressions. This will also
1328    /// try to deduplicate errors that are due to the same cause but might
1329    /// have been created with different [`ObligationCause`][traits::ObligationCause]s.
1330    pub(super) fn adjust_fulfillment_errors_for_expr_obligation(
1331        &self,
1332        errors: &mut Vec<traits::FulfillmentError<'tcx>>,
1333    ) {
1334        // Store a mapping from `(Span, Predicate) -> ObligationCause`, so that
1335        // other errors that have the same span and predicate can also get fixed,
1336        // even if their `ObligationCauseCode` isn't an `Expr*Obligation` kind.
1337        // This is important since if we adjust one span but not the other, then
1338        // we will have "duplicated" the error on the UI side.
1339        let mut remap_cause = FxIndexSet::default();
1340        let mut not_adjusted = vec![];
1341
1342        for error in errors {
1343            let before_span = error.obligation.cause.span;
1344            if self.adjust_fulfillment_error_for_expr_obligation(error)
1345                || before_span != error.obligation.cause.span
1346            {
1347                remap_cause.insert((
1348                    before_span,
1349                    error.obligation.predicate,
1350                    error.obligation.cause.clone(),
1351                ));
1352            } else {
1353                // If it failed to be adjusted once around, it may be adjusted
1354                // via the "remap cause" mapping the second time...
1355                not_adjusted.push(error);
1356            }
1357        }
1358
1359        // Adjust any other errors that come from other cause codes, when these
1360        // errors are of the same predicate as one we successfully adjusted, and
1361        // when their spans overlap (suggesting they're due to the same root cause).
1362        //
1363        // This is because due to normalization, we often register duplicate
1364        // obligations with misc obligations that are basically impossible to
1365        // line back up with a useful WhereClauseInExpr.
1366        for error in not_adjusted {
1367            for (span, predicate, cause) in &remap_cause {
1368                if *predicate == error.obligation.predicate
1369                    && span.contains(error.obligation.cause.span)
1370                {
1371                    error.obligation.cause = cause.clone();
1372                    continue;
1373                }
1374            }
1375        }
1376    }
1377
1378    fn label_fn_like(
1379        &self,
1380        err: &mut Diag<'_>,
1381        callable_def_id: Option<DefId>,
1382        callee_ty: Option<Ty<'tcx>>,
1383        call_expr: &'tcx hir::Expr<'tcx>,
1384        expected_ty: Option<Ty<'tcx>>,
1385        // A specific argument should be labeled, instead of all of them
1386        expected_idx: Option<usize>,
1387        matched_inputs: &IndexVec<ExpectedIdx, Option<ProvidedIdx>>,
1388        formal_and_expected_inputs: &IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
1389        is_method: bool,
1390        tuple_arguments: TupleArgumentsFlag,
1391    ) {
1392        let Some(mut def_id) = callable_def_id else {
1393            return;
1394        };
1395
1396        // If we're calling a method of a Fn/FnMut/FnOnce trait object implicitly
1397        // (eg invoking a closure) we want to point at the underlying callable,
1398        // not the method implicitly invoked (eg call_once).
1399        // TupleArguments is set only when this is an implicit call (my_closure(...)) rather than explicit (my_closure.call(...))
1400        if tuple_arguments == TupleArguments
1401            && let Some(assoc_item) = self.tcx.opt_associated_item(def_id)
1402            // Since this is an associated item, it might point at either an impl or a trait item.
1403            // We want it to always point to the trait item.
1404            // If we're pointing at an inherent function, we don't need to do anything,
1405            // so we fetch the parent and verify if it's a trait item.
1406            && let Ok(maybe_trait_item_def_id) = assoc_item.trait_item_or_self()
1407            && let maybe_trait_def_id = self.tcx.parent(maybe_trait_item_def_id)
1408            // Just an easy way to check "trait_def_id == Fn/FnMut/FnOnce"
1409            && let Some(call_kind) = self.tcx.fn_trait_kind_from_def_id(maybe_trait_def_id)
1410            && let Some(callee_ty) = callee_ty
1411        {
1412            let callee_ty = callee_ty.peel_refs();
1413            match *callee_ty.kind() {
1414                ty::Param(param) => {
1415                    let param = self.tcx.generics_of(self.body_id).type_param(param, self.tcx);
1416                    if param.kind.is_synthetic() {
1417                        // if it's `impl Fn() -> ..` then just fall down to the def-id based logic
1418                        def_id = param.def_id;
1419                    } else {
1420                        // Otherwise, find the predicate that makes this generic callable,
1421                        // and point at that.
1422                        let instantiated = self
1423                            .tcx
1424                            .explicit_predicates_of(self.body_id)
1425                            .instantiate_identity(self.tcx);
1426                        // FIXME(compiler-errors): This could be problematic if something has two
1427                        // fn-like predicates with different args, but callable types really never
1428                        // do that, so it's OK.
1429                        for (predicate, span) in instantiated {
1430                            if let ty::ClauseKind::Trait(pred) = predicate.kind().skip_binder()
1431                                && pred.self_ty().peel_refs() == callee_ty
1432                                && self.tcx.is_fn_trait(pred.def_id())
1433                            {
1434                                err.span_note(span, "callable defined here");
1435                                return;
1436                            }
1437                        }
1438                    }
1439                }
1440                ty::Alias(ty::Opaque, ty::AliasTy { def_id: new_def_id, .. })
1441                | ty::Closure(new_def_id, _)
1442                | ty::FnDef(new_def_id, _) => {
1443                    def_id = new_def_id;
1444                }
1445                _ => {
1446                    // Look for a user-provided impl of a `Fn` trait, and point to it.
1447                    let new_def_id = self.probe(|_| {
1448                        let trait_ref = ty::TraitRef::new(
1449                            self.tcx,
1450                            self.tcx.fn_trait_kind_to_def_id(call_kind)?,
1451                            [callee_ty, self.next_ty_var(DUMMY_SP)],
1452                        );
1453                        let obligation = traits::Obligation::new(
1454                            self.tcx,
1455                            traits::ObligationCause::dummy(),
1456                            self.param_env,
1457                            trait_ref,
1458                        );
1459                        match SelectionContext::new(self).select(&obligation) {
1460                            Ok(Some(traits::ImplSource::UserDefined(impl_source))) => {
1461                                Some(impl_source.impl_def_id)
1462                            }
1463                            _ => None,
1464                        }
1465                    });
1466                    let Some(new_def_id) = new_def_id else { return };
1467                    def_id = new_def_id;
1468                }
1469            }
1470        }
1471
1472        if let Some(def_span) = self.tcx.def_ident_span(def_id)
1473            && !def_span.is_dummy()
1474        {
1475            let mut spans: MultiSpan = def_span.into();
1476            if let Some((params_with_generics, hir_generics)) =
1477                self.get_hir_param_info(def_id, is_method)
1478            {
1479                struct MismatchedParam<'a> {
1480                    idx: ExpectedIdx,
1481                    generic: GenericIdx,
1482                    param: &'a FnParam<'a>,
1483                    deps: SmallVec<[ExpectedIdx; 4]>,
1484                }
1485
1486                debug_assert_eq!(params_with_generics.len(), matched_inputs.len());
1487                // Gather all mismatched parameters with generics.
1488                let mut mismatched_params = Vec::<MismatchedParam<'_>>::new();
1489                if let Some(expected_idx) = expected_idx {
1490                    let expected_idx = ExpectedIdx::from_usize(expected_idx);
1491                    let &(expected_generic, ref expected_param) =
1492                        &params_with_generics[expected_idx];
1493                    if let Some(expected_generic) = expected_generic {
1494                        mismatched_params.push(MismatchedParam {
1495                            idx: expected_idx,
1496                            generic: expected_generic,
1497                            param: expected_param,
1498                            deps: SmallVec::new(),
1499                        });
1500                    } else {
1501                        // Still mark the mismatched parameter
1502                        spans.push_span_label(expected_param.span(), "");
1503                    }
1504                } else {
1505                    mismatched_params.extend(
1506                        params_with_generics.iter_enumerated().zip(matched_inputs).filter_map(
1507                            |((idx, &(generic, ref param)), matched_idx)| {
1508                                if matched_idx.is_some() {
1509                                    None
1510                                } else if let Some(generic) = generic {
1511                                    Some(MismatchedParam {
1512                                        idx,
1513                                        generic,
1514                                        param,
1515                                        deps: SmallVec::new(),
1516                                    })
1517                                } else {
1518                                    // Still mark mismatched parameters
1519                                    spans.push_span_label(param.span(), "");
1520                                    None
1521                                }
1522                            },
1523                        ),
1524                    );
1525                }
1526
1527                if !mismatched_params.is_empty() {
1528                    // For each mismatched parameter, create a two-way link to each matched parameter
1529                    // of the same type.
1530                    let mut dependants = IndexVec::<ExpectedIdx, _>::from_fn_n(
1531                        |_| SmallVec::<[u32; 4]>::new(),
1532                        params_with_generics.len(),
1533                    );
1534                    let mut generic_uses = IndexVec::<GenericIdx, _>::from_fn_n(
1535                        |_| SmallVec::<[ExpectedIdx; 4]>::new(),
1536                        hir_generics.params.len(),
1537                    );
1538                    for (idx, param) in mismatched_params.iter_mut().enumerate() {
1539                        for ((other_idx, &(other_generic, _)), &other_matched_idx) in
1540                            params_with_generics.iter_enumerated().zip(matched_inputs)
1541                        {
1542                            if other_generic == Some(param.generic) && other_matched_idx.is_some() {
1543                                generic_uses[param.generic].extend([param.idx, other_idx]);
1544                                dependants[other_idx].push(idx as u32);
1545                                param.deps.push(other_idx);
1546                            }
1547                        }
1548                    }
1549
1550                    // Highlight each mismatched type along with a note about which other parameters
1551                    // the type depends on (if any).
1552                    for param in &mismatched_params {
1553                        if let Some(deps_list) = listify(&param.deps, |&dep| {
1554                            params_with_generics[dep].1.display(dep.as_usize()).to_string()
1555                        }) {
1556                            spans.push_span_label(
1557                                param.param.span(),
1558                                format!(
1559                                    "this parameter needs to match the {} type of {deps_list}",
1560                                    self.resolve_vars_if_possible(
1561                                        formal_and_expected_inputs[param.deps[0]].1
1562                                    )
1563                                    .sort_string(self.tcx),
1564                                ),
1565                            );
1566                        } else {
1567                            // Still mark mismatched parameters
1568                            spans.push_span_label(param.param.span(), "");
1569                        }
1570                    }
1571                    // Highlight each parameter being depended on for a generic type.
1572                    for ((&(_, param), deps), &(_, expected_ty)) in
1573                        params_with_generics.iter().zip(&dependants).zip(formal_and_expected_inputs)
1574                    {
1575                        if let Some(deps_list) = listify(deps, |&dep| {
1576                            let param = &mismatched_params[dep as usize];
1577                            param.param.display(param.idx.as_usize()).to_string()
1578                        }) {
1579                            spans.push_span_label(
1580                                param.span(),
1581                                format!(
1582                                    "{deps_list} need{} to match the {} type of this parameter",
1583                                    pluralize!((deps.len() != 1) as u32),
1584                                    self.resolve_vars_if_possible(expected_ty)
1585                                        .sort_string(self.tcx),
1586                                ),
1587                            );
1588                        }
1589                    }
1590                    // Highlight each generic parameter in use.
1591                    for (param, uses) in hir_generics.params.iter().zip(&mut generic_uses) {
1592                        uses.sort();
1593                        uses.dedup();
1594                        if let Some(param_list) = listify(uses, |&idx| {
1595                            params_with_generics[idx].1.display(idx.as_usize()).to_string()
1596                        }) {
1597                            spans.push_span_label(
1598                                param.span,
1599                                format!(
1600                                    "{param_list} {} reference this parameter `{}`",
1601                                    if uses.len() == 2 { "both" } else { "all" },
1602                                    param.name.ident().name,
1603                                ),
1604                            );
1605                        }
1606                    }
1607                }
1608            }
1609            err.span_note(spans, format!("{} defined here", self.tcx.def_descr(def_id)));
1610        } else if let Some(hir::Node::Expr(e)) = self.tcx.hir_get_if_local(def_id)
1611            && let hir::ExprKind::Closure(hir::Closure { body, .. }) = &e.kind
1612        {
1613            let param = expected_idx
1614                .and_then(|expected_idx| self.tcx.hir_body(*body).params.get(expected_idx));
1615            let (kind, span) = if let Some(param) = param {
1616                // Try to find earlier invocations of this closure to find if the type mismatch
1617                // is because of inference. If we find one, point at them.
1618                let mut call_finder = FindClosureArg { tcx: self.tcx, calls: vec![] };
1619                let parent_def_id = self.tcx.hir_get_parent_item(call_expr.hir_id).def_id;
1620                match self.tcx.hir_node_by_def_id(parent_def_id) {
1621                    hir::Node::Item(item) => call_finder.visit_item(item),
1622                    hir::Node::TraitItem(item) => call_finder.visit_trait_item(item),
1623                    hir::Node::ImplItem(item) => call_finder.visit_impl_item(item),
1624                    _ => {}
1625                }
1626                let typeck = self.typeck_results.borrow();
1627                for (rcvr, args) in call_finder.calls {
1628                    if rcvr.hir_id.owner == typeck.hir_owner
1629                        && let Some(rcvr_ty) = typeck.node_type_opt(rcvr.hir_id)
1630                        && let ty::Closure(call_def_id, _) = rcvr_ty.kind()
1631                        && def_id == *call_def_id
1632                        && let Some(idx) = expected_idx
1633                        && let Some(arg) = args.get(idx)
1634                        && let Some(arg_ty) = typeck.node_type_opt(arg.hir_id)
1635                        && let Some(expected_ty) = expected_ty
1636                        && self.can_eq(self.param_env, arg_ty, expected_ty)
1637                    {
1638                        let mut sp: MultiSpan = vec![arg.span].into();
1639                        sp.push_span_label(
1640                            arg.span,
1641                            format!("expected because this argument is of type `{arg_ty}`"),
1642                        );
1643                        sp.push_span_label(rcvr.span, "in this closure call");
1644                        err.span_note(
1645                            sp,
1646                            format!(
1647                                "expected because the closure was earlier called with an \
1648                                argument of type `{arg_ty}`",
1649                            ),
1650                        );
1651                        break;
1652                    }
1653                }
1654
1655                ("closure parameter", param.span)
1656            } else {
1657                ("closure", self.tcx.def_span(def_id))
1658            };
1659            err.span_note(span, format!("{kind} defined here"));
1660        } else {
1661            err.span_note(
1662                self.tcx.def_span(def_id),
1663                format!("{} defined here", self.tcx.def_descr(def_id)),
1664            );
1665        }
1666    }
1667
1668    fn label_generic_mismatches(
1669        &self,
1670        err: &mut Diag<'_>,
1671        callable_def_id: Option<DefId>,
1672        matched_inputs: &IndexVec<ExpectedIdx, Option<ProvidedIdx>>,
1673        provided_arg_tys: &IndexVec<ProvidedIdx, (Ty<'tcx>, Span)>,
1674        formal_and_expected_inputs: &IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
1675        is_method: bool,
1676    ) {
1677        let Some(def_id) = callable_def_id else {
1678            return;
1679        };
1680
1681        if let Some((params_with_generics, _)) = self.get_hir_param_info(def_id, is_method) {
1682            debug_assert_eq!(params_with_generics.len(), matched_inputs.len());
1683            for (idx, (generic_param, _)) in params_with_generics.iter_enumerated() {
1684                if matched_inputs[idx].is_none() {
1685                    continue;
1686                }
1687
1688                let Some((_, matched_arg_span)) = provided_arg_tys.get(idx.to_provided_idx())
1689                else {
1690                    continue;
1691                };
1692
1693                let Some(generic_param) = generic_param else {
1694                    continue;
1695                };
1696
1697                let idxs_matched = params_with_generics
1698                    .iter_enumerated()
1699                    .filter(|&(other_idx, (other_generic_param, _))| {
1700                        if other_idx == idx {
1701                            return false;
1702                        }
1703                        let Some(other_generic_param) = other_generic_param else {
1704                            return false;
1705                        };
1706                        if matched_inputs[other_idx].is_some() {
1707                            return false;
1708                        }
1709                        other_generic_param == generic_param
1710                    })
1711                    .count();
1712
1713                if idxs_matched == 0 {
1714                    continue;
1715                }
1716
1717                let expected_display_type = self
1718                    .resolve_vars_if_possible(formal_and_expected_inputs[idx].1)
1719                    .sort_string(self.tcx);
1720                let label = if idxs_matched == params_with_generics.len() - 1 {
1721                    format!(
1722                        "expected all arguments to be this {} type because they need to match the type of this parameter",
1723                        expected_display_type
1724                    )
1725                } else {
1726                    format!(
1727                        "expected some other arguments to be {} {} type to match the type of this parameter",
1728                        a_or_an(&expected_display_type),
1729                        expected_display_type,
1730                    )
1731                };
1732
1733                err.span_label(*matched_arg_span, label);
1734            }
1735        }
1736    }
1737
1738    /// Returns the parameters of a function, with their generic parameters if those are the full
1739    /// type of that parameter.
1740    ///
1741    /// Returns `None` if the body is not a named function (e.g. a closure).
1742    fn get_hir_param_info(
1743        &self,
1744        def_id: DefId,
1745        is_method: bool,
1746    ) -> Option<(IndexVec<ExpectedIdx, (Option<GenericIdx>, FnParam<'_>)>, &hir::Generics<'_>)>
1747    {
1748        let (sig, generics, body_id, params) = match self.tcx.hir_get_if_local(def_id)? {
1749            hir::Node::TraitItem(&hir::TraitItem {
1750                generics,
1751                kind: hir::TraitItemKind::Fn(sig, trait_fn),
1752                ..
1753            }) => match trait_fn {
1754                hir::TraitFn::Required(params) => (sig, generics, None, Some(params)),
1755                hir::TraitFn::Provided(body) => (sig, generics, Some(body), None),
1756            },
1757            hir::Node::ImplItem(&hir::ImplItem {
1758                generics,
1759                kind: hir::ImplItemKind::Fn(sig, body),
1760                ..
1761            })
1762            | hir::Node::Item(&hir::Item {
1763                kind: hir::ItemKind::Fn { sig, generics, body, .. },
1764                ..
1765            }) => (sig, generics, Some(body), None),
1766            hir::Node::ForeignItem(&hir::ForeignItem {
1767                kind: hir::ForeignItemKind::Fn(sig, params, generics),
1768                ..
1769            }) => (sig, generics, None, Some(params)),
1770            _ => return None,
1771        };
1772
1773        // Make sure to remove both the receiver and variadic argument. Both are removed
1774        // when matching parameter types.
1775        let fn_inputs = sig.decl.inputs.get(is_method as usize..)?.iter().map(|param| {
1776            if let hir::TyKind::Path(QPath::Resolved(
1777                _,
1778                &hir::Path { res: Res::Def(_, res_def_id), .. },
1779            )) = param.kind
1780            {
1781                generics
1782                    .params
1783                    .iter()
1784                    .position(|param| param.def_id.to_def_id() == res_def_id)
1785                    .map(GenericIdx::from_usize)
1786            } else {
1787                None
1788            }
1789        });
1790        match (body_id, params) {
1791            (Some(_), Some(_)) | (None, None) => unreachable!(),
1792            (Some(body), None) => {
1793                let params = self.tcx.hir_body(body).params;
1794                let params =
1795                    params.get(is_method as usize..params.len() - sig.decl.c_variadic as usize)?;
1796                debug_assert_eq!(params.len(), fn_inputs.len());
1797                Some((fn_inputs.zip(params.iter().map(FnParam::Param)).collect(), generics))
1798            }
1799            (None, Some(params)) => {
1800                let params =
1801                    params.get(is_method as usize..params.len() - sig.decl.c_variadic as usize)?;
1802                debug_assert_eq!(params.len(), fn_inputs.len());
1803                Some((
1804                    fn_inputs.zip(params.iter().map(|&ident| FnParam::Ident(ident))).collect(),
1805                    generics,
1806                ))
1807            }
1808        }
1809    }
1810}
1811
1812struct FindClosureArg<'tcx> {
1813    tcx: TyCtxt<'tcx>,
1814    calls: Vec<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
1815}
1816
1817impl<'tcx> Visitor<'tcx> for FindClosureArg<'tcx> {
1818    type NestedFilter = rustc_middle::hir::nested_filter::All;
1819
1820    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1821        self.tcx
1822    }
1823
1824    fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1825        if let hir::ExprKind::Call(rcvr, args) = ex.kind {
1826            self.calls.push((rcvr, args));
1827        }
1828        hir::intravisit::walk_expr(self, ex);
1829    }
1830}
1831
1832#[derive(Clone, Copy)]
1833enum FnParam<'hir> {
1834    Param(&'hir hir::Param<'hir>),
1835    Ident(Option<Ident>),
1836}
1837
1838impl FnParam<'_> {
1839    fn span(&self) -> Span {
1840        match self {
1841            Self::Param(param) => param.span,
1842            Self::Ident(ident) => {
1843                if let Some(ident) = ident {
1844                    ident.span
1845                } else {
1846                    DUMMY_SP
1847                }
1848            }
1849        }
1850    }
1851
1852    fn display(&self, idx: usize) -> impl '_ + fmt::Display {
1853        struct D<'a>(FnParam<'a>, usize);
1854        impl fmt::Display for D<'_> {
1855            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1856                // A "unique" param name is one that (a) exists, and (b) is guaranteed to be unique
1857                // among the parameters, i.e. `_` does not count.
1858                let unique_name = match self.0 {
1859                    FnParam::Param(param)
1860                        if let hir::PatKind::Binding(_, _, ident, _) = param.pat.kind =>
1861                    {
1862                        Some(ident.name)
1863                    }
1864                    FnParam::Ident(ident)
1865                        if let Some(ident) = ident
1866                            && ident.name != kw::Underscore =>
1867                    {
1868                        Some(ident.name)
1869                    }
1870                    _ => None,
1871                };
1872                if let Some(unique_name) = unique_name {
1873                    write!(f, "`{unique_name}`")
1874                } else {
1875                    write!(f, "parameter #{}", self.1 + 1)
1876                }
1877            }
1878        }
1879        D(*self, idx)
1880    }
1881}
1882
1883struct FnCallDiagCtxt<'a, 'b, 'tcx> {
1884    arg_matching_ctxt: ArgMatchingCtxt<'a, 'b, 'tcx>,
1885    errors: Vec<Error<'tcx>>,
1886    matched_inputs: IndexVec<ExpectedIdx, Option<ProvidedIdx>>,
1887}
1888
1889impl<'a, 'b, 'tcx> Deref for FnCallDiagCtxt<'a, 'b, 'tcx> {
1890    type Target = ArgMatchingCtxt<'a, 'b, 'tcx>;
1891
1892    fn deref(&self) -> &Self::Target {
1893        &self.arg_matching_ctxt
1894    }
1895}
1896
1897// Controls how the arguments should be listed in the suggestion.
1898enum ArgumentsFormatting {
1899    SingleLine,
1900    Multiline { fallback_indent: String, brace_indent: String },
1901}
1902
1903impl<'a, 'b, 'tcx> FnCallDiagCtxt<'a, 'b, 'tcx> {
1904    fn new(
1905        arg: &'a FnCtxt<'b, 'tcx>,
1906        compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
1907        formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
1908        provided_args: IndexVec<ProvidedIdx, &'tcx Expr<'tcx>>,
1909        c_variadic: bool,
1910        err_code: ErrCode,
1911        fn_def_id: Option<DefId>,
1912        call_span: Span,
1913        call_expr: &'tcx Expr<'tcx>,
1914        tuple_arguments: TupleArgumentsFlag,
1915    ) -> Self {
1916        let arg_matching_ctxt = ArgMatchingCtxt::new(
1917            arg,
1918            compatibility_diagonal,
1919            formal_and_expected_inputs,
1920            provided_args,
1921            c_variadic,
1922            err_code,
1923            fn_def_id,
1924            call_span,
1925            call_expr,
1926            tuple_arguments,
1927        );
1928
1929        // The algorithm here is inspired by levenshtein distance and longest common subsequence.
1930        // We'll try to detect 4 different types of mistakes:
1931        // - An extra parameter has been provided that doesn't satisfy *any* of the other inputs
1932        // - An input is missing, which isn't satisfied by *any* of the other arguments
1933        // - Some number of arguments have been provided in the wrong order
1934        // - A type is straight up invalid
1935        let (errors, matched_inputs) = ArgMatrix::new(
1936            arg_matching_ctxt.provided_args.len(),
1937            arg_matching_ctxt.formal_and_expected_inputs.len(),
1938            |provided, expected| arg_matching_ctxt.check_compatible(provided, expected),
1939        )
1940        .find_errors();
1941
1942        FnCallDiagCtxt { arg_matching_ctxt, errors, matched_inputs }
1943    }
1944
1945    fn check_wrap_args_in_tuple(&self) -> Option<ErrorGuaranteed> {
1946        if let Some((mismatch_idx, terr)) = self.first_incompatible_error() {
1947            // Is the first bad expected argument a tuple?
1948            // Do we have as many extra provided arguments as the tuple's length?
1949            // If so, we might have just forgotten to wrap some args in a tuple.
1950            if let Some(ty::Tuple(tys)) =
1951               self.formal_and_expected_inputs.get(mismatch_idx.to_expected_idx()).map(|tys| tys.1.kind())
1952                // If the tuple is unit, we're not actually wrapping any arguments.
1953                && !tys.is_empty()
1954                && self.provided_arg_tys.len() == self.formal_and_expected_inputs.len() - 1 + tys.len()
1955            {
1956                // Wrap up the N provided arguments starting at this position in a tuple.
1957                let provided_args_to_tuple = &self.provided_arg_tys[mismatch_idx..];
1958                let (provided_args_to_tuple, provided_args_after_tuple) =
1959                    provided_args_to_tuple.split_at(tys.len());
1960                let provided_as_tuple = Ty::new_tup_from_iter(
1961                    self.tcx,
1962                    provided_args_to_tuple.iter().map(|&(ty, _)| ty),
1963                );
1964
1965                let mut satisfied = true;
1966                // Check if the newly wrapped tuple + rest of the arguments are compatible.
1967                for ((_, expected_ty), provided_ty) in std::iter::zip(
1968                    self.formal_and_expected_inputs[mismatch_idx.to_expected_idx()..].iter(),
1969                    [provided_as_tuple]
1970                        .into_iter()
1971                        .chain(provided_args_after_tuple.iter().map(|&(ty, _)| ty)),
1972                ) {
1973                    if !self.may_coerce(provided_ty, *expected_ty) {
1974                        satisfied = false;
1975                        break;
1976                    }
1977                }
1978
1979                // If they're compatible, suggest wrapping in an arg, and we're done!
1980                // Take some care with spans, so we don't suggest wrapping a macro's
1981                // innards in parenthesis, for example.
1982                if satisfied
1983                    && let &[(_, hi @ lo)] | &[(_, lo), .., (_, hi)] = provided_args_to_tuple
1984                {
1985                    let mut err;
1986                    if tys.len() == 1 {
1987                        // A tuple wrap suggestion actually occurs within,
1988                        // so don't do anything special here.
1989                        err = self.err_ctxt().report_and_explain_type_error(
1990                            self.arg_matching_ctxt.args_ctxt.call_ctxt.mk_trace(
1991                                lo,
1992                                self.formal_and_expected_inputs[mismatch_idx.to_expected_idx()],
1993                                self.provided_arg_tys[mismatch_idx].0,
1994                            ),
1995                            self.param_env,
1996                            terr,
1997                        );
1998                        let call_name = self.call_metadata.call_name;
1999                        err.span_label(
2000                            self.call_metadata.full_call_span,
2001                            format!("arguments to this {call_name} are incorrect"),
2002                        );
2003                    } else {
2004                        let call_name = self.call_metadata.call_name;
2005                        err = self.dcx().struct_span_err(
2006                            self.arg_matching_ctxt.args_ctxt.call_metadata.full_call_span,
2007                            format!(
2008                                "{call_name} takes {}{} but {} {} supplied",
2009                                if self.c_variadic { "at least " } else { "" },
2010                                potentially_plural_count(
2011                                    self.formal_and_expected_inputs.len(),
2012                                    "argument"
2013                                ),
2014                                potentially_plural_count(self.provided_args.len(), "argument"),
2015                                pluralize!("was", self.provided_args.len())
2016                            ),
2017                        );
2018                        err.code(self.err_code.to_owned());
2019                        err.multipart_suggestion_verbose(
2020                            "wrap these arguments in parentheses to construct a tuple",
2021                            vec![
2022                                (lo.shrink_to_lo(), "(".to_string()),
2023                                (hi.shrink_to_hi(), ")".to_string()),
2024                            ],
2025                            Applicability::MachineApplicable,
2026                        );
2027                    };
2028                    self.arg_matching_ctxt.args_ctxt.call_ctxt.fn_ctxt.label_fn_like(
2029                        &mut err,
2030                        self.fn_def_id,
2031                        self.callee_ty,
2032                        self.call_expr,
2033                        None,
2034                        Some(mismatch_idx.as_usize()),
2035                        &self.matched_inputs,
2036                        &self.formal_and_expected_inputs,
2037                        self.call_metadata.is_method,
2038                        self.tuple_arguments,
2039                    );
2040                    self.suggest_confusable(&mut err);
2041                    Some(err.emit())
2042                } else {
2043                    None
2044                }
2045            } else {
2046                None
2047            }
2048        } else {
2049            None
2050        }
2051    }
2052
2053    fn ensure_has_errors(&self) -> Option<ErrorGuaranteed> {
2054        if self.errors.is_empty() {
2055            if cfg!(debug_assertions) {
2056                span_bug!(self.call_metadata.error_span, "expected errors from argument matrix");
2057            } else {
2058                let mut err = self.dcx().create_err(errors::ArgMismatchIndeterminate {
2059                    span: self.call_metadata.error_span,
2060                });
2061                self.arg_matching_ctxt.suggest_confusable(&mut err);
2062                return Some(err.emit());
2063            }
2064        }
2065
2066        None
2067    }
2068
2069    fn detect_dotdot(&self, err: &mut Diag<'_>, ty: Ty<'tcx>, expr: &hir::Expr<'tcx>) {
2070        if let ty::Adt(adt, _) = ty.kind()
2071            && self.tcx().is_lang_item(adt.did(), hir::LangItem::RangeFull)
2072            && is_range_literal(expr)
2073            && let hir::ExprKind::Struct(&path, [], _) = expr.kind
2074            && self.tcx().qpath_is_lang_item(path, hir::LangItem::RangeFull)
2075        {
2076            // We have `Foo(a, .., c)`, where the user might be trying to use the "rest" syntax
2077            // from default field values, which is not supported on tuples.
2078            let explanation = if self.tcx.features().default_field_values() {
2079                "this is only supported on non-tuple struct literals"
2080            } else if self.tcx.sess.is_nightly_build() {
2081                "this is only supported on non-tuple struct literals when \
2082                 `#![feature(default_field_values)]` is enabled"
2083            } else {
2084                "this is not supported"
2085            };
2086            let msg = format!(
2087                "you might have meant to use `..` to skip providing a value for \
2088                 expected fields, but {explanation}; it is instead interpreted as a \
2089                 `std::ops::RangeFull` literal",
2090            );
2091            err.span_help(expr.span, msg);
2092        }
2093    }
2094
2095    fn filter_out_invalid_arguments(&mut self) -> Option<ErrorGuaranteed> {
2096        let mut reported = None;
2097
2098        self.errors.retain(|error| {
2099            let Error::Invalid(provided_idx, expected_idx, Compatibility::Incompatible(Some(e))) =
2100                error
2101            else {
2102                return true;
2103            };
2104            let (provided_ty, provided_span) =
2105                self.arg_matching_ctxt.provided_arg_tys[*provided_idx];
2106            let trace = self.arg_matching_ctxt.mk_trace(
2107                provided_span,
2108                self.arg_matching_ctxt.formal_and_expected_inputs[*expected_idx],
2109                provided_ty,
2110            );
2111            if !matches!(trace.cause.as_failure_code(*e), FailureCode::Error0308) {
2112                let mut err = self.arg_matching_ctxt.err_ctxt().report_and_explain_type_error(
2113                    trace,
2114                    self.arg_matching_ctxt.param_env,
2115                    *e,
2116                );
2117                self.arg_matching_ctxt.suggest_confusable(&mut err);
2118                reported = Some(err.emit());
2119                return false;
2120            }
2121            true
2122        });
2123
2124        reported
2125    }
2126
2127    fn check_single_incompatible(&self) -> Option<ErrorGuaranteed> {
2128        if let &[
2129            Error::Invalid(provided_idx, expected_idx, Compatibility::Incompatible(Some(err))),
2130        ] = &self.errors[..]
2131        {
2132            let (formal_ty, expected_ty) = self.formal_and_expected_inputs[expected_idx];
2133            let (provided_ty, provided_arg_span) = self.provided_arg_tys[provided_idx];
2134            let trace = self.mk_trace(provided_arg_span, (formal_ty, expected_ty), provided_ty);
2135            let mut err = self.err_ctxt().report_and_explain_type_error(trace, self.param_env, err);
2136            self.emit_coerce_suggestions(
2137                &mut err,
2138                self.provided_args[provided_idx],
2139                provided_ty,
2140                Expectation::rvalue_hint(self.fn_ctxt, expected_ty)
2141                    .only_has_type(self.fn_ctxt)
2142                    .unwrap_or(formal_ty),
2143                None,
2144                None,
2145            );
2146            let call_name = self.call_metadata.call_name;
2147            err.span_label(
2148                self.call_metadata.full_call_span,
2149                format!("arguments to this {call_name} are incorrect"),
2150            );
2151
2152            self.fn_ctxt.label_generic_mismatches(
2153                &mut err,
2154                self.fn_def_id,
2155                &self.matched_inputs,
2156                &self.provided_arg_tys,
2157                &self.formal_and_expected_inputs,
2158                self.call_metadata.is_method,
2159            );
2160
2161            if let hir::ExprKind::MethodCall(_, rcvr, _, _) =
2162                self.arg_matching_ctxt.args_ctxt.call_ctxt.call_expr.kind
2163                && provided_idx.as_usize() == expected_idx.as_usize()
2164            {
2165                self.note_source_of_type_mismatch_constraint(
2166                    &mut err,
2167                    rcvr,
2168                    crate::demand::TypeMismatchSource::Arg {
2169                        call_expr: self.call_expr,
2170                        incompatible_arg: provided_idx.as_usize(),
2171                    },
2172                );
2173            }
2174
2175            self.suggest_ptr_null_mut(
2176                expected_ty,
2177                provided_ty,
2178                self.provided_args[provided_idx],
2179                &mut err,
2180            );
2181
2182            self.suggest_deref_unwrap_or(
2183                &mut err,
2184                self.callee_ty,
2185                self.call_metadata.call_ident,
2186                expected_ty,
2187                provided_ty,
2188                self.provided_args[provided_idx],
2189                self.call_metadata.is_method,
2190            );
2191
2192            // Call out where the function is defined
2193            self.label_fn_like(
2194                &mut err,
2195                self.fn_def_id,
2196                self.callee_ty,
2197                self.call_expr,
2198                Some(expected_ty),
2199                Some(expected_idx.as_usize()),
2200                &self.matched_inputs,
2201                &self.formal_and_expected_inputs,
2202                self.call_metadata.is_method,
2203                self.tuple_arguments,
2204            );
2205            self.arg_matching_ctxt.suggest_confusable(&mut err);
2206            self.detect_dotdot(&mut err, provided_ty, self.provided_args[provided_idx]);
2207            return Some(err.emit());
2208        }
2209
2210        None
2211    }
2212
2213    fn maybe_optimize_extra_arg_suggestion(&mut self) {
2214        if let [Error::Extra(provided_idx)] = &self.errors[..] {
2215            if !self.remove_idx_is_perfect(provided_idx.as_usize()) {
2216                if let Some(i) = (0..self.args_ctxt.call_ctxt.provided_args.len())
2217                    .find(|&i| self.remove_idx_is_perfect(i))
2218                {
2219                    self.errors = vec![Error::Extra(ProvidedIdx::from_usize(i))];
2220                }
2221            }
2222        }
2223    }
2224
2225    fn initial_final_diagnostic(&self) -> Diag<'_> {
2226        if self.formal_and_expected_inputs.len() == self.provided_args.len() {
2227            struct_span_code_err!(
2228                self.dcx(),
2229                self.call_metadata.full_call_span,
2230                E0308,
2231                "arguments to this {} are incorrect",
2232                self.call_metadata.call_name,
2233            )
2234        } else {
2235            self.arg_matching_ctxt
2236                .dcx()
2237                .struct_span_err(
2238                    self.call_metadata.full_call_span,
2239                    format!(
2240                        "this {} takes {}{} but {} {} supplied",
2241                        self.call_metadata.call_name,
2242                        if self.c_variadic { "at least " } else { "" },
2243                        potentially_plural_count(self.formal_and_expected_inputs.len(), "argument"),
2244                        potentially_plural_count(self.provided_args.len(), "argument"),
2245                        pluralize!("was", self.provided_args.len())
2246                    ),
2247                )
2248                .with_code(self.err_code.to_owned())
2249        }
2250    }
2251
2252    fn labels_and_suggestion_text(
2253        &self,
2254        err: &mut Diag<'_>,
2255    ) -> (Vec<(Span, String)>, Vec<(Span, String)>, SuggestionText) {
2256        // Don't print if it has error types or is just plain `_`
2257        fn has_error_or_infer<'tcx>(tys: impl IntoIterator<Item = Ty<'tcx>>) -> bool {
2258            tys.into_iter().any(|ty| ty.references_error() || ty.is_ty_var())
2259        }
2260
2261        let mut labels = Vec::new();
2262        let mut suggestion_text = SuggestionText::None;
2263
2264        let mut errors = self.errors.iter().peekable();
2265        let mut only_extras_so_far = errors
2266            .peek()
2267            .is_some_and(|first| matches!(first, Error::Extra(arg_idx) if arg_idx.index() == 0));
2268        let mut prev_extra_idx = None;
2269        let mut suggestions = vec![];
2270        while let Some(error) = errors.next() {
2271            only_extras_so_far &= matches!(error, Error::Extra(_));
2272
2273            match error {
2274                Error::Invalid(provided_idx, expected_idx, compatibility) => {
2275                    let (formal_ty, expected_ty) =
2276                        self.arg_matching_ctxt.args_ctxt.call_ctxt.formal_and_expected_inputs
2277                            [*expected_idx];
2278                    let (provided_ty, provided_span) =
2279                        self.arg_matching_ctxt.provided_arg_tys[*provided_idx];
2280                    if let Compatibility::Incompatible(error) = compatibility {
2281                        let trace = self.arg_matching_ctxt.args_ctxt.call_ctxt.mk_trace(
2282                            provided_span,
2283                            (formal_ty, expected_ty),
2284                            provided_ty,
2285                        );
2286                        if let Some(e) = error {
2287                            self.err_ctxt().note_type_err(
2288                                err,
2289                                &trace.cause,
2290                                None,
2291                                Some(self.param_env.and(trace.values)),
2292                                *e,
2293                                true,
2294                                None,
2295                            );
2296                        }
2297                    }
2298
2299                    self.emit_coerce_suggestions(
2300                        err,
2301                        self.provided_args[*provided_idx],
2302                        provided_ty,
2303                        Expectation::rvalue_hint(self.fn_ctxt, expected_ty)
2304                            .only_has_type(self.fn_ctxt)
2305                            .unwrap_or(formal_ty),
2306                        None,
2307                        None,
2308                    );
2309                    self.detect_dotdot(err, provided_ty, self.provided_args[*provided_idx]);
2310                }
2311                Error::Extra(arg_idx) => {
2312                    let (provided_ty, provided_span) = self.provided_arg_tys[*arg_idx];
2313                    let provided_ty_name = if !has_error_or_infer([provided_ty]) {
2314                        // FIXME: not suggestable, use something else
2315                        format!(" of type `{provided_ty}`")
2316                    } else {
2317                        "".to_string()
2318                    };
2319                    let idx = if self.provided_arg_tys.len() == 1 {
2320                        "".to_string()
2321                    } else {
2322                        format!(" #{}", arg_idx.as_usize() + 1)
2323                    };
2324                    labels.push((
2325                        provided_span,
2326                        format!("unexpected argument{idx}{provided_ty_name}"),
2327                    ));
2328                    let mut span = provided_span;
2329                    if span.can_be_used_for_suggestions()
2330                        && self.call_metadata.error_span.can_be_used_for_suggestions()
2331                    {
2332                        if arg_idx.index() > 0
2333                            && let Some((_, prev)) = self
2334                                .provided_arg_tys
2335                                .get(ProvidedIdx::from_usize(arg_idx.index() - 1))
2336                        {
2337                            // Include previous comma
2338                            span = prev.shrink_to_hi().to(span);
2339                        }
2340
2341                        // Is last argument for deletion in a row starting from the 0-th argument?
2342                        // Then delete the next comma, so we are not left with `f(, ...)`
2343                        //
2344                        //     fn f() {}
2345                        //   - f(0, 1,)
2346                        //   + f()
2347                        let trim_next_comma = match errors.peek() {
2348                            Some(Error::Extra(provided_idx))
2349                                if only_extras_so_far
2350                                    && provided_idx.index() > arg_idx.index() + 1 =>
2351                            // If the next Error::Extra ("next") doesn't next to current ("current"),
2352                            // fn foo(_: (), _: u32) {}
2353                            // - foo("current", (), 1u32, "next")
2354                            // + foo((), 1u32)
2355                            // If the previous error is not a `Error::Extra`, then do not trim the next comma
2356                            // - foo((), "current", 42u32, "next")
2357                            // + foo((), 42u32)
2358                            {
2359                                prev_extra_idx.is_none_or(|prev_extra_idx| {
2360                                    prev_extra_idx + 1 == arg_idx.index()
2361                                })
2362                            }
2363                            // If no error left, we need to delete the next comma
2364                            None if only_extras_so_far => true,
2365                            // Not sure if other error type need to be handled as well
2366                            _ => false,
2367                        };
2368
2369                        if trim_next_comma {
2370                            let next = self
2371                                .provided_arg_tys
2372                                .get(*arg_idx + 1)
2373                                .map(|&(_, sp)| sp)
2374                                .unwrap_or_else(|| {
2375                                    // Try to move before `)`. Note that `)` here is not necessarily
2376                                    // the latin right paren, it could be a Unicode-confusable that
2377                                    // looks like a `)`, so we must not use `- BytePos(1)`
2378                                    // manipulations here.
2379                                    self.arg_matching_ctxt
2380                                        .tcx()
2381                                        .sess
2382                                        .source_map()
2383                                        .end_point(self.call_expr.span)
2384                                });
2385
2386                            // Include next comma
2387                            span = span.until(next);
2388                        }
2389
2390                        suggestions.push((span, String::new()));
2391
2392                        suggestion_text = match suggestion_text {
2393                            SuggestionText::None => SuggestionText::Remove(false),
2394                            SuggestionText::Remove(_) => SuggestionText::Remove(true),
2395                            _ => SuggestionText::DidYouMean,
2396                        };
2397                        prev_extra_idx = Some(arg_idx.index())
2398                    }
2399                    self.detect_dotdot(err, provided_ty, self.provided_args[*arg_idx]);
2400                }
2401                Error::Missing(expected_idx) => {
2402                    // If there are multiple missing arguments adjacent to each other,
2403                    // then we can provide a single error.
2404
2405                    let mut missing_idxs = vec![*expected_idx];
2406                    while let Some(e) = errors.next_if(|e| {
2407                        matches!(e, Error::Missing(next_expected_idx)
2408                            if *next_expected_idx == *missing_idxs.last().unwrap() + 1)
2409                    }) {
2410                        match e {
2411                            Error::Missing(expected_idx) => missing_idxs.push(*expected_idx),
2412                            _ => unreachable!(
2413                                "control flow ensures that we should always get an `Error::Missing`"
2414                            ),
2415                        }
2416                    }
2417
2418                    // NOTE: Because we might be re-arranging arguments, might have extra
2419                    // arguments, etc. it's hard to *really* know where we should provide
2420                    // this error label, so as a heuristic, we point to the provided arg, or
2421                    // to the call if the missing inputs pass the provided args.
2422                    match &missing_idxs[..] {
2423                        &[expected_idx] => {
2424                            let (_, input_ty) = self.formal_and_expected_inputs[expected_idx];
2425                            let span = if let Some((_, arg_span)) =
2426                                self.provided_arg_tys.get(expected_idx.to_provided_idx())
2427                            {
2428                                *arg_span
2429                            } else {
2430                                self.args_span
2431                            };
2432                            let rendered = if !has_error_or_infer([input_ty]) {
2433                                format!(" of type `{input_ty}`")
2434                            } else {
2435                                "".to_string()
2436                            };
2437                            labels.push((
2438                                span,
2439                                format!(
2440                                    "argument #{}{rendered} is missing",
2441                                    expected_idx.as_usize() + 1
2442                                ),
2443                            ));
2444
2445                            suggestion_text = match suggestion_text {
2446                                SuggestionText::None => SuggestionText::Provide(false),
2447                                SuggestionText::Provide(_) => SuggestionText::Provide(true),
2448                                _ => SuggestionText::DidYouMean,
2449                            };
2450                        }
2451                        &[first_idx, second_idx] => {
2452                            let (_, first_expected_ty) = self.formal_and_expected_inputs[first_idx];
2453                            let (_, second_expected_ty) =
2454                                self.formal_and_expected_inputs[second_idx];
2455                            let span = if let (Some((_, first_span)), Some((_, second_span))) = (
2456                                self.provided_arg_tys.get(first_idx.to_provided_idx()),
2457                                self.provided_arg_tys.get(second_idx.to_provided_idx()),
2458                            ) {
2459                                first_span.to(*second_span)
2460                            } else {
2461                                self.args_span
2462                            };
2463                            let rendered =
2464                                if !has_error_or_infer([first_expected_ty, second_expected_ty]) {
2465                                    format!(
2466                                        " of type `{first_expected_ty}` and `{second_expected_ty}`"
2467                                    )
2468                                } else {
2469                                    "".to_string()
2470                                };
2471                            labels.push((span, format!("two arguments{rendered} are missing")));
2472                            suggestion_text = match suggestion_text {
2473                                SuggestionText::None | SuggestionText::Provide(_) => {
2474                                    SuggestionText::Provide(true)
2475                                }
2476                                _ => SuggestionText::DidYouMean,
2477                            };
2478                        }
2479                        &[first_idx, second_idx, third_idx] => {
2480                            let (_, first_expected_ty) = self.formal_and_expected_inputs[first_idx];
2481                            let (_, second_expected_ty) =
2482                                self.formal_and_expected_inputs[second_idx];
2483                            let (_, third_expected_ty) = self.formal_and_expected_inputs[third_idx];
2484                            let span = if let (Some((_, first_span)), Some((_, third_span))) = (
2485                                self.provided_arg_tys.get(first_idx.to_provided_idx()),
2486                                self.provided_arg_tys.get(third_idx.to_provided_idx()),
2487                            ) {
2488                                first_span.to(*third_span)
2489                            } else {
2490                                self.args_span
2491                            };
2492                            let rendered = if !has_error_or_infer([
2493                                first_expected_ty,
2494                                second_expected_ty,
2495                                third_expected_ty,
2496                            ]) {
2497                                format!(
2498                                    " of type `{first_expected_ty}`, `{second_expected_ty}`, and `{third_expected_ty}`"
2499                                )
2500                            } else {
2501                                "".to_string()
2502                            };
2503                            labels.push((span, format!("three arguments{rendered} are missing")));
2504                            suggestion_text = match suggestion_text {
2505                                SuggestionText::None | SuggestionText::Provide(_) => {
2506                                    SuggestionText::Provide(true)
2507                                }
2508                                _ => SuggestionText::DidYouMean,
2509                            };
2510                        }
2511                        missing_idxs => {
2512                            let first_idx = *missing_idxs.first().unwrap();
2513                            let last_idx = *missing_idxs.last().unwrap();
2514                            // NOTE: Because we might be re-arranging arguments, might have extra arguments, etc.
2515                            // It's hard to *really* know where we should provide this error label, so this is a
2516                            // decent heuristic
2517                            let span = if let (Some((_, first_span)), Some((_, last_span))) = (
2518                                self.provided_arg_tys.get(first_idx.to_provided_idx()),
2519                                self.provided_arg_tys.get(last_idx.to_provided_idx()),
2520                            ) {
2521                                first_span.to(*last_span)
2522                            } else {
2523                                self.args_span
2524                            };
2525                            labels.push((span, "multiple arguments are missing".to_string()));
2526                            suggestion_text = match suggestion_text {
2527                                SuggestionText::None | SuggestionText::Provide(_) => {
2528                                    SuggestionText::Provide(true)
2529                                }
2530                                _ => SuggestionText::DidYouMean,
2531                            };
2532                        }
2533                    }
2534                }
2535                Error::Swap(
2536                    first_provided_idx,
2537                    second_provided_idx,
2538                    first_expected_idx,
2539                    second_expected_idx,
2540                ) => {
2541                    let (first_provided_ty, first_span) =
2542                        self.provided_arg_tys[*first_provided_idx];
2543                    let (_, first_expected_ty) =
2544                        self.formal_and_expected_inputs[*first_expected_idx];
2545                    let first_provided_ty_name = if !has_error_or_infer([first_provided_ty]) {
2546                        format!(", found `{first_provided_ty}`")
2547                    } else {
2548                        String::new()
2549                    };
2550                    labels.push((
2551                        first_span,
2552                        format!("expected `{first_expected_ty}`{first_provided_ty_name}"),
2553                    ));
2554
2555                    let (second_provided_ty, second_span) =
2556                        self.provided_arg_tys[*second_provided_idx];
2557                    let (_, second_expected_ty) =
2558                        self.formal_and_expected_inputs[*second_expected_idx];
2559                    let second_provided_ty_name = if !has_error_or_infer([second_provided_ty]) {
2560                        format!(", found `{second_provided_ty}`")
2561                    } else {
2562                        String::new()
2563                    };
2564                    labels.push((
2565                        second_span,
2566                        format!("expected `{second_expected_ty}`{second_provided_ty_name}"),
2567                    ));
2568
2569                    suggestion_text = match suggestion_text {
2570                        SuggestionText::None => SuggestionText::Swap,
2571                        _ => SuggestionText::DidYouMean,
2572                    };
2573                }
2574                Error::Permutation(args) => {
2575                    for (dst_arg, dest_input) in args {
2576                        let (_, expected_ty) = self.formal_and_expected_inputs[*dst_arg];
2577                        let (provided_ty, provided_span) = self.provided_arg_tys[*dest_input];
2578                        let provided_ty_name = if !has_error_or_infer([provided_ty]) {
2579                            format!(", found `{provided_ty}`")
2580                        } else {
2581                            String::new()
2582                        };
2583                        labels.push((
2584                            provided_span,
2585                            format!("expected `{expected_ty}`{provided_ty_name}"),
2586                        ));
2587                    }
2588
2589                    suggestion_text = match suggestion_text {
2590                        SuggestionText::None => SuggestionText::Reorder,
2591                        _ => SuggestionText::DidYouMean,
2592                    };
2593                }
2594            }
2595        }
2596
2597        (suggestions, labels, suggestion_text)
2598    }
2599
2600    fn label_generic_mismatches(&self, err: &mut Diag<'b>) {
2601        self.fn_ctxt.label_generic_mismatches(
2602            err,
2603            self.fn_def_id,
2604            &self.matched_inputs,
2605            &self.provided_arg_tys,
2606            &self.formal_and_expected_inputs,
2607            self.call_metadata.is_method,
2608        );
2609    }
2610
2611    /// Incorporate the argument changes in the removal suggestion.
2612    ///
2613    /// When a type is *missing*, and the rest are additional, we want to suggest these with a
2614    /// multipart suggestion, but in order to do so we need to figure out *where* the arg that
2615    /// was provided but had the wrong type should go, because when looking at `expected_idx`
2616    /// that is the position in the argument list in the definition, while `provided_idx` will
2617    /// not be present. So we have to look at what the *last* provided position was, and point
2618    /// one after to suggest the replacement.
2619    fn append_arguments_changes(&self, suggestions: &mut Vec<(Span, String)>) {
2620        // FIXME(estebank): This is hacky, and there's
2621        // probably a better more involved change we can make to make this work.
2622        // For example, if we have
2623        // ```
2624        // fn foo(i32, &'static str) {}
2625        // foo((), (), ());
2626        // ```
2627        // what should be suggested is
2628        // ```
2629        // foo(/* i32 */, /* &str */);
2630        // ```
2631        // which includes the replacement of the first two `()` for the correct type, and the
2632        // removal of the last `()`.
2633
2634        let mut prev = -1;
2635        for (expected_idx, provided_idx) in self.matched_inputs.iter_enumerated() {
2636            // We want to point not at the *current* argument expression index, but rather at the
2637            // index position where it *should have been*, which is *after* the previous one.
2638            if let Some(provided_idx) = provided_idx {
2639                prev = provided_idx.index() as i64;
2640                continue;
2641            }
2642            let idx = ProvidedIdx::from_usize((prev + 1) as usize);
2643            if let Some((_, arg_span)) = self.provided_arg_tys.get(idx) {
2644                prev += 1;
2645                // There is a type that was *not* found anywhere, so it isn't a move, but a
2646                // replacement and we look at what type it should have been. This will allow us
2647                // To suggest a multipart suggestion when encountering `foo(1, "")` where the def
2648                // was `fn foo(())`.
2649                let (_, expected_ty) = self.formal_and_expected_inputs[expected_idx];
2650                suggestions.push((*arg_span, self.ty_to_snippet(expected_ty, expected_idx)));
2651            }
2652        }
2653    }
2654
2655    fn format_suggestion_text(
2656        err: &mut Diag<'_>,
2657        suggestions: Vec<(Span, String)>,
2658        suggestion_text: SuggestionText,
2659    ) -> Option<String> {
2660        match suggestion_text {
2661            SuggestionText::None => None,
2662            SuggestionText::Provide(plural) => {
2663                Some(format!("provide the argument{}", if plural { "s" } else { "" }))
2664            }
2665            SuggestionText::Remove(plural) => {
2666                err.multipart_suggestion_verbose(
2667                    format!("remove the extra argument{}", if plural { "s" } else { "" }),
2668                    suggestions,
2669                    Applicability::HasPlaceholders,
2670                );
2671                None
2672            }
2673            SuggestionText::Swap => Some("swap these arguments".to_string()),
2674            SuggestionText::Reorder => Some("reorder these arguments".to_string()),
2675            SuggestionText::DidYouMean => Some("did you mean".to_string()),
2676        }
2677    }
2678
2679    fn arguments_formatting(&self, suggestion_span: Span) -> ArgumentsFormatting {
2680        let source_map = self.sess().source_map();
2681        let mut provided_inputs = self.matched_inputs.iter().filter_map(|a| *a);
2682        if let Some(brace_indent) = source_map.indentation_before(suggestion_span)
2683            && let Some(first_idx) = provided_inputs.by_ref().next()
2684            && let Some(last_idx) = provided_inputs.by_ref().next()
2685            && let (_, first_span) = self.provided_arg_tys[first_idx]
2686            && let (_, last_span) = self.provided_arg_tys[last_idx]
2687            && source_map.is_multiline(first_span.to(last_span))
2688            && let Some(fallback_indent) = source_map.indentation_before(first_span)
2689        {
2690            ArgumentsFormatting::Multiline { fallback_indent, brace_indent }
2691        } else {
2692            ArgumentsFormatting::SingleLine
2693        }
2694    }
2695
2696    fn suggestion_code(&self) -> (Span, String) {
2697        let source_map = self.sess().source_map();
2698        let suggestion_span = if let Some(args_span) =
2699            self.call_metadata.error_span.trim_start(self.call_metadata.full_call_span)
2700        {
2701            // Span of the braces, e.g. `(a, b, c)`.
2702            args_span
2703        } else {
2704            // The arg span of a function call that wasn't even given braces
2705            // like what might happen with delegation reuse.
2706            // e.g. `reuse HasSelf::method;` should suggest `reuse HasSelf::method($args);`.
2707            self.call_metadata.full_call_span.shrink_to_hi()
2708        };
2709
2710        let arguments_formatting = self.arguments_formatting(suggestion_span);
2711
2712        let mut suggestion = "(".to_owned();
2713        let mut needs_comma = false;
2714        for (expected_idx, provided_idx) in self.matched_inputs.iter_enumerated() {
2715            if needs_comma {
2716                suggestion += ",";
2717            }
2718            match &arguments_formatting {
2719                ArgumentsFormatting::SingleLine if needs_comma => suggestion += " ",
2720                ArgumentsFormatting::SingleLine => {}
2721                ArgumentsFormatting::Multiline { .. } => suggestion += "\n",
2722            }
2723            needs_comma = true;
2724            let (suggestion_span, suggestion_text) = if let Some(provided_idx) = provided_idx
2725                && let (_, provided_span) = self.provided_arg_tys[*provided_idx]
2726                && let Ok(arg_text) = source_map.span_to_snippet(provided_span)
2727            {
2728                (Some(provided_span), arg_text)
2729            } else {
2730                // Propose a placeholder of the correct type
2731                let (_, expected_ty) = self.formal_and_expected_inputs[expected_idx];
2732                (None, self.ty_to_snippet(expected_ty, expected_idx))
2733            };
2734            if let ArgumentsFormatting::Multiline { fallback_indent, .. } = &arguments_formatting {
2735                let indent = suggestion_span
2736                    .and_then(|span| source_map.indentation_before(span))
2737                    .unwrap_or_else(|| fallback_indent.clone());
2738                suggestion += &indent;
2739            }
2740            suggestion += &suggestion_text;
2741        }
2742        if let ArgumentsFormatting::Multiline { brace_indent, .. } = arguments_formatting {
2743            suggestion += ",\n";
2744            suggestion += &brace_indent;
2745        }
2746        suggestion += ")";
2747
2748        (suggestion_span, suggestion)
2749    }
2750}
2751
2752struct ArgMatchingCtxt<'a, 'b, 'tcx> {
2753    args_ctxt: ArgsCtxt<'a, 'b, 'tcx>,
2754    provided_arg_tys: IndexVec<ProvidedIdx, (Ty<'tcx>, Span)>,
2755}
2756
2757impl<'a, 'b, 'tcx> Deref for ArgMatchingCtxt<'a, 'b, 'tcx> {
2758    type Target = ArgsCtxt<'a, 'b, 'tcx>;
2759
2760    fn deref(&self) -> &Self::Target {
2761        &self.args_ctxt
2762    }
2763}
2764
2765impl<'a, 'b, 'tcx> ArgMatchingCtxt<'a, 'b, 'tcx> {
2766    fn new(
2767        arg: &'a FnCtxt<'b, 'tcx>,
2768        compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
2769        formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
2770        provided_args: IndexVec<ProvidedIdx, &'tcx Expr<'tcx>>,
2771        c_variadic: bool,
2772        err_code: ErrCode,
2773        fn_def_id: Option<DefId>,
2774        call_span: Span,
2775        call_expr: &'tcx Expr<'tcx>,
2776        tuple_arguments: TupleArgumentsFlag,
2777    ) -> Self {
2778        let args_ctxt = ArgsCtxt::new(
2779            arg,
2780            compatibility_diagonal,
2781            formal_and_expected_inputs,
2782            provided_args,
2783            c_variadic,
2784            err_code,
2785            fn_def_id,
2786            call_span,
2787            call_expr,
2788            tuple_arguments,
2789        );
2790        let provided_arg_tys = args_ctxt.provided_arg_tys();
2791
2792        ArgMatchingCtxt { args_ctxt, provided_arg_tys }
2793    }
2794
2795    fn suggest_confusable(&self, err: &mut Diag<'_>) {
2796        let Some(call_name) = self.call_metadata.call_ident else {
2797            return;
2798        };
2799        let Some(callee_ty) = self.callee_ty else {
2800            return;
2801        };
2802        let input_types: Vec<Ty<'_>> = self.provided_arg_tys.iter().map(|(ty, _)| *ty).collect();
2803
2804        // Check for other methods in the following order
2805        //  - methods marked as `rustc_confusables` with the provided arguments
2806        //  - methods with the same argument type/count and short levenshtein distance
2807        //  - methods marked as `rustc_confusables` (done)
2808        //  - methods with short levenshtein distance
2809
2810        // Look for commonly confusable method names considering arguments.
2811        if let Some(_name) = self.confusable_method_name(
2812            err,
2813            callee_ty.peel_refs(),
2814            call_name,
2815            Some(input_types.clone()),
2816        ) {
2817            return;
2818        }
2819        // Look for method names with short levenshtein distance, considering arguments.
2820        if let Some((assoc, fn_sig)) = self.similar_assoc(call_name)
2821            && fn_sig.inputs()[1..]
2822                .iter()
2823                .eq_by(input_types, |expected, found| self.may_coerce(*expected, found))
2824        {
2825            let assoc_name = assoc.name();
2826            err.span_suggestion_verbose(
2827                call_name.span,
2828                format!("you might have meant to use `{}`", assoc_name),
2829                assoc_name,
2830                Applicability::MaybeIncorrect,
2831            );
2832            return;
2833        }
2834    }
2835
2836    /// A "softer" version of the `demand_compatible`, which checks types without persisting them,
2837    /// and treats error types differently
2838    /// This will allow us to "probe" for other argument orders that would likely have been correct
2839    fn check_compatible(
2840        &self,
2841        provided_idx: ProvidedIdx,
2842        expected_idx: ExpectedIdx,
2843    ) -> Compatibility<'tcx> {
2844        if provided_idx.as_usize() == expected_idx.as_usize() {
2845            return self.compatibility_diagonal[provided_idx].clone();
2846        }
2847
2848        let (formal_input_ty, expected_input_ty) = self.formal_and_expected_inputs[expected_idx];
2849        // If either is an error type, we defy the usual convention and consider them to *not* be
2850        // coercible. This prevents our error message heuristic from trying to pass errors into
2851        // every argument.
2852        if (formal_input_ty, expected_input_ty).references_error() {
2853            return Compatibility::Incompatible(None);
2854        }
2855
2856        let (arg_ty, arg_span) = self.provided_arg_tys[provided_idx];
2857
2858        let expectation = Expectation::rvalue_hint(self.fn_ctxt, expected_input_ty);
2859        let coerced_ty = expectation.only_has_type(self.fn_ctxt).unwrap_or(formal_input_ty);
2860        let can_coerce = self.may_coerce(arg_ty, coerced_ty);
2861        if !can_coerce {
2862            return Compatibility::Incompatible(Some(ty::error::TypeError::Sorts(
2863                ty::error::ExpectedFound::new(coerced_ty, arg_ty),
2864            )));
2865        }
2866
2867        // Using probe here, since we don't want this subtyping to affect inference.
2868        let subtyping_error = self.probe(|_| {
2869            self.at(&self.misc(arg_span), self.param_env)
2870                .sup(DefineOpaqueTypes::Yes, formal_input_ty, coerced_ty)
2871                .err()
2872        });
2873
2874        // Same as above: if either the coerce type or the checked type is an error type,
2875        // consider them *not* compatible.
2876        let references_error = (coerced_ty, arg_ty).references_error();
2877        match (references_error, subtyping_error) {
2878            (false, None) => Compatibility::Compatible,
2879            (_, subtyping_error) => Compatibility::Incompatible(subtyping_error),
2880        }
2881    }
2882
2883    fn remove_idx_is_perfect(&self, idx: usize) -> bool {
2884        let removed_arg_tys = self
2885            .provided_arg_tys
2886            .iter()
2887            .enumerate()
2888            .filter_map(|(j, arg)| if idx == j { None } else { Some(arg) })
2889            .collect::<IndexVec<ProvidedIdx, _>>();
2890        std::iter::zip(self.formal_and_expected_inputs.iter(), removed_arg_tys.iter()).all(
2891            |((expected_ty, _), (provided_ty, _))| {
2892                !provided_ty.references_error() && self.may_coerce(*provided_ty, *expected_ty)
2893            },
2894        )
2895    }
2896}
2897
2898struct ArgsCtxt<'a, 'b, 'tcx> {
2899    call_ctxt: CallCtxt<'a, 'b, 'tcx>,
2900    call_metadata: CallMetadata,
2901    args_span: Span,
2902}
2903
2904impl<'a, 'b, 'tcx> Deref for ArgsCtxt<'a, 'b, 'tcx> {
2905    type Target = CallCtxt<'a, 'b, 'tcx>;
2906
2907    fn deref(&self) -> &Self::Target {
2908        &self.call_ctxt
2909    }
2910}
2911
2912impl<'a, 'b, 'tcx> ArgsCtxt<'a, 'b, 'tcx> {
2913    fn new(
2914        arg: &'a FnCtxt<'b, 'tcx>,
2915        compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
2916        formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
2917        provided_args: IndexVec<ProvidedIdx, &'tcx Expr<'tcx>>,
2918        c_variadic: bool,
2919        err_code: ErrCode,
2920        fn_def_id: Option<DefId>,
2921        call_span: Span,
2922        call_expr: &'tcx Expr<'tcx>,
2923        tuple_arguments: TupleArgumentsFlag,
2924    ) -> Self {
2925        let call_ctxt: CallCtxt<'_, '_, '_> = CallCtxt::new(
2926            arg,
2927            compatibility_diagonal,
2928            formal_and_expected_inputs,
2929            provided_args,
2930            c_variadic,
2931            err_code,
2932            fn_def_id,
2933            call_span,
2934            call_expr,
2935            tuple_arguments,
2936        );
2937
2938        let call_metadata = call_ctxt.call_metadata();
2939        let args_span = call_metadata
2940            .error_span
2941            .trim_start(call_metadata.full_call_span)
2942            .unwrap_or(call_metadata.error_span);
2943
2944        ArgsCtxt { args_span, call_metadata, call_ctxt }
2945    }
2946
2947    /// Get the argument span in the context of the call span so that
2948    /// suggestions and labels are (more) correct when an arg is a
2949    /// macro invocation.
2950    fn normalize_span(&self, span: Span) -> Span {
2951        let normalized_span =
2952            span.find_ancestor_inside_same_ctxt(self.call_metadata.error_span).unwrap_or(span);
2953        // Sometimes macros mess up the spans, so do not normalize the
2954        // arg span to equal the error span, because that's less useful
2955        // than pointing out the arg expr in the wrong context.
2956        if normalized_span.source_equal(self.call_metadata.error_span) {
2957            span
2958        } else {
2959            normalized_span
2960        }
2961    }
2962
2963    /// Computes the provided types and spans.
2964    fn provided_arg_tys(&self) -> IndexVec<ProvidedIdx, (Ty<'tcx>, Span)> {
2965        self.call_ctxt
2966            .provided_args
2967            .iter()
2968            .map(|expr| {
2969                let ty = self
2970                    .call_ctxt
2971                    .fn_ctxt
2972                    .typeck_results
2973                    .borrow()
2974                    .expr_ty_adjusted_opt(expr)
2975                    .unwrap_or_else(|| Ty::new_misc_error(self.call_ctxt.fn_ctxt.tcx));
2976                (
2977                    self.call_ctxt.fn_ctxt.resolve_vars_if_possible(ty),
2978                    self.normalize_span(expr.span),
2979                )
2980            })
2981            .collect()
2982    }
2983
2984    // Obtain another method on `Self` that have similar name.
2985    fn similar_assoc(&self, call_name: Ident) -> Option<(ty::AssocItem, ty::FnSig<'tcx>)> {
2986        if let Some(callee_ty) = self.call_ctxt.callee_ty
2987            && let Ok(Some(assoc)) = self.call_ctxt.fn_ctxt.probe_op(
2988                call_name.span,
2989                MethodCall,
2990                Some(call_name),
2991                None,
2992                IsSuggestion(true),
2993                callee_ty.peel_refs(),
2994                self.call_ctxt.callee_expr.unwrap().hir_id,
2995                TraitsInScope,
2996                |mut ctxt| ctxt.probe_for_similar_candidate(),
2997            )
2998            && assoc.is_method()
2999        {
3000            let args =
3001                self.call_ctxt.fn_ctxt.infcx.fresh_args_for_item(call_name.span, assoc.def_id);
3002            let fn_sig = self
3003                .call_ctxt
3004                .fn_ctxt
3005                .tcx
3006                .fn_sig(assoc.def_id)
3007                .instantiate(self.call_ctxt.fn_ctxt.tcx, args);
3008
3009            self.call_ctxt.fn_ctxt.instantiate_binder_with_fresh_vars(
3010                call_name.span,
3011                BoundRegionConversionTime::FnCall,
3012                fn_sig,
3013            );
3014        }
3015        None
3016    }
3017
3018    fn call_is_in_macro(&self) -> bool {
3019        self.call_metadata.full_call_span.in_external_macro(self.sess().source_map())
3020    }
3021}
3022
3023struct CallMetadata {
3024    error_span: Span,
3025    call_ident: Option<Ident>,
3026    full_call_span: Span,
3027    call_name: &'static str,
3028    is_method: bool,
3029}
3030
3031struct CallCtxt<'a, 'b, 'tcx> {
3032    fn_ctxt: &'a FnCtxt<'b, 'tcx>,
3033    compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
3034    formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
3035    provided_args: IndexVec<ProvidedIdx, &'tcx hir::Expr<'tcx>>,
3036    c_variadic: bool,
3037    err_code: ErrCode,
3038    fn_def_id: Option<DefId>,
3039    call_span: Span,
3040    call_expr: &'tcx hir::Expr<'tcx>,
3041    tuple_arguments: TupleArgumentsFlag,
3042    callee_expr: Option<&'tcx Expr<'tcx>>,
3043    callee_ty: Option<Ty<'tcx>>,
3044}
3045
3046impl<'a, 'b, 'tcx> Deref for CallCtxt<'a, 'b, 'tcx> {
3047    type Target = &'a FnCtxt<'b, 'tcx>;
3048
3049    fn deref(&self) -> &Self::Target {
3050        &self.fn_ctxt
3051    }
3052}
3053
3054impl<'a, 'b, 'tcx> CallCtxt<'a, 'b, 'tcx> {
3055    fn new(
3056        fn_ctxt: &'a FnCtxt<'b, 'tcx>,
3057        compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
3058        formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
3059        provided_args: IndexVec<ProvidedIdx, &'tcx hir::Expr<'tcx>>,
3060        c_variadic: bool,
3061        err_code: ErrCode,
3062        fn_def_id: Option<DefId>,
3063        call_span: Span,
3064        call_expr: &'tcx hir::Expr<'tcx>,
3065        tuple_arguments: TupleArgumentsFlag,
3066    ) -> CallCtxt<'a, 'b, 'tcx> {
3067        let callee_expr = match &call_expr.peel_blocks().kind {
3068            hir::ExprKind::Call(callee, _) => Some(*callee),
3069            hir::ExprKind::MethodCall(_, receiver, ..) => {
3070                if let Some((DefKind::AssocFn, def_id)) =
3071                    fn_ctxt.typeck_results.borrow().type_dependent_def(call_expr.hir_id)
3072                    && let Some(assoc) = fn_ctxt.tcx.opt_associated_item(def_id)
3073                    && assoc.is_method()
3074                {
3075                    Some(*receiver)
3076                } else {
3077                    None
3078                }
3079            }
3080            _ => None,
3081        };
3082
3083        let callee_ty = callee_expr.and_then(|callee_expr| {
3084            fn_ctxt.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)
3085        });
3086
3087        CallCtxt {
3088            fn_ctxt,
3089            compatibility_diagonal,
3090            formal_and_expected_inputs,
3091            provided_args,
3092            c_variadic,
3093            err_code,
3094            fn_def_id,
3095            call_span,
3096            call_expr,
3097            tuple_arguments,
3098            callee_expr,
3099            callee_ty,
3100        }
3101    }
3102
3103    fn call_metadata(&self) -> CallMetadata {
3104        match &self.call_expr.kind {
3105            hir::ExprKind::Call(
3106                hir::Expr { hir_id, span, kind: hir::ExprKind::Path(qpath), .. },
3107                _,
3108            ) => {
3109                if let Res::Def(DefKind::Ctor(of, _), _) =
3110                    self.typeck_results.borrow().qpath_res(qpath, *hir_id)
3111                {
3112                    let name = match of {
3113                        CtorOf::Struct => "struct",
3114                        CtorOf::Variant => "enum variant",
3115                    };
3116                    CallMetadata {
3117                        error_span: self.call_span,
3118                        call_ident: None,
3119                        full_call_span: *span,
3120                        call_name: name,
3121                        is_method: false,
3122                    }
3123                } else {
3124                    CallMetadata {
3125                        error_span: self.call_span,
3126                        call_ident: None,
3127                        full_call_span: *span,
3128                        call_name: "function",
3129                        is_method: false,
3130                    }
3131                }
3132            }
3133            hir::ExprKind::Call(hir::Expr { span, .. }, _) => CallMetadata {
3134                error_span: self.call_span,
3135                call_ident: None,
3136                full_call_span: *span,
3137                call_name: "function",
3138                is_method: false,
3139            },
3140            hir::ExprKind::MethodCall(path_segment, _, _, span) => {
3141                let ident_span = path_segment.ident.span;
3142                let ident_span = if let Some(args) = path_segment.args {
3143                    ident_span.with_hi(args.span_ext.hi())
3144                } else {
3145                    ident_span
3146                };
3147                CallMetadata {
3148                    error_span: *span,
3149                    call_ident: Some(path_segment.ident),
3150                    full_call_span: ident_span,
3151                    call_name: "method",
3152                    is_method: true,
3153                }
3154            }
3155            k => span_bug!(self.call_span, "checking argument types on a non-call: `{:?}`", k),
3156        }
3157    }
3158
3159    fn mk_trace(
3160        &self,
3161        span: Span,
3162        (formal_ty, expected_ty): (Ty<'tcx>, Ty<'tcx>),
3163        provided_ty: Ty<'tcx>,
3164    ) -> TypeTrace<'tcx> {
3165        let mismatched_ty = if expected_ty == provided_ty {
3166            // If expected == provided, then we must have failed to sup
3167            // the formal type. Avoid printing out "expected Ty, found Ty"
3168            // in that case.
3169            formal_ty
3170        } else {
3171            expected_ty
3172        };
3173        TypeTrace::types(&self.misc(span), mismatched_ty, provided_ty)
3174    }
3175
3176    fn ty_to_snippet(&self, ty: Ty<'tcx>, expected_idx: ExpectedIdx) -> String {
3177        if ty.is_unit() {
3178            "()".to_string()
3179        } else if ty.is_suggestable(self.tcx, false) {
3180            format!("/* {ty} */")
3181        } else if let Some(fn_def_id) = self.fn_def_id
3182            && self.tcx.def_kind(fn_def_id).is_fn_like()
3183            && let self_implicit =
3184                matches!(self.call_expr.kind, hir::ExprKind::MethodCall(..)) as usize
3185            && let Some(Some(arg)) =
3186                self.tcx.fn_arg_idents(fn_def_id).get(expected_idx.as_usize() + self_implicit)
3187            && arg.name != kw::SelfLower
3188        {
3189            format!("/* {} */", arg.name)
3190        } else {
3191            "/* value */".to_string()
3192        }
3193    }
3194
3195    fn first_incompatible_error(&self) -> Option<(ProvidedIdx, TypeError<'tcx>)> {
3196        self.compatibility_diagonal.iter_enumerated().find_map(|(i, c)| {
3197            if let Compatibility::Incompatible(Some(terr)) = c { Some((i, *terr)) } else { None }
3198        })
3199    }
3200}
3201
3202enum SuggestionText {
3203    None,
3204    Provide(bool),
3205    Remove(bool),
3206    Swap,
3207    Reorder,
3208    DidYouMean,
3209}