Skip to main content

rustc_trait_selection/error_reporting/infer/
mod.rs

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