rustc_hir_typeck/fn_ctxt/
checks.rs

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