Skip to main content

rustc_trait_selection/error_reporting/infer/
mod.rs

1//! Error Reporting Code for the inference engine
2//!
3//! Because of the way inference, and in particular region inference,
4//! works, it often happens that errors are not detected until far after
5//! the relevant line of code has been type-checked. Therefore, there is
6//! an elaborate system to track why a particular constraint in the
7//! inference graph arose so that we can explain to the user what gave
8//! rise to a particular error.
9//!
10//! The system is based around a set of "origin" types. An "origin" is the
11//! reason that a constraint or inference variable arose. There are
12//! different "origin" enums for different kinds of constraints/variables
13//! (e.g., `TypeOrigin`, `RegionVariableOrigin`). An origin always has
14//! a span, but also more information so that we can generate a meaningful
15//! error message.
16//!
17//! Having a catalog of all the different reasons an error can arise is
18//! also useful for other reasons, like cross-referencing FAQs etc, though
19//! we are not really taking advantage of this yet.
20//!
21//! # Region Inference
22//!
23//! Region inference is particularly tricky because it always succeeds "in
24//! the moment" and simply registers a constraint. Then, at the end, we
25//! can compute the full graph and report errors, so we need to be able to
26//! store and later report what gave rise to the conflicting constraints.
27//!
28//! # Subtype Trace
29//!
30//! Determining whether `T1 <: T2` often involves a number of subtypes and
31//! subconstraints along the way. A "TypeTrace" is an extended version
32//! of an origin that traces the types and other values that were being
33//! compared. It is not necessarily comprehensive (in fact, at the time of
34//! this writing it only tracks the root values being compared) but I'd
35//! like to extend it to include significant "waypoints". For example, if
36//! you are comparing `(T1, T2) <: (T3, T4)`, and the problem is that `T2
37//! <: T4` fails, I'd like the trace to include enough information to say
38//! "in the 2nd element of the tuple". Similarly, failures when comparing
39//! arguments or return types in fn types should be able to cite the
40//! specific position, etc.
41//!
42//! # Reality vs plan
43//!
44//! Of course, there is still a LOT of code in typeck that has yet to be
45//! ported to this system, and which relies on string concatenation at the
46//! time of error detection.
47
48use std::borrow::Cow;
49use std::ops::ControlFlow;
50use std::path::PathBuf;
51use std::{cmp, fmt, iter};
52
53use rustc_abi::ExternAbi;
54use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
55use rustc_errors::{Applicability, Diag, DiagStyledString, IntoDiagArg, StringPart, pluralize};
56use rustc_hir::def::DefKind;
57use rustc_hir::def_id::DefId;
58use rustc_hir::intravisit::Visitor;
59use rustc_hir::lang_items::LangItem;
60use rustc_hir::{self as hir};
61use rustc_infer::infer::DefineOpaqueTypes;
62use rustc_macros::extension;
63use rustc_middle::bug;
64use rustc_middle::dep_graph::DepContext;
65use rustc_middle::traits::PatternOriginExpr;
66use rustc_middle::ty::error::{ExpectedFound, TypeError, TypeErrorToStringExt};
67use rustc_middle::ty::print::{PrintTraitRefExt as _, WrapBinderMode, with_forced_trimmed_paths};
68use rustc_middle::ty::{
69    self, List, ParamEnv, Region, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable, TypeVisitable,
70    TypeVisitableExt,
71};
72use rustc_span::{BytePos, DUMMY_SP, DesugaringKind, Pos, Span, sym};
73use tracing::{debug, instrument};
74
75use crate::error_reporting::TypeErrCtxt;
76use crate::error_reporting::traits::ambiguity::{
77    CandidateSource, compute_applicable_impls_for_diagnostics,
78};
79use crate::errors::{ObligationCauseFailureCode, TypeErrorAdditionalDiags};
80use crate::infer;
81use crate::infer::relate::{self, RelateResult, TypeRelation};
82use crate::infer::{InferCtxt, InferCtxtExt as _, TypeTrace, ValuePairs};
83use crate::solve::deeply_normalize_for_diagnostics;
84use crate::traits::{
85    MatchExpressionArmCause, Obligation, ObligationCause, ObligationCauseCode, specialization_graph,
86};
87
88mod note_and_explain;
89mod suggest;
90
91pub mod need_type_info;
92pub mod nice_region_error;
93pub mod region;
94
95/// Makes a valid string literal from a string by escaping special characters (" and \),
96/// unless they are already escaped.
97fn escape_literal(s: &str) -> String {
98    let mut escaped = String::with_capacity(s.len());
99    let mut chrs = s.chars().peekable();
100    while let Some(first) = chrs.next() {
101        match (first, chrs.peek()) {
102            ('\\', Some(&delim @ '"') | Some(&delim @ '\'')) => {
103                escaped.push('\\');
104                escaped.push(delim);
105                chrs.next();
106            }
107            ('"' | '\'', _) => {
108                escaped.push('\\');
109                escaped.push(first)
110            }
111            (c, _) => escaped.push(c),
112        };
113    }
114    escaped
115}
116
117impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
118    // [Note-Type-error-reporting]
119    // An invariant is that anytime the expected or actual type is Error (the special
120    // error type, meaning that an error occurred when typechecking this expression),
121    // this is a derived error. The error cascaded from another error (that was already
122    // reported), so it's not useful to display it to the user.
123    // The following methods implement this logic.
124    // They check if either the actual or expected type is Error, and don't print the error
125    // in this case. The typechecker should only ever report type errors involving mismatched
126    // types using one of these methods, and should not call span_err directly for such
127    // errors.
128    pub fn type_error_struct_with_diag<M>(
129        &self,
130        sp: Span,
131        mk_diag: M,
132        actual_ty: Ty<'tcx>,
133    ) -> Diag<'a>
134    where
135        M: FnOnce(String) -> Diag<'a>,
136    {
137        let actual_ty = self.resolve_vars_if_possible(actual_ty);
138        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:138",
                        "rustc_trait_selection::error_reporting::infer",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(138u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("type_error_struct_with_diag({0:?}, {1:?})",
                                                    sp, actual_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
139
140        let mut err = mk_diag(self.ty_to_string(actual_ty));
141
142        // Don't report an error if actual type is `Error`.
143        if actual_ty.references_error() {
144            err.downgrade_to_delayed_bug();
145        }
146
147        err
148    }
149
150    pub fn report_mismatched_types(
151        &self,
152        cause: &ObligationCause<'tcx>,
153        param_env: ty::ParamEnv<'tcx>,
154        expected: Ty<'tcx>,
155        actual: Ty<'tcx>,
156        err: TypeError<'tcx>,
157    ) -> Diag<'a> {
158        let mut diag = self.report_and_explain_type_error(
159            TypeTrace::types(cause, expected, actual),
160            param_env,
161            err,
162        );
163
164        self.suggest_param_env_shadowing(&mut diag, expected, actual, param_env);
165
166        diag
167    }
168
169    pub fn report_mismatched_consts(
170        &self,
171        cause: &ObligationCause<'tcx>,
172        param_env: ty::ParamEnv<'tcx>,
173        expected: ty::Const<'tcx>,
174        actual: ty::Const<'tcx>,
175        err: TypeError<'tcx>,
176    ) -> Diag<'a> {
177        self.report_and_explain_type_error(
178            TypeTrace::consts(cause, expected, actual),
179            param_env,
180            err,
181        )
182    }
183
184    pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
185        let (def_id, args) = match *ty.kind() {
186            ty::Alias(_, ty::AliasTy { def_id, args, .. })
187                if self.tcx.def_kind(def_id) == DefKind::OpaqueTy =>
188            {
189                (def_id, args)
190            }
191            ty::Alias(_, ty::AliasTy { def_id, args, .. })
192                if self.tcx.is_impl_trait_in_trait(def_id) =>
193            {
194                (def_id, args)
195            }
196            _ => return None,
197        };
198
199        let future_trait = self.tcx.require_lang_item(LangItem::Future, DUMMY_SP);
200        let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
201
202        self.tcx
203            .explicit_item_self_bounds(def_id)
204            .iter_instantiated_copied(self.tcx, args)
205            .find_map(|(predicate, _)| {
206                predicate
207                    .kind()
208                    .map_bound(|kind| match kind {
209                        ty::ClauseKind::Projection(projection_predicate)
210                            if projection_predicate.projection_term.def_id == item_def_id =>
211                        {
212                            projection_predicate.term.as_type()
213                        }
214                        _ => None,
215                    })
216                    .no_bound_vars()
217                    .flatten()
218            })
219    }
220
221    /// Adds a note if the types come from similarly named crates
222    fn check_and_note_conflicting_crates(&self, err: &mut Diag<'_>, terr: TypeError<'tcx>) -> bool {
223        match terr {
224            TypeError::Sorts(ref exp_found) => {
225                // if they are both "path types", there's a chance of ambiguity
226                // due to different versions of the same crate
227                if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
228                    (exp_found.expected.kind(), exp_found.found.kind())
229                {
230                    return self.check_same_definition_different_crate(
231                        err,
232                        exp_adt.did(),
233                        [found_adt.did()].into_iter(),
234                        |did| <[_]>::into_vec(::alloc::boxed::box_new([self.tcx.def_span(did)]))vec![self.tcx.def_span(did)],
235                        "type",
236                    );
237                }
238            }
239            TypeError::Traits(ref exp_found) => {
240                return self.check_same_definition_different_crate(
241                    err,
242                    exp_found.expected,
243                    [exp_found.found].into_iter(),
244                    |did| <[_]>::into_vec(::alloc::boxed::box_new([self.tcx.def_span(did)]))vec![self.tcx.def_span(did)],
245                    "trait",
246                );
247            }
248            _ => (), // FIXME(#22750) handle traits and stuff
249        }
250        false
251    }
252
253    fn suggest_param_env_shadowing(
254        &self,
255        diag: &mut Diag<'_>,
256        expected: Ty<'tcx>,
257        found: Ty<'tcx>,
258        param_env: ty::ParamEnv<'tcx>,
259    ) {
260        let (alias, concrete) = match (expected.kind(), found.kind()) {
261            (ty::Alias(ty::Projection, proj), _) => (proj, found),
262            (_, ty::Alias(ty::Projection, proj)) => (proj, expected),
263            _ => return,
264        };
265
266        let tcx = self.tcx;
267
268        let trait_ref = alias.trait_ref(tcx);
269        let obligation =
270            Obligation::new(tcx, ObligationCause::dummy(), param_env, ty::Binder::dummy(trait_ref));
271
272        let applicable_impls = compute_applicable_impls_for_diagnostics(self.infcx, &obligation);
273
274        for candidate in applicable_impls {
275            let impl_def_id = match candidate {
276                CandidateSource::DefId(did) => did,
277                CandidateSource::ParamEnv(_) => continue,
278            };
279
280            let is_shadowed = self.infcx.probe(|_| {
281                let impl_substs = self.infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
282                let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).instantiate(tcx, impl_substs);
283
284                let expected_trait_ref = alias.trait_ref(tcx);
285
286                if let Err(_) = self.infcx.at(&ObligationCause::dummy(), param_env).eq(
287                    DefineOpaqueTypes::No,
288                    expected_trait_ref,
289                    impl_trait_ref,
290                ) {
291                    return false;
292                }
293
294                let leaf_def = match specialization_graph::assoc_def(tcx, impl_def_id, alias.def_id)
295                {
296                    Ok(leaf) => leaf,
297                    Err(_) => return false,
298                };
299
300                let trait_def_id = alias.trait_def_id(tcx);
301                let rebased_args = alias.args.rebase_onto(tcx, trait_def_id, impl_substs);
302
303                let impl_item_def_id = leaf_def.item.def_id;
304                let impl_assoc_ty = tcx.type_of(impl_item_def_id).instantiate(tcx, rebased_args);
305
306                self.infcx.can_eq(param_env, impl_assoc_ty, concrete)
307            });
308
309            if is_shadowed {
310                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the associated type `{0}` is defined as `{1}` in the implementation, but the where-bound `{2}` shadows this definition\nsee issue #152409 <https://github.com/rust-lang/rust/issues/152409> for more information",
                self.ty_to_string(tcx.mk_ty_from_kind(ty::Alias(ty::Projection,
                            *alias))), self.ty_to_string(concrete),
                self.ty_to_string(alias.self_ty())))
    })format!(
311                    "the associated type `{}` is defined as `{}` in the implementation, \
312                    but the where-bound `{}` shadows this definition\n\
313                    see issue #152409 <https://github.com/rust-lang/rust/issues/152409> for more information",
314                    self.ty_to_string(tcx.mk_ty_from_kind(ty::Alias(ty::Projection, *alias))),
315                    self.ty_to_string(concrete),
316                    self.ty_to_string(alias.self_ty())
317                ));
318                return;
319            }
320        }
321    }
322
323    fn note_error_origin(
324        &self,
325        err: &mut Diag<'_>,
326        cause: &ObligationCause<'tcx>,
327        exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
328        terr: TypeError<'tcx>,
329        param_env: Option<ParamEnv<'tcx>>,
330    ) {
331        match *cause.code() {
332            ObligationCauseCode::Pattern {
333                origin_expr: Some(origin_expr),
334                span: Some(span),
335                root_ty,
336            } => {
337                let expected_ty = self.resolve_vars_if_possible(root_ty);
338                if !#[allow(non_exhaustive_omitted_patterns)] match expected_ty.kind() {
    ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)) => true,
    _ => false,
}matches!(
339                    expected_ty.kind(),
340                    ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_))
341                ) {
342                    // don't show type `_`
343                    if span.desugaring_kind() == Some(DesugaringKind::ForLoop)
344                        && let ty::Adt(def, args) = expected_ty.kind()
345                        && Some(def.did()) == self.tcx.get_diagnostic_item(sym::Option)
346                    {
347                        err.span_label(
348                            span,
349                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this is an iterator with items of type `{0}`",
                args.type_at(0)))
    })format!("this is an iterator with items of type `{}`", args.type_at(0)),
350                        );
351                    } else if !span.overlaps(cause.span) {
352                        let expected_ty = self.tcx.short_string(expected_ty, err.long_ty_path());
353                        err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this expression has type `{0}`",
                expected_ty))
    })format!("this expression has type `{expected_ty}`"));
354                    }
355                }
356                if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
357                    && let Ok(mut peeled_snippet) =
358                        self.tcx.sess.source_map().span_to_snippet(origin_expr.peeled_span)
359                {
360                    // Parentheses are needed for cases like as casts.
361                    // We use the peeled_span for deref suggestions.
362                    // It's also safe to use for box, since box only triggers if there
363                    // wasn't a reference to begin with.
364                    if origin_expr.peeled_prefix_suggestion_parentheses {
365                        peeled_snippet = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})", peeled_snippet))
    })format!("({peeled_snippet})");
366                    }
367
368                    // Try giving a box suggestion first, as it is a special case of the
369                    // deref suggestion.
370                    if expected_ty.boxed_ty() == Some(found) {
371                        err.span_suggestion_verbose(
372                            span,
373                            "consider dereferencing the boxed value",
374                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("*{0}", peeled_snippet))
    })format!("*{peeled_snippet}"),
375                            Applicability::MachineApplicable,
376                        );
377                    } else if let Some(param_env) = param_env
378                        && let Some(prefix) = self.should_deref_suggestion_on_mismatch(
379                            param_env,
380                            found,
381                            expected_ty,
382                            origin_expr,
383                        )
384                    {
385                        err.span_suggestion_verbose(
386                            span,
387                            "consider dereferencing to access the inner value using the Deref trait",
388                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", prefix, peeled_snippet))
    })format!("{prefix}{peeled_snippet}"),
389                            Applicability::MaybeIncorrect,
390                        );
391                    }
392                }
393            }
394            ObligationCauseCode::Pattern { origin_expr: None, span: Some(span), .. } => {
395                err.span_label(span, "expected due to this");
396            }
397            ObligationCauseCode::BlockTailExpression(
398                _,
399                hir::MatchSource::TryDesugar(scrut_hir_id),
400            ) => {
401                if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
402                    let scrut_expr = self.tcx.hir_expect_expr(scrut_hir_id);
403                    let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
404                        let arg_expr = args.first().expect("try desugaring call w/out arg");
405                        self.typeck_results
406                            .as_ref()
407                            .and_then(|typeck_results| typeck_results.expr_ty_opt(arg_expr))
408                    } else {
409                        ::rustc_middle::util::bug::bug_fmt(format_args!("try desugaring w/out call expr as scrutinee"));bug!("try desugaring w/out call expr as scrutinee");
410                    };
411
412                    match scrut_ty {
413                        Some(ty) if expected == ty => {
414                            let source_map = self.tcx.sess.source_map();
415                            err.span_suggestion(
416                                source_map.end_point(cause.span),
417                                "try removing this `?`",
418                                "",
419                                Applicability::MachineApplicable,
420                            );
421                        }
422                        _ => {}
423                    }
424                }
425            }
426            ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
427                arm_block_id,
428                arm_span,
429                arm_ty,
430                prior_arm_block_id,
431                prior_arm_span,
432                prior_arm_ty,
433                source,
434                ref prior_non_diverging_arms,
435                scrut_span,
436                expr_span,
437                ..
438            }) => match source {
439                hir::MatchSource::TryDesugar(scrut_hir_id) => {
440                    if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
441                        let scrut_expr = self.tcx.hir_expect_expr(scrut_hir_id);
442                        let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
443                            let arg_expr = args.first().expect("try desugaring call w/out arg");
444                            self.typeck_results
445                                .as_ref()
446                                .and_then(|typeck_results| typeck_results.expr_ty_opt(arg_expr))
447                        } else {
448                            ::rustc_middle::util::bug::bug_fmt(format_args!("try desugaring w/out call expr as scrutinee"));bug!("try desugaring w/out call expr as scrutinee");
449                        };
450
451                        match scrut_ty {
452                            Some(ty) if expected == ty => {
453                                let source_map = self.tcx.sess.source_map();
454                                err.span_suggestion(
455                                    source_map.end_point(cause.span),
456                                    "try removing this `?`",
457                                    "",
458                                    Applicability::MachineApplicable,
459                                );
460                            }
461                            _ => {}
462                        }
463                    }
464                }
465                _ => {
466                    // `prior_arm_ty` can be `!`, `expected` will have better info when present.
467                    let t = self.resolve_vars_if_possible(match exp_found {
468                        Some(ty::error::ExpectedFound { expected, .. }) => expected,
469                        _ => prior_arm_ty,
470                    });
471                    let source_map = self.tcx.sess.source_map();
472                    let mut any_multiline_arm = source_map.is_multiline(arm_span);
473                    if prior_non_diverging_arms.len() <= 4 {
474                        for sp in prior_non_diverging_arms {
475                            any_multiline_arm |= source_map.is_multiline(*sp);
476                            err.span_label(*sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this is found to be of type `{0}`",
                t))
    })format!("this is found to be of type `{t}`"));
477                        }
478                    } else if let Some(sp) = prior_non_diverging_arms.last() {
479                        any_multiline_arm |= source_map.is_multiline(*sp);
480                        err.span_label(
481                            *sp,
482                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this and all prior arms are found to be of type `{0}`",
                t))
    })format!("this and all prior arms are found to be of type `{t}`"),
483                        );
484                    }
485                    let outer = if any_multiline_arm || !source_map.is_multiline(expr_span) {
486                        // Cover just `match` and the scrutinee expression, not
487                        // the entire match body, to reduce diagram noise.
488                        expr_span.shrink_to_lo().to(scrut_span)
489                    } else {
490                        expr_span
491                    };
492                    let msg = "`match` arms have incompatible types";
493                    err.span_label(outer, msg);
494                    if let Some(subdiag) = self.suggest_remove_semi_or_return_binding(
495                        prior_arm_block_id,
496                        prior_arm_ty,
497                        prior_arm_span,
498                        arm_block_id,
499                        arm_ty,
500                        arm_span,
501                    ) {
502                        err.subdiagnostic(subdiag);
503                    }
504                }
505            },
506            ObligationCauseCode::IfExpression { expr_id, .. } => {
507                let hir::Node::Expr(&hir::Expr {
508                    kind: hir::ExprKind::If(cond_expr, then_expr, Some(else_expr)),
509                    span: expr_span,
510                    ..
511                }) = self.tcx.hir_node(expr_id)
512                else {
513                    return;
514                };
515                let then_span = self.find_block_span_from_hir_id(then_expr.hir_id);
516                let then_ty = self
517                    .typeck_results
518                    .as_ref()
519                    .expect("if expression only expected inside FnCtxt")
520                    .expr_ty(then_expr);
521                let else_span = self.find_block_span_from_hir_id(else_expr.hir_id);
522                let else_ty = self
523                    .typeck_results
524                    .as_ref()
525                    .expect("if expression only expected inside FnCtxt")
526                    .expr_ty(else_expr);
527                if let hir::ExprKind::If(_cond, _then, None) = else_expr.kind
528                    && else_ty.is_unit()
529                {
530                    // Account for `let x = if a { 1 } else if b { 2 };`
531                    err.note("`if` expressions without `else` evaluate to `()`");
532                    err.note("consider adding an `else` block that evaluates to the expected type");
533                }
534                err.span_label(then_span, "expected because of this");
535
536                let outer_span = if self.tcx.sess.source_map().is_multiline(expr_span) {
537                    if then_span.hi() == expr_span.hi() || else_span.hi() == expr_span.hi() {
538                        // Point at condition only if either block has the same end point as
539                        // the whole expression, since that'll cause awkward overlapping spans.
540                        Some(expr_span.shrink_to_lo().to(cond_expr.peel_drop_temps().span))
541                    } else {
542                        Some(expr_span)
543                    }
544                } else {
545                    None
546                };
547                if let Some(sp) = outer_span {
548                    err.span_label(sp, "`if` and `else` have incompatible types");
549                }
550
551                let then_id = if let hir::ExprKind::Block(then_blk, _) = then_expr.kind {
552                    then_blk.hir_id
553                } else {
554                    then_expr.hir_id
555                };
556                let else_id = if let hir::ExprKind::Block(else_blk, _) = else_expr.kind {
557                    else_blk.hir_id
558                } else {
559                    else_expr.hir_id
560                };
561                if let Some(subdiag) = self.suggest_remove_semi_or_return_binding(
562                    Some(then_id),
563                    then_ty,
564                    then_span,
565                    Some(else_id),
566                    else_ty,
567                    else_span,
568                ) {
569                    err.subdiagnostic(subdiag);
570                }
571            }
572            ObligationCauseCode::LetElse => {
573                err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
574                err.help("...or use `match` instead of `let...else`");
575            }
576            _ => {
577                if let ObligationCauseCode::WhereClause(_, span)
578                | ObligationCauseCode::WhereClauseInExpr(_, span, ..) =
579                    cause.code().peel_derives()
580                    && !span.is_dummy()
581                    && let TypeError::RegionsPlaceholderMismatch = terr
582                {
583                    err.span_note(*span, "the lifetime requirement is introduced here");
584                }
585            }
586        }
587    }
588
589    /// Determines whether deref_to == <deref_from as Deref>::Target, and if so,
590    /// returns a prefix that should be added to deref_from as a suggestion.
591    fn should_deref_suggestion_on_mismatch(
592        &self,
593        param_env: ParamEnv<'tcx>,
594        deref_to: Ty<'tcx>,
595        deref_from: Ty<'tcx>,
596        origin_expr: PatternOriginExpr,
597    ) -> Option<String> {
598        // origin_expr contains stripped away versions of our expression.
599        // We'll want to use that to avoid suggesting things like *&x.
600        // However, the type that we have access to hasn't been stripped away,
601        // so we need to ignore the first n dereferences, where n is the number
602        // that's been stripped away in origin_expr.
603
604        // Find a way to autoderef from deref_from to deref_to.
605        let Some((num_derefs, (after_deref_ty, _))) = (self.autoderef_steps)(deref_from)
606            .into_iter()
607            .enumerate()
608            .find(|(_, (ty, _))| self.infcx.can_eq(param_env, *ty, deref_to))
609        else {
610            return None;
611        };
612
613        if num_derefs <= origin_expr.peeled_count {
614            return None;
615        }
616
617        let deref_part = "*".repeat(num_derefs - origin_expr.peeled_count);
618
619        // If the user used a reference in the original expression, they probably
620        // want the suggestion to still give a reference.
621        if deref_from.is_ref() && !after_deref_ty.is_ref() {
622            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", deref_part))
    })format!("&{deref_part}"))
623        } else {
624            Some(deref_part)
625        }
626    }
627
628    /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
629    /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
630    /// populate `other_value` with `other_ty`.
631    ///
632    /// ```text
633    /// Foo<Bar<Qux>>
634    /// ^^^^--------^ this is highlighted
635    /// |   |
636    /// |   this type argument is exactly the same as the other type, not highlighted
637    /// this is highlighted
638    /// Bar<Qux>
639    /// -------- this type is the same as a type argument in the other type, not highlighted
640    /// ```
641    fn highlight_outer(
642        &self,
643        value: &mut DiagStyledString,
644        other_value: &mut DiagStyledString,
645        name: String,
646        args: &[ty::GenericArg<'tcx>],
647        pos: usize,
648        other_ty: Ty<'tcx>,
649    ) {
650        // `value` and `other_value` hold two incomplete type representation for display.
651        // `name` is the path of both types being compared. `sub`
652        value.push_highlighted(name);
653
654        if args.is_empty() {
655            return;
656        }
657        value.push_highlighted("<");
658
659        for (i, arg) in args.iter().enumerate() {
660            if i > 0 {
661                value.push_normal(", ");
662            }
663
664            match arg.kind() {
665                ty::GenericArgKind::Lifetime(lt) => {
666                    let s = lt.to_string();
667                    value.push_normal(if s.is_empty() { "'_" } else { &s });
668                }
669                ty::GenericArgKind::Const(ct) => {
670                    value.push_normal(ct.to_string());
671                }
672                // Highlight all the type arguments that aren't at `pos` and compare
673                // the type argument at `pos` and `other_ty`.
674                ty::GenericArgKind::Type(type_arg) => {
675                    if i == pos {
676                        let values = self.cmp(type_arg, other_ty);
677                        value.0.extend((values.0).0);
678                        other_value.0.extend((values.1).0);
679                    } else {
680                        value.push_highlighted(type_arg.to_string());
681                    }
682                }
683            }
684        }
685
686        value.push_highlighted(">");
687    }
688
689    /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
690    /// as that is the difference to the other type.
691    ///
692    /// For the following code:
693    ///
694    /// ```ignore (illustrative)
695    /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
696    /// ```
697    ///
698    /// The type error output will behave in the following way:
699    ///
700    /// ```text
701    /// Foo<Bar<Qux>>
702    /// ^^^^--------^ this is highlighted
703    /// |   |
704    /// |   this type argument is exactly the same as the other type, not highlighted
705    /// this is highlighted
706    /// Bar<Qux>
707    /// -------- this type is the same as a type argument in the other type, not highlighted
708    /// ```
709    fn cmp_type_arg(
710        &self,
711        t1_out: &mut DiagStyledString,
712        t2_out: &mut DiagStyledString,
713        path: String,
714        args: &'tcx [ty::GenericArg<'tcx>],
715        other_path: String,
716        other_ty: Ty<'tcx>,
717    ) -> bool {
718        for (i, arg) in args.iter().enumerate() {
719            if let Some(ta) = arg.as_type() {
720                if ta == other_ty {
721                    self.highlight_outer(t1_out, t2_out, path, args, i, other_ty);
722                    return true;
723                }
724                if let ty::Adt(def, _) = ta.kind() {
725                    let path_ = self.tcx.def_path_str(def.did());
726                    if path_ == other_path {
727                        self.highlight_outer(t1_out, t2_out, path, args, i, other_ty);
728                        return true;
729                    }
730                }
731            }
732        }
733        false
734    }
735
736    /// Adds a `,` to the type representation only if it is appropriate.
737    fn push_comma(
738        &self,
739        value: &mut DiagStyledString,
740        other_value: &mut DiagStyledString,
741        pos: usize,
742    ) {
743        if pos > 0 {
744            value.push_normal(", ");
745            other_value.push_normal(", ");
746        }
747    }
748
749    /// Given two `fn` signatures highlight only sub-parts that are different.
750    fn cmp_fn_sig(
751        &self,
752        sig1: &ty::PolyFnSig<'tcx>,
753        fn_def1: Option<(DefId, Option<&'tcx [ty::GenericArg<'tcx>]>)>,
754        sig2: &ty::PolyFnSig<'tcx>,
755        fn_def2: Option<(DefId, Option<&'tcx [ty::GenericArg<'tcx>]>)>,
756    ) -> (DiagStyledString, DiagStyledString) {
757        let sig1 = &(self.normalize_fn_sig)(*sig1);
758        let sig2 = &(self.normalize_fn_sig)(*sig2);
759
760        let get_lifetimes = |sig| {
761            use rustc_hir::def::Namespace;
762            let (sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS)
763                .name_all_regions(sig, WrapBinderMode::ForAll)
764                .unwrap();
765            let lts: Vec<String> =
766                reg.into_items().map(|(_, kind)| kind.to_string()).into_sorted_stable_ord();
767            (if lts.is_empty() { String::new() } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("for<{0}> ", lts.join(", ")))
    })format!("for<{}> ", lts.join(", ")) }, sig)
768        };
769
770        let (lt1, sig1) = get_lifetimes(sig1);
771        let (lt2, sig2) = get_lifetimes(sig2);
772
773        // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
774        let mut values =
775            (DiagStyledString::normal("".to_string()), DiagStyledString::normal("".to_string()));
776
777        // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
778        // ^^^^^^
779        let safety = |fn_def, sig: ty::FnSig<'_>| match fn_def {
780            None => sig.safety.prefix_str(),
781            Some((did, _)) => {
782                if self.tcx.codegen_fn_attrs(did).safe_target_features {
783                    "#[target_features] "
784                } else {
785                    sig.safety.prefix_str()
786                }
787            }
788        };
789        let safety1 = safety(fn_def1, sig1);
790        let safety2 = safety(fn_def2, sig2);
791        values.0.push(safety1, safety1 != safety2);
792        values.1.push(safety2, safety1 != safety2);
793
794        // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
795        //        ^^^^^^^^^^
796        if sig1.abi != ExternAbi::Rust {
797            values.0.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("extern {0} ", sig1.abi))
    })format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
798        }
799        if sig2.abi != ExternAbi::Rust {
800            values.1.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("extern {0} ", sig2.abi))
    })format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
801        }
802
803        // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
804        //                   ^^^^^^^^
805        let lifetime_diff = lt1 != lt2;
806        values.0.push(lt1, lifetime_diff);
807        values.1.push(lt2, lifetime_diff);
808
809        // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
810        //                           ^^^
811        values.0.push_normal("fn(");
812        values.1.push_normal("fn(");
813
814        // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
815        //                              ^^^^^
816        let len1 = sig1.inputs().len();
817        let len2 = sig2.inputs().len();
818        if len1 == len2 {
819            for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
820                self.push_comma(&mut values.0, &mut values.1, i);
821                let (x1, x2) = self.cmp(*l, *r);
822                (values.0).0.extend(x1.0);
823                (values.1).0.extend(x2.0);
824            }
825        } else {
826            for (i, l) in sig1.inputs().iter().enumerate() {
827                values.0.push_highlighted(l.to_string());
828                if i != len1 - 1 {
829                    values.0.push_highlighted(", ");
830                }
831            }
832            for (i, r) in sig2.inputs().iter().enumerate() {
833                values.1.push_highlighted(r.to_string());
834                if i != len2 - 1 {
835                    values.1.push_highlighted(", ");
836                }
837            }
838        }
839
840        if sig1.c_variadic {
841            if len1 > 0 {
842                values.0.push_normal(", ");
843            }
844            values.0.push("...", !sig2.c_variadic);
845        }
846        if sig2.c_variadic {
847            if len2 > 0 {
848                values.1.push_normal(", ");
849            }
850            values.1.push("...", !sig1.c_variadic);
851        }
852
853        // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
854        //                                   ^
855        values.0.push_normal(")");
856        values.1.push_normal(")");
857
858        // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
859        //                                     ^^^^^^^^
860        let output1 = sig1.output();
861        let output2 = sig2.output();
862        let (x1, x2) = self.cmp(output1, output2);
863        let output_diff = x1 != x2;
864        if !output1.is_unit() || output_diff {
865            values.0.push_normal(" -> ");
866            (values.0).0.extend(x1.0);
867        }
868        if !output2.is_unit() || output_diff {
869            values.1.push_normal(" -> ");
870            (values.1).0.extend(x2.0);
871        }
872
873        let fmt = |did, args| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {{{0}}}",
                self.tcx.def_path_str_with_args(did, args)))
    })format!(" {{{}}}", self.tcx.def_path_str_with_args(did, args));
874
875        match (fn_def1, fn_def2) {
876            (Some((fn_def1, Some(fn_args1))), Some((fn_def2, Some(fn_args2)))) => {
877                let path1 = fmt(fn_def1, fn_args1);
878                let path2 = fmt(fn_def2, fn_args2);
879                let same_path = path1 == path2;
880                values.0.push(path1, !same_path);
881                values.1.push(path2, !same_path);
882            }
883            (Some((fn_def1, Some(fn_args1))), None) => {
884                values.0.push_highlighted(fmt(fn_def1, fn_args1));
885            }
886            (None, Some((fn_def2, Some(fn_args2)))) => {
887                values.1.push_highlighted(fmt(fn_def2, fn_args2));
888            }
889            _ => {}
890        }
891
892        values
893    }
894
895    pub fn cmp_traits(
896        &self,
897        def_id1: DefId,
898        args1: &[ty::GenericArg<'tcx>],
899        def_id2: DefId,
900        args2: &[ty::GenericArg<'tcx>],
901    ) -> (DiagStyledString, DiagStyledString) {
902        let mut values = (DiagStyledString::new(), DiagStyledString::new());
903
904        if def_id1 != def_id2 {
905            values.0.push_highlighted(self.tcx.def_path_str(def_id1).as_str());
906            values.1.push_highlighted(self.tcx.def_path_str(def_id2).as_str());
907        } else {
908            values.0.push_normal(self.tcx.item_name(def_id1).as_str());
909            values.1.push_normal(self.tcx.item_name(def_id2).as_str());
910        }
911
912        if args1.len() != args2.len() {
913            let (pre, post) = if args1.len() > 0 { ("<", ">") } else { ("", "") };
914            values.0.push_normal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}{0}{2}",
                args1.iter().map(|a|
                                a.to_string()).collect::<Vec<_>>().join(", "), pre, post))
    })format!(
915                "{pre}{}{post}",
916                args1.iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ")
917            ));
918            let (pre, post) = if args2.len() > 0 { ("<", ">") } else { ("", "") };
919            values.1.push_normal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}{0}{2}",
                args2.iter().map(|a|
                                a.to_string()).collect::<Vec<_>>().join(", "), pre, post))
    })format!(
920                "{pre}{}{post}",
921                args2.iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ")
922            ));
923            return values;
924        }
925
926        if args1.len() > 0 {
927            values.0.push_normal("<");
928            values.1.push_normal("<");
929        }
930        for (i, (a, b)) in std::iter::zip(args1, args2).enumerate() {
931            let a_str = a.to_string();
932            let b_str = b.to_string();
933            if let (Some(a), Some(b)) = (a.as_type(), b.as_type()) {
934                let (a, b) = self.cmp(a, b);
935                values.0.0.extend(a.0);
936                values.1.0.extend(b.0);
937            } else if a_str != b_str {
938                values.0.push_highlighted(a_str);
939                values.1.push_highlighted(b_str);
940            } else {
941                values.0.push_normal(a_str);
942                values.1.push_normal(b_str);
943            }
944            if i + 1 < args1.len() {
945                values.0.push_normal(", ");
946                values.1.push_normal(", ");
947            }
948        }
949        if args1.len() > 0 {
950            values.0.push_normal(">");
951            values.1.push_normal(">");
952        }
953        values
954    }
955
956    /// Compares two given types, eliding parts that are the same between them and highlighting
957    /// relevant differences, and return two representation of those types for highlighted printing.
958    pub fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagStyledString, DiagStyledString) {
959        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:959",
                        "rustc_trait_selection::error_reporting::infer",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(959u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("cmp(t1={0}, t1.kind={1:?}, t2={2}, t2.kind={3:?})",
                                                    t1, t1.kind(), t2, t2.kind()) as &dyn Value))])
            });
    } else { ; }
};debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
960
961        // helper functions
962        let recurse = |t1, t2, values: &mut (DiagStyledString, DiagStyledString)| {
963            let (x1, x2) = self.cmp(t1, t2);
964            (values.0).0.extend(x1.0);
965            (values.1).0.extend(x2.0);
966        };
967
968        fn fmt_region<'tcx>(region: ty::Region<'tcx>) -> String {
969            let mut r = region.to_string();
970            if r == "'_" {
971                r.clear();
972            } else {
973                r.push(' ');
974            }
975            ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", r)) })format!("&{r}")
976        }
977
978        fn push_ref<'tcx>(
979            region: ty::Region<'tcx>,
980            mutbl: hir::Mutability,
981            s: &mut DiagStyledString,
982        ) {
983            s.push_highlighted(fmt_region(region));
984            s.push_highlighted(mutbl.prefix_str());
985        }
986
987        fn maybe_highlight<T: Eq + ToString>(
988            t1: T,
989            t2: T,
990            (buf1, buf2): &mut (DiagStyledString, DiagStyledString),
991            tcx: TyCtxt<'_>,
992        ) {
993            let highlight = t1 != t2;
994            let (t1, t2) = if highlight || tcx.sess.opts.verbose {
995                (t1.to_string(), t2.to_string())
996            } else {
997                // The two types are the same, elide and don't highlight.
998                ("_".into(), "_".into())
999            };
1000            buf1.push(t1, highlight);
1001            buf2.push(t2, highlight);
1002        }
1003
1004        fn cmp_ty_refs<'tcx>(
1005            r1: ty::Region<'tcx>,
1006            mut1: hir::Mutability,
1007            r2: ty::Region<'tcx>,
1008            mut2: hir::Mutability,
1009            ss: &mut (DiagStyledString, DiagStyledString),
1010        ) {
1011            let (r1, r2) = (fmt_region(r1), fmt_region(r2));
1012            if r1 != r2 {
1013                ss.0.push_highlighted(r1);
1014                ss.1.push_highlighted(r2);
1015            } else {
1016                ss.0.push_normal(r1);
1017                ss.1.push_normal(r2);
1018            }
1019
1020            if mut1 != mut2 {
1021                ss.0.push_highlighted(mut1.prefix_str());
1022                ss.1.push_highlighted(mut2.prefix_str());
1023            } else {
1024                ss.0.push_normal(mut1.prefix_str());
1025                ss.1.push_normal(mut2.prefix_str());
1026            }
1027        }
1028
1029        // process starts here
1030        match (t1.kind(), t2.kind()) {
1031            (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1032                let did1 = def1.did();
1033                let did2 = def2.did();
1034
1035                let generics1 = self.tcx.generics_of(did1);
1036                let generics2 = self.tcx.generics_of(did2);
1037
1038                let non_default_after_default = generics1
1039                    .check_concrete_type_after_default(self.tcx, sub1)
1040                    || generics2.check_concrete_type_after_default(self.tcx, sub2);
1041                let sub_no_defaults_1 = if non_default_after_default {
1042                    generics1.own_args(sub1)
1043                } else {
1044                    generics1.own_args_no_defaults(self.tcx, sub1)
1045                };
1046                let sub_no_defaults_2 = if non_default_after_default {
1047                    generics2.own_args(sub2)
1048                } else {
1049                    generics2.own_args_no_defaults(self.tcx, sub2)
1050                };
1051                let mut values = (DiagStyledString::new(), DiagStyledString::new());
1052                let path1 = self.tcx.def_path_str(did1);
1053                let path2 = self.tcx.def_path_str(did2);
1054                if did1 == did2 {
1055                    // Easy case. Replace same types with `_` to shorten the output and highlight
1056                    // the differing ones.
1057                    //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1058                    //     Foo<Bar, _>
1059                    //     Foo<Quz, _>
1060                    //         ---  ^ type argument elided
1061                    //         |
1062                    //         highlighted in output
1063                    values.0.push_normal(path1);
1064                    values.1.push_normal(path2);
1065
1066                    // Avoid printing out default generic parameters that are common to both
1067                    // types.
1068                    let len1 = sub_no_defaults_1.len();
1069                    let len2 = sub_no_defaults_2.len();
1070                    let common_len = cmp::min(len1, len2);
1071                    let remainder1 = &sub1[common_len..];
1072                    let remainder2 = &sub2[common_len..];
1073                    let common_default_params =
1074                        iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1075                            .filter(|(a, b)| a == b)
1076                            .count();
1077                    let len = sub1.len() - common_default_params;
1078
1079                    // Only draw `<...>` if there are lifetime/type arguments.
1080                    if len > 0 {
1081                        values.0.push_normal("<");
1082                        values.1.push_normal("<");
1083                    }
1084
1085                    fn lifetime_display(lifetime: Region<'_>) -> String {
1086                        let s = lifetime.to_string();
1087                        if s.is_empty() { "'_".to_string() } else { s }
1088                    }
1089
1090                    for (i, (arg1, arg2)) in sub1.iter().zip(sub2).enumerate().take(len) {
1091                        self.push_comma(&mut values.0, &mut values.1, i);
1092                        match arg1.kind() {
1093                            // At one point we'd like to elide all lifetimes here, they are
1094                            // irrelevant for all diagnostics that use this output.
1095                            //
1096                            //     Foo<'x, '_, Bar>
1097                            //     Foo<'y, '_, Qux>
1098                            //         ^^  ^^  --- type arguments are not elided
1099                            //         |   |
1100                            //         |   elided as they were the same
1101                            //         not elided, they were different, but irrelevant
1102                            //
1103                            // For bound lifetimes, keep the names of the lifetimes,
1104                            // even if they are the same so that it's clear what's happening
1105                            // if we have something like
1106                            //
1107                            // for<'r, 's> fn(Inv<'r>, Inv<'s>)
1108                            // for<'r> fn(Inv<'r>, Inv<'r>)
1109                            ty::GenericArgKind::Lifetime(l1) => {
1110                                let l1_str = lifetime_display(l1);
1111                                let l2 = arg2.expect_region();
1112                                let l2_str = lifetime_display(l2);
1113                                if l1 != l2 {
1114                                    values.0.push_highlighted(l1_str);
1115                                    values.1.push_highlighted(l2_str);
1116                                } else if l1.is_bound() || self.tcx.sess.opts.verbose {
1117                                    values.0.push_normal(l1_str);
1118                                    values.1.push_normal(l2_str);
1119                                } else {
1120                                    values.0.push_normal("'_");
1121                                    values.1.push_normal("'_");
1122                                }
1123                            }
1124                            ty::GenericArgKind::Type(ta1) => {
1125                                let ta2 = arg2.expect_ty();
1126                                if ta1 == ta2 && !self.tcx.sess.opts.verbose {
1127                                    values.0.push_normal("_");
1128                                    values.1.push_normal("_");
1129                                } else {
1130                                    recurse(ta1, ta2, &mut values);
1131                                }
1132                            }
1133                            // We're comparing two types with the same path, so we compare the type
1134                            // arguments for both. If they are the same, do not highlight and elide
1135                            // from the output.
1136                            //     Foo<_, Bar>
1137                            //     Foo<_, Qux>
1138                            //         ^ elided type as this type argument was the same in both sides
1139
1140                            // Do the same for const arguments, if they are equal, do not highlight and
1141                            // elide them from the output.
1142                            ty::GenericArgKind::Const(ca1) => {
1143                                let ca2 = arg2.expect_const();
1144                                maybe_highlight(ca1, ca2, &mut values, self.tcx);
1145                            }
1146                        }
1147                    }
1148
1149                    // Close the type argument bracket.
1150                    // Only draw `<...>` if there are arguments.
1151                    if len > 0 {
1152                        values.0.push_normal(">");
1153                        values.1.push_normal(">");
1154                    }
1155                    values
1156                } else {
1157                    // Check for case:
1158                    //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1159                    //     Foo<Bar<Qux>
1160                    //         ------- this type argument is exactly the same as the other type
1161                    //     Bar<Qux>
1162                    if self.cmp_type_arg(
1163                        &mut values.0,
1164                        &mut values.1,
1165                        path1.clone(),
1166                        sub_no_defaults_1,
1167                        path2.clone(),
1168                        t2,
1169                    ) {
1170                        return values;
1171                    }
1172                    // Check for case:
1173                    //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1174                    //     Bar<Qux>
1175                    //     Foo<Bar<Qux>>
1176                    //         ------- this type argument is exactly the same as the other type
1177                    if self.cmp_type_arg(
1178                        &mut values.1,
1179                        &mut values.0,
1180                        path2,
1181                        sub_no_defaults_2,
1182                        path1,
1183                        t1,
1184                    ) {
1185                        return values;
1186                    }
1187
1188                    // We can't find anything in common, highlight relevant part of type path.
1189                    //     let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1190                    //     foo::bar::Baz<Qux>
1191                    //     foo::bar::Bar<Zar>
1192                    //               -------- this part of the path is different
1193
1194                    let t1_str = t1.to_string();
1195                    let t2_str = t2.to_string();
1196                    let min_len = t1_str.len().min(t2_str.len());
1197
1198                    const SEPARATOR: &str = "::";
1199                    let separator_len = SEPARATOR.len();
1200                    let split_idx: usize =
1201                        iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1202                            .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1203                            .map(|(mod_str, _)| mod_str.len() + separator_len)
1204                            .sum();
1205
1206                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1206",
                        "rustc_trait_selection::error_reporting::infer",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1206u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "separator_len", "split_idx", "min_len"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("cmp")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&separator_len)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&split_idx)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&min_len) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?separator_len, ?split_idx, ?min_len, "cmp");
1207
1208                    if split_idx >= min_len {
1209                        // paths are identical, highlight everything
1210                        (
1211                            DiagStyledString::highlighted(t1_str),
1212                            DiagStyledString::highlighted(t2_str),
1213                        )
1214                    } else {
1215                        let (common, uniq1) = t1_str.split_at(split_idx);
1216                        let (_, uniq2) = t2_str.split_at(split_idx);
1217                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1217",
                        "rustc_trait_selection::error_reporting::infer",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1217u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                        ::tracing_core::field::FieldSet::new(&["message", "common",
                                        "uniq1", "uniq2"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("cmp")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&common) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&uniq1) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&uniq2) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?common, ?uniq1, ?uniq2, "cmp");
1218
1219                        values.0.push_normal(common);
1220                        values.0.push_highlighted(uniq1);
1221                        values.1.push_normal(common);
1222                        values.1.push_highlighted(uniq2);
1223
1224                        values
1225                    }
1226                }
1227            }
1228
1229            // When finding `&T != &T`, compare the references, then recurse into pointee type
1230            (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2)) => {
1231                let mut values = (DiagStyledString::new(), DiagStyledString::new());
1232                cmp_ty_refs(r1, mutbl1, r2, mutbl2, &mut values);
1233                recurse(ref_ty1, ref_ty2, &mut values);
1234                values
1235            }
1236            // When finding T != &T, highlight the borrow
1237            (&ty::Ref(r1, ref_ty1, mutbl1), _) => {
1238                let mut values = (DiagStyledString::new(), DiagStyledString::new());
1239                push_ref(r1, mutbl1, &mut values.0);
1240                recurse(ref_ty1, t2, &mut values);
1241                values
1242            }
1243            (_, &ty::Ref(r2, ref_ty2, mutbl2)) => {
1244                let mut values = (DiagStyledString::new(), DiagStyledString::new());
1245                push_ref(r2, mutbl2, &mut values.1);
1246                recurse(t1, ref_ty2, &mut values);
1247                values
1248            }
1249
1250            // When encountering tuples of the same size, highlight only the differing types
1251            (&ty::Tuple(args1), &ty::Tuple(args2)) if args1.len() == args2.len() => {
1252                let mut values = (DiagStyledString::normal("("), DiagStyledString::normal("("));
1253                let len = args1.len();
1254                for (i, (left, right)) in args1.iter().zip(args2).enumerate() {
1255                    self.push_comma(&mut values.0, &mut values.1, i);
1256                    recurse(left, right, &mut values);
1257                }
1258                if len == 1 {
1259                    // Keep the output for single element tuples as `(ty,)`.
1260                    values.0.push_normal(",");
1261                    values.1.push_normal(",");
1262                }
1263                values.0.push_normal(")");
1264                values.1.push_normal(")");
1265                values
1266            }
1267
1268            (ty::FnDef(did1, args1), ty::FnDef(did2, args2)) => {
1269                let sig1 = self.tcx.fn_sig(*did1).instantiate(self.tcx, args1);
1270                let sig2 = self.tcx.fn_sig(*did2).instantiate(self.tcx, args2);
1271                self.cmp_fn_sig(
1272                    &sig1,
1273                    Some((*did1, Some(args1))),
1274                    &sig2,
1275                    Some((*did2, Some(args2))),
1276                )
1277            }
1278
1279            (ty::FnDef(did1, args1), ty::FnPtr(sig_tys2, hdr2)) => {
1280                let sig1 = self.tcx.fn_sig(*did1).instantiate(self.tcx, args1);
1281                self.cmp_fn_sig(&sig1, Some((*did1, Some(args1))), &sig_tys2.with(*hdr2), None)
1282            }
1283
1284            (ty::FnPtr(sig_tys1, hdr1), ty::FnDef(did2, args2)) => {
1285                let sig2 = self.tcx.fn_sig(*did2).instantiate(self.tcx, args2);
1286                self.cmp_fn_sig(&sig_tys1.with(*hdr1), None, &sig2, Some((*did2, Some(args2))))
1287            }
1288
1289            (ty::FnPtr(sig_tys1, hdr1), ty::FnPtr(sig_tys2, hdr2)) => {
1290                self.cmp_fn_sig(&sig_tys1.with(*hdr1), None, &sig_tys2.with(*hdr2), None)
1291            }
1292
1293            _ => {
1294                let mut strs = (DiagStyledString::new(), DiagStyledString::new());
1295                maybe_highlight(t1, t2, &mut strs, self.tcx);
1296                strs
1297            }
1298        }
1299    }
1300
1301    /// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
1302    /// the return type of `async fn`s.
1303    ///
1304    /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
1305    ///
1306    /// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
1307    /// the message in `secondary_span` as the primary label, and apply the message that would
1308    /// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
1309    /// E0271, like `tests/ui/issues/issue-39970.stderr`.
1310    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("note_type_err",
                                    "rustc_trait_selection::error_reporting::infer",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1310u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                                    ::tracing_core::field::FieldSet::new(&["cause", "values",
                                                    "terr", "override_span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&values)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&terr)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&override_span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let span = override_span.unwrap_or(cause.span);
            if let TypeError::CyclicTy(_) = terr { values = None; }
            struct OpaqueTypesVisitor<'tcx> {
                types: FxIndexMap<TyCategory, FxIndexSet<Span>>,
                expected: FxIndexMap<TyCategory, FxIndexSet<Span>>,
                found: FxIndexMap<TyCategory, FxIndexSet<Span>>,
                ignore_span: Span,
                tcx: TyCtxt<'tcx>,
            }
            impl<'tcx> OpaqueTypesVisitor<'tcx> {
                fn visit_expected_found(tcx: TyCtxt<'tcx>,
                    expected: impl TypeVisitable<TyCtxt<'tcx>>,
                    found: impl TypeVisitable<TyCtxt<'tcx>>, ignore_span: Span)
                    -> Self {
                    let mut types_visitor =
                        OpaqueTypesVisitor {
                            types: Default::default(),
                            expected: Default::default(),
                            found: Default::default(),
                            ignore_span,
                            tcx,
                        };
                    expected.visit_with(&mut types_visitor);
                    std::mem::swap(&mut types_visitor.expected,
                        &mut types_visitor.types);
                    found.visit_with(&mut types_visitor);
                    std::mem::swap(&mut types_visitor.found,
                        &mut types_visitor.types);
                    types_visitor
                }
                fn report(&self, err: &mut Diag<'_>) {
                    self.add_labels_for_types(err, "expected", &self.expected);
                    self.add_labels_for_types(err, "found", &self.found);
                }
                fn add_labels_for_types(&self, err: &mut Diag<'_>,
                    target: &str,
                    types: &FxIndexMap<TyCategory, FxIndexSet<Span>>) {
                    for (kind, values) in types.iter() {
                        let count = values.len();
                        for &sp in values {
                            err.span_label(sp,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("{0}{1} {2:#}{3}",
                                                if count == 1 { "the " } else { "one of the " }, target,
                                                kind, if count == 1 { "" } else { "s" }))
                                    }));
                        }
                    }
                }
            }
            impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for
                OpaqueTypesVisitor<'tcx> {
                fn visit_ty(&mut self, t: Ty<'tcx>) {
                    if let Some((kind, def_id)) =
                            TyCategory::from_ty(self.tcx, t) {
                        let span = self.tcx.def_span(def_id);
                        if !self.ignore_span.overlaps(span) &&
                                !span.is_desugaring(DesugaringKind::Async) {
                            self.types.entry(kind).or_default().insert(span);
                        }
                    }
                    t.super_visit_with(self)
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1421",
                                    "rustc_trait_selection::error_reporting::infer",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1421u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("note_type_err(diag={0:?})",
                                                                diag) as &dyn Value))])
                        });
                } else { ; }
            };
            enum Mismatch<'a> {
                Variable(ty::error::ExpectedFound<Ty<'a>>),
                Fixed(&'static str),
            }
            let (expected_found, exp_found, is_simple_error, values,
                    param_env) =
                match values {
                    None => (None, Mismatch::Fixed("type"), false, None, None),
                    Some(ty::ParamEnvAnd { param_env, value: values }) => {
                        let mut values = self.resolve_vars_if_possible(values);
                        if self.next_trait_solver() {
                            values =
                                deeply_normalize_for_diagnostics(self, param_env, values);
                        }
                        let (is_simple_error, exp_found) =
                            match values {
                                ValuePairs::Terms(ExpectedFound { expected, found }) => {
                                    match (expected.kind(), found.kind()) {
                                        (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
                                            let is_simple_err =
                                                expected.is_simple_text() && found.is_simple_text();
                                            OpaqueTypesVisitor::visit_expected_found(self.tcx, expected,
                                                    found, span).report(diag);
                                            (is_simple_err,
                                                Mismatch::Variable(ExpectedFound { expected, found }))
                                        }
                                        (ty::TermKind::Const(_), ty::TermKind::Const(_)) => {
                                            (false, Mismatch::Fixed("constant"))
                                        }
                                        _ => (false, Mismatch::Fixed("type")),
                                    }
                                }
                                ValuePairs::PolySigs(ExpectedFound { expected, found }) => {
                                    OpaqueTypesVisitor::visit_expected_found(self.tcx, expected,
                                            found, span).report(diag);
                                    (false, Mismatch::Fixed("signature"))
                                }
                                ValuePairs::TraitRefs(_) =>
                                    (false, Mismatch::Fixed("trait")),
                                ValuePairs::Aliases(ExpectedFound { expected, .. }) => {
                                    (false,
                                        Mismatch::Fixed(self.tcx.def_descr(expected.def_id)))
                                }
                                ValuePairs::Regions(_) =>
                                    (false, Mismatch::Fixed("lifetime")),
                                ValuePairs::ExistentialTraitRef(_) => {
                                    (false, Mismatch::Fixed("existential trait ref"))
                                }
                                ValuePairs::ExistentialProjection(_) => {
                                    (false, Mismatch::Fixed("existential projection"))
                                }
                            };
                        let Some(vals) =
                            self.values_str(values, cause,
                                diag.long_ty_path()) else {
                                diag.downgrade_to_delayed_bug();
                                return;
                            };
                        (Some(vals), exp_found, is_simple_error, Some(values),
                            Some(param_env))
                    }
                };
            let mut label_or_note =
                |span: Span, msg: Cow<'static, str>|
                    {
                        if (prefer_label && is_simple_error) ||
                                &[span] == diag.span.primary_spans() {
                            diag.span_label(span, msg);
                        } else { diag.span_note(span, msg); }
                    };
            if let Some((secondary_span, secondary_msg,
                    swap_secondary_and_primary)) = secondary_span {
                if swap_secondary_and_primary {
                    let terr =
                        if let Some(infer::ValuePairs::Terms(ExpectedFound {
                                expected, .. })) = values {
                            Cow::from(::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("expected this to be `{0}`",
                                                expected))
                                    }))
                        } else { terr.to_string(self.tcx) };
                    label_or_note(secondary_span, terr);
                    label_or_note(span, secondary_msg);
                } else {
                    label_or_note(span, terr.to_string(self.tcx));
                    label_or_note(secondary_span, secondary_msg);
                }
            } else if let Some(values) = values &&
                        let Some((e, f)) = values.ty() &&
                    let TypeError::ArgumentSorts(..) | TypeError::Sorts(_) =
                        terr {
                let e = self.tcx.erase_and_anonymize_regions(e);
                let f = self.tcx.erase_and_anonymize_regions(f);
                let expected =
                    {
                        let _guard = ForceTrimmedGuard::new();
                        e.sort_string(self.tcx)
                    };
                let found =
                    {
                        let _guard = ForceTrimmedGuard::new();
                        f.sort_string(self.tcx)
                    };
                if expected == found {
                    label_or_note(span, terr.to_string(self.tcx));
                } else {
                    label_or_note(span,
                        Cow::from(::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("expected {0}, found {1}",
                                            expected, found))
                                })));
                }
            } else { label_or_note(span, terr.to_string(self.tcx)); }
            if self.check_and_note_conflicting_crates(diag, terr) { return; }
            if let Some((expected, found)) = expected_found {
                let (expected_label, found_label, exp_found) =
                    match exp_found {
                        Mismatch::Variable(ef) =>
                            (ef.expected.prefix_string(self.tcx),
                                ef.found.prefix_string(self.tcx), Some(ef)),
                        Mismatch::Fixed(s) => (s.into(), s.into(), None),
                    };
                enum Similar<'tcx> {
                    Adts {
                        expected: ty::AdtDef<'tcx>,
                        found: ty::AdtDef<'tcx>,
                    },
                    PrimitiveFound {
                        expected: ty::AdtDef<'tcx>,
                        found: Ty<'tcx>,
                    },
                    PrimitiveExpected {
                        expected: Ty<'tcx>,
                        found: ty::AdtDef<'tcx>,
                    },
                }
                let similarity =
                    |ExpectedFound { expected, found }: ExpectedFound<Ty<'tcx>>|
                        {
                            if let ty::Adt(expected, _) = expected.kind() &&
                                    let Some(primitive) = found.primitive_symbol() {
                                let path = self.tcx.def_path(expected.did()).data;
                                let name = path.last().unwrap().data.get_opt_name();
                                if name == Some(primitive) {
                                    return Some(Similar::PrimitiveFound {
                                                expected: *expected,
                                                found,
                                            });
                                }
                            } else if let Some(primitive) = expected.primitive_symbol()
                                    && let ty::Adt(found, _) = found.kind() {
                                let path = self.tcx.def_path(found.did()).data;
                                let name = path.last().unwrap().data.get_opt_name();
                                if name == Some(primitive) {
                                    return Some(Similar::PrimitiveExpected {
                                                expected,
                                                found: *found,
                                            });
                                }
                            } else if let ty::Adt(expected, _) = expected.kind() &&
                                    let ty::Adt(found, _) = found.kind() {
                                if !expected.did().is_local() &&
                                        expected.did().krate == found.did().krate {
                                    return None;
                                }
                                let f_path = self.tcx.def_path(found.did()).data;
                                let e_path = self.tcx.def_path(expected.did()).data;
                                if let (Some(e_last), Some(f_last)) =
                                            (e_path.last(), f_path.last()) && e_last == f_last {
                                    return Some(Similar::Adts {
                                                expected: *expected,
                                                found: *found,
                                            });
                                }
                            }
                            None
                        };
                match terr {
                    TypeError::Sorts(values) if let Some(s) = similarity(values)
                        => {
                        let diagnose_primitive =
                            |prim: Ty<'tcx>, shadow: Ty<'tcx>, defid: DefId,
                                diag: &mut Diag<'_>|
                                {
                                    let name = shadow.sort_string(self.tcx);
                                    diag.note(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("`{0}` and {1} have similar names, but are actually distinct types",
                                                        prim, name))
                                            }));
                                    diag.note(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("one `{0}` is a primitive defined by the language",
                                                        prim))
                                            }));
                                    let def_span = self.tcx.def_span(defid);
                                    let msg =
                                        if defid.is_local() {
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("the other {0} is defined in the current crate",
                                                            name))
                                                })
                                        } else {
                                            let crate_name = self.tcx.crate_name(defid.krate);
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("the other {0} is defined in crate `{1}`",
                                                            name, crate_name))
                                                })
                                        };
                                    diag.span_note(def_span, msg);
                                };
                        let diagnose_adts =
                            |expected_adt: ty::AdtDef<'tcx>,
                                found_adt: ty::AdtDef<'tcx>, diag: &mut Diag<'_>|
                                {
                                    let found_name = values.found.sort_string(self.tcx);
                                    let expected_name = values.expected.sort_string(self.tcx);
                                    let found_defid = found_adt.did();
                                    let expected_defid = expected_adt.did();
                                    diag.note(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("{0} and {1} have similar names, but are actually distinct types",
                                                        found_name, expected_name))
                                            }));
                                    for (defid, name) in
                                        [(found_defid, found_name), (expected_defid, expected_name)]
                                        {
                                        let def_span = self.tcx.def_span(defid);
                                        let msg =
                                            if found_defid.is_local() && expected_defid.is_local() {
                                                let module =
                                                    self.tcx.parent_module_from_def_id(defid.expect_local()).to_def_id();
                                                let module_name =
                                                    self.tcx.def_path(module).to_string_no_crate_verbose();
                                                ::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("{0} is defined in module `crate{1}` of the current crate",
                                                                name, module_name))
                                                    })
                                            } else if defid.is_local() {
                                                ::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("{0} is defined in the current crate",
                                                                name))
                                                    })
                                            } else {
                                                let crate_name = self.tcx.crate_name(defid.krate);
                                                ::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("{0} is defined in crate `{1}`",
                                                                name, crate_name))
                                                    })
                                            };
                                        diag.span_note(def_span, msg);
                                    }
                                };
                        match s {
                            Similar::Adts { expected, found } =>
                                diagnose_adts(expected, found, diag),
                            Similar::PrimitiveFound { expected, found: prim } => {
                                diagnose_primitive(prim, values.expected, expected.did(),
                                    diag)
                            }
                            Similar::PrimitiveExpected { expected: prim, found } => {
                                diagnose_primitive(prim, values.found, found.did(), diag)
                            }
                        }
                    }
                    TypeError::Sorts(values) => {
                        let extra =
                            expected == found &&
                                values.expected.sort_string(self.tcx) !=
                                    values.found.sort_string(self.tcx);
                        let sort_string =
                            |ty: Ty<'tcx>|
                                match (extra, ty.kind()) {
                                    (true, ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. })) =>
                                        {
                                        let sm = self.tcx.sess.source_map();
                                        let pos =
                                            sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
                                        DiagStyledString::normal(::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!(" (opaque type at <{0}:{1}:{2}>)",
                                                            sm.filename_for_diagnostics(&pos.file.name), pos.line,
                                                            pos.col.to_usize() + 1))
                                                }))
                                    }
                                    (true, ty::Alias(ty::Projection, proj)) if
                                        self.tcx.is_impl_trait_in_trait(proj.def_id) => {
                                        let sm = self.tcx.sess.source_map();
                                        let pos =
                                            sm.lookup_char_pos(self.tcx.def_span(proj.def_id).lo());
                                        DiagStyledString::normal(::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!(" (trait associated opaque type at <{0}:{1}:{2}>)",
                                                            sm.filename_for_diagnostics(&pos.file.name), pos.line,
                                                            pos.col.to_usize() + 1))
                                                }))
                                    }
                                    (true, _) => {
                                        let mut s = DiagStyledString::normal(" (");
                                        s.push_highlighted(ty.sort_string(self.tcx));
                                        s.push_normal(")");
                                        s
                                    }
                                    (false, _) => DiagStyledString::normal(""),
                                };
                        if !(values.expected.is_simple_text() &&
                                            values.found.is_simple_text()) ||
                                (exp_found.is_some_and(|ef|
                                            {
                                                if !ef.expected.is_ty_or_numeric_infer() {
                                                    ef.expected != values.expected
                                                } else if !ef.found.is_ty_or_numeric_infer() {
                                                    ef.found != values.found
                                                } else { false }
                                            })) {
                            if let Some(ExpectedFound { found: found_ty, .. }) =
                                        exp_found && !self.tcx.ty_is_opaque_future(found_ty) {
                                diag.note_expected_found_extra(&expected_label, expected,
                                    &found_label, found, sort_string(values.expected),
                                    sort_string(values.found));
                            }
                        }
                    }
                    _ => {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1723",
                                                "rustc_trait_selection::error_reporting::infer",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                                                ::tracing_core::__macro_support::Option::Some(1723u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("note_type_err: exp_found={0:?}, expected={1:?} found={2:?}",
                                                                            exp_found, expected, found) as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        if !is_simple_error || terr.must_include_note() {
                            diag.note_expected_found(&expected_label, expected,
                                &found_label, found);
                            if let Some(ty::Closure(_, args)) =
                                    exp_found.map(|expected_type_found|
                                            expected_type_found.found.kind()) {
                                diag.highlighted_note(<[_]>::into_vec(::alloc::boxed::box_new([StringPart::normal("closure has signature: `"),
                                                    StringPart::highlighted(self.tcx.signature_unclosure(args.as_closure().sig(),
                                                                rustc_hir::Safety::Safe).to_string()),
                                                    StringPart::normal("`")])));
                            }
                        }
                    }
                }
            }
            let exp_found =
                match exp_found {
                    Mismatch::Variable(exp_found) => Some(exp_found),
                    Mismatch::Fixed(_) => None,
                };
            let exp_found =
                match terr {
                    ty::error::TypeError::Sorts(terr) if
                        exp_found.is_some_and(|ef| terr.found == ef.found) => {
                        Some(terr)
                    }
                    _ => exp_found,
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1763",
                                    "rustc_trait_selection::error_reporting::infer",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1763u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("exp_found {0:?} terr {1:?} cause.code {2:?}",
                                                                exp_found, terr, cause.code()) as &dyn Value))])
                        });
                } else { ; }
            };
            if let Some(exp_found) = exp_found {
                let should_suggest_fixes =
                    if let ObligationCauseCode::Pattern { root_ty, .. } =
                            cause.code() {
                        self.same_type_modulo_infer(*root_ty, exp_found.expected)
                    } else { true };
                if should_suggest_fixes &&
                        !#[allow(non_exhaustive_omitted_patterns)] match terr {
                                TypeError::RegionsInsufficientlyPolymorphic(..) => true,
                                _ => false,
                            } {
                    self.suggest_tuple_pattern(cause, &exp_found, diag);
                    self.suggest_accessing_field_where_appropriate(cause,
                        &exp_found, diag);
                    self.suggest_await_on_expect_found(cause, span, &exp_found,
                        diag);
                    self.suggest_function_pointers(cause, span, &exp_found,
                        terr, diag);
                    self.suggest_turning_stmt_into_expr(cause, &exp_found,
                        diag);
                }
            }
            self.note_and_explain_type_err(diag, terr, cause, span,
                cause.body_id.to_def_id());
            if let Some(exp_found) = exp_found &&
                        let exp_found = TypeError::Sorts(exp_found) &&
                    exp_found != terr {
                self.note_and_explain_type_err(diag, exp_found, cause, span,
                    cause.body_id.to_def_id());
            }
            if let Some(ValuePairs::TraitRefs(exp_found)) = values &&
                            let ty::Closure(def_id, _) =
                                exp_found.expected.self_ty().kind() &&
                        let Some(def_id) = def_id.as_local() &&
                    terr.involves_regions() {
                let span = self.tcx.def_span(def_id);
                diag.span_note(span,
                    "this closure does not fulfill the lifetime requirements");
                self.suggest_for_all_lifetime_closure(span,
                    self.tcx.hir_node_by_def_id(def_id), &exp_found, diag);
            }
            self.note_error_origin(diag, cause, exp_found, terr, param_env);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1815",
                                    "rustc_trait_selection::error_reporting::infer",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1815u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                                    ::tracing_core::field::FieldSet::new(&["diag"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&diag) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
        }
    }
}#[instrument(level = "debug", skip(self, diag, secondary_span, prefer_label))]
1311    pub fn note_type_err(
1312        &self,
1313        diag: &mut Diag<'_>,
1314        cause: &ObligationCause<'tcx>,
1315        secondary_span: Option<(Span, Cow<'static, str>, bool)>,
1316        mut values: Option<ty::ParamEnvAnd<'tcx, ValuePairs<'tcx>>>,
1317        terr: TypeError<'tcx>,
1318        prefer_label: bool,
1319        override_span: Option<Span>,
1320    ) {
1321        // We use `override_span` when we want the error to point at a `Span` other than
1322        // `cause.span`. This is used in E0271, when a closure is passed in where the return type
1323        // isn't what was expected. We want to point at the closure's return type (or expression),
1324        // instead of the expression where the closure is passed as call argument.
1325        let span = override_span.unwrap_or(cause.span);
1326        // For some types of errors, expected-found does not make
1327        // sense, so just ignore the values we were given.
1328        if let TypeError::CyclicTy(_) = terr {
1329            values = None;
1330        }
1331        struct OpaqueTypesVisitor<'tcx> {
1332            types: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1333            expected: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1334            found: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1335            ignore_span: Span,
1336            tcx: TyCtxt<'tcx>,
1337        }
1338
1339        impl<'tcx> OpaqueTypesVisitor<'tcx> {
1340            fn visit_expected_found(
1341                tcx: TyCtxt<'tcx>,
1342                expected: impl TypeVisitable<TyCtxt<'tcx>>,
1343                found: impl TypeVisitable<TyCtxt<'tcx>>,
1344                ignore_span: Span,
1345            ) -> Self {
1346                let mut types_visitor = OpaqueTypesVisitor {
1347                    types: Default::default(),
1348                    expected: Default::default(),
1349                    found: Default::default(),
1350                    ignore_span,
1351                    tcx,
1352                };
1353                // The visitor puts all the relevant encountered types in `self.types`, but in
1354                // here we want to visit two separate types with no relation to each other, so we
1355                // move the results from `types` to `expected` or `found` as appropriate.
1356                expected.visit_with(&mut types_visitor);
1357                std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1358                found.visit_with(&mut types_visitor);
1359                std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1360                types_visitor
1361            }
1362
1363            fn report(&self, err: &mut Diag<'_>) {
1364                self.add_labels_for_types(err, "expected", &self.expected);
1365                self.add_labels_for_types(err, "found", &self.found);
1366            }
1367
1368            fn add_labels_for_types(
1369                &self,
1370                err: &mut Diag<'_>,
1371                target: &str,
1372                types: &FxIndexMap<TyCategory, FxIndexSet<Span>>,
1373            ) {
1374                for (kind, values) in types.iter() {
1375                    let count = values.len();
1376                    for &sp in values {
1377                        err.span_label(
1378                            sp,
1379                            format!(
1380                                "{}{} {:#}{}",
1381                                if count == 1 { "the " } else { "one of the " },
1382                                target,
1383                                kind,
1384                                pluralize!(count),
1385                            ),
1386                        );
1387                    }
1388                }
1389            }
1390        }
1391
1392        impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypesVisitor<'tcx> {
1393            fn visit_ty(&mut self, t: Ty<'tcx>) {
1394                if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1395                    let span = self.tcx.def_span(def_id);
1396                    // Avoid cluttering the output when the "found" and error span overlap:
1397                    //
1398                    // error[E0308]: mismatched types
1399                    //   --> $DIR/issue-20862.rs:2:5
1400                    //    |
1401                    // LL |     |y| x + y
1402                    //    |     ^^^^^^^^^
1403                    //    |     |
1404                    //    |     the found closure
1405                    //    |     expected `()`, found closure
1406                    //    |
1407                    //    = note: expected unit type `()`
1408                    //                 found closure `{closure@$DIR/issue-20862.rs:2:5: 2:14 x:_}`
1409                    //
1410                    // Also ignore opaque `Future`s that come from async fns.
1411                    if !self.ignore_span.overlaps(span)
1412                        && !span.is_desugaring(DesugaringKind::Async)
1413                    {
1414                        self.types.entry(kind).or_default().insert(span);
1415                    }
1416                }
1417                t.super_visit_with(self)
1418            }
1419        }
1420
1421        debug!("note_type_err(diag={:?})", diag);
1422        enum Mismatch<'a> {
1423            Variable(ty::error::ExpectedFound<Ty<'a>>),
1424            Fixed(&'static str),
1425        }
1426        let (expected_found, exp_found, is_simple_error, values, param_env) = match values {
1427            None => (None, Mismatch::Fixed("type"), false, None, None),
1428            Some(ty::ParamEnvAnd { param_env, value: values }) => {
1429                let mut values = self.resolve_vars_if_possible(values);
1430                if self.next_trait_solver() {
1431                    values = deeply_normalize_for_diagnostics(self, param_env, values);
1432                }
1433                let (is_simple_error, exp_found) = match values {
1434                    ValuePairs::Terms(ExpectedFound { expected, found }) => {
1435                        match (expected.kind(), found.kind()) {
1436                            (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
1437                                let is_simple_err =
1438                                    expected.is_simple_text() && found.is_simple_text();
1439                                OpaqueTypesVisitor::visit_expected_found(
1440                                    self.tcx, expected, found, span,
1441                                )
1442                                .report(diag);
1443
1444                                (
1445                                    is_simple_err,
1446                                    Mismatch::Variable(ExpectedFound { expected, found }),
1447                                )
1448                            }
1449                            (ty::TermKind::Const(_), ty::TermKind::Const(_)) => {
1450                                (false, Mismatch::Fixed("constant"))
1451                            }
1452                            _ => (false, Mismatch::Fixed("type")),
1453                        }
1454                    }
1455                    ValuePairs::PolySigs(ExpectedFound { expected, found }) => {
1456                        OpaqueTypesVisitor::visit_expected_found(self.tcx, expected, found, span)
1457                            .report(diag);
1458                        (false, Mismatch::Fixed("signature"))
1459                    }
1460                    ValuePairs::TraitRefs(_) => (false, Mismatch::Fixed("trait")),
1461                    ValuePairs::Aliases(ExpectedFound { expected, .. }) => {
1462                        (false, Mismatch::Fixed(self.tcx.def_descr(expected.def_id)))
1463                    }
1464                    ValuePairs::Regions(_) => (false, Mismatch::Fixed("lifetime")),
1465                    ValuePairs::ExistentialTraitRef(_) => {
1466                        (false, Mismatch::Fixed("existential trait ref"))
1467                    }
1468                    ValuePairs::ExistentialProjection(_) => {
1469                        (false, Mismatch::Fixed("existential projection"))
1470                    }
1471                };
1472                let Some(vals) = self.values_str(values, cause, diag.long_ty_path()) else {
1473                    // Derived error. Cancel the emitter.
1474                    // NOTE(eddyb) this was `.cancel()`, but `diag`
1475                    // is borrowed, so we can't fully defuse it.
1476                    diag.downgrade_to_delayed_bug();
1477                    return;
1478                };
1479                (Some(vals), exp_found, is_simple_error, Some(values), Some(param_env))
1480            }
1481        };
1482
1483        let mut label_or_note = |span: Span, msg: Cow<'static, str>| {
1484            if (prefer_label && is_simple_error) || &[span] == diag.span.primary_spans() {
1485                diag.span_label(span, msg);
1486            } else {
1487                diag.span_note(span, msg);
1488            }
1489        };
1490        if let Some((secondary_span, secondary_msg, swap_secondary_and_primary)) = secondary_span {
1491            if swap_secondary_and_primary {
1492                let terr = if let Some(infer::ValuePairs::Terms(ExpectedFound {
1493                    expected, ..
1494                })) = values
1495                {
1496                    Cow::from(format!("expected this to be `{expected}`"))
1497                } else {
1498                    terr.to_string(self.tcx)
1499                };
1500                label_or_note(secondary_span, terr);
1501                label_or_note(span, secondary_msg);
1502            } else {
1503                label_or_note(span, terr.to_string(self.tcx));
1504                label_or_note(secondary_span, secondary_msg);
1505            }
1506        } else if let Some(values) = values
1507            && let Some((e, f)) = values.ty()
1508            && let TypeError::ArgumentSorts(..) | TypeError::Sorts(_) = terr
1509        {
1510            let e = self.tcx.erase_and_anonymize_regions(e);
1511            let f = self.tcx.erase_and_anonymize_regions(f);
1512            let expected = with_forced_trimmed_paths!(e.sort_string(self.tcx));
1513            let found = with_forced_trimmed_paths!(f.sort_string(self.tcx));
1514            if expected == found {
1515                label_or_note(span, terr.to_string(self.tcx));
1516            } else {
1517                label_or_note(span, Cow::from(format!("expected {expected}, found {found}")));
1518            }
1519        } else {
1520            label_or_note(span, terr.to_string(self.tcx));
1521        }
1522
1523        if self.check_and_note_conflicting_crates(diag, terr) {
1524            return;
1525        }
1526
1527        if let Some((expected, found)) = expected_found {
1528            let (expected_label, found_label, exp_found) = match exp_found {
1529                Mismatch::Variable(ef) => (
1530                    ef.expected.prefix_string(self.tcx),
1531                    ef.found.prefix_string(self.tcx),
1532                    Some(ef),
1533                ),
1534                Mismatch::Fixed(s) => (s.into(), s.into(), None),
1535            };
1536
1537            enum Similar<'tcx> {
1538                Adts { expected: ty::AdtDef<'tcx>, found: ty::AdtDef<'tcx> },
1539                PrimitiveFound { expected: ty::AdtDef<'tcx>, found: Ty<'tcx> },
1540                PrimitiveExpected { expected: Ty<'tcx>, found: ty::AdtDef<'tcx> },
1541            }
1542
1543            let similarity = |ExpectedFound { expected, found }: ExpectedFound<Ty<'tcx>>| {
1544                if let ty::Adt(expected, _) = expected.kind()
1545                    && let Some(primitive) = found.primitive_symbol()
1546                {
1547                    let path = self.tcx.def_path(expected.did()).data;
1548                    let name = path.last().unwrap().data.get_opt_name();
1549                    if name == Some(primitive) {
1550                        return Some(Similar::PrimitiveFound { expected: *expected, found });
1551                    }
1552                } else if let Some(primitive) = expected.primitive_symbol()
1553                    && let ty::Adt(found, _) = found.kind()
1554                {
1555                    let path = self.tcx.def_path(found.did()).data;
1556                    let name = path.last().unwrap().data.get_opt_name();
1557                    if name == Some(primitive) {
1558                        return Some(Similar::PrimitiveExpected { expected, found: *found });
1559                    }
1560                } else if let ty::Adt(expected, _) = expected.kind()
1561                    && let ty::Adt(found, _) = found.kind()
1562                {
1563                    if !expected.did().is_local() && expected.did().krate == found.did().krate {
1564                        // Most likely types from different versions of the same crate
1565                        // are in play, in which case this message isn't so helpful.
1566                        // A "perhaps two different versions..." error is already emitted for that.
1567                        return None;
1568                    }
1569                    let f_path = self.tcx.def_path(found.did()).data;
1570                    let e_path = self.tcx.def_path(expected.did()).data;
1571
1572                    if let (Some(e_last), Some(f_last)) = (e_path.last(), f_path.last())
1573                        && e_last == f_last
1574                    {
1575                        return Some(Similar::Adts { expected: *expected, found: *found });
1576                    }
1577                }
1578                None
1579            };
1580
1581            match terr {
1582                // If two types mismatch but have similar names, mention that specifically.
1583                TypeError::Sorts(values) if let Some(s) = similarity(values) => {
1584                    let diagnose_primitive =
1585                        |prim: Ty<'tcx>, shadow: Ty<'tcx>, defid: DefId, diag: &mut Diag<'_>| {
1586                            let name = shadow.sort_string(self.tcx);
1587                            diag.note(format!(
1588                                "`{prim}` and {name} have similar names, but are actually distinct types"
1589                            ));
1590                            diag.note(format!(
1591                                "one `{prim}` is a primitive defined by the language",
1592                            ));
1593                            let def_span = self.tcx.def_span(defid);
1594                            let msg = if defid.is_local() {
1595                                format!("the other {name} is defined in the current crate")
1596                            } else {
1597                                let crate_name = self.tcx.crate_name(defid.krate);
1598                                format!("the other {name} is defined in crate `{crate_name}`")
1599                            };
1600                            diag.span_note(def_span, msg);
1601                        };
1602
1603                    let diagnose_adts =
1604                        |expected_adt: ty::AdtDef<'tcx>,
1605                         found_adt: ty::AdtDef<'tcx>,
1606                         diag: &mut Diag<'_>| {
1607                            let found_name = values.found.sort_string(self.tcx);
1608                            let expected_name = values.expected.sort_string(self.tcx);
1609
1610                            let found_defid = found_adt.did();
1611                            let expected_defid = expected_adt.did();
1612
1613                            diag.note(format!("{found_name} and {expected_name} have similar names, but are actually distinct types"));
1614                            for (defid, name) in
1615                                [(found_defid, found_name), (expected_defid, expected_name)]
1616                            {
1617                                let def_span = self.tcx.def_span(defid);
1618
1619                                let msg = if found_defid.is_local() && expected_defid.is_local() {
1620                                    let module = self
1621                                        .tcx
1622                                        .parent_module_from_def_id(defid.expect_local())
1623                                        .to_def_id();
1624                                    let module_name =
1625                                        self.tcx.def_path(module).to_string_no_crate_verbose();
1626                                    format!(
1627                                        "{name} is defined in module `crate{module_name}` of the current crate"
1628                                    )
1629                                } else if defid.is_local() {
1630                                    format!("{name} is defined in the current crate")
1631                                } else {
1632                                    let crate_name = self.tcx.crate_name(defid.krate);
1633                                    format!("{name} is defined in crate `{crate_name}`")
1634                                };
1635                                diag.span_note(def_span, msg);
1636                            }
1637                        };
1638
1639                    match s {
1640                        Similar::Adts { expected, found } => diagnose_adts(expected, found, diag),
1641                        Similar::PrimitiveFound { expected, found: prim } => {
1642                            diagnose_primitive(prim, values.expected, expected.did(), diag)
1643                        }
1644                        Similar::PrimitiveExpected { expected: prim, found } => {
1645                            diagnose_primitive(prim, values.found, found.did(), diag)
1646                        }
1647                    }
1648                }
1649                TypeError::Sorts(values) => {
1650                    let extra = expected == found
1651                        // Ensure that we don't ever say something like
1652                        // expected `impl Trait` (opaque type `impl Trait`)
1653                        //    found `impl Trait` (opaque type `impl Trait`)
1654                        && values.expected.sort_string(self.tcx)
1655                            != values.found.sort_string(self.tcx);
1656                    let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1657                        (true, ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. })) => {
1658                            let sm = self.tcx.sess.source_map();
1659                            let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1660                            DiagStyledString::normal(format!(
1661                                " (opaque type at <{}:{}:{}>)",
1662                                sm.filename_for_diagnostics(&pos.file.name),
1663                                pos.line,
1664                                pos.col.to_usize() + 1,
1665                            ))
1666                        }
1667                        (true, ty::Alias(ty::Projection, proj))
1668                            if self.tcx.is_impl_trait_in_trait(proj.def_id) =>
1669                        {
1670                            let sm = self.tcx.sess.source_map();
1671                            let pos = sm.lookup_char_pos(self.tcx.def_span(proj.def_id).lo());
1672                            DiagStyledString::normal(format!(
1673                                " (trait associated opaque type at <{}:{}:{}>)",
1674                                sm.filename_for_diagnostics(&pos.file.name),
1675                                pos.line,
1676                                pos.col.to_usize() + 1,
1677                            ))
1678                        }
1679                        (true, _) => {
1680                            let mut s = DiagStyledString::normal(" (");
1681                            s.push_highlighted(ty.sort_string(self.tcx));
1682                            s.push_normal(")");
1683                            s
1684                        }
1685                        (false, _) => DiagStyledString::normal(""),
1686                    };
1687                    if !(values.expected.is_simple_text() && values.found.is_simple_text())
1688                        || (exp_found.is_some_and(|ef| {
1689                            // This happens when the type error is a subset of the expectation,
1690                            // like when you have two references but one is `usize` and the other
1691                            // is `f32`. In those cases we still want to show the `note`. If the
1692                            // value from `ef` is `Infer(_)`, then we ignore it.
1693                            if !ef.expected.is_ty_or_numeric_infer() {
1694                                ef.expected != values.expected
1695                            } else if !ef.found.is_ty_or_numeric_infer() {
1696                                ef.found != values.found
1697                            } else {
1698                                false
1699                            }
1700                        }))
1701                    {
1702                        if let Some(ExpectedFound { found: found_ty, .. }) = exp_found
1703                            && !self.tcx.ty_is_opaque_future(found_ty)
1704                        {
1705                            // `Future` is a special opaque type that the compiler
1706                            // will try to hide in some case such as `async fn`, so
1707                            // to make an error more use friendly we will
1708                            // avoid to suggest a mismatch type with a
1709                            // type that the user usually are not using
1710                            // directly such as `impl Future<Output = u8>`.
1711                            diag.note_expected_found_extra(
1712                                &expected_label,
1713                                expected,
1714                                &found_label,
1715                                found,
1716                                sort_string(values.expected),
1717                                sort_string(values.found),
1718                            );
1719                        }
1720                    }
1721                }
1722                _ => {
1723                    debug!(
1724                        "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1725                        exp_found, expected, found
1726                    );
1727                    if !is_simple_error || terr.must_include_note() {
1728                        diag.note_expected_found(&expected_label, expected, &found_label, found);
1729
1730                        if let Some(ty::Closure(_, args)) =
1731                            exp_found.map(|expected_type_found| expected_type_found.found.kind())
1732                        {
1733                            diag.highlighted_note(vec![
1734                                StringPart::normal("closure has signature: `"),
1735                                StringPart::highlighted(
1736                                    self.tcx
1737                                        .signature_unclosure(
1738                                            args.as_closure().sig(),
1739                                            rustc_hir::Safety::Safe,
1740                                        )
1741                                        .to_string(),
1742                                ),
1743                                StringPart::normal("`"),
1744                            ]);
1745                        }
1746                    }
1747                }
1748            }
1749        }
1750        let exp_found = match exp_found {
1751            Mismatch::Variable(exp_found) => Some(exp_found),
1752            Mismatch::Fixed(_) => None,
1753        };
1754        let exp_found = match terr {
1755            // `terr` has more accurate type information than `exp_found` in match expressions.
1756            ty::error::TypeError::Sorts(terr)
1757                if exp_found.is_some_and(|ef| terr.found == ef.found) =>
1758            {
1759                Some(terr)
1760            }
1761            _ => exp_found,
1762        };
1763        debug!("exp_found {:?} terr {:?} cause.code {:?}", exp_found, terr, cause.code());
1764        if let Some(exp_found) = exp_found {
1765            let should_suggest_fixes =
1766                if let ObligationCauseCode::Pattern { root_ty, .. } = cause.code() {
1767                    // Skip if the root_ty of the pattern is not the same as the expected_ty.
1768                    // If these types aren't equal then we've probably peeled off a layer of arrays.
1769                    self.same_type_modulo_infer(*root_ty, exp_found.expected)
1770                } else {
1771                    true
1772                };
1773
1774            // FIXME(#73154): For now, we do leak check when coercing function
1775            // pointers in typeck, instead of only during borrowck. This can lead
1776            // to these `RegionsInsufficientlyPolymorphic` errors that aren't helpful.
1777            if should_suggest_fixes
1778                && !matches!(terr, TypeError::RegionsInsufficientlyPolymorphic(..))
1779            {
1780                self.suggest_tuple_pattern(cause, &exp_found, diag);
1781                self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1782                self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1783                self.suggest_function_pointers(cause, span, &exp_found, terr, diag);
1784                self.suggest_turning_stmt_into_expr(cause, &exp_found, diag);
1785            }
1786        }
1787
1788        self.note_and_explain_type_err(diag, terr, cause, span, cause.body_id.to_def_id());
1789        if let Some(exp_found) = exp_found
1790            && let exp_found = TypeError::Sorts(exp_found)
1791            && exp_found != terr
1792        {
1793            self.note_and_explain_type_err(diag, exp_found, cause, span, cause.body_id.to_def_id());
1794        }
1795
1796        if let Some(ValuePairs::TraitRefs(exp_found)) = values
1797            && let ty::Closure(def_id, _) = exp_found.expected.self_ty().kind()
1798            && let Some(def_id) = def_id.as_local()
1799            && terr.involves_regions()
1800        {
1801            let span = self.tcx.def_span(def_id);
1802            diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1803            self.suggest_for_all_lifetime_closure(
1804                span,
1805                self.tcx.hir_node_by_def_id(def_id),
1806                &exp_found,
1807                diag,
1808            );
1809        }
1810
1811        // It reads better to have the error origin as the final
1812        // thing.
1813        self.note_error_origin(diag, cause, exp_found, terr, param_env);
1814
1815        debug!(?diag);
1816    }
1817
1818    pub fn type_error_additional_suggestions(
1819        &self,
1820        trace: &TypeTrace<'tcx>,
1821        terr: TypeError<'tcx>,
1822        long_ty_path: &mut Option<PathBuf>,
1823    ) -> Vec<TypeErrorAdditionalDiags> {
1824        let mut suggestions = Vec::new();
1825        let span = trace.cause.span;
1826        let values = self.resolve_vars_if_possible(trace.values);
1827        if let Some((expected, found)) = values.ty() {
1828            match (expected.kind(), found.kind()) {
1829                (ty::Tuple(_), ty::Tuple(_)) => {}
1830                // If a tuple of length one was expected and the found expression has
1831                // parentheses around it, perhaps the user meant to write `(expr,)` to
1832                // build a tuple (issue #86100)
1833                (ty::Tuple(fields), _) => {
1834                    suggestions.extend(self.suggest_wrap_to_build_a_tuple(span, found, fields))
1835                }
1836                // If a byte was expected and the found expression is a char literal
1837                // containing a single ASCII character, perhaps the user meant to write `b'c'` to
1838                // specify a byte literal
1839                (ty::Uint(ty::UintTy::U8), ty::Char) => {
1840                    if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
1841                        && let Some(code) = code.strip_circumfix('\'', '\'')
1842                        // forbid all Unicode escapes
1843                        && !code.starts_with("\\u")
1844                        // forbids literal Unicode characters beyond ASCII
1845                        && code.chars().next().is_some_and(|c| c.is_ascii())
1846                    {
1847                        suggestions.push(TypeErrorAdditionalDiags::MeantByteLiteral {
1848                            span,
1849                            code: escape_literal(code),
1850                        })
1851                    }
1852                }
1853                // If a character was expected and the found expression is a string literal
1854                // containing a single character, perhaps the user meant to write `'c'` to
1855                // specify a character literal (issue #92479)
1856                (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
1857                    if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
1858                        && let Some(code) = code.strip_circumfix('"', '"')
1859                        && code.chars().count() == 1
1860                    {
1861                        suggestions.push(TypeErrorAdditionalDiags::MeantCharLiteral {
1862                            span,
1863                            code: escape_literal(code),
1864                        })
1865                    }
1866                }
1867                // If a string was expected and the found expression is a character literal,
1868                // perhaps the user meant to write `"s"` to specify a string literal.
1869                (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
1870                    if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
1871                        && code.starts_with("'")
1872                        && code.ends_with("'")
1873                    {
1874                        suggestions.push(TypeErrorAdditionalDiags::MeantStrLiteral {
1875                            start: span.with_hi(span.lo() + BytePos(1)),
1876                            end: span.with_lo(span.hi() - BytePos(1)),
1877                        });
1878                    }
1879                }
1880                // For code `if Some(..) = expr `, the type mismatch may be expected `bool` but found `()`,
1881                // we try to suggest to add the missing `let` for `if let Some(..) = expr`
1882                (ty::Bool, ty::Tuple(list)) => {
1883                    if list.len() == 0 {
1884                        suggestions.extend(self.suggest_let_for_letchains(&trace.cause, span));
1885                    }
1886                }
1887                (ty::Array(_, _), ty::Array(_, _)) => {
1888                    suggestions.extend(self.suggest_specify_actual_length(terr, trace, span))
1889                }
1890                _ => {}
1891            }
1892        }
1893        let code = trace.cause.code();
1894        if let &(ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1895            source,
1896            ..
1897        })
1898        | ObligationCauseCode::BlockTailExpression(.., source)) = code
1899            && let hir::MatchSource::TryDesugar(_) = source
1900            && let Some((expected_ty, found_ty)) =
1901                self.values_str(trace.values, &trace.cause, long_ty_path)
1902        {
1903            suggestions.push(TypeErrorAdditionalDiags::TryCannotConvert {
1904                found: found_ty.content(),
1905                expected: expected_ty.content(),
1906            });
1907        }
1908        suggestions
1909    }
1910
1911    fn suggest_specify_actual_length(
1912        &self,
1913        terr: TypeError<'tcx>,
1914        trace: &TypeTrace<'tcx>,
1915        span: Span,
1916    ) -> Option<TypeErrorAdditionalDiags> {
1917        let TypeError::ArraySize(sz) = terr else {
1918            return None;
1919        };
1920        let tykind = match self.tcx.hir_node_by_def_id(trace.cause.body_id) {
1921            hir::Node::Item(hir::Item {
1922                kind: hir::ItemKind::Fn { body: body_id, .. }, ..
1923            }) => {
1924                let body = self.tcx.hir_body(*body_id);
1925                struct LetVisitor {
1926                    span: Span,
1927                }
1928                impl<'v> Visitor<'v> for LetVisitor {
1929                    type Result = ControlFlow<&'v hir::TyKind<'v>>;
1930                    fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
1931                        // Find a local statement where the initializer has
1932                        // the same span as the error and the type is specified.
1933                        if let hir::Stmt {
1934                            kind:
1935                                hir::StmtKind::Let(hir::LetStmt {
1936                                    init: Some(hir::Expr { span: init_span, .. }),
1937                                    ty: Some(array_ty),
1938                                    ..
1939                                }),
1940                            ..
1941                        } = s
1942                            && init_span == &self.span
1943                        {
1944                            ControlFlow::Break(&array_ty.peel_refs().kind)
1945                        } else {
1946                            ControlFlow::Continue(())
1947                        }
1948                    }
1949                }
1950                LetVisitor { span }.visit_body(body).break_value()
1951            }
1952            hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(_, _, ty, _), .. }) => {
1953                Some(&ty.peel_refs().kind)
1954            }
1955            _ => None,
1956        };
1957        if let Some(tykind) = tykind
1958            && let hir::TyKind::Array(_, length_arg) = tykind
1959            && let Some(length_val) = sz.found.try_to_target_usize(self.tcx)
1960        {
1961            Some(TypeErrorAdditionalDiags::ConsiderSpecifyingLength {
1962                span: length_arg.span,
1963                length: length_val,
1964            })
1965        } else {
1966            None
1967        }
1968    }
1969
1970    pub fn report_and_explain_type_error(
1971        &self,
1972        trace: TypeTrace<'tcx>,
1973        param_env: ty::ParamEnv<'tcx>,
1974        terr: TypeError<'tcx>,
1975    ) -> Diag<'a> {
1976        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1976",
                        "rustc_trait_selection::error_reporting::infer",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1976u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_and_explain_type_error(trace={0:?}, terr={1:?})",
                                                    trace, terr) as &dyn Value))])
            });
    } else { ; }
};debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
1977
1978        let span = trace.cause.span;
1979        let mut path = None;
1980        let failure_code = trace.cause.as_failure_code_diag(
1981            terr,
1982            span,
1983            self.type_error_additional_suggestions(&trace, terr, &mut path),
1984        );
1985        let mut diag = self.dcx().create_err(failure_code);
1986        *diag.long_ty_path() = path;
1987        self.note_type_err(
1988            &mut diag,
1989            &trace.cause,
1990            None,
1991            Some(param_env.and(trace.values)),
1992            terr,
1993            false,
1994            None,
1995        );
1996        diag
1997    }
1998
1999    fn suggest_wrap_to_build_a_tuple(
2000        &self,
2001        span: Span,
2002        found: Ty<'tcx>,
2003        expected_fields: &List<Ty<'tcx>>,
2004    ) -> Option<TypeErrorAdditionalDiags> {
2005        let [expected_tup_elem] = expected_fields[..] else { return None };
2006
2007        if !self.same_type_modulo_infer(expected_tup_elem, found) {
2008            return None;
2009        }
2010
2011        let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) else { return None };
2012
2013        let sugg = if code.starts_with('(') && code.ends_with(')') {
2014            let before_close = span.hi() - BytePos::from_u32(1);
2015            TypeErrorAdditionalDiags::TupleOnlyComma {
2016                span: span.with_hi(before_close).shrink_to_hi(),
2017            }
2018        } else {
2019            TypeErrorAdditionalDiags::TupleAlsoParentheses {
2020                span_low: span.shrink_to_lo(),
2021                span_high: span.shrink_to_hi(),
2022            }
2023        };
2024        Some(sugg)
2025    }
2026
2027    fn values_str(
2028        &self,
2029        values: ValuePairs<'tcx>,
2030        cause: &ObligationCause<'tcx>,
2031        long_ty_path: &mut Option<PathBuf>,
2032    ) -> Option<(DiagStyledString, DiagStyledString)> {
2033        match values {
2034            ValuePairs::Regions(exp_found) => self.expected_found_str(exp_found),
2035            ValuePairs::Terms(exp_found) => self.expected_found_str_term(exp_found, long_ty_path),
2036            ValuePairs::Aliases(exp_found) => self.expected_found_str(exp_found),
2037            ValuePairs::ExistentialTraitRef(exp_found) => self.expected_found_str(exp_found),
2038            ValuePairs::ExistentialProjection(exp_found) => self.expected_found_str(exp_found),
2039            ValuePairs::TraitRefs(exp_found) => {
2040                let pretty_exp_found = ty::error::ExpectedFound {
2041                    expected: exp_found.expected.print_trait_sugared(),
2042                    found: exp_found.found.print_trait_sugared(),
2043                };
2044                match self.expected_found_str(pretty_exp_found) {
2045                    Some((expected, found)) if expected == found => {
2046                        self.expected_found_str(exp_found)
2047                    }
2048                    ret => ret,
2049                }
2050            }
2051            ValuePairs::PolySigs(exp_found) => {
2052                let exp_found = self.resolve_vars_if_possible(exp_found);
2053                if exp_found.references_error() {
2054                    return None;
2055                }
2056                let (fn_def1, fn_def2) = if let ObligationCauseCode::CompareImplItem {
2057                    impl_item_def_id,
2058                    trait_item_def_id,
2059                    ..
2060                } = *cause.code()
2061                {
2062                    (Some((trait_item_def_id, None)), Some((impl_item_def_id.to_def_id(), None)))
2063                } else {
2064                    (None, None)
2065                };
2066
2067                Some(self.cmp_fn_sig(&exp_found.expected, fn_def1, &exp_found.found, fn_def2))
2068            }
2069        }
2070    }
2071
2072    fn expected_found_str_term(
2073        &self,
2074        exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2075        long_ty_path: &mut Option<PathBuf>,
2076    ) -> Option<(DiagStyledString, DiagStyledString)> {
2077        let exp_found = self.resolve_vars_if_possible(exp_found);
2078        if exp_found.references_error() {
2079            return None;
2080        }
2081
2082        Some(match (exp_found.expected.kind(), exp_found.found.kind()) {
2083            (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
2084                let (mut exp, mut fnd) = self.cmp(expected, found);
2085                // Use the terminal width as the basis to determine when to compress the printed
2086                // out type, but give ourselves some leeway to avoid ending up creating a file for
2087                // a type that is somewhat shorter than the path we'd write to.
2088                let len = self.tcx.sess().diagnostic_width() + 40;
2089                let exp_s = exp.content();
2090                let fnd_s = fnd.content();
2091                if exp_s.len() > len {
2092                    let exp_s = self.tcx.short_string(expected, long_ty_path);
2093                    exp = DiagStyledString::highlighted(exp_s);
2094                }
2095                if fnd_s.len() > len {
2096                    let fnd_s = self.tcx.short_string(found, long_ty_path);
2097                    fnd = DiagStyledString::highlighted(fnd_s);
2098                }
2099                (exp, fnd)
2100            }
2101            _ => (
2102                DiagStyledString::highlighted(exp_found.expected.to_string()),
2103                DiagStyledString::highlighted(exp_found.found.to_string()),
2104            ),
2105        })
2106    }
2107
2108    /// Returns a string of the form "expected `{}`, found `{}`".
2109    fn expected_found_str<T: fmt::Display + TypeFoldable<TyCtxt<'tcx>>>(
2110        &self,
2111        exp_found: ty::error::ExpectedFound<T>,
2112    ) -> Option<(DiagStyledString, DiagStyledString)> {
2113        let exp_found = self.resolve_vars_if_possible(exp_found);
2114        if exp_found.references_error() {
2115            return None;
2116        }
2117
2118        Some((
2119            DiagStyledString::highlighted(exp_found.expected.to_string()),
2120            DiagStyledString::highlighted(exp_found.found.to_string()),
2121        ))
2122    }
2123
2124    /// Determine whether an error associated with the given span and definition
2125    /// should be treated as being caused by the implicit `From` conversion
2126    /// within `?` desugaring.
2127    pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2128        span.is_desugaring(DesugaringKind::QuestionMark)
2129            && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2130    }
2131
2132    /// Structurally compares two types, modulo any inference variables.
2133    ///
2134    /// Returns `true` if two types are equal, or if one type is an inference variable compatible
2135    /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or
2136    /// FloatVar inference type are compatible with themselves or their concrete types (Int and
2137    /// Float types, respectively). When comparing two ADTs, these rules apply recursively.
2138    pub fn same_type_modulo_infer<T: relate::Relate<TyCtxt<'tcx>>>(&self, a: T, b: T) -> bool {
2139        let (a, b) = self.resolve_vars_if_possible((a, b));
2140        SameTypeModuloInfer(self).relate(a, b).is_ok()
2141    }
2142}
2143
2144struct SameTypeModuloInfer<'a, 'tcx>(&'a InferCtxt<'tcx>);
2145
2146impl<'tcx> TypeRelation<TyCtxt<'tcx>> for SameTypeModuloInfer<'_, 'tcx> {
2147    fn cx(&self) -> TyCtxt<'tcx> {
2148        self.0.tcx
2149    }
2150
2151    fn relate_ty_args(
2152        &mut self,
2153        a_ty: Ty<'tcx>,
2154        _: Ty<'tcx>,
2155        _: DefId,
2156        a_args: ty::GenericArgsRef<'tcx>,
2157        b_args: ty::GenericArgsRef<'tcx>,
2158        _: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>,
2159    ) -> RelateResult<'tcx, Ty<'tcx>> {
2160        relate::relate_args_invariantly(self, a_args, b_args)?;
2161        Ok(a_ty)
2162    }
2163
2164    fn relate_with_variance<T: relate::Relate<TyCtxt<'tcx>>>(
2165        &mut self,
2166        _variance: ty::Variance,
2167        _info: ty::VarianceDiagInfo<TyCtxt<'tcx>>,
2168        a: T,
2169        b: T,
2170    ) -> relate::RelateResult<'tcx, T> {
2171        self.relate(a, b)
2172    }
2173
2174    fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
2175        match (a.kind(), b.kind()) {
2176            (ty::Int(_) | ty::Uint(_), ty::Infer(ty::InferTy::IntVar(_)))
2177            | (
2178                ty::Infer(ty::InferTy::IntVar(_)),
2179                ty::Int(_) | ty::Uint(_) | ty::Infer(ty::InferTy::IntVar(_)),
2180            )
2181            | (ty::Float(_), ty::Infer(ty::InferTy::FloatVar(_)))
2182            | (
2183                ty::Infer(ty::InferTy::FloatVar(_)),
2184                ty::Float(_) | ty::Infer(ty::InferTy::FloatVar(_)),
2185            )
2186            | (ty::Infer(ty::InferTy::TyVar(_)), _)
2187            | (_, ty::Infer(ty::InferTy::TyVar(_))) => Ok(a),
2188            (ty::Infer(_), _) | (_, ty::Infer(_)) => Err(TypeError::Mismatch),
2189            _ => relate::structurally_relate_tys(self, a, b),
2190        }
2191    }
2192
2193    fn regions(
2194        &mut self,
2195        a: ty::Region<'tcx>,
2196        b: ty::Region<'tcx>,
2197    ) -> RelateResult<'tcx, ty::Region<'tcx>> {
2198        if (a.is_var() && b.is_free())
2199            || (b.is_var() && a.is_free())
2200            || (a.is_var() && b.is_var())
2201            || a == b
2202        {
2203            Ok(a)
2204        } else {
2205            Err(TypeError::Mismatch)
2206        }
2207    }
2208
2209    fn binders<T>(
2210        &mut self,
2211        a: ty::Binder<'tcx, T>,
2212        b: ty::Binder<'tcx, T>,
2213    ) -> relate::RelateResult<'tcx, ty::Binder<'tcx, T>>
2214    where
2215        T: relate::Relate<TyCtxt<'tcx>>,
2216    {
2217        Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
2218    }
2219
2220    fn consts(
2221        &mut self,
2222        a: ty::Const<'tcx>,
2223        _b: ty::Const<'tcx>,
2224    ) -> relate::RelateResult<'tcx, ty::Const<'tcx>> {
2225        // FIXME(compiler-errors): This could at least do some first-order
2226        // relation
2227        Ok(a)
2228    }
2229}
2230
2231pub enum FailureCode {
2232    Error0317,
2233    Error0580,
2234    Error0308,
2235    Error0644,
2236}
2237
2238impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
    fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
        match self.code() {
            ObligationCauseCode::IfExpressionWithNoElse =>
                FailureCode::Error0317,
            ObligationCauseCode::MainFunctionType => FailureCode::Error0580,
            ObligationCauseCode::CompareImplItem { .. } |
                ObligationCauseCode::MatchExpressionArm(_) |
                ObligationCauseCode::IfExpression { .. } |
                ObligationCauseCode::LetElse |
                ObligationCauseCode::LangFunctionType(_) |
                ObligationCauseCode::IntrinsicType |
                ObligationCauseCode::MethodReceiver => FailureCode::Error0308,
            _ =>
                match terr {
                    TypeError::CyclicTy(ty) if
                        ty.is_closure() || ty.is_coroutine() ||
                            ty.is_coroutine_closure() => {
                        FailureCode::Error0644
                    }
                    TypeError::IntrinsicCast | TypeError::ForceInlineCast =>
                        FailureCode::Error0308,
                    _ => FailureCode::Error0308,
                },
        }
    }
    fn as_failure_code_diag(&self, terr: TypeError<'tcx>, span: Span,
        subdiags: Vec<TypeErrorAdditionalDiags>)
        -> ObligationCauseFailureCode {
        match self.code() {
            ObligationCauseCode::CompareImplItem {
                kind: ty::AssocKind::Fn { .. }, .. } => {
                ObligationCauseFailureCode::MethodCompat { span, subdiags }
            }
            ObligationCauseCode::CompareImplItem {
                kind: ty::AssocKind::Type { .. }, .. } => {
                ObligationCauseFailureCode::TypeCompat { span, subdiags }
            }
            ObligationCauseCode::CompareImplItem {
                kind: ty::AssocKind::Const { .. }, .. } => {
                ObligationCauseFailureCode::ConstCompat { span, subdiags }
            }
            ObligationCauseCode::BlockTailExpression(..,
                hir::MatchSource::TryDesugar(_)) => {
                ObligationCauseFailureCode::TryCompat { span, subdiags }
            }
            ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
                source, .. }) =>
                match source {
                    hir::MatchSource::TryDesugar(_) => {
                        ObligationCauseFailureCode::TryCompat { span, subdiags }
                    }
                    _ =>
                        ObligationCauseFailureCode::MatchCompat { span, subdiags },
                },
            ObligationCauseCode::IfExpression { .. } => {
                ObligationCauseFailureCode::IfElseDifferent { span, subdiags }
            }
            ObligationCauseCode::IfExpressionWithNoElse => {
                ObligationCauseFailureCode::NoElse { span }
            }
            ObligationCauseCode::LetElse => {
                ObligationCauseFailureCode::NoDiverge { span, subdiags }
            }
            ObligationCauseCode::MainFunctionType => {
                ObligationCauseFailureCode::FnMainCorrectType { span }
            }
            &ObligationCauseCode::LangFunctionType(lang_item_name) => {
                ObligationCauseFailureCode::FnLangCorrectType {
                    span,
                    subdiags,
                    lang_item_name,
                }
            }
            ObligationCauseCode::IntrinsicType => {
                ObligationCauseFailureCode::IntrinsicCorrectType {
                    span,
                    subdiags,
                }
            }
            ObligationCauseCode::MethodReceiver => {
                ObligationCauseFailureCode::MethodCorrectType {
                    span,
                    subdiags,
                }
            }
            _ =>
                match terr {
                    TypeError::CyclicTy(ty) if
                        ty.is_closure() || ty.is_coroutine() ||
                            ty.is_coroutine_closure() => {
                        ObligationCauseFailureCode::ClosureSelfref { span }
                    }
                    TypeError::ForceInlineCast => {
                        ObligationCauseFailureCode::CantCoerceForceInline {
                            span,
                            subdiags,
                        }
                    }
                    TypeError::IntrinsicCast => {
                        ObligationCauseFailureCode::CantCoerceIntrinsic {
                            span,
                            subdiags,
                        }
                    }
                    _ => ObligationCauseFailureCode::Generic { span, subdiags },
                },
        }
    }
    fn as_requirement_str(&self) -> &'static str {
        match self.code() {
            ObligationCauseCode::CompareImplItem {
                kind: ty::AssocKind::Fn { .. }, .. } => {
                "method type is compatible with trait"
            }
            ObligationCauseCode::CompareImplItem {
                kind: ty::AssocKind::Type { .. }, .. } => {
                "associated type is compatible with trait"
            }
            ObligationCauseCode::CompareImplItem {
                kind: ty::AssocKind::Const { .. }, .. } => {
                "const is compatible with trait"
            }
            ObligationCauseCode::MainFunctionType =>
                "`main` function has the correct type",
            ObligationCauseCode::LangFunctionType(_) =>
                "lang item function has the correct type",
            ObligationCauseCode::IntrinsicType =>
                "intrinsic has the correct type",
            ObligationCauseCode::MethodReceiver =>
                "method receiver has the correct type",
            _ => "types are compatible",
        }
    }
}#[extension(pub trait ObligationCauseExt<'tcx>)]
2239impl<'tcx> ObligationCause<'tcx> {
2240    fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
2241        match self.code() {
2242            ObligationCauseCode::IfExpressionWithNoElse => FailureCode::Error0317,
2243            ObligationCauseCode::MainFunctionType => FailureCode::Error0580,
2244            ObligationCauseCode::CompareImplItem { .. }
2245            | ObligationCauseCode::MatchExpressionArm(_)
2246            | ObligationCauseCode::IfExpression { .. }
2247            | ObligationCauseCode::LetElse
2248            | ObligationCauseCode::LangFunctionType(_)
2249            | ObligationCauseCode::IntrinsicType
2250            | ObligationCauseCode::MethodReceiver => FailureCode::Error0308,
2251
2252            // In the case where we have no more specific thing to
2253            // say, also take a look at the error code, maybe we can
2254            // tailor to that.
2255            _ => match terr {
2256                TypeError::CyclicTy(ty)
2257                    if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() =>
2258                {
2259                    FailureCode::Error0644
2260                }
2261                TypeError::IntrinsicCast | TypeError::ForceInlineCast => FailureCode::Error0308,
2262                _ => FailureCode::Error0308,
2263            },
2264        }
2265    }
2266    fn as_failure_code_diag(
2267        &self,
2268        terr: TypeError<'tcx>,
2269        span: Span,
2270        subdiags: Vec<TypeErrorAdditionalDiags>,
2271    ) -> ObligationCauseFailureCode {
2272        match self.code() {
2273            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
2274                ObligationCauseFailureCode::MethodCompat { span, subdiags }
2275            }
2276            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
2277                ObligationCauseFailureCode::TypeCompat { span, subdiags }
2278            }
2279            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
2280                ObligationCauseFailureCode::ConstCompat { span, subdiags }
2281            }
2282            ObligationCauseCode::BlockTailExpression(.., hir::MatchSource::TryDesugar(_)) => {
2283                ObligationCauseFailureCode::TryCompat { span, subdiags }
2284            }
2285            ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
2286                source, ..
2287            }) => match source {
2288                hir::MatchSource::TryDesugar(_) => {
2289                    ObligationCauseFailureCode::TryCompat { span, subdiags }
2290                }
2291                _ => ObligationCauseFailureCode::MatchCompat { span, subdiags },
2292            },
2293            ObligationCauseCode::IfExpression { .. } => {
2294                ObligationCauseFailureCode::IfElseDifferent { span, subdiags }
2295            }
2296            ObligationCauseCode::IfExpressionWithNoElse => {
2297                ObligationCauseFailureCode::NoElse { span }
2298            }
2299            ObligationCauseCode::LetElse => {
2300                ObligationCauseFailureCode::NoDiverge { span, subdiags }
2301            }
2302            ObligationCauseCode::MainFunctionType => {
2303                ObligationCauseFailureCode::FnMainCorrectType { span }
2304            }
2305            &ObligationCauseCode::LangFunctionType(lang_item_name) => {
2306                ObligationCauseFailureCode::FnLangCorrectType { span, subdiags, lang_item_name }
2307            }
2308            ObligationCauseCode::IntrinsicType => {
2309                ObligationCauseFailureCode::IntrinsicCorrectType { span, subdiags }
2310            }
2311            ObligationCauseCode::MethodReceiver => {
2312                ObligationCauseFailureCode::MethodCorrectType { span, subdiags }
2313            }
2314
2315            // In the case where we have no more specific thing to
2316            // say, also take a look at the error code, maybe we can
2317            // tailor to that.
2318            _ => match terr {
2319                TypeError::CyclicTy(ty)
2320                    if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() =>
2321                {
2322                    ObligationCauseFailureCode::ClosureSelfref { span }
2323                }
2324                TypeError::ForceInlineCast => {
2325                    ObligationCauseFailureCode::CantCoerceForceInline { span, subdiags }
2326                }
2327                TypeError::IntrinsicCast => {
2328                    ObligationCauseFailureCode::CantCoerceIntrinsic { span, subdiags }
2329                }
2330                _ => ObligationCauseFailureCode::Generic { span, subdiags },
2331            },
2332        }
2333    }
2334
2335    fn as_requirement_str(&self) -> &'static str {
2336        match self.code() {
2337            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
2338                "method type is compatible with trait"
2339            }
2340            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
2341                "associated type is compatible with trait"
2342            }
2343            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
2344                "const is compatible with trait"
2345            }
2346            ObligationCauseCode::MainFunctionType => "`main` function has the correct type",
2347            ObligationCauseCode::LangFunctionType(_) => "lang item function has the correct type",
2348            ObligationCauseCode::IntrinsicType => "intrinsic has the correct type",
2349            ObligationCauseCode::MethodReceiver => "method receiver has the correct type",
2350            _ => "types are compatible",
2351        }
2352    }
2353}
2354
2355/// Newtype to allow implementing IntoDiagArg
2356pub struct ObligationCauseAsDiagArg<'tcx>(pub ObligationCause<'tcx>);
2357
2358impl IntoDiagArg for ObligationCauseAsDiagArg<'_> {
2359    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
2360        let kind = match self.0.code() {
2361            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
2362                "method_compat"
2363            }
2364            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
2365                "type_compat"
2366            }
2367            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
2368                "const_compat"
2369            }
2370            ObligationCauseCode::MainFunctionType => "fn_main_correct_type",
2371            ObligationCauseCode::LangFunctionType(_) => "fn_lang_correct_type",
2372            ObligationCauseCode::IntrinsicType => "intrinsic_correct_type",
2373            ObligationCauseCode::MethodReceiver => "method_correct_type",
2374            _ => "other",
2375        }
2376        .into();
2377        rustc_errors::DiagArgValue::Str(kind)
2378    }
2379}
2380
2381/// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2382/// extra information about each type, but we only care about the category.
2383#[derive(#[automatically_derived]
impl ::core::clone::Clone for TyCategory {
    #[inline]
    fn clone(&self) -> TyCategory {
        let _: ::core::clone::AssertParamIsClone<hir::CoroutineKind>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TyCategory { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for TyCategory {
    #[inline]
    fn eq(&self, other: &TyCategory) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (TyCategory::Coroutine(__self_0),
                    TyCategory::Coroutine(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for TyCategory {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<hir::CoroutineKind>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for TyCategory {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            TyCategory::Coroutine(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash)]
2384pub enum TyCategory {
2385    Closure,
2386    Opaque,
2387    OpaqueFuture,
2388    Coroutine(hir::CoroutineKind),
2389    Foreign,
2390}
2391
2392impl fmt::Display for TyCategory {
2393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2394        match self {
2395            Self::Closure => "closure".fmt(f),
2396            Self::Opaque => "opaque type".fmt(f),
2397            Self::OpaqueFuture => "future".fmt(f),
2398            Self::Coroutine(gk) => gk.fmt(f),
2399            Self::Foreign => "foreign type".fmt(f),
2400        }
2401    }
2402}
2403
2404impl TyCategory {
2405    pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
2406        match *ty.kind() {
2407            ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2408            ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
2409                let kind =
2410                    if tcx.ty_is_opaque_future(ty) { Self::OpaqueFuture } else { Self::Opaque };
2411                Some((kind, def_id))
2412            }
2413            ty::Coroutine(def_id, ..) => {
2414                Some((Self::Coroutine(tcx.coroutine_kind(def_id).unwrap()), def_id))
2415            }
2416            ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
2417            _ => None,
2418        }
2419    }
2420}