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