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::{FxHashSet, FxIndexMap, FxIndexSet};
55use rustc_errors::{Applicability, Diag, DiagStyledString, IntoDiagArg, StringPart, pluralize};
56use rustc_hir::attrs::diagnostic::{CustomDiagnostic, Directive, FormatArgs};
57use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
58use rustc_hir::intravisit::Visitor;
59use rustc_hir::{self as hir, find_attr};
60use rustc_infer::infer::DefineOpaqueTypes;
61use rustc_macros::extension;
62use rustc_middle::bug;
63use rustc_middle::traits::PatternOriginExpr;
64use rustc_middle::ty::error::{ExpectedFound, TypeError, TypeErrorToStringExt};
65use rustc_middle::ty::print::{PrintTraitRefExt as _, WrapBinderMode, with_forced_trimmed_paths};
66use rustc_middle::ty::{
67    self, List, Mutability, ParamEnv, Region, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
68    TypeVisitable, TypeVisitableExt, Unnormalized,
69};
70use rustc_span::{BytePos, DUMMY_SP, DesugaringKind, Pos, Span, sym};
71use thin_vec::ThinVec;
72use tracing::{debug, instrument};
73
74use crate::diagnostics::{ObligationCauseFailureCode, TypeErrorAdditionalDiags};
75use crate::error_reporting::TypeErrCtxt;
76use crate::error_reporting::traits::ambiguity::{
77    CandidateSource, compute_applicable_impls_for_diagnostics,
78};
79use crate::infer;
80use crate::infer::relate::{self, RelateResult, TypeRelation};
81use crate::infer::{InferCtxt, InferCtxtExt as _, TypeTrace, ValuePairs};
82use crate::traits::{
83    MatchExpressionArmCause, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
84    specialization_graph,
85};
86
87mod note_and_explain;
88mod suggest;
89
90pub mod need_type_info;
91pub mod nice_region_error;
92pub mod region;
93
94/// Makes a valid string literal from a string by escaping special characters (" and \),
95/// unless they are already escaped.
96fn escape_literal(s: &str) -> String {
97    let mut escaped = String::with_capacity(s.len());
98    let mut chrs = s.chars().peekable();
99    while let Some(first) = chrs.next() {
100        match (first, chrs.peek()) {
101            ('\\', Some(&delim @ '"') | Some(&delim @ '\'')) => {
102                escaped.push('\\');
103                escaped.push(delim);
104                chrs.next();
105            }
106            ('"' | '\'', _) => {
107                escaped.push('\\');
108                escaped.push(first)
109            }
110            (c, _) => escaped.push(c),
111        };
112    }
113    escaped
114}
115
116impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
117    fn normalize_fn_sig(
118        &self,
119        fn_sig: Unnormalized<'tcx, ty::PolyFnSig<'tcx>>,
120    ) -> ty::PolyFnSig<'tcx> {
121        let Some(param_env) = self.param_env else {
122            return fn_sig.skip_normalization();
123        };
124
125        if fn_sig.skip_normalization().has_escaping_bound_vars() {
126            return fn_sig.skip_normalization();
127        }
128
129        self.probe(|_| {
130            let ocx = ObligationCtxt::new(self);
131            let normalized_fn_sig = ocx.normalize(&ObligationCause::dummy(), param_env, fn_sig);
132            if ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
133                let normalized_fn_sig = self.resolve_vars_if_possible(normalized_fn_sig);
134                if !normalized_fn_sig.has_infer() {
135                    return normalized_fn_sig;
136                }
137            }
138            fn_sig.skip_normalization()
139        })
140    }
141
142    // [Note-Type-error-reporting]
143    // An invariant is that anytime the expected or actual type is Error (the special
144    // error type, meaning that an error occurred when typechecking this expression),
145    // this is a derived error. The error cascaded from another error (that was already
146    // reported), so it's not useful to display it to the user.
147    // The following methods implement this logic.
148    // They check if either the actual or expected type is Error, and don't print the error
149    // in this case. The typechecker should only ever report type errors involving mismatched
150    // types using one of these methods, and should not call span_err directly for such
151    // errors.
152    pub fn type_error_struct_with_diag<M>(
153        &self,
154        sp: Span,
155        mk_diag: M,
156        actual_ty: Ty<'tcx>,
157    ) -> Diag<'a>
158    where
159        M: FnOnce(String) -> Diag<'a>,
160    {
161        let actual_ty = self.resolve_vars_if_possible(actual_ty);
162        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:162",
                        "rustc_trait_selection::error_reporting::infer",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(162u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("type_error_struct_with_diag({0:?}, {1:?})",
                                                    sp, actual_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
163
164        let mut err = mk_diag(self.ty_to_string(actual_ty));
165
166        // Don't report an error if actual type is `Error`.
167        if actual_ty.references_error() {
168            err.downgrade_to_delayed_bug();
169        }
170
171        err
172    }
173
174    pub fn report_mismatched_types(
175        &self,
176        cause: &ObligationCause<'tcx>,
177        param_env: ty::ParamEnv<'tcx>,
178        expected: Ty<'tcx>,
179        actual: Ty<'tcx>,
180        err: TypeError<'tcx>,
181    ) -> Diag<'a> {
182        let mut diag = self.report_and_explain_type_error(
183            TypeTrace::types(cause, expected, actual),
184            param_env,
185            err,
186        );
187
188        self.suggest_param_env_shadowing(&mut diag, expected, actual, param_env);
189
190        diag
191    }
192
193    pub fn report_mismatched_consts(
194        &self,
195        cause: &ObligationCause<'tcx>,
196        param_env: ty::ParamEnv<'tcx>,
197        expected: ty::Const<'tcx>,
198        actual: ty::Const<'tcx>,
199        err: TypeError<'tcx>,
200    ) -> Diag<'a> {
201        self.report_and_explain_type_error(
202            TypeTrace::consts(cause, expected, actual),
203            param_env,
204            err,
205        )
206    }
207
208    /// Adds a note if the types come from similarly named crates
209    fn check_and_note_conflicting_crates(&self, err: &mut Diag<'_>, terr: TypeError<'tcx>) -> bool {
210        match terr {
211            TypeError::Sorts(ref exp_found) => {
212                // if they are both "path types", there's a chance of ambiguity
213                // due to different versions of the same crate
214                if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
215                    (exp_found.expected.kind(), exp_found.found.kind())
216                {
217                    return self.check_same_definition_different_crate(
218                        err,
219                        exp_adt.did(),
220                        [found_adt.did()].into_iter(),
221                        |did| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.tcx.def_span(did)]))vec![self.tcx.def_span(did)],
222                        "type",
223                    );
224                }
225            }
226            TypeError::Traits(ref exp_found) => {
227                return self.check_same_definition_different_crate(
228                    err,
229                    exp_found.expected,
230                    [exp_found.found].into_iter(),
231                    |did| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.tcx.def_span(did)]))vec![self.tcx.def_span(did)],
232                    "trait",
233                );
234            }
235            _ => (), // FIXME(#22750) handle traits and stuff
236        }
237        false
238    }
239
240    fn suggest_param_env_shadowing(
241        &self,
242        diag: &mut Diag<'_>,
243        expected: Ty<'tcx>,
244        found: Ty<'tcx>,
245        param_env: ty::ParamEnv<'tcx>,
246    ) {
247        let (alias, &def_id, concrete) = match (expected.kind(), found.kind()) {
248            (ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { def_id }, .. }), _) => {
249                (proj, def_id, found)
250            }
251            (_, ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { def_id }, .. })) => {
252                (proj, def_id, expected)
253            }
254            _ => return,
255        };
256
257        let tcx = self.tcx;
258
259        let trait_ref = alias.trait_ref(tcx);
260        let obligation =
261            Obligation::new(tcx, ObligationCause::dummy(), param_env, ty::Binder::dummy(trait_ref));
262
263        let applicable_impls =
264            compute_applicable_impls_for_diagnostics(self.infcx, &obligation, false);
265
266        for candidate in applicable_impls {
267            let impl_def_id = match candidate {
268                CandidateSource::DefId(did) => did,
269                CandidateSource::ParamEnv(_) => continue,
270            };
271
272            let is_shadowed = self.infcx.probe(|_| {
273                let impl_substs = self.infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
274                let impl_trait_ref =
275                    tcx.impl_trait_ref(impl_def_id).instantiate(tcx, impl_substs).skip_norm_wip();
276
277                let expected_trait_ref = alias.trait_ref(tcx);
278
279                if let Err(_) = self.infcx.at(&ObligationCause::dummy(), param_env).eq(
280                    DefineOpaqueTypes::No,
281                    expected_trait_ref,
282                    impl_trait_ref,
283                ) {
284                    return false;
285                }
286
287                let leaf_def = match specialization_graph::assoc_def(tcx, impl_def_id, def_id) {
288                    Ok(leaf) => leaf,
289                    Err(_) => return false,
290                };
291
292                let trait_def_id = alias.trait_def_id(tcx);
293                let rebased_args = alias.args.rebase_onto(tcx, trait_def_id, impl_substs);
294
295                // The impl is erroneous missing a definition for the associated type.
296                // Skipping it since calling `TyCtxt::type_of` on its assoc ty will trigger an ICE.
297                if !leaf_def.item.defaultness(tcx).has_value() {
298                    return false;
299                }
300
301                let impl_item_def_id = leaf_def.item.def_id;
302                if !tcx.check_args_compatible(impl_item_def_id, rebased_args) {
303                    return false;
304                }
305                let impl_assoc_ty =
306                    tcx.type_of(impl_item_def_id).instantiate(tcx, rebased_args).skip_norm_wip();
307
308                self.infcx.can_eq(param_env, impl_assoc_ty, concrete)
309            });
310
311            if is_shadowed {
312                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(alias.to_ty(tcx, ty::IsRigid::No)),
                self.ty_to_string(concrete),
                self.ty_to_string(alias.self_ty())))
    })format!(
313                    "the associated type `{}` is defined as `{}` in the implementation, \
314                    but the where-bound `{}` shadows this definition\n\
315                    see issue #152409 <https://github.com/rust-lang/rust/issues/152409> for more information",
316                    self.ty_to_string(alias.to_ty(tcx, ty::IsRigid::No)),
317                    self.ty_to_string(concrete),
318                    self.ty_to_string(alias.self_ty())
319                ));
320                return;
321            }
322        }
323    }
324
325    fn note_error_origin(
326        &self,
327        err: &mut Diag<'_>,
328        cause: &ObligationCause<'tcx>,
329        exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
330        terr: TypeError<'tcx>,
331        param_env: Option<ParamEnv<'tcx>>,
332    ) {
333        match *cause.code() {
334            ObligationCauseCode::Pattern {
335                origin_expr: Some(origin_expr),
336                span: Some(span),
337                root_ty,
338            } => {
339                let expected_ty = self.resolve_vars_if_possible(root_ty);
340                if !#[allow(non_exhaustive_omitted_patterns)] match expected_ty.kind() {
    ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)) => true,
    _ => false,
}matches!(
341                    expected_ty.kind(),
342                    ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_))
343                ) {
344                    // don't show type `_`
345                    if span.desugaring_kind() == Some(DesugaringKind::ForLoop)
346                        && let ty::Adt(def, args) = expected_ty.kind()
347                        && Some(def.did()) == self.tcx.get_diagnostic_item(sym::Option)
348                    {
349                        err.span_label(
350                            span,
351                            ::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)),
352                        );
353                    } else if !span.overlaps(cause.span) {
354                        let expected_ty = self.tcx.short_string(expected_ty, err.long_ty_path());
355                        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}`"));
356                    }
357                }
358                if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
359                    && let Ok(mut peeled_snippet) =
360                        self.tcx.sess.source_map().span_to_snippet(origin_expr.peeled_span)
361                {
362                    // Parentheses are needed for cases like as casts.
363                    // We use the peeled_span for deref suggestions.
364                    // It's also safe to use for box, since box only triggers if there
365                    // wasn't a reference to begin with.
366                    if origin_expr.peeled_prefix_suggestion_parentheses {
367                        peeled_snippet = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})", peeled_snippet))
    })format!("({peeled_snippet})");
368                    }
369
370                    // Try giving a box suggestion first, as it is a special case of the
371                    // deref suggestion.
372                    if expected_ty.boxed_ty() == Some(found) {
373                        err.span_suggestion_verbose(
374                            span,
375                            "consider dereferencing the boxed value",
376                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("*{0}", peeled_snippet))
    })format!("*{peeled_snippet}"),
377                            Applicability::MachineApplicable,
378                        );
379                    } else if let Some(param_env) = param_env
380                        && let Some(prefix) = self.should_deref_suggestion_on_mismatch(
381                            param_env,
382                            found,
383                            expected_ty,
384                            origin_expr,
385                        )
386                    {
387                        err.span_suggestion_verbose(
388                            span,
389                            "consider dereferencing to access the inner value using the `Deref` trait",
390                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", prefix, peeled_snippet))
    })format!("{prefix}{peeled_snippet}"),
391                            Applicability::MaybeIncorrect,
392                        );
393                    }
394                }
395            }
396            ObligationCauseCode::Pattern { origin_expr: None, span: Some(span), .. } => {
397                err.span_label(span, "expected due to this");
398            }
399            ObligationCauseCode::BlockTailExpression(
400                _,
401                hir::MatchSource::TryDesugar(scrut_hir_id),
402            ) => {
403                if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
404                    let scrut_expr = self.tcx.hir_expect_expr(scrut_hir_id);
405                    let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
406                        let arg_expr = args.first().expect("try desugaring call w/out arg");
407                        self.typeck_results
408                            .as_ref()
409                            .and_then(|typeck_results| typeck_results.expr_ty_opt(arg_expr))
410                    } else {
411                        ::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");
412                    };
413
414                    match scrut_ty {
415                        Some(ty) if expected == ty => {
416                            let source_map = self.tcx.sess.source_map();
417                            err.span_suggestion(
418                                source_map.end_point(cause.span),
419                                "try removing this `?`",
420                                "",
421                                Applicability::MachineApplicable,
422                            );
423                        }
424                        _ => {}
425                    }
426                }
427            }
428            ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
429                arm_block_id,
430                arm_span,
431                arm_ty,
432                prior_arm_block_id,
433                prior_arm_span,
434                prior_arm_ty,
435                source,
436                ref prior_non_diverging_arms,
437                scrut_span,
438                expr_span,
439                ..
440            }) => match source {
441                hir::MatchSource::TryDesugar(scrut_hir_id) => {
442                    if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
443                        let scrut_expr = self.tcx.hir_expect_expr(scrut_hir_id);
444                        let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
445                            let arg_expr = args.first().expect("try desugaring call w/out arg");
446                            self.typeck_results
447                                .as_ref()
448                                .and_then(|typeck_results| typeck_results.expr_ty_opt(arg_expr))
449                        } else {
450                            ::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");
451                        };
452
453                        match scrut_ty {
454                            Some(ty) if expected == ty => {
455                                let source_map = self.tcx.sess.source_map();
456                                err.span_suggestion(
457                                    source_map.end_point(cause.span),
458                                    "try removing this `?`",
459                                    "",
460                                    Applicability::MachineApplicable,
461                                );
462                            }
463                            _ => {}
464                        }
465                    }
466                }
467                _ => {
468                    // `prior_arm_ty` can be `!`, `expected` will have better info when present.
469                    let t = self.resolve_vars_if_possible(match exp_found {
470                        Some(ty::error::ExpectedFound { expected, .. }) => expected,
471                        _ => prior_arm_ty,
472                    });
473                    let source_map = self.tcx.sess.source_map();
474                    let mut any_multiline_arm = source_map.is_multiline(arm_span);
475                    if prior_non_diverging_arms.len() <= 4 {
476                        for sp in prior_non_diverging_arms {
477                            any_multiline_arm |= source_map.is_multiline(*sp);
478                            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}`"));
479                        }
480                    } else if let Some(sp) = prior_non_diverging_arms.last() {
481                        any_multiline_arm |= source_map.is_multiline(*sp);
482                        err.span_label(
483                            *sp,
484                            ::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}`"),
485                        );
486                    }
487                    let outer = if any_multiline_arm || !source_map.is_multiline(expr_span) {
488                        // Cover just `match` and the scrutinee expression, not
489                        // the entire match body, to reduce diagram noise.
490                        expr_span.shrink_to_lo().to(scrut_span)
491                    } else {
492                        expr_span
493                    };
494                    let msg = "`match` arms have incompatible types";
495                    err.span_label(outer, msg);
496                    if let Some(subdiag) = self.suggest_remove_semi_or_return_binding(
497                        prior_arm_block_id,
498                        prior_arm_ty,
499                        prior_arm_span,
500                        arm_block_id,
501                        arm_ty,
502                        arm_span,
503                    ) {
504                        err.subdiagnostic(subdiag);
505                    }
506                }
507            },
508            ObligationCauseCode::IfExpression { expr_id, .. } => {
509                let hir::Node::Expr(&hir::Expr {
510                    kind: hir::ExprKind::If(cond_expr, then_expr, Some(else_expr)),
511                    span: expr_span,
512                    ..
513                }) = self.tcx.hir_node(expr_id)
514                else {
515                    return;
516                };
517                let then_span = self.find_block_span_from_hir_id(then_expr.hir_id);
518                let then_ty = self
519                    .typeck_results
520                    .as_ref()
521                    .expect("if expression only expected inside FnCtxt")
522                    .expr_ty(then_expr);
523                let else_span = self.find_block_span_from_hir_id(else_expr.hir_id);
524                let else_ty = self
525                    .typeck_results
526                    .as_ref()
527                    .expect("if expression only expected inside FnCtxt")
528                    .expr_ty(else_expr);
529                if let hir::ExprKind::If(_cond, _then, None) = else_expr.kind
530                    && else_ty.is_unit()
531                {
532                    // Account for `let x = if a { 1 } else if b { 2 };`
533                    err.note("`if` expressions without `else` evaluate to `()`");
534                    err.note("consider adding an `else` block that evaluates to the expected type");
535                }
536                err.span_label(then_span, "expected because of this");
537
538                let outer_span = if self.tcx.sess.source_map().is_multiline(expr_span) {
539                    if then_span.hi() == expr_span.hi() || else_span.hi() == expr_span.hi() {
540                        // Point at condition only if either block has the same end point as
541                        // the whole expression, since that'll cause awkward overlapping spans.
542                        Some(expr_span.shrink_to_lo().to(cond_expr.peel_drop_temps().span))
543                    } else {
544                        Some(expr_span)
545                    }
546                } else {
547                    None
548                };
549                if let Some(sp) = outer_span {
550                    err.span_label(sp, "`if` and `else` have incompatible types");
551                }
552
553                let then_id = if let hir::ExprKind::Block(then_blk, _) = then_expr.kind {
554                    then_blk.hir_id
555                } else {
556                    then_expr.hir_id
557                };
558                let else_id = if let hir::ExprKind::Block(else_blk, _) = else_expr.kind {
559                    else_blk.hir_id
560                } else {
561                    else_expr.hir_id
562                };
563                if let Some(subdiag) = self.suggest_remove_semi_or_return_binding(
564                    Some(then_id),
565                    then_ty,
566                    then_span,
567                    Some(else_id),
568                    else_ty,
569                    else_span,
570                ) {
571                    err.subdiagnostic(subdiag);
572                }
573            }
574            ObligationCauseCode::LetElse => {
575                err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
576                err.help("...or use `match` instead of `let...else`");
577            }
578            _ => {
579                if let ObligationCauseCode::WhereClause(_, span)
580                | ObligationCauseCode::WhereClauseInExpr(_, span, ..) =
581                    cause.code().peel_derives()
582                    && !span.is_dummy()
583                    && let TypeError::RegionsPlaceholderMismatch = terr
584                {
585                    err.span_note(*span, "the lifetime requirement is introduced here");
586                }
587            }
588        }
589    }
590
591    /// Determines whether deref_to == <deref_from as Deref>::Target, and if so,
592    /// returns a prefix that should be added to deref_from as a suggestion.
593    fn should_deref_suggestion_on_mismatch(
594        &self,
595        param_env: ParamEnv<'tcx>,
596        deref_to: Ty<'tcx>,
597        deref_from: Ty<'tcx>,
598        origin_expr: PatternOriginExpr,
599    ) -> Option<String> {
600        // origin_expr contains stripped away versions of our expression.
601        // We'll want to use that to avoid suggesting things like *&x.
602        // However, the type that we have access to hasn't been stripped away,
603        // so we need to ignore the first n dereferences, where n is the number
604        // that's been stripped away in origin_expr.
605
606        // Find a way to autoderef from deref_from to deref_to.
607        let Some((num_derefs, (after_deref_ty, _))) = (self.autoderef_steps)(deref_from)
608            .into_iter()
609            .enumerate()
610            .find(|(_, (ty, _))| self.infcx.can_eq(param_env, *ty, deref_to))
611        else {
612            return None;
613        };
614
615        if num_derefs <= origin_expr.peeled_count {
616            return None;
617        }
618
619        let deref_part = "*".repeat(num_derefs - origin_expr.peeled_count);
620
621        // If the user used a reference in the original expression, they probably
622        // want the suggestion to still give a reference.
623        if deref_from.is_ref() && !after_deref_ty.is_ref() {
624            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", deref_part))
    })format!("&{deref_part}"))
625        } else {
626            Some(deref_part)
627        }
628    }
629
630    /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
631    /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
632    /// populate `other_value` with `other_ty`.
633    ///
634    /// ```text
635    /// Foo<Bar<Qux>>
636    /// ^^^^--------^ this is highlighted
637    /// |   |
638    /// |   this type argument is exactly the same as the other type, not highlighted
639    /// this is highlighted
640    /// Bar<Qux>
641    /// -------- this type is the same as a type argument in the other type, not highlighted
642    /// ```
643    fn highlight_outer(
644        &self,
645        value: &mut DiagStyledString,
646        other_value: &mut DiagStyledString,
647        name: String,
648        args: &[ty::GenericArg<'tcx>],
649        pos: usize,
650        other_ty: Ty<'tcx>,
651    ) {
652        // `value` and `other_value` hold two incomplete type representation for display.
653        // `name` is the path of both types being compared. `sub`
654        value.push_highlighted(name);
655
656        if args.is_empty() {
657            return;
658        }
659        value.push_highlighted("<");
660
661        for (i, arg) in args.iter().enumerate() {
662            if i > 0 {
663                value.push_normal(", ");
664            }
665
666            match arg.kind() {
667                ty::GenericArgKind::Lifetime(lt) => {
668                    let s = lt.to_string();
669                    value.push_normal(if s.is_empty() { "'_" } else { &s });
670                }
671                ty::GenericArgKind::Const(ct) => {
672                    value.push_normal(ct.to_string());
673                }
674                // Highlight all the type arguments that aren't at `pos` and compare
675                // the type argument at `pos` and `other_ty`.
676                ty::GenericArgKind::Type(type_arg) => {
677                    if i == pos {
678                        let values = self.cmp(type_arg, other_ty);
679                        value.0.extend((values.0).0);
680                        other_value.0.extend((values.1).0);
681                    } else {
682                        value.push_highlighted(type_arg.to_string());
683                    }
684                }
685            }
686        }
687
688        value.push_highlighted(">");
689    }
690
691    /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
692    /// as that is the difference to the other type.
693    ///
694    /// For the following code:
695    ///
696    /// ```ignore (illustrative)
697    /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
698    /// ```
699    ///
700    /// The type error output will behave in the following way:
701    ///
702    /// ```text
703    /// Foo<Bar<Qux>>
704    /// ^^^^--------^ this is highlighted
705    /// |   |
706    /// |   this type argument is exactly the same as the other type, not highlighted
707    /// this is highlighted
708    /// Bar<Qux>
709    /// -------- this type is the same as a type argument in the other type, not highlighted
710    /// ```
711    fn cmp_type_arg(
712        &self,
713        t1_out: &mut DiagStyledString,
714        t2_out: &mut DiagStyledString,
715        path: String,
716        args: &'tcx [ty::GenericArg<'tcx>],
717        other_path: String,
718        other_ty: Ty<'tcx>,
719    ) -> bool {
720        for (i, arg) in args.iter().enumerate() {
721            if let Some(ta) = arg.as_type() {
722                if ta == other_ty {
723                    self.highlight_outer(t1_out, t2_out, path, args, i, other_ty);
724                    return true;
725                }
726                if let ty::Adt(def, _) = ta.kind() {
727                    let path_ = self.tcx.def_path_str(def.did());
728                    if path_ == other_path {
729                        self.highlight_outer(t1_out, t2_out, path, args, i, other_ty);
730                        return true;
731                    }
732                }
733            }
734        }
735        false
736    }
737
738    /// Adds a `,` to the type representation only if it is appropriate.
739    fn push_comma(
740        &self,
741        value: &mut DiagStyledString,
742        other_value: &mut DiagStyledString,
743        pos: usize,
744    ) {
745        if pos > 0 {
746            value.push_normal(", ");
747            other_value.push_normal(", ");
748        }
749    }
750
751    /// Given two `fn` signatures highlight only sub-parts that are different.
752    fn cmp_fn_sig(
753        &self,
754        sig1: ty::PolyFnSig<'tcx>,
755        fn_def1: Option<(DefId, Option<&'tcx [ty::GenericArg<'tcx>]>)>,
756        sig2: ty::PolyFnSig<'tcx>,
757        fn_def2: Option<(DefId, Option<&'tcx [ty::GenericArg<'tcx>]>)>,
758    ) -> (DiagStyledString, DiagStyledString) {
759        let sig1 = self.normalize_fn_sig(Unnormalized::new_wip(sig1));
760        let sig2 = self.normalize_fn_sig(Unnormalized::new_wip(sig2));
761
762        let get_lifetimes = |sig| {
763            use rustc_hir::def::Namespace;
764            let (sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS)
765                .name_all_regions(&sig, WrapBinderMode::ForAll)
766                .unwrap();
767            let lts: Vec<String> =
768                reg.into_items().map(|(_, kind)| kind.to_string()).into_sorted_stable_ord();
769            (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)
770        };
771
772        let (lt1, sig1) = get_lifetimes(sig1);
773        let (lt2, sig2) = get_lifetimes(sig2);
774
775        // #[target_feature(..)] for<'a> unsafe extern "C" fn(&'a T) -> &'a T
776        let mut values =
777            (DiagStyledString::normal("".to_string()), DiagStyledString::normal("".to_string()));
778
779        // #[target_feature(..)] for<'a> unsafe extern "C" fn(&'a T) -> &'a T
780        // ^^^^^^^^^^^^^^^^^^^^^
781        let fn_item_prefix_and_safety = |fn_def, sig: ty::FnSig<'_>| match fn_def {
782            None => ("", sig.safety().prefix_str()),
783            Some((did, _)) => {
784                if self.tcx.codegen_fn_attrs(did).safe_target_features {
785                    ("#[target_feature(..)] ", "")
786                } else {
787                    ("", sig.safety().prefix_str())
788                }
789            }
790        };
791        let (prefix1, safety1) = fn_item_prefix_and_safety(fn_def1, sig1);
792        let (prefix2, safety2) = fn_item_prefix_and_safety(fn_def2, sig2);
793        values.0.push(prefix1, prefix1 != prefix2);
794        values.1.push(prefix2, prefix1 != prefix2);
795
796        // #[target_feature(..)] for<'a> unsafe extern "C" fn(&'a T) -> &'a T
797        //                       ^^^^^^^^
798        let lifetime_diff = lt1 != lt2;
799        values.0.push(lt1, lifetime_diff);
800        values.1.push(lt2, lifetime_diff);
801
802        // #[target_feature(..)] for<'a> unsafe extern "C" fn(&'a T) -> &'a T
803        //                               ^^^^^^
804        values.0.push(safety1, safety1 != safety2);
805        values.1.push(safety2, safety1 != safety2);
806
807        // #[target_feature(..)] for<'a> unsafe extern "C" fn(&'a T) -> &'a T
808        //                                      ^^^^^^^^^^
809        if sig1.abi() != ExternAbi::Rust {
810            values.0.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("extern {0} ", sig1.abi()))
    })format!("extern {} ", sig1.abi()), sig1.abi() != sig2.abi());
811        }
812        if sig2.abi() != ExternAbi::Rust {
813            values.1.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("extern {0} ", sig2.abi()))
    })format!("extern {} ", sig2.abi()), sig1.abi() != sig2.abi());
814        }
815
816        // #[target_feature(..)] for<'a> unsafe extern "C" fn(&'a T) -> &'a T
817        //                                                 ^^^
818        values.0.push_normal("fn(");
819        values.1.push_normal("fn(");
820
821        // #[target_feature(..)] for<'a> unsafe extern "C" fn(&'a T) -> &'a T
822        //                                                    ^^^^^
823        let len1 = sig1.inputs().len();
824        let len2 = sig2.inputs().len();
825        let splatted_arg_index1 = sig1.splatted().map(usize::from);
826        let splatted_arg_index2 = sig2.splatted().map(usize::from);
827        if len1 == len2 {
828            for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
829                self.push_comma(&mut values.0, &mut values.1, i);
830                if Some(i) == splatted_arg_index1 {
831                    values.0.push("#[rustc_splat]", splatted_arg_index1 != splatted_arg_index2);
832                    values.0.push_normal(" ");
833                }
834                if Some(i) == splatted_arg_index2 {
835                    values.1.push("#[rustc_splat]", splatted_arg_index1 != splatted_arg_index2);
836                    values.1.push_normal(" ");
837                }
838                let (x1, x2) = self.cmp(*l, *r);
839                (values.0).0.extend(x1.0);
840                (values.1).0.extend(x2.0);
841            }
842        } else {
843            for (i, l) in sig1.inputs().iter().enumerate() {
844                values.0.push_highlighted(l.to_string());
845                if i != len1 - 1 {
846                    values.0.push_highlighted(", ");
847                }
848            }
849            for (i, r) in sig2.inputs().iter().enumerate() {
850                values.1.push_highlighted(r.to_string());
851                if i != len2 - 1 {
852                    values.1.push_highlighted(", ");
853                }
854            }
855        }
856
857        if sig1.c_variadic() {
858            if len1 > 0 {
859                values.0.push_normal(", ");
860            }
861            values.0.push("...", !sig2.c_variadic());
862        }
863        if sig2.c_variadic() {
864            if len2 > 0 {
865                values.1.push_normal(", ");
866            }
867            values.1.push("...", !sig1.c_variadic());
868        }
869
870        // #[target_feature(..)] for<'a> unsafe extern "C" fn(&'a T) -> &'a T
871        //                                                         ^
872        values.0.push_normal(")");
873        values.1.push_normal(")");
874
875        // #[target_feature(..)] for<'a> unsafe extern "C" fn(&'a T) -> &'a T
876        //                                                           ^^^^^^^^
877        let output1 = sig1.output();
878        let output2 = sig2.output();
879        let (x1, x2) = self.cmp(output1, output2);
880        let output_diff = x1 != x2;
881        if !output1.is_unit() || output_diff {
882            values.0.push_normal(" -> ");
883            (values.0).0.extend(x1.0);
884        }
885        if !output2.is_unit() || output_diff {
886            values.1.push_normal(" -> ");
887            (values.1).0.extend(x2.0);
888        }
889
890        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));
891
892        match (fn_def1, fn_def2) {
893            (Some((fn_def1, Some(fn_args1))), Some((fn_def2, Some(fn_args2)))) => {
894                let path1 = fmt(fn_def1, fn_args1);
895                let path2 = fmt(fn_def2, fn_args2);
896                let same_path = path1 == path2;
897                values.0.push(path1, !same_path);
898                values.1.push(path2, !same_path);
899            }
900            (Some((fn_def1, Some(fn_args1))), None) => {
901                values.0.push_highlighted(fmt(fn_def1, fn_args1));
902            }
903            (None, Some((fn_def2, Some(fn_args2)))) => {
904                values.1.push_highlighted(fmt(fn_def2, fn_args2));
905            }
906            _ => {}
907        }
908
909        values
910    }
911
912    pub fn cmp_traits(
913        &self,
914        def_id1: DefId,
915        args1: &[ty::GenericArg<'tcx>],
916        def_id2: DefId,
917        args2: &[ty::GenericArg<'tcx>],
918    ) -> (DiagStyledString, DiagStyledString) {
919        let mut values = (DiagStyledString::new(), DiagStyledString::new());
920
921        if def_id1 != def_id2 {
922            values.0.push_highlighted(self.tcx.def_path_str(def_id1).as_str());
923            values.1.push_highlighted(self.tcx.def_path_str(def_id2).as_str());
924        } else {
925            values.0.push_normal(self.tcx.item_name(def_id1).as_str());
926            values.1.push_normal(self.tcx.item_name(def_id2).as_str());
927        }
928
929        if args1.len() != args2.len() {
930            let (pre, post) = if args1.len() > 0 { ("<", ">") } else { ("", "") };
931            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!(
932                "{pre}{}{post}",
933                args1.iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ")
934            ));
935            let (pre, post) = if args2.len() > 0 { ("<", ">") } else { ("", "") };
936            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!(
937                "{pre}{}{post}",
938                args2.iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ")
939            ));
940            return values;
941        }
942
943        if args1.len() > 0 {
944            values.0.push_normal("<");
945            values.1.push_normal("<");
946        }
947        for (i, (a, b)) in std::iter::zip(args1, args2).enumerate() {
948            let a_str = a.to_string();
949            let b_str = b.to_string();
950            if let (Some(a), Some(b)) = (a.as_type(), b.as_type()) {
951                let (a, b) = self.cmp(a, b);
952                values.0.0.extend(a.0);
953                values.1.0.extend(b.0);
954            } else if a_str != b_str {
955                values.0.push_highlighted(a_str);
956                values.1.push_highlighted(b_str);
957            } else {
958                values.0.push_normal(a_str);
959                values.1.push_normal(b_str);
960            }
961            if i + 1 < args1.len() {
962                values.0.push_normal(", ");
963                values.1.push_normal(", ");
964            }
965        }
966        if args1.len() > 0 {
967            values.0.push_normal(">");
968            values.1.push_normal(">");
969        }
970        values
971    }
972
973    fn lifetime_display(&self, lifetime: Region<'_>) -> String {
974        let s = lifetime.to_string();
975        if s.is_empty() { "'_".to_string() } else { s }
976    }
977
978    fn compare_generics(
979        &self,
980        mut values: &mut (DiagStyledString, DiagStyledString),
981        sub1: &[ty::GenericArg<'tcx>],
982        sub2: &[ty::GenericArg<'tcx>],
983    ) {
984        let len = sub1.len();
985        // Only draw `<...>` if there are lifetime/type arguments.
986        if sub1.len() > 0 {
987            values.0.push_normal("<");
988        }
989        if sub2.len() > 0 {
990            values.1.push_normal("<");
991        }
992
993        if sub1.len() == sub2.len() {
994            for (i, (arg1, arg2)) in sub1.iter().zip(sub2).enumerate().take(len) {
995                self.push_comma(&mut values.0, &mut values.1, i);
996                match (arg1.kind(), arg2.kind()) {
997                    // At one point we'd like to elide all lifetimes here, they are
998                    // irrelevant for all diagnostics that use this output.
999                    //
1000                    //     Foo<'x, '_, Bar>
1001                    //     Foo<'y, '_, Qux>
1002                    //         ^^  ^^  --- type arguments are not elided
1003                    //         |   |
1004                    //         |   elided as they were the same
1005                    //         not elided, they were different, but irrelevant
1006                    //
1007                    // For bound lifetimes, keep the names of the lifetimes,
1008                    // even if they are the same so that it's clear what's happening
1009                    // if we have something like
1010                    //
1011                    // for<'r, 's> fn(Inv<'r>, Inv<'s>)
1012                    // for<'r> fn(Inv<'r>, Inv<'r>)
1013                    (ty::GenericArgKind::Lifetime(l1), ty::GenericArgKind::Lifetime(l2)) => {
1014                        let l1_str = self.lifetime_display(l1);
1015                        let l2_str = self.lifetime_display(l2);
1016                        if l1 != l2 {
1017                            values.0.push_highlighted(l1_str);
1018                            values.1.push_highlighted(l2_str);
1019                        } else if l1.is_bound() || self.tcx.sess.opts.verbose {
1020                            values.0.push_normal(l1_str);
1021                            values.1.push_normal(l2_str);
1022                        } else {
1023                            values.0.push_normal("'_");
1024                            values.1.push_normal("'_");
1025                        }
1026                    }
1027                    (ty::GenericArgKind::Type(ta1), ty::GenericArgKind::Type(ta2)) => {
1028                        if ta1 == ta2 && !self.tcx.sess.opts.verbose {
1029                            values.0.push_normal("_");
1030                            values.1.push_normal("_");
1031                        } else {
1032                            self.recurse(ta1, ta2, &mut values);
1033                        }
1034                    }
1035                    // We're comparing two types with the same path, so we compare the type
1036                    // arguments for both. If they are the same, do not highlight and elide
1037                    // from the output.
1038                    //     Foo<_, Bar>
1039                    //     Foo<_, Qux>
1040                    //         ^ elided type as this type argument was the same in both sides
1041
1042                    // Do the same for const arguments, if they are equal, do not highlight and
1043                    // elide them from the output.
1044                    (ty::GenericArgKind::Const(ca1), ty::GenericArgKind::Const(ca2)) => {
1045                        self.maybe_highlight(ca1, ca2, &mut values, self.tcx);
1046                    }
1047                    // The two params are of different kinds. We don't highlight because the problem
1048                    // is not with these arguments, but rather with the type containing them.
1049                    _ => {
1050                        values.0.push_normal(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", arg1))
    })format!("{arg1}"));
1051                        values.1.push_normal(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", arg2))
    })format!("{arg2}"));
1052                    }
1053                }
1054            }
1055        } else {
1056            // The argument count is different on both sides, highlight both sides
1057            for (value, args) in [(&mut values.0, sub1), (&mut values.1, sub2)] {
1058                for (i, arg) in args.iter().enumerate() {
1059                    if i > 0 {
1060                        value.push_normal(", ");
1061                    }
1062                    match arg.kind() {
1063                        ty::GenericArgKind::Lifetime(l) => {
1064                            let l_str = self.lifetime_display(l);
1065                            if l.is_bound() || self.tcx.sess.opts.verbose {
1066                                value.push_normal(l_str);
1067                            } else {
1068                                value.push_normal("'_");
1069                            }
1070                        }
1071                        ty::GenericArgKind::Type(ty) => {
1072                            if !self.tcx.sess.opts.verbose {
1073                                value.push_normal("_");
1074                            } else {
1075                                value.push_normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}", ty)) })format!("{ty}"));
1076                            }
1077                        }
1078                        ty::GenericArgKind::Const(ca) => {
1079                            value.push_normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}", ca)) })format!("{ca}"));
1080                        }
1081                    }
1082                }
1083            }
1084        }
1085
1086        // Close the type argument bracket.
1087        // Only draw `<...>` if there are arguments.
1088        if sub1.len() > 0 {
1089            values.0.push_normal(">");
1090        }
1091        if sub2.len() > 0 {
1092            values.1.push_normal(">");
1093        }
1094    }
1095
1096    fn recurse(
1097        &self,
1098        t1: Ty<'tcx>,
1099        t2: Ty<'tcx>,
1100        values: &mut (DiagStyledString, DiagStyledString),
1101    ) {
1102        let (x1, x2) = self.cmp(t1, t2);
1103        (values.0).0.extend(x1.0);
1104        (values.1).0.extend(x2.0);
1105    }
1106
1107    fn maybe_highlight<T: Eq + ToString>(
1108        &self,
1109        t1: T,
1110        t2: T,
1111        (buf1, buf2): &mut (DiagStyledString, DiagStyledString),
1112        tcx: TyCtxt<'_>,
1113    ) {
1114        let highlight = t1 != t2;
1115        let (t1, t2) = if highlight || tcx.sess.opts.verbose {
1116            (t1.to_string(), t2.to_string())
1117        } else {
1118            // The two types are the same, elide and don't highlight.
1119            ("_".into(), "_".into())
1120        };
1121        buf1.push(t1, highlight);
1122        buf2.push(t2, highlight);
1123    }
1124
1125    /// Compares two given types, eliding parts that are the same between them and highlighting
1126    /// relevant differences, and return two representation of those types for highlighted printing.
1127    pub fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagStyledString, DiagStyledString) {
1128        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1128",
                        "rustc_trait_selection::error_reporting::infer",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1128u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
            });
    } else { ; }
};debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1129
1130        // helper functions
1131        fn fmt_region<'tcx>(region: ty::Region<'tcx>) -> String {
1132            let mut r = region.to_string();
1133            if r == "'_" {
1134                r.clear();
1135            } else {
1136                r.push(' ');
1137            }
1138            ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", r)) })format!("&{r}")
1139        }
1140
1141        fn push_ref<'tcx>(
1142            region: ty::Region<'tcx>,
1143            mutbl: hir::Mutability,
1144            s: &mut DiagStyledString,
1145        ) {
1146            s.push_highlighted(fmt_region(region));
1147            s.push_highlighted(mutbl.prefix_str());
1148        }
1149
1150        fn cmp_ty_refs<'tcx>(
1151            r1: ty::Region<'tcx>,
1152            mut1: hir::Mutability,
1153            r2: ty::Region<'tcx>,
1154            mut2: hir::Mutability,
1155            ss: &mut (DiagStyledString, DiagStyledString),
1156        ) {
1157            let (r1, r2) = (fmt_region(r1), fmt_region(r2));
1158            if r1 != r2 {
1159                ss.0.push_highlighted(r1);
1160                ss.1.push_highlighted(r2);
1161            } else {
1162                ss.0.push_normal(r1);
1163                ss.1.push_normal(r2);
1164            }
1165
1166            if mut1 != mut2 {
1167                ss.0.push_highlighted(mut1.prefix_str());
1168                ss.1.push_highlighted(mut2.prefix_str());
1169            } else {
1170                ss.0.push_normal(mut1.prefix_str());
1171                ss.1.push_normal(mut2.prefix_str());
1172            }
1173        }
1174
1175        // process starts here
1176        match (t1.kind(), t2.kind()) {
1177            (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1178                let did1 = def1.did();
1179                let did2 = def2.did();
1180
1181                let generics1 = self.tcx.generics_of(did1);
1182                let generics2 = self.tcx.generics_of(did2);
1183
1184                let non_default_after_default = generics1
1185                    .check_concrete_type_after_default(self.tcx, sub1)
1186                    || generics2.check_concrete_type_after_default(self.tcx, sub2);
1187                let sub_no_defaults_1 = if non_default_after_default {
1188                    generics1.own_args(sub1)
1189                } else {
1190                    generics1.own_args_no_defaults(self.tcx, sub1)
1191                };
1192                let sub_no_defaults_2 = if non_default_after_default {
1193                    generics2.own_args(sub2)
1194                } else {
1195                    generics2.own_args_no_defaults(self.tcx, sub2)
1196                };
1197                let mut values = (DiagStyledString::new(), DiagStyledString::new());
1198                let path1 = self.tcx.def_path_str(did1);
1199                let path2 = self.tcx.def_path_str(did2);
1200                if did1 == did2 {
1201                    // Easy case. Replace same types with `_` to shorten the output and highlight
1202                    // the differing ones.
1203                    //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1204                    //     Foo<Bar, _>
1205                    //     Foo<Quz, _>
1206                    //         ---  ^ type argument elided
1207                    //         |
1208                    //         highlighted in output
1209                    values.0.push_normal(self.tcx.item_name(did1).to_string());
1210                    values.1.push_normal(self.tcx.item_name(did2).to_string());
1211
1212                    // Avoid printing out default generic parameters that are common to both
1213                    // types.
1214                    let len1 = sub_no_defaults_1.len();
1215                    let len2 = sub_no_defaults_2.len();
1216                    let common_len = cmp::min(len1, len2);
1217                    let remainder1 = &sub1[common_len..];
1218                    let remainder2 = &sub2[common_len..];
1219                    let common_default_params =
1220                        iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1221                            .filter(|(a, b)| a == b)
1222                            .count();
1223                    let len = sub1.len() - common_default_params;
1224                    self.compare_generics(&mut values, &sub1[..len], &sub2[..len]);
1225                    values
1226                } else {
1227                    // Check for case:
1228                    //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1229                    //     Foo<Bar<Qux>
1230                    //         ------- this type argument is exactly the same as the other type
1231                    //     Bar<Qux>
1232                    if self.cmp_type_arg(
1233                        &mut values.0,
1234                        &mut values.1,
1235                        path1.clone(),
1236                        sub_no_defaults_1,
1237                        path2.clone(),
1238                        t2,
1239                    ) {
1240                        return values;
1241                    }
1242                    // Check for case:
1243                    //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1244                    //     Bar<Qux>
1245                    //     Foo<Bar<Qux>>
1246                    //         ------- this type argument is exactly the same as the other type
1247                    if self.cmp_type_arg(
1248                        &mut values.1,
1249                        &mut values.0,
1250                        path2,
1251                        sub_no_defaults_2,
1252                        path1,
1253                        t1,
1254                    ) {
1255                        return values;
1256                    }
1257
1258                    // We can't find anything in common, highlight relevant part of type path.
1259                    //     let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1260                    //     foo::bar::Baz<Qux>
1261                    //     foo::bar::Bar<Zar>
1262                    //               -------- this part of the path is different
1263
1264                    let t1_str = t1.to_string();
1265                    let t2_str = t2.to_string();
1266                    let min_len = t1_str.len().min(t2_str.len());
1267
1268                    const SEPARATOR: &str = "::";
1269                    let separator_len = SEPARATOR.len();
1270                    let split_idx: usize =
1271                        iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1272                            .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1273                            .map(|(mod_str, _)| mod_str.len() + separator_len)
1274                            .sum();
1275
1276                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1276",
                        "rustc_trait_selection::error_reporting::infer",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1276u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("separator_len")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("separator_len");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("split_idx")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("split_idx");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("min_len")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("min_len");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("cmp")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&separator_len)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&split_idx)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&min_len)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?separator_len, ?split_idx, ?min_len, "cmp");
1277
1278                    if split_idx >= min_len {
1279                        // paths are identical, highlight everything
1280                        (
1281                            DiagStyledString::highlighted(t1_str),
1282                            DiagStyledString::highlighted(t2_str),
1283                        )
1284                    } else {
1285                        let (common, uniq1) = t1_str.split_at(split_idx);
1286                        let (_, uniq2) = t2_str.split_at(split_idx);
1287                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1287",
                        "rustc_trait_selection::error_reporting::infer",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1287u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("common")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("common");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("uniq1")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("uniq1");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("uniq2")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("uniq2");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("cmp")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&common)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&uniq1)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&uniq2)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?common, ?uniq1, ?uniq2, "cmp");
1288
1289                        values.0.push_normal(common);
1290                        values.0.push_highlighted(uniq1);
1291                        values.1.push_normal(common);
1292                        values.1.push_highlighted(uniq2);
1293
1294                        values
1295                    }
1296                }
1297            }
1298
1299            // When finding `&T != &T`, compare the references, then recurse into pointee type
1300            (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2)) => {
1301                let mut values = (DiagStyledString::new(), DiagStyledString::new());
1302                cmp_ty_refs(r1, mutbl1, r2, mutbl2, &mut values);
1303                self.recurse(ref_ty1, ref_ty2, &mut values);
1304                values
1305            }
1306            // When finding T != &T, highlight the borrow
1307            (&ty::Ref(r1, ref_ty1, mutbl1), _) => {
1308                let mut values = (DiagStyledString::new(), DiagStyledString::new());
1309                push_ref(r1, mutbl1, &mut values.0);
1310                self.recurse(ref_ty1, t2, &mut values);
1311                values
1312            }
1313            (_, &ty::Ref(r2, ref_ty2, mutbl2)) => {
1314                let mut values = (DiagStyledString::new(), DiagStyledString::new());
1315                push_ref(r2, mutbl2, &mut values.1);
1316                self.recurse(t1, ref_ty2, &mut values);
1317                values
1318            }
1319
1320            // When encountering tuples of the same size, highlight only the differing types
1321            (&ty::Tuple(args1), &ty::Tuple(args2)) if args1.len() == args2.len() => {
1322                let mut values = (DiagStyledString::normal("("), DiagStyledString::normal("("));
1323                let len = args1.len();
1324                for (i, (left, right)) in args1.iter().zip(args2).enumerate() {
1325                    self.push_comma(&mut values.0, &mut values.1, i);
1326                    self.recurse(left, right, &mut values);
1327                }
1328                if len == 1 {
1329                    // Keep the output for single element tuples as `(ty,)`.
1330                    values.0.push_normal(",");
1331                    values.1.push_normal(",");
1332                }
1333                values.0.push_normal(")");
1334                values.1.push_normal(")");
1335                values
1336            }
1337
1338            (ty::FnDef(did1, args1), ty::FnDef(did2, args2)) => {
1339                let args1 = args1.no_bound_vars().unwrap();
1340                let args2 = args2.no_bound_vars().unwrap();
1341
1342                let sig1 = self.tcx.fn_sig(*did1).instantiate(self.tcx, args1).skip_norm_wip();
1343                let sig2 = self.tcx.fn_sig(*did2).instantiate(self.tcx, args2).skip_norm_wip();
1344                self.cmp_fn_sig(sig1, Some((*did1, Some(args1))), sig2, Some((*did2, Some(args2))))
1345            }
1346
1347            (ty::FnDef(did1, args1), ty::FnPtr(sig_tys2, hdr2)) => {
1348                let args1 = args1.no_bound_vars().unwrap();
1349                let sig1 = self.tcx.fn_sig(*did1).instantiate(self.tcx, args1).skip_norm_wip();
1350                self.cmp_fn_sig(sig1, Some((*did1, Some(args1))), sig_tys2.with(*hdr2), None)
1351            }
1352
1353            (ty::FnPtr(sig_tys1, hdr1), ty::FnDef(did2, args2)) => {
1354                let args2 = args2.no_bound_vars().unwrap();
1355
1356                let sig2 = self.tcx.fn_sig(*did2).instantiate(self.tcx, args2).skip_norm_wip();
1357                self.cmp_fn_sig(sig_tys1.with(*hdr1), None, sig2, Some((*did2, Some(args2))))
1358            }
1359
1360            (ty::FnPtr(sig_tys1, hdr1), ty::FnPtr(sig_tys2, hdr2)) => {
1361                self.cmp_fn_sig(sig_tys1.with(*hdr1), None, sig_tys2.with(*hdr2), None)
1362            }
1363
1364            (ty::Alias(kind1, alias1), ty::Alias(kind2, alias2))
1365                if kind1 == kind2 && alias1 == alias2 && !self.tcx.sess.opts.verbose =>
1366            {
1367                let mut strs = (DiagStyledString::new(), DiagStyledString::new());
1368                strs.0.push_normal("_");
1369                strs.1.push_normal("_");
1370                strs
1371            }
1372
1373            (ty::Alias(kind1, alias1), ty::Alias(kind2, alias2)) if kind1 == kind2 => {
1374                let mut values = (DiagStyledString::new(), DiagStyledString::new());
1375                match (alias1.kind, alias2.kind) {
1376                    (ty::Projection { def_id: def_id1 }, ty::Projection { def_id: def_id2 })
1377                        // RPITIT projections use anonymous associated type and have no item name,
1378                        // so it will be ICE from call of `tcx.item_name(def_id)` below, issue #161915.
1379                        if !self.tcx.is_impl_trait_in_trait(def_id1)
1380                            && !self.tcx.is_impl_trait_in_trait(def_id2) =>
1381                    {
1382                        // `<Type as Trait>::Name<args>`
1383                        values.0.push_normal("<");
1384                        values.1.push_normal("<");
1385                        let (trait_ref1, args1) = alias1.trait_ref_and_own_args(self.tcx);
1386                        let (trait_ref2, args2) = alias2.trait_ref_and_own_args(self.tcx);
1387                        self.recurse(trait_ref1.self_ty(), trait_ref2.self_ty(), &mut values);
1388
1389                        values.0.push_normal(" as ");
1390                        values.1.push_normal(" as ");
1391                        if trait_ref1.def_id == trait_ref2.def_id {
1392                            if self.tcx.sess.opts.verbose {
1393                                values
1394                                    .0
1395                                    .push_normal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}",
                trait_ref1.print_only_trait_name()))
    })format!("{}", trait_ref1.print_only_trait_name()));
1396                                values
1397                                    .1
1398                                    .push_normal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}",
                trait_ref2.print_only_trait_name()))
    })format!("{}", trait_ref2.print_only_trait_name()));
1399                            } else {
1400                                {
    let _guard = ForceTrimmedGuard::new();
    {
        values.0.push_normal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0}",
                            trait_ref1.print_only_trait_name()))
                }));
        values.1.push_normal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0}",
                            trait_ref2.print_only_trait_name()))
                }));
    }
}with_forced_trimmed_paths! {{
1401                                    values
1402                                        .0
1403                                        .push_normal(format!("{}", trait_ref1.print_only_trait_name()));
1404                                    values
1405                                        .1
1406                                        .push_normal(format!("{}", trait_ref2.print_only_trait_name()));
1407                                }}
1408                            }
1409                            // We skip the type of `Self`:
1410                            let args1 = &trait_ref1.args[1..];
1411                            let args2 = &trait_ref2.args[1..];
1412                            self.compare_generics(&mut values, args1, args2);
1413                        } else {
1414                            values
1415                                .0
1416                                .push_highlighted(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}",
                trait_ref1.print_trait_sugared()))
    })format!("{}", trait_ref1.print_trait_sugared()));
1417                            values
1418                                .1
1419                                .push_highlighted(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}",
                trait_ref2.print_trait_sugared()))
    })format!("{}", trait_ref2.print_trait_sugared()));
1420                        }
1421                        values.0.push_normal(">::");
1422                        values.1.push_normal(">::");
1423                        let name1 = self.tcx.item_name(def_id1);
1424                        let name2 = self.tcx.item_name(def_id2);
1425                        if def_id1 == def_id2 {
1426                            values.0.push_normal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", name1))
    })format!("{name1}"));
1427                            values.1.push_normal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", name2))
    })format!("{name2}"));
1428                        } else {
1429                            // The two types are already different, so the arguments are not
1430                            // illuminating anything by highlighting them in any way.
1431                            values.0.push_highlighted(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", name1))
    })format!("{name1}"));
1432                            values.1.push_highlighted(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", name2))
    })format!("{name2}"));
1433                        }
1434                        self.compare_generics(&mut values, args1, args2);
1435                    }
1436                    _ => {
1437                        self.maybe_highlight(t1, t2, &mut values, self.tcx);
1438                    }
1439                }
1440                values
1441            }
1442
1443            _ => {
1444                let mut strs = (DiagStyledString::new(), DiagStyledString::new());
1445                self.maybe_highlight(t1, t2, &mut strs, self.tcx);
1446                strs
1447            }
1448        }
1449    }
1450
1451    /// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
1452    /// the return type of `async fn`s.
1453    ///
1454    /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
1455    ///
1456    /// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
1457    /// the message in `secondary_span` as the primary label, and apply the message that would
1458    /// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
1459    /// E0271, like `tests/ui/issues/issue-39970.stderr`.
1460    {}
#[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("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1460u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cause")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cause");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("values")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("values");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("terr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("terr");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("override_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("override_span");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&values)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&terr)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&override_span)
                                                            as &dyn ::tracing::field::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1571",
                                    "rustc_trait_selection::error_reporting::infer",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1571u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("note_type_err(diag={0:?})",
                                                                diag) as &dyn ::tracing::field::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 values = self.resolve_vars_if_possible(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, .. }) => {
                                    let def_id =
                                        match expected.kind {
                                            ty::AliasTermKind::ProjectionTy { def_id } => def_id.into(),
                                            ty::AliasTermKind::InherentTy { def_id } => def_id.into(),
                                            ty::AliasTermKind::OpaqueTy { def_id } => def_id.into(),
                                            ty::AliasTermKind::FreeTy { def_id } => def_id.into(),
                                            ty::AliasTermKind::AnonConst { def_id } => def_id.into(),
                                            ty::AliasTermKind::ProjectionConst { def_id } =>
                                                def_id.into(),
                                            ty::AliasTermKind::FreeConst { def_id } => def_id.into(),
                                            ty::AliasTermKind::InherentConstSelf { def_id } =>
                                                def_id.into(),
                                            ty::AliasTermKind::InherentConstImpl { def_id } =>
                                                def_id.into(),
                                        };
                                    (false, Mismatch::Fixed(self.tcx.def_descr(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 let Some(param_env) = param_env {
                self.note_field_shadowed_by_private_candidate_in_cause(diag,
                    cause, param_env);
            }
            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::AliasTy { kind: ty::Opaque { 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::AliasTy { kind: ty::Projection { def_id },
                                        .. })) if self.tcx.is_impl_trait_in_trait(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!(" (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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1886",
                                                "rustc_trait_selection::error_reporting::infer",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                                                ::tracing_core::__macro_support::Option::Some(1886u32),
                                                ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("note_type_err: exp_found={0:?}, expected={1:?} found={2:?}",
                                                                            exp_found, expected, found) as
                                                                    &dyn ::tracing::field::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(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                            [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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1926",
                                    "rustc_trait_selection::error_reporting::infer",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1926u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("exp_found {0:?} terr {1:?} cause.code {2:?}",
                                                                exp_found, terr, cause.code()) as
                                                        &dyn ::tracing::field::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);
                }
            }
            let body_owner_def_id =
                (cause.body_def_id !=
                            CRATE_DEF_ID).then(|| cause.body_def_id.to_def_id());
            self.note_and_explain_type_err(diag, terr, cause, span,
                body_owner_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,
                    body_owner_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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1980",
                                    "rustc_trait_selection::error_reporting::infer",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1980u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("diag")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("diag");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
        }
    }
}#[instrument(level = "debug", skip(self, diag, secondary_span, prefer_label))]
1461    pub fn note_type_err(
1462        &self,
1463        diag: &mut Diag<'_>,
1464        cause: &ObligationCause<'tcx>,
1465        secondary_span: Option<(Span, Cow<'static, str>, bool)>,
1466        mut values: Option<ty::ParamEnvAnd<'tcx, ValuePairs<'tcx>>>,
1467        terr: TypeError<'tcx>,
1468        prefer_label: bool,
1469        override_span: Option<Span>,
1470    ) {
1471        // We use `override_span` when we want the error to point at a `Span` other than
1472        // `cause.span`. This is used in E0271, when a closure is passed in where the return type
1473        // isn't what was expected. We want to point at the closure's return type (or expression),
1474        // instead of the expression where the closure is passed as call argument.
1475        let span = override_span.unwrap_or(cause.span);
1476        // For some types of errors, expected-found does not make
1477        // sense, so just ignore the values we were given.
1478        if let TypeError::CyclicTy(_) = terr {
1479            values = None;
1480        }
1481        struct OpaqueTypesVisitor<'tcx> {
1482            types: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1483            expected: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1484            found: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1485            ignore_span: Span,
1486            tcx: TyCtxt<'tcx>,
1487        }
1488
1489        impl<'tcx> OpaqueTypesVisitor<'tcx> {
1490            fn visit_expected_found(
1491                tcx: TyCtxt<'tcx>,
1492                expected: impl TypeVisitable<TyCtxt<'tcx>>,
1493                found: impl TypeVisitable<TyCtxt<'tcx>>,
1494                ignore_span: Span,
1495            ) -> Self {
1496                let mut types_visitor = OpaqueTypesVisitor {
1497                    types: Default::default(),
1498                    expected: Default::default(),
1499                    found: Default::default(),
1500                    ignore_span,
1501                    tcx,
1502                };
1503                // The visitor puts all the relevant encountered types in `self.types`, but in
1504                // here we want to visit two separate types with no relation to each other, so we
1505                // move the results from `types` to `expected` or `found` as appropriate.
1506                expected.visit_with(&mut types_visitor);
1507                std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1508                found.visit_with(&mut types_visitor);
1509                std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1510                types_visitor
1511            }
1512
1513            fn report(&self, err: &mut Diag<'_>) {
1514                self.add_labels_for_types(err, "expected", &self.expected);
1515                self.add_labels_for_types(err, "found", &self.found);
1516            }
1517
1518            fn add_labels_for_types(
1519                &self,
1520                err: &mut Diag<'_>,
1521                target: &str,
1522                types: &FxIndexMap<TyCategory, FxIndexSet<Span>>,
1523            ) {
1524                for (kind, values) in types.iter() {
1525                    let count = values.len();
1526                    for &sp in values {
1527                        err.span_label(
1528                            sp,
1529                            format!(
1530                                "{}{} {:#}{}",
1531                                if count == 1 { "the " } else { "one of the " },
1532                                target,
1533                                kind,
1534                                pluralize!(count),
1535                            ),
1536                        );
1537                    }
1538                }
1539            }
1540        }
1541
1542        impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypesVisitor<'tcx> {
1543            fn visit_ty(&mut self, t: Ty<'tcx>) {
1544                if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1545                    let span = self.tcx.def_span(def_id);
1546                    // Avoid cluttering the output when the "found" and error span overlap:
1547                    //
1548                    // error[E0308]: mismatched types
1549                    //   --> $DIR/issue-20862.rs:2:5
1550                    //    |
1551                    // LL |     |y| x + y
1552                    //    |     ^^^^^^^^^
1553                    //    |     |
1554                    //    |     the found closure
1555                    //    |     expected `()`, found closure
1556                    //    |
1557                    //    = note: expected unit type `()`
1558                    //                 found closure `{closure@$DIR/issue-20862.rs:2:5: 2:14 x:_}`
1559                    //
1560                    // Also ignore opaque `Future`s that come from async fns.
1561                    if !self.ignore_span.overlaps(span)
1562                        && !span.is_desugaring(DesugaringKind::Async)
1563                    {
1564                        self.types.entry(kind).or_default().insert(span);
1565                    }
1566                }
1567                t.super_visit_with(self)
1568            }
1569        }
1570
1571        debug!("note_type_err(diag={:?})", diag);
1572        enum Mismatch<'a> {
1573            Variable(ty::error::ExpectedFound<Ty<'a>>),
1574            Fixed(&'static str),
1575        }
1576        let (expected_found, exp_found, is_simple_error, values, param_env) = match values {
1577            None => (None, Mismatch::Fixed("type"), false, None, None),
1578            Some(ty::ParamEnvAnd { param_env, value: values }) => {
1579                let values = self.resolve_vars_if_possible(values);
1580                let (is_simple_error, exp_found) = match values {
1581                    ValuePairs::Terms(ExpectedFound { expected, found }) => {
1582                        match (expected.kind(), found.kind()) {
1583                            (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
1584                                let is_simple_err =
1585                                    expected.is_simple_text() && found.is_simple_text();
1586                                OpaqueTypesVisitor::visit_expected_found(
1587                                    self.tcx, expected, found, span,
1588                                )
1589                                .report(diag);
1590
1591                                (
1592                                    is_simple_err,
1593                                    Mismatch::Variable(ExpectedFound { expected, found }),
1594                                )
1595                            }
1596                            (ty::TermKind::Const(_), ty::TermKind::Const(_)) => {
1597                                (false, Mismatch::Fixed("constant"))
1598                            }
1599                            _ => (false, Mismatch::Fixed("type")),
1600                        }
1601                    }
1602                    ValuePairs::PolySigs(ExpectedFound { expected, found }) => {
1603                        OpaqueTypesVisitor::visit_expected_found(self.tcx, expected, found, span)
1604                            .report(diag);
1605                        (false, Mismatch::Fixed("signature"))
1606                    }
1607                    ValuePairs::TraitRefs(_) => (false, Mismatch::Fixed("trait")),
1608                    ValuePairs::Aliases(ExpectedFound { expected, .. }) => {
1609                        let def_id = match expected.kind {
1610                            ty::AliasTermKind::ProjectionTy { def_id } => def_id.into(),
1611                            ty::AliasTermKind::InherentTy { def_id } => def_id.into(),
1612                            ty::AliasTermKind::OpaqueTy { def_id } => def_id.into(),
1613                            ty::AliasTermKind::FreeTy { def_id } => def_id.into(),
1614                            ty::AliasTermKind::AnonConst { def_id } => def_id.into(),
1615                            ty::AliasTermKind::ProjectionConst { def_id } => def_id.into(),
1616                            ty::AliasTermKind::FreeConst { def_id } => def_id.into(),
1617                            ty::AliasTermKind::InherentConstSelf { def_id } => def_id.into(),
1618                            ty::AliasTermKind::InherentConstImpl { def_id } => def_id.into(),
1619                        };
1620                        (false, Mismatch::Fixed(self.tcx.def_descr(def_id)))
1621                    }
1622                    ValuePairs::Regions(_) => (false, Mismatch::Fixed("lifetime")),
1623                    ValuePairs::ExistentialTraitRef(_) => {
1624                        (false, Mismatch::Fixed("existential trait ref"))
1625                    }
1626                    ValuePairs::ExistentialProjection(_) => {
1627                        (false, Mismatch::Fixed("existential projection"))
1628                    }
1629                };
1630                let Some(vals) = self.values_str(values, cause, diag.long_ty_path()) else {
1631                    // Derived error. Cancel the emitter.
1632                    // NOTE(eddyb) this was `.cancel()`, but `diag`
1633                    // is borrowed, so we can't fully defuse it.
1634                    diag.downgrade_to_delayed_bug();
1635                    return;
1636                };
1637                (Some(vals), exp_found, is_simple_error, Some(values), Some(param_env))
1638            }
1639        };
1640
1641        let mut label_or_note = |span: Span, msg: Cow<'static, str>| {
1642            if (prefer_label && is_simple_error) || &[span] == diag.span.primary_spans() {
1643                diag.span_label(span, msg);
1644            } else {
1645                diag.span_note(span, msg);
1646            }
1647        };
1648        if let Some((secondary_span, secondary_msg, swap_secondary_and_primary)) = secondary_span {
1649            if swap_secondary_and_primary {
1650                let terr = if let Some(infer::ValuePairs::Terms(ExpectedFound {
1651                    expected, ..
1652                })) = values
1653                {
1654                    Cow::from(format!("expected this to be `{expected}`"))
1655                } else {
1656                    terr.to_string(self.tcx)
1657                };
1658                label_or_note(secondary_span, terr);
1659                label_or_note(span, secondary_msg);
1660            } else {
1661                label_or_note(span, terr.to_string(self.tcx));
1662                label_or_note(secondary_span, secondary_msg);
1663            }
1664        } else if let Some(values) = values
1665            && let Some((e, f)) = values.ty()
1666            && let TypeError::ArgumentSorts(..) | TypeError::Sorts(_) = terr
1667        {
1668            let e = self.tcx.erase_and_anonymize_regions(e);
1669            let f = self.tcx.erase_and_anonymize_regions(f);
1670            let expected = with_forced_trimmed_paths!(e.sort_string(self.tcx));
1671            let found = with_forced_trimmed_paths!(f.sort_string(self.tcx));
1672            if expected == found {
1673                label_or_note(span, terr.to_string(self.tcx));
1674            } else {
1675                label_or_note(span, Cow::from(format!("expected {expected}, found {found}")));
1676            }
1677        } else {
1678            label_or_note(span, terr.to_string(self.tcx));
1679        }
1680
1681        if let Some(param_env) = param_env {
1682            self.note_field_shadowed_by_private_candidate_in_cause(diag, cause, param_env);
1683        }
1684
1685        if self.check_and_note_conflicting_crates(diag, terr) {
1686            return;
1687        }
1688
1689        if let Some((expected, found)) = expected_found {
1690            let (expected_label, found_label, exp_found) = match exp_found {
1691                Mismatch::Variable(ef) => (
1692                    ef.expected.prefix_string(self.tcx),
1693                    ef.found.prefix_string(self.tcx),
1694                    Some(ef),
1695                ),
1696                Mismatch::Fixed(s) => (s.into(), s.into(), None),
1697            };
1698
1699            enum Similar<'tcx> {
1700                Adts { expected: ty::AdtDef<'tcx>, found: ty::AdtDef<'tcx> },
1701                PrimitiveFound { expected: ty::AdtDef<'tcx>, found: Ty<'tcx> },
1702                PrimitiveExpected { expected: Ty<'tcx>, found: ty::AdtDef<'tcx> },
1703            }
1704
1705            let similarity = |ExpectedFound { expected, found }: ExpectedFound<Ty<'tcx>>| {
1706                if let ty::Adt(expected, _) = expected.kind()
1707                    && let Some(primitive) = found.primitive_symbol()
1708                {
1709                    let path = self.tcx.def_path(expected.did()).data;
1710                    let name = path.last().unwrap().data.get_opt_name();
1711                    if name == Some(primitive) {
1712                        return Some(Similar::PrimitiveFound { expected: *expected, found });
1713                    }
1714                } else if let Some(primitive) = expected.primitive_symbol()
1715                    && let ty::Adt(found, _) = found.kind()
1716                {
1717                    let path = self.tcx.def_path(found.did()).data;
1718                    let name = path.last().unwrap().data.get_opt_name();
1719                    if name == Some(primitive) {
1720                        return Some(Similar::PrimitiveExpected { expected, found: *found });
1721                    }
1722                } else if let ty::Adt(expected, _) = expected.kind()
1723                    && let ty::Adt(found, _) = found.kind()
1724                {
1725                    if !expected.did().is_local() && expected.did().krate == found.did().krate {
1726                        // Most likely types from different versions of the same crate
1727                        // are in play, in which case this message isn't so helpful.
1728                        // A "perhaps two different versions..." error is already emitted for that.
1729                        return None;
1730                    }
1731                    let f_path = self.tcx.def_path(found.did()).data;
1732                    let e_path = self.tcx.def_path(expected.did()).data;
1733
1734                    if let (Some(e_last), Some(f_last)) = (e_path.last(), f_path.last())
1735                        && e_last == f_last
1736                    {
1737                        return Some(Similar::Adts { expected: *expected, found: *found });
1738                    }
1739                }
1740                None
1741            };
1742
1743            match terr {
1744                // If two types mismatch but have similar names, mention that specifically.
1745                TypeError::Sorts(values) if let Some(s) = similarity(values) => {
1746                    let diagnose_primitive =
1747                        |prim: Ty<'tcx>, shadow: Ty<'tcx>, defid: DefId, diag: &mut Diag<'_>| {
1748                            let name = shadow.sort_string(self.tcx);
1749                            diag.note(format!(
1750                                "`{prim}` and {name} have similar names, but are actually distinct types"
1751                            ));
1752                            diag.note(format!(
1753                                "one `{prim}` is a primitive defined by the language",
1754                            ));
1755                            let def_span = self.tcx.def_span(defid);
1756                            let msg = if defid.is_local() {
1757                                format!("the other {name} is defined in the current crate")
1758                            } else {
1759                                let crate_name = self.tcx.crate_name(defid.krate);
1760                                format!("the other {name} is defined in crate `{crate_name}`")
1761                            };
1762                            diag.span_note(def_span, msg);
1763                        };
1764
1765                    let diagnose_adts =
1766                        |expected_adt: ty::AdtDef<'tcx>,
1767                         found_adt: ty::AdtDef<'tcx>,
1768                         diag: &mut Diag<'_>| {
1769                            let found_name = values.found.sort_string(self.tcx);
1770                            let expected_name = values.expected.sort_string(self.tcx);
1771
1772                            let found_defid = found_adt.did();
1773                            let expected_defid = expected_adt.did();
1774
1775                            diag.note(format!("{found_name} and {expected_name} have similar names, but are actually distinct types"));
1776                            for (defid, name) in
1777                                [(found_defid, found_name), (expected_defid, expected_name)]
1778                            {
1779                                let def_span = self.tcx.def_span(defid);
1780
1781                                let msg = if found_defid.is_local() && expected_defid.is_local() {
1782                                    let module = self
1783                                        .tcx
1784                                        .parent_module_from_def_id(defid.expect_local())
1785                                        .to_def_id();
1786                                    let module_name =
1787                                        self.tcx.def_path(module).to_string_no_crate_verbose();
1788                                    format!(
1789                                        "{name} is defined in module `crate{module_name}` of the current crate"
1790                                    )
1791                                } else if defid.is_local() {
1792                                    format!("{name} is defined in the current crate")
1793                                } else {
1794                                    let crate_name = self.tcx.crate_name(defid.krate);
1795                                    format!("{name} is defined in crate `{crate_name}`")
1796                                };
1797                                diag.span_note(def_span, msg);
1798                            }
1799                        };
1800
1801                    match s {
1802                        Similar::Adts { expected, found } => diagnose_adts(expected, found, diag),
1803                        Similar::PrimitiveFound { expected, found: prim } => {
1804                            diagnose_primitive(prim, values.expected, expected.did(), diag)
1805                        }
1806                        Similar::PrimitiveExpected { expected: prim, found } => {
1807                            diagnose_primitive(prim, values.found, found.did(), diag)
1808                        }
1809                    }
1810                }
1811                TypeError::Sorts(values) => {
1812                    let extra = expected == found
1813                        // Ensure that we don't ever say something like
1814                        // expected `impl Trait` (opaque type `impl Trait`)
1815                        //    found `impl Trait` (opaque type `impl Trait`)
1816                        && values.expected.sort_string(self.tcx)
1817                            != values.found.sort_string(self.tcx);
1818                    let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1819                        (true, ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. })) => {
1820                            let sm = self.tcx.sess.source_map();
1821                            let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1822                            DiagStyledString::normal(format!(
1823                                " (opaque type at <{}:{}:{}>)",
1824                                sm.filename_for_diagnostics(&pos.file.name),
1825                                pos.line,
1826                                pos.col.to_usize() + 1,
1827                            ))
1828                        }
1829                        (
1830                            true,
1831                            &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, .. }),
1832                        ) if self.tcx.is_impl_trait_in_trait(def_id) => {
1833                            let sm = self.tcx.sess.source_map();
1834                            let pos = sm.lookup_char_pos(self.tcx.def_span(def_id).lo());
1835                            DiagStyledString::normal(format!(
1836                                " (trait associated opaque type at <{}:{}:{}>)",
1837                                sm.filename_for_diagnostics(&pos.file.name),
1838                                pos.line,
1839                                pos.col.to_usize() + 1,
1840                            ))
1841                        }
1842                        (true, _) => {
1843                            let mut s = DiagStyledString::normal(" (");
1844                            s.push_highlighted(ty.sort_string(self.tcx));
1845                            s.push_normal(")");
1846                            s
1847                        }
1848                        (false, _) => DiagStyledString::normal(""),
1849                    };
1850                    if !(values.expected.is_simple_text() && values.found.is_simple_text())
1851                        || (exp_found.is_some_and(|ef| {
1852                            // This happens when the type error is a subset of the expectation,
1853                            // like when you have two references but one is `usize` and the other
1854                            // is `f32`. In those cases we still want to show the `note`. If the
1855                            // value from `ef` is `Infer(_)`, then we ignore it.
1856                            if !ef.expected.is_ty_or_numeric_infer() {
1857                                ef.expected != values.expected
1858                            } else if !ef.found.is_ty_or_numeric_infer() {
1859                                ef.found != values.found
1860                            } else {
1861                                false
1862                            }
1863                        }))
1864                    {
1865                        if let Some(ExpectedFound { found: found_ty, .. }) = exp_found
1866                            && !self.tcx.ty_is_opaque_future(found_ty)
1867                        {
1868                            // `Future` is a special opaque type that the compiler
1869                            // will try to hide in some case such as `async fn`, so
1870                            // to make an error more use friendly we will
1871                            // avoid to suggest a mismatch type with a
1872                            // type that the user usually are not using
1873                            // directly such as `impl Future<Output = u8>`.
1874                            diag.note_expected_found_extra(
1875                                &expected_label,
1876                                expected,
1877                                &found_label,
1878                                found,
1879                                sort_string(values.expected),
1880                                sort_string(values.found),
1881                            );
1882                        }
1883                    }
1884                }
1885                _ => {
1886                    debug!(
1887                        "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1888                        exp_found, expected, found
1889                    );
1890                    if !is_simple_error || terr.must_include_note() {
1891                        diag.note_expected_found(&expected_label, expected, &found_label, found);
1892
1893                        if let Some(ty::Closure(_, args)) =
1894                            exp_found.map(|expected_type_found| expected_type_found.found.kind())
1895                        {
1896                            diag.highlighted_note(vec![
1897                                StringPart::normal("closure has signature: `"),
1898                                StringPart::highlighted(
1899                                    self.tcx
1900                                        .signature_unclosure(
1901                                            args.as_closure().sig(),
1902                                            rustc_hir::Safety::Safe,
1903                                        )
1904                                        .to_string(),
1905                                ),
1906                                StringPart::normal("`"),
1907                            ]);
1908                        }
1909                    }
1910                }
1911            }
1912        }
1913        let exp_found = match exp_found {
1914            Mismatch::Variable(exp_found) => Some(exp_found),
1915            Mismatch::Fixed(_) => None,
1916        };
1917        let exp_found = match terr {
1918            // `terr` has more accurate type information than `exp_found` in match expressions.
1919            ty::error::TypeError::Sorts(terr)
1920                if exp_found.is_some_and(|ef| terr.found == ef.found) =>
1921            {
1922                Some(terr)
1923            }
1924            _ => exp_found,
1925        };
1926        debug!("exp_found {:?} terr {:?} cause.code {:?}", exp_found, terr, cause.code());
1927        if let Some(exp_found) = exp_found {
1928            let should_suggest_fixes =
1929                if let ObligationCauseCode::Pattern { root_ty, .. } = cause.code() {
1930                    // Skip if the root_ty of the pattern is not the same as the expected_ty.
1931                    // If these types aren't equal then we've probably peeled off a layer of arrays.
1932                    self.same_type_modulo_infer(*root_ty, exp_found.expected)
1933                } else {
1934                    true
1935                };
1936
1937            // FIXME(#73154): For now, we do leak check when coercing function
1938            // pointers in typeck, instead of only during borrowck. This can lead
1939            // to these `RegionsInsufficientlyPolymorphic` errors that aren't helpful.
1940            if should_suggest_fixes
1941                && !matches!(terr, TypeError::RegionsInsufficientlyPolymorphic(..))
1942            {
1943                self.suggest_tuple_pattern(cause, &exp_found, diag);
1944                self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1945                self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1946                self.suggest_function_pointers(cause, span, &exp_found, terr, diag);
1947                self.suggest_turning_stmt_into_expr(cause, &exp_found, diag);
1948            }
1949        }
1950
1951        let body_owner_def_id =
1952            (cause.body_def_id != CRATE_DEF_ID).then(|| cause.body_def_id.to_def_id());
1953        self.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id);
1954        if let Some(exp_found) = exp_found
1955            && let exp_found = TypeError::Sorts(exp_found)
1956            && exp_found != terr
1957        {
1958            self.note_and_explain_type_err(diag, exp_found, cause, span, body_owner_def_id);
1959        }
1960
1961        if let Some(ValuePairs::TraitRefs(exp_found)) = values
1962            && let ty::Closure(def_id, _) = exp_found.expected.self_ty().kind()
1963            && let Some(def_id) = def_id.as_local()
1964            && terr.involves_regions()
1965        {
1966            let span = self.tcx.def_span(def_id);
1967            diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1968            self.suggest_for_all_lifetime_closure(
1969                span,
1970                self.tcx.hir_node_by_def_id(def_id),
1971                &exp_found,
1972                diag,
1973            );
1974        }
1975
1976        // It reads better to have the error origin as the final
1977        // thing.
1978        self.note_error_origin(diag, cause, exp_found, terr, param_env);
1979
1980        debug!(?diag);
1981    }
1982
1983    pub(crate) fn type_error_additional_suggestions(
1984        &self,
1985        trace: &TypeTrace<'tcx>,
1986        terr: TypeError<'tcx>,
1987        long_ty_path: &mut Option<PathBuf>,
1988    ) -> Vec<TypeErrorAdditionalDiags> {
1989        let mut suggestions = Vec::new();
1990        let span = trace.cause.span;
1991        let values = self.resolve_vars_if_possible(trace.values);
1992        if let Some((expected, found)) = values.ty() {
1993            match (expected.kind(), found.kind()) {
1994                (ty::Tuple(_), ty::Tuple(_)) => {}
1995                // If a tuple of length one was expected and the found expression has
1996                // parentheses around it, perhaps the user meant to write `(expr,)` to
1997                // build a tuple (issue #86100)
1998                (ty::Tuple(fields), _) => {
1999                    suggestions.extend(self.suggest_wrap_to_build_a_tuple(span, found, fields))
2000                }
2001                // If a byte was expected and the found expression is a char literal
2002                // containing a single ASCII character, perhaps the user meant to write `b'c'` to
2003                // specify a byte literal
2004                (ty::Uint(ty::UintTy::U8), ty::Char) => {
2005                    if let Ok(code) = self.tcx.sess.source_map().span_to_snippet(span)
2006                        && let Some(code) = code.strip_circumfix('\'', '\'')
2007                        // forbid all Unicode escapes
2008                        && !code.starts_with("\\u")
2009                        // forbids literal Unicode characters beyond ASCII
2010                        && code.chars().next().is_some_and(|c| c.is_ascii())
2011                    {
2012                        suggestions.push(TypeErrorAdditionalDiags::MeantByteLiteral {
2013                            span,
2014                            code: escape_literal(code),
2015                        })
2016                    }
2017                }
2018                // If a character was expected and the found expression is a string literal
2019                // containing a single character, perhaps the user meant to write `'c'` to
2020                // specify a character literal (issue #92479)
2021                (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
2022                    if let Ok(code) = self.tcx.sess.source_map().span_to_snippet(span)
2023                        && let Some(code) = code.strip_circumfix('"', '"')
2024                        && code.chars().count() == 1
2025                    {
2026                        suggestions.push(TypeErrorAdditionalDiags::MeantCharLiteral {
2027                            span,
2028                            code: escape_literal(code),
2029                        })
2030                    }
2031                }
2032                // If a string was expected and the found expression is a character literal,
2033                // perhaps the user meant to write `"s"` to specify a string literal.
2034                (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
2035                    if let Ok(code) = self.tcx.sess.source_map().span_to_snippet(span)
2036                        && code.starts_with("'")
2037                        && code.ends_with("'")
2038                    {
2039                        suggestions.push(TypeErrorAdditionalDiags::MeantStrLiteral {
2040                            start: span.with_hi(span.lo() + BytePos(1)),
2041                            end: span.with_lo(span.hi() - BytePos(1)),
2042                        });
2043                    }
2044                }
2045                // For code `if Some(..) = expr `, the type mismatch may be expected `bool` but found `()`,
2046                // we try to suggest to add the missing `let` for `if let Some(..) = expr`
2047                (ty::Bool, ty::Tuple(list)) => {
2048                    if list.len() == 0 {
2049                        suggestions.extend(self.suggest_let_for_letchains(&trace.cause, span));
2050                    }
2051                }
2052                (ty::Array(_, _), ty::Array(_, _)) => {
2053                    suggestions.extend(self.suggest_specify_actual_length(terr, trace, span))
2054                }
2055                _ => {}
2056            }
2057        }
2058        let code = trace.cause.code();
2059        if let &(ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
2060            source, ..
2061        })
2062        | ObligationCauseCode::BlockTailExpression(.., source)) = code
2063            && let hir::MatchSource::TryDesugar(_) = source
2064            && let Some((expected_ty, found_ty)) =
2065                self.values_str(trace.values, &trace.cause, long_ty_path)
2066        {
2067            suggestions.push(TypeErrorAdditionalDiags::TryCannotConvert {
2068                found: found_ty.content(),
2069                expected: expected_ty.content(),
2070            });
2071        }
2072        suggestions
2073    }
2074
2075    fn suggest_specify_actual_length(
2076        &self,
2077        terr: TypeError<'tcx>,
2078        trace: &TypeTrace<'tcx>,
2079        span: Span,
2080    ) -> Option<TypeErrorAdditionalDiags> {
2081        let TypeError::ArraySize(sz) = terr else {
2082            return None;
2083        };
2084        let tykind = match self.tcx.hir_node_by_def_id(trace.cause.body_def_id) {
2085            hir::Node::Item(hir::Item {
2086                kind: hir::ItemKind::Fn { body: body_id, .. }, ..
2087            }) => {
2088                let body = self.tcx.hir_body(*body_id);
2089                struct LetVisitor {
2090                    span: Span,
2091                }
2092                impl<'v> Visitor<'v> for LetVisitor {
2093                    type Result = ControlFlow<&'v hir::TyKind<'v>>;
2094                    fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
2095                        // Find a local statement where the initializer has
2096                        // the same span as the error and the type is specified.
2097                        if let hir::Stmt {
2098                            kind:
2099                                hir::StmtKind::Let(hir::LetStmt {
2100                                    init: Some(hir::Expr { span: init_span, .. }),
2101                                    ty: Some(array_ty),
2102                                    ..
2103                                }),
2104                            ..
2105                        } = s
2106                            && init_span == &self.span
2107                        {
2108                            ControlFlow::Break(&array_ty.peel_refs().kind)
2109                        } else {
2110                            ControlFlow::Continue(())
2111                        }
2112                    }
2113                }
2114                LetVisitor { span }.visit_body(body).break_value()
2115            }
2116            hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(_, _, ty, _), .. }) => {
2117                Some(&ty.peel_refs().kind)
2118            }
2119            _ => None,
2120        };
2121        if let Some(tykind) = tykind
2122            && let hir::TyKind::Array(_, length_arg) = tykind
2123            && let Some(length_val) = sz.found.try_to_target_usize(self.tcx)
2124        {
2125            Some(TypeErrorAdditionalDiags::ConsiderSpecifyingLength {
2126                span: length_arg.span,
2127                length: length_val,
2128            })
2129        } else {
2130            None
2131        }
2132    }
2133
2134    fn check_on_type_error_attribute(
2135        &self,
2136        expected_ty: Ty<'tcx>,
2137        found_ty: Ty<'tcx>,
2138    ) -> ThinVec<String> {
2139        let mut seen = FxHashSet::default();
2140        let mut unique_notes: ThinVec<String> = ThinVec::new();
2141
2142        // Check found type for attribute
2143        if let ty::Adt(item_def, args) = found_ty.kind() {
2144            if let Some(Some(directive)) =
2145                {
    {
        'done:
            {
            for i in
                ::rustc_attr_ir::HasAttrs::get_attrs(item_def.did(),
                    &self.tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(OnTypeError { directive,
                        .. }) => {
                        break 'done Some(directive);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self.tcx, item_def.did(), OnTypeError { directive, .. } => directive)
2146            {
2147                let notes = self.format_on_type_error_notes(
2148                    directive,
2149                    args,
2150                    item_def.clone(),
2151                    expected_ty,
2152                    found_ty,
2153                );
2154
2155                for note in notes {
2156                    if seen.insert(note.clone()) {
2157                        unique_notes.push(note);
2158                    }
2159                }
2160            }
2161        }
2162
2163        // Check expected type for attribute
2164        if let ty::Adt(item_def, args) = expected_ty.kind() {
2165            if let Some(Some(directive)) =
2166                {
    {
        'done:
            {
            for i in
                ::rustc_attr_ir::HasAttrs::get_attrs(item_def.did(),
                    &self.tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(OnTypeError { directive,
                        .. }) => {
                        break 'done Some(directive);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self.tcx, item_def.did(), OnTypeError { directive, .. } => directive)
2167            {
2168                let notes = self.format_on_type_error_notes(
2169                    directive,
2170                    args,
2171                    item_def.clone(),
2172                    expected_ty,
2173                    found_ty,
2174                );
2175
2176                for note in notes {
2177                    if seen.insert(note.clone()) {
2178                        unique_notes.push(note);
2179                    }
2180                }
2181            }
2182        }
2183
2184        unique_notes
2185    }
2186
2187    fn format_on_type_error_notes(
2188        &self,
2189        directive: &Directive,
2190        args: &ty::GenericArgsRef<'tcx>,
2191        item_def: ty::AdtDef<'tcx>,
2192        expected_ty: Ty<'tcx>,
2193        found_ty: Ty<'tcx>,
2194    ) -> ThinVec<String> {
2195        let item_name = self.tcx.item_name(item_def.did()).to_string();
2196        let generic_args: Vec<_> = self
2197            .tcx
2198            .generics_of(item_def.did())
2199            .own_params
2200            .iter()
2201            .filter_map(|param| Some((param.name, args[param.index as usize].to_string())))
2202            .collect();
2203
2204        let format_args = FormatArgs {
2205            this: item_name,
2206            generic_args,
2207            found: found_ty.to_string(),
2208            expected: expected_ty.to_string(),
2209            ..
2210        };
2211        let CustomDiagnostic { notes, .. } = directive.eval(None, &format_args);
2212
2213        notes.into()
2214    }
2215
2216    pub fn report_and_explain_type_error(
2217        &self,
2218        mut trace: TypeTrace<'tcx>,
2219        param_env: ty::ParamEnv<'tcx>,
2220        terr: TypeError<'tcx>,
2221    ) -> Diag<'a> {
2222        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:2222",
                        "rustc_trait_selection::error_reporting::infer",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2222u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_and_explain_type_error(trace={0:?}, terr={1:?})",
                                                    trace, terr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
2223
2224        let span = trace.cause.span;
2225        let mut path = None;
2226
2227        self.simplify_pin_macro_arg_ty_mismatch(&mut trace);
2228
2229        // Check for on_type_error attribute
2230        let on_type_error_notes = if let Some((expected_ty, found_ty)) = trace.values.ty() {
2231            self.check_on_type_error_attribute(expected_ty, found_ty)
2232        } else {
2233            ThinVec::new()
2234        };
2235
2236        let failure_code = trace.cause.as_failure_code_diag(
2237            terr,
2238            span,
2239            self.type_error_additional_suggestions(&trace, terr, &mut path),
2240        );
2241        let mut diag = self.dcx().create_err(failure_code);
2242        *diag.long_ty_path() = path;
2243
2244        // Add custom notes
2245        for note in on_type_error_notes {
2246            diag.note(note);
2247        }
2248
2249        self.note_type_err(
2250            &mut diag,
2251            &trace.cause,
2252            None,
2253            Some(param_env.and(trace.values)),
2254            terr,
2255            false,
2256            None,
2257        );
2258        diag
2259    }
2260
2261    /// If the `pin!()` macro gets a wrong argument type, don't show its internals
2262    /// in user-facing diagnostics.
2263    /// See the `ui/pin/dont-deref-coerce-pinned-value` test.
2264    fn simplify_pin_macro_arg_ty_mismatch(&self, trace: &mut TypeTrace<'tcx>) {
2265        // Check whether `expected_ty` and `found_ty` are both `&mut PinMacroHelper<....>`,
2266        // in which case we peel off the wrapping.
2267        if let Some((expected_ty, found_ty)) = trace.values.ty()
2268            && let ty::Ref(_, expected_ty_kind_inside_mut, Mutability::Mut) = expected_ty.kind()
2269            && let ty::Adt(expected_adt, expected_generics) = expected_ty_kind_inside_mut.kind()
2270            && self.tcx.is_diagnostic_item(sym::PinMacroHelper, expected_adt.did())
2271            && let ty::Ref(_, found_ty_kind_inside_mut, Mutability::Mut) = found_ty.kind()
2272            && let ty::Adt(found_adt, found_generics) = found_ty_kind_inside_mut.kind()
2273            && self.tcx.is_diagnostic_item(sym::PinMacroHelper, found_adt.did())
2274        {
2275            let [expected_generic] = expected_generics
2276                .as_slice()
2277                .try_into()
2278                .expect("PinMacroHelper should only have one generic");
2279            let [found_generic] = found_generics
2280                .as_slice()
2281                .try_into()
2282                .expect("PinMacroHelper should only have one generic");
2283            let expected_ty_inner =
2284                expected_generic.as_type().expect("PinMacroHelper should have a generic type");
2285            let found_ty_inner =
2286                found_generic.as_type().expect("PinMacroHelper should have a generic type");
2287            trace.values = ValuePairs::Terms(ExpectedFound::new(
2288                expected_ty_inner.into(),
2289                found_ty_inner.into(),
2290            ));
2291        }
2292    }
2293
2294    fn suggest_wrap_to_build_a_tuple(
2295        &self,
2296        span: Span,
2297        found: Ty<'tcx>,
2298        expected_fields: &List<Ty<'tcx>>,
2299    ) -> Option<TypeErrorAdditionalDiags> {
2300        let [expected_tup_elem] = expected_fields[..] else { return None };
2301
2302        if !self.same_type_modulo_infer(expected_tup_elem, found) {
2303            return None;
2304        }
2305
2306        let Ok(code) = self.tcx.sess.source_map().span_to_snippet(span) else { return None };
2307
2308        let sugg = if code.starts_with('(') && code.ends_with(')') {
2309            let before_close = span.hi() - BytePos::from_u32(1);
2310            TypeErrorAdditionalDiags::TupleOnlyComma {
2311                span: span.with_hi(before_close).shrink_to_hi(),
2312            }
2313        } else {
2314            TypeErrorAdditionalDiags::TupleAlsoParentheses {
2315                span_low: span.shrink_to_lo(),
2316                span_high: span.shrink_to_hi(),
2317            }
2318        };
2319        Some(sugg)
2320    }
2321
2322    fn values_str(
2323        &self,
2324        values: ValuePairs<'tcx>,
2325        cause: &ObligationCause<'tcx>,
2326        long_ty_path: &mut Option<PathBuf>,
2327    ) -> Option<(DiagStyledString, DiagStyledString)> {
2328        match values {
2329            ValuePairs::Regions(exp_found) => self.expected_found_str(exp_found),
2330            ValuePairs::Terms(exp_found) => self.expected_found_str_term(exp_found, long_ty_path),
2331            ValuePairs::Aliases(exp_found) => self.expected_found_str(exp_found),
2332            ValuePairs::ExistentialTraitRef(exp_found) => self.expected_found_str(exp_found),
2333            ValuePairs::ExistentialProjection(exp_found) => self.expected_found_str(exp_found),
2334            ValuePairs::TraitRefs(exp_found) => {
2335                let pretty_exp_found = ty::error::ExpectedFound {
2336                    expected: exp_found.expected.print_trait_sugared(),
2337                    found: exp_found.found.print_trait_sugared(),
2338                };
2339                match self.expected_found_str(pretty_exp_found) {
2340                    Some((expected, found)) if expected == found => {
2341                        self.expected_found_str(exp_found)
2342                    }
2343                    ret => ret,
2344                }
2345            }
2346            ValuePairs::PolySigs(exp_found) => {
2347                let exp_found = self.resolve_vars_if_possible(exp_found);
2348                if exp_found.references_error() {
2349                    return None;
2350                }
2351                let (fn_def1, fn_def2) = if let ObligationCauseCode::CompareImplItem {
2352                    impl_item_def_id,
2353                    trait_item_def_id,
2354                    ..
2355                } = *cause.code()
2356                {
2357                    (Some((trait_item_def_id, None)), Some((impl_item_def_id.to_def_id(), None)))
2358                } else {
2359                    (None, None)
2360                };
2361
2362                Some(self.cmp_fn_sig(exp_found.expected, fn_def1, exp_found.found, fn_def2))
2363            }
2364        }
2365    }
2366
2367    fn expected_found_str_term(
2368        &self,
2369        exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2370        long_ty_path: &mut Option<PathBuf>,
2371    ) -> Option<(DiagStyledString, DiagStyledString)> {
2372        let exp_found = self.resolve_vars_if_possible(exp_found);
2373        if exp_found.references_error() {
2374            return None;
2375        }
2376
2377        Some(match (exp_found.expected.kind(), exp_found.found.kind()) {
2378            (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
2379                let (mut exp, mut fnd) = self.cmp(expected, found);
2380                // Use the terminal width as the basis to determine when to compress the printed
2381                // out type, but give ourselves some leeway to avoid ending up creating a file for
2382                // a type that is somewhat shorter than the path we'd write to.
2383                let len = self.tcx.sess.diagnostic_width();
2384                let exp_s = exp.content();
2385                let fnd_s = fnd.content();
2386                if !self.tcx.sess.opts.verbose
2387                    && self.tcx.sess.opts.unstable_opts.write_long_types_to_disk
2388                {
2389                    // We aren't explicitly asking for `--verbose` output, and we are storing long
2390                    // types to disk, so we try to shorten the output.
2391                    if exp_s.len() > len && fnd_s.len() > len {
2392                        let exp_short = self.tcx.short_string(expected, long_ty_path);
2393                        let fnd_short = self.tcx.short_string(found, long_ty_path);
2394                        // We use a crude shortening on the highlighted strings themselves. This
2395                        // doesn't ensure that the two strings will look different, or that the
2396                        // output is very readable, but at least keeps the highlighting around.
2397                        exp.shorten();
2398                        fnd.shorten();
2399                        if exp_short != fnd_short {
2400                            // The short strings aren't the same visually, so it might make sense
2401                            // to use them instead.
2402                            if exp.0.len() <= 1 {
2403                                // The entire type is highlighted, let's use the short string
2404                                // instead, which is slightly better.
2405                                exp = DiagStyledString::highlighted(exp_short);
2406                            }
2407                            if fnd.0.len() <= 1 {
2408                                // The entire type is highlighted, let's use the short string
2409                                // instead, which is slightly better.
2410                                fnd = DiagStyledString::highlighted(fnd_short);
2411                            }
2412                        }
2413                    } else {
2414                        if exp_s.len() > len {
2415                            exp.shorten();
2416                            let exp_short = self.tcx.short_string(expected, long_ty_path);
2417                            if exp.0.len() <= 1 {
2418                                exp = DiagStyledString::highlighted(exp_short);
2419                            }
2420                        }
2421                        if fnd_s.len() > len {
2422                            fnd.shorten();
2423                            let fnd_short = self.tcx.short_string(found, long_ty_path);
2424                            if fnd.0.len() <= 1 {
2425                                fnd = DiagStyledString::highlighted(fnd_short);
2426                            }
2427                        }
2428                    }
2429                }
2430                (exp, fnd)
2431            }
2432            _ => (
2433                DiagStyledString::highlighted(exp_found.expected.to_string()),
2434                DiagStyledString::highlighted(exp_found.found.to_string()),
2435            ),
2436        })
2437    }
2438
2439    /// Returns a string of the form "expected `{}`, found `{}`".
2440    fn expected_found_str<T: fmt::Display + TypeFoldable<TyCtxt<'tcx>>>(
2441        &self,
2442        exp_found: ty::error::ExpectedFound<T>,
2443    ) -> Option<(DiagStyledString, DiagStyledString)> {
2444        let exp_found = self.resolve_vars_if_possible(exp_found);
2445        if exp_found.references_error() {
2446            return None;
2447        }
2448
2449        Some((
2450            DiagStyledString::highlighted(exp_found.expected.to_string()),
2451            DiagStyledString::highlighted(exp_found.found.to_string()),
2452        ))
2453    }
2454
2455    /// Determine whether an error associated with the given span and definition
2456    /// should be treated as being caused by the implicit `From` conversion
2457    /// within `?` desugaring.
2458    pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2459        span.is_desugaring(DesugaringKind::QuestionMark)
2460            && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2461    }
2462
2463    /// Structurally compares two types, modulo any inference variables.
2464    ///
2465    /// Returns `true` if two types are equal, or if one type is an inference variable compatible
2466    /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or
2467    /// FloatVar inference type are compatible with themselves or their concrete types (Int and
2468    /// Float types, respectively). When comparing two ADTs, these rules apply recursively.
2469    pub fn same_type_modulo_infer<T: relate::Relate<TyCtxt<'tcx>>>(&self, a: T, b: T) -> bool {
2470        let (a, b) = self.resolve_vars_if_possible((a, b));
2471        SameTypeModuloInfer(self).relate(a, b).is_ok()
2472    }
2473}
2474
2475struct SameTypeModuloInfer<'a, 'tcx>(&'a InferCtxt<'tcx>);
2476
2477impl<'tcx> TypeRelation<TyCtxt<'tcx>> for SameTypeModuloInfer<'_, 'tcx> {
2478    fn cx(&self) -> TyCtxt<'tcx> {
2479        self.0.tcx
2480    }
2481
2482    fn relate_ty_args(
2483        &mut self,
2484        a_ty: Ty<'tcx>,
2485        _: Ty<'tcx>,
2486        _: DefId,
2487        a_args: ty::GenericArgsRef<'tcx>,
2488        b_args: ty::GenericArgsRef<'tcx>,
2489        _: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>,
2490    ) -> RelateResult<'tcx, Ty<'tcx>> {
2491        relate::relate_args_invariantly(self, a_args, b_args)?;
2492        Ok(a_ty)
2493    }
2494
2495    fn relate_with_variance<T: relate::Relate<TyCtxt<'tcx>>>(
2496        &mut self,
2497        _variance: ty::Variance,
2498        _info: ty::VarianceDiagInfo<TyCtxt<'tcx>>,
2499        a: T,
2500        b: T,
2501    ) -> relate::RelateResult<'tcx, T> {
2502        self.relate(a, b)
2503    }
2504
2505    fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
2506        match (a.kind(), b.kind()) {
2507            (ty::Int(_) | ty::Uint(_), ty::Infer(ty::InferTy::IntVar(_)))
2508            | (
2509                ty::Infer(ty::InferTy::IntVar(_)),
2510                ty::Int(_) | ty::Uint(_) | ty::Infer(ty::InferTy::IntVar(_)),
2511            )
2512            | (ty::Float(_), ty::Infer(ty::InferTy::FloatVar(_)))
2513            | (
2514                ty::Infer(ty::InferTy::FloatVar(_)),
2515                ty::Float(_) | ty::Infer(ty::InferTy::FloatVar(_)),
2516            )
2517            | (ty::Infer(ty::InferTy::TyVar(_)), _)
2518            | (_, ty::Infer(ty::InferTy::TyVar(_))) => Ok(a),
2519            (ty::Infer(_), _) | (_, ty::Infer(_)) => Err(TypeError::Mismatch),
2520            _ => relate::structurally_relate_tys(self, a, b),
2521        }
2522    }
2523
2524    fn regions(
2525        &mut self,
2526        a: ty::Region<'tcx>,
2527        b: ty::Region<'tcx>,
2528    ) -> RelateResult<'tcx, ty::Region<'tcx>> {
2529        if (a.is_var() && b.is_free())
2530            || (b.is_var() && a.is_free())
2531            || (a.is_var() && b.is_var())
2532            || a == b
2533        {
2534            Ok(a)
2535        } else {
2536            Err(TypeError::Mismatch)
2537        }
2538    }
2539
2540    fn binders<T>(
2541        &mut self,
2542        a: ty::Binder<'tcx, T>,
2543        b: ty::Binder<'tcx, T>,
2544    ) -> relate::RelateResult<'tcx, ty::Binder<'tcx, T>>
2545    where
2546        T: relate::Relate<TyCtxt<'tcx>>,
2547    {
2548        Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
2549    }
2550
2551    fn consts(
2552        &mut self,
2553        a: ty::Const<'tcx>,
2554        _b: ty::Const<'tcx>,
2555    ) -> relate::RelateResult<'tcx, ty::Const<'tcx>> {
2556        // FIXME(compiler-errors): This could at least do some first-order
2557        // relation
2558        Ok(a)
2559    }
2560}
2561
2562pub enum FailureCode {
2563    Error0317,
2564    Error0580,
2565    Error0308,
2566    Error0644,
2567}
2568
2569pub trait ObligationCauseExt<'tcx> {
    fn as_failure_code(&self, terr: TypeError<'tcx>)
    -> FailureCode;
    fn as_failure_code_diag(&self, terr: TypeError<'tcx>, span: Span,
    subdiags: Vec<TypeErrorAdditionalDiags>)
    -> ObligationCauseFailureCode;
    fn as_requirement_str(&self)
    -> &'static str;
}
impl<'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(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>)]
2570impl<'tcx> ObligationCause<'tcx> {
2571    fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
2572        match self.code() {
2573            ObligationCauseCode::IfExpressionWithNoElse => FailureCode::Error0317,
2574            ObligationCauseCode::MainFunctionType => FailureCode::Error0580,
2575            ObligationCauseCode::CompareImplItem { .. }
2576            | ObligationCauseCode::MatchExpressionArm(_)
2577            | ObligationCauseCode::IfExpression { .. }
2578            | ObligationCauseCode::LetElse
2579            | ObligationCauseCode::LangFunctionType(_)
2580            | ObligationCauseCode::IntrinsicType
2581            | ObligationCauseCode::MethodReceiver => FailureCode::Error0308,
2582
2583            // In the case where we have no more specific thing to
2584            // say, also take a look at the error code, maybe we can
2585            // tailor to that.
2586            _ => match terr {
2587                TypeError::CyclicTy(ty)
2588                    if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() =>
2589                {
2590                    FailureCode::Error0644
2591                }
2592                TypeError::IntrinsicCast | TypeError::ForceInlineCast => FailureCode::Error0308,
2593                _ => FailureCode::Error0308,
2594            },
2595        }
2596    }
2597
2598    fn as_failure_code_diag(
2599        &self,
2600        terr: TypeError<'tcx>,
2601        span: Span,
2602        subdiags: Vec<TypeErrorAdditionalDiags>,
2603    ) -> ObligationCauseFailureCode {
2604        match self.code() {
2605            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
2606                ObligationCauseFailureCode::MethodCompat { span, subdiags }
2607            }
2608            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
2609                ObligationCauseFailureCode::TypeCompat { span, subdiags }
2610            }
2611            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
2612                ObligationCauseFailureCode::ConstCompat { span, subdiags }
2613            }
2614            ObligationCauseCode::BlockTailExpression(.., hir::MatchSource::TryDesugar(_)) => {
2615                ObligationCauseFailureCode::TryCompat { span, subdiags }
2616            }
2617            ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause { source, .. }) => {
2618                match source {
2619                    hir::MatchSource::TryDesugar(_) => {
2620                        ObligationCauseFailureCode::TryCompat { span, subdiags }
2621                    }
2622                    _ => ObligationCauseFailureCode::MatchCompat { span, subdiags },
2623                }
2624            }
2625            ObligationCauseCode::IfExpression { .. } => {
2626                ObligationCauseFailureCode::IfElseDifferent { span, subdiags }
2627            }
2628            ObligationCauseCode::IfExpressionWithNoElse => {
2629                ObligationCauseFailureCode::NoElse { span }
2630            }
2631            ObligationCauseCode::LetElse => {
2632                ObligationCauseFailureCode::NoDiverge { span, subdiags }
2633            }
2634            ObligationCauseCode::MainFunctionType => {
2635                ObligationCauseFailureCode::FnMainCorrectType { span }
2636            }
2637            &ObligationCauseCode::LangFunctionType(lang_item_name) => {
2638                ObligationCauseFailureCode::FnLangCorrectType { span, subdiags, lang_item_name }
2639            }
2640            ObligationCauseCode::IntrinsicType => {
2641                ObligationCauseFailureCode::IntrinsicCorrectType { span, subdiags }
2642            }
2643            ObligationCauseCode::MethodReceiver => {
2644                ObligationCauseFailureCode::MethodCorrectType { span, subdiags }
2645            }
2646
2647            // In the case where we have no more specific thing to
2648            // say, also take a look at the error code, maybe we can
2649            // tailor to that.
2650            _ => match terr {
2651                TypeError::CyclicTy(ty)
2652                    if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() =>
2653                {
2654                    ObligationCauseFailureCode::ClosureSelfref { span }
2655                }
2656                TypeError::ForceInlineCast => {
2657                    ObligationCauseFailureCode::CantCoerceForceInline { span, subdiags }
2658                }
2659                TypeError::IntrinsicCast => {
2660                    ObligationCauseFailureCode::CantCoerceIntrinsic { span, subdiags }
2661                }
2662                _ => ObligationCauseFailureCode::Generic { span, subdiags },
2663            },
2664        }
2665    }
2666
2667    fn as_requirement_str(&self) -> &'static str {
2668        match self.code() {
2669            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
2670                "method type is compatible with trait"
2671            }
2672            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
2673                "associated type is compatible with trait"
2674            }
2675            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
2676                "const is compatible with trait"
2677            }
2678            ObligationCauseCode::MainFunctionType => "`main` function has the correct type",
2679            ObligationCauseCode::LangFunctionType(_) => "lang item function has the correct type",
2680            ObligationCauseCode::IntrinsicType => "intrinsic has the correct type",
2681            ObligationCauseCode::MethodReceiver => "method receiver has the correct type",
2682            _ => "types are compatible",
2683        }
2684    }
2685}
2686
2687/// Newtype to allow implementing IntoDiagArg
2688pub struct ObligationCauseAsDiagArg<'tcx>(pub ObligationCause<'tcx>);
2689
2690impl IntoDiagArg for ObligationCauseAsDiagArg<'_> {
2691    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
2692        let kind = match self.0.code() {
2693            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
2694                "method_compat"
2695            }
2696            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
2697                "type_compat"
2698            }
2699            ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
2700                "const_compat"
2701            }
2702            ObligationCauseCode::MainFunctionType => "fn_main_correct_type",
2703            ObligationCauseCode::LangFunctionType(_) => "fn_lang_correct_type",
2704            ObligationCauseCode::IntrinsicType => "intrinsic_correct_type",
2705            ObligationCauseCode::MethodReceiver => "method_correct_type",
2706            _ => "other",
2707        }
2708        .into();
2709        rustc_errors::DiagArgValue::Str(kind)
2710    }
2711}
2712
2713/// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2714/// extra information about each type, but we only care about the category.
2715#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TyCategory { }
#[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::marker::StructuralPartialEq for TyCategory { }
#[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_fields_are_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)]
2716pub enum TyCategory {
2717    Closure,
2718    Opaque,
2719    OpaqueFuture,
2720    Coroutine(hir::CoroutineKind),
2721    Foreign,
2722}
2723
2724impl fmt::Display for TyCategory {
2725    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2726        match self {
2727            Self::Closure => "closure".fmt(f),
2728            Self::Opaque => "opaque type".fmt(f),
2729            Self::OpaqueFuture => "future".fmt(f),
2730            Self::Coroutine(gk) => gk.fmt(f),
2731            Self::Foreign => "foreign type".fmt(f),
2732        }
2733    }
2734}
2735
2736impl TyCategory {
2737    pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
2738        match *ty.kind() {
2739            ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2740            ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
2741                let kind =
2742                    if tcx.ty_is_opaque_future(ty) { Self::OpaqueFuture } else { Self::Opaque };
2743                Some((kind, def_id))
2744            }
2745            ty::Coroutine(def_id, ..) => {
2746                Some((Self::Coroutine(tcx.coroutine_kind(def_id).unwrap()), def_id))
2747            }
2748            ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
2749            _ => None,
2750        }
2751    }
2752}