Skip to main content

rustc_trait_selection/traits/select/
mod.rs

1//! Candidate selection. See the [rustc dev guide] for more information on how this works.
2//!
3//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection
4
5use std::cell::{Cell, RefCell};
6use std::cmp;
7use std::fmt::{self, Display};
8use std::ops::ControlFlow;
9
10use hir::def::DefKind;
11use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
12use rustc_data_structures::stack::ensure_sufficient_stack;
13use rustc_errors::{Diag, EmissionGuarantee};
14use rustc_hir::def_id::DefId;
15use rustc_hir::{self as hir, LangItem, find_attr};
16use rustc_infer::infer::BoundRegionConversionTime::{self, HigherRankedType};
17use rustc_infer::infer::DefineOpaqueTypes;
18use rustc_infer::infer::at::ToTrace;
19use rustc_infer::infer::relate::TypeRelation;
20use rustc_infer::traits::{PredicateObligations, TraitObligation};
21use rustc_macros::{TypeFoldable, TypeVisitable};
22use rustc_middle::bug;
23use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
24pub use rustc_middle::traits::select::*;
25use rustc_middle::ty::abstract_const::NotConstEvaluatable;
26use rustc_middle::ty::error::TypeErrorToStringExt;
27use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths};
28use rustc_middle::ty::{
29    self, CandidatePreferenceMode, DeepRejectCtxt, GenericArgsRef, PolyProjectionPredicate,
30    SizedTraitKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, TypingMode, Unnormalized, Upcast,
31    elaborate, may_use_unstable_feature,
32};
33use rustc_next_trait_solver::solve::AliasBoundKind;
34use rustc_span::Symbol;
35use tracing::{debug, instrument, trace};
36
37use self::EvaluationResult::*;
38use self::SelectionCandidate::*;
39use super::coherence::{self, Conflict};
40use super::project::ProjectionTermObligation;
41use super::util::closure_trait_ref_and_return_type;
42use super::{
43    ImplDerivedCause, Normalized, Obligation, ObligationCause, ObligationCauseCode,
44    PolyTraitObligation, PredicateObligation, Selection, SelectionError, SelectionResult,
45    TraitQueryMode, const_evaluatable, project, util, wf,
46};
47use crate::error_reporting::InferCtxtErrorExt;
48use crate::infer::{InferCtxt, InferOk, TypeFreshener};
49use crate::solve::InferCtxtSelectExt as _;
50use crate::traits::normalize::{normalize_with_depth, normalize_with_depth_to};
51use crate::traits::project::{ProjectAndUnifyResult, ProjectionCacheKeyExt};
52use crate::traits::{EvaluateConstErr, ProjectionCacheKey, effects, sizedness_fast_path};
53
54mod _match;
55mod candidate_assembly;
56mod confirmation;
57
58#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for IntercrateAmbiguityCause<'tcx> {
    #[inline]
    fn clone(&self) -> IntercrateAmbiguityCause<'tcx> {
        match self {
            IntercrateAmbiguityCause::DownstreamCrate {
                trait_ref: __self_0, self_ty: __self_1 } =>
                IntercrateAmbiguityCause::DownstreamCrate {
                    trait_ref: ::core::clone::Clone::clone(__self_0),
                    self_ty: ::core::clone::Clone::clone(__self_1),
                },
            IntercrateAmbiguityCause::UpstreamCrateUpdate {
                trait_ref: __self_0, self_ty: __self_1 } =>
                IntercrateAmbiguityCause::UpstreamCrateUpdate {
                    trait_ref: ::core::clone::Clone::clone(__self_0),
                    self_ty: ::core::clone::Clone::clone(__self_1),
                },
            IntercrateAmbiguityCause::ReservationImpl { message: __self_0 } =>
                IntercrateAmbiguityCause::ReservationImpl {
                    message: ::core::clone::Clone::clone(__self_0),
                },
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for IntercrateAmbiguityCause<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            IntercrateAmbiguityCause::DownstreamCrate {
                trait_ref: __self_0, self_ty: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "DownstreamCrate", "trait_ref", __self_0, "self_ty",
                    &__self_1),
            IntercrateAmbiguityCause::UpstreamCrateUpdate {
                trait_ref: __self_0, self_ty: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "UpstreamCrateUpdate", "trait_ref", __self_0, "self_ty",
                    &__self_1),
            IntercrateAmbiguityCause::ReservationImpl { message: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ReservationImpl", "message", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for IntercrateAmbiguityCause<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<ty::TraitRef<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Option<Ty<'tcx>>>;
        let _: ::core::cmp::AssertParamIsEq<ty::TraitRef<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Option<Ty<'tcx>>>;
        let _: ::core::cmp::AssertParamIsEq<Symbol>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for IntercrateAmbiguityCause<'tcx> {
    #[inline]
    fn eq(&self, other: &IntercrateAmbiguityCause<'tcx>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (IntercrateAmbiguityCause::DownstreamCrate {
                    trait_ref: __self_0, self_ty: __self_1 },
                    IntercrateAmbiguityCause::DownstreamCrate {
                    trait_ref: __arg1_0, self_ty: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (IntercrateAmbiguityCause::UpstreamCrateUpdate {
                    trait_ref: __self_0, self_ty: __self_1 },
                    IntercrateAmbiguityCause::UpstreamCrateUpdate {
                    trait_ref: __arg1_0, self_ty: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (IntercrateAmbiguityCause::ReservationImpl { message: __self_0
                    }, IntercrateAmbiguityCause::ReservationImpl {
                    message: __arg1_0 }) => __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for IntercrateAmbiguityCause<'tcx> {
    #[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 {
            IntercrateAmbiguityCause::DownstreamCrate {
                trait_ref: __self_0, self_ty: __self_1 } => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            IntercrateAmbiguityCause::UpstreamCrateUpdate {
                trait_ref: __self_0, self_ty: __self_1 } => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            IntercrateAmbiguityCause::ReservationImpl { message: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
        }
    }
}Hash)]
59pub enum IntercrateAmbiguityCause<'tcx> {
60    DownstreamCrate { trait_ref: ty::TraitRef<'tcx>, self_ty: Option<Ty<'tcx>> },
61    UpstreamCrateUpdate { trait_ref: ty::TraitRef<'tcx>, self_ty: Option<Ty<'tcx>> },
62    ReservationImpl { message: Symbol },
63}
64
65impl<'tcx> IntercrateAmbiguityCause<'tcx> {
66    /// Emits notes when the overlap is caused by complex intercrate ambiguities.
67    /// See #23980 for details.
68    pub fn add_intercrate_ambiguity_hint<G: EmissionGuarantee>(&self, err: &mut Diag<'_, G>) {
69        err.note(self.intercrate_ambiguity_hint());
70    }
71
72    pub fn intercrate_ambiguity_hint(&self) -> String {
73        {
    let _guard = NoTrimmedGuard::new();
    match self {
        IntercrateAmbiguityCause::DownstreamCrate { trait_ref, self_ty } => {
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("downstream crates may implement trait `{0}`{1}",
                            trait_ref.print_trait_sugared(),
                            if let Some(self_ty) = self_ty {
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!(" for type `{0}`",
                                                self_ty))
                                    })
                            } else { String::new() }))
                })
        }
        IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_ref, self_ty }
            => {
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("upstream crates may add a new impl of trait `{0}`{1} in future versions",
                            trait_ref.print_trait_sugared(),
                            if let Some(self_ty) = self_ty {
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!(" for type `{0}`",
                                                self_ty))
                                    })
                            } else { String::new() }))
                })
        }
        IntercrateAmbiguityCause::ReservationImpl { message } =>
            message.to_string(),
    }
}with_no_trimmed_paths!(match self {
74            IntercrateAmbiguityCause::DownstreamCrate { trait_ref, self_ty } => {
75                format!(
76                    "downstream crates may implement trait `{trait_desc}`{self_desc}",
77                    trait_desc = trait_ref.print_trait_sugared(),
78                    self_desc = if let Some(self_ty) = self_ty {
79                        format!(" for type `{self_ty}`")
80                    } else {
81                        String::new()
82                    }
83                )
84            }
85            IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_ref, self_ty } => {
86                format!(
87                    "upstream crates may add a new impl of trait `{trait_desc}`{self_desc} \
88                in future versions",
89                    trait_desc = trait_ref.print_trait_sugared(),
90                    self_desc = if let Some(self_ty) = self_ty {
91                        format!(" for type `{self_ty}`")
92                    } else {
93                        String::new()
94                    }
95                )
96            }
97            IntercrateAmbiguityCause::ReservationImpl { message } => message.to_string(),
98        })
99    }
100}
101
102pub struct SelectionContext<'cx, 'tcx> {
103    pub infcx: &'cx InferCtxt<'tcx>,
104
105    /// Freshener used specifically for entries on the obligation
106    /// stack. This ensures that all entries on the stack at one time
107    /// will have the same set of placeholder entries, which is
108    /// important for checking for trait bounds that recursively
109    /// require themselves.
110    freshener: TypeFreshener<'cx, 'tcx>,
111
112    /// If `intercrate` is set, we remember predicates which were
113    /// considered ambiguous because of impls potentially added in other crates.
114    /// This is used in coherence to give improved diagnostics.
115    /// We don't do his until we detect a coherence error because it can
116    /// lead to false overflow results (#47139) and because always
117    /// computing it may negatively impact performance.
118    intercrate_ambiguity_causes: Option<FxIndexSet<IntercrateAmbiguityCause<'tcx>>>,
119
120    /// The mode that trait queries run in, which informs our error handling
121    /// policy. In essence, canonicalized queries need their errors propagated
122    /// rather than immediately reported because we do not have accurate spans.
123    query_mode: TraitQueryMode,
124}
125
126// A stack that walks back up the stack frame.
127struct TraitObligationStack<'prev, 'tcx> {
128    obligation: &'prev PolyTraitObligation<'tcx>,
129
130    /// The trait predicate from `obligation` but "freshened" with the
131    /// selection-context's freshener. Used to check for recursion.
132    fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
133
134    /// Starts out equal to `depth` -- if, during evaluation, we
135    /// encounter a cycle, then we will set this flag to the minimum
136    /// depth of that cycle for all participants in the cycle. These
137    /// participants will then forego caching their results. This is
138    /// not the most efficient solution, but it addresses #60010. The
139    /// problem we are trying to prevent:
140    ///
141    /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
142    /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
143    /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
144    ///
145    /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
146    /// is `EvaluatedToOk`; this is because they were only considered
147    /// ok on the premise that if `A: AutoTrait` held, but we indeed
148    /// encountered a problem (later on) with `A: AutoTrait`. So we
149    /// currently set a flag on the stack node for `B: AutoTrait` (as
150    /// well as the second instance of `A: AutoTrait`) to suppress
151    /// caching.
152    ///
153    /// This is a simple, targeted fix. A more-performant fix requires
154    /// deeper changes, but would permit more caching: we could
155    /// basically defer caching until we have fully evaluated the
156    /// tree, and then cache the entire tree at once. In any case, the
157    /// performance impact here shouldn't be so horrible: every time
158    /// this is hit, we do cache at least one trait, so we only
159    /// evaluate each member of a cycle up to N times, where N is the
160    /// length of the cycle. This means the performance impact is
161    /// bounded and we shouldn't have any terrible worst-cases.
162    reached_depth: Cell<usize>,
163
164    previous: TraitObligationStackList<'prev, 'tcx>,
165
166    /// The number of parent frames plus one (thus, the topmost frame has depth 1).
167    depth: usize,
168
169    /// The depth-first number of this node in the search graph -- a
170    /// pre-order index. Basically, a freshly incremented counter.
171    dfn: usize,
172}
173
174struct SelectionCandidateSet<'tcx> {
175    /// A list of candidates that definitely apply to the current
176    /// obligation (meaning: types unify).
177    vec: Vec<SelectionCandidate<'tcx>>,
178
179    /// If `true`, then there were candidates that might or might
180    /// not have applied, but we couldn't tell. This occurs when some
181    /// of the input types are type variables, in which case there are
182    /// various "builtin" rules that might or might not trigger.
183    ambiguous: bool,
184}
185
186#[derive(#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for EvaluatedCandidate<'tcx> {
    #[inline]
    fn eq(&self, other: &EvaluatedCandidate<'tcx>) -> bool {
        self.candidate == other.candidate &&
            self.evaluation == other.evaluation
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for EvaluatedCandidate<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<SelectionCandidate<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<EvaluationResult>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for EvaluatedCandidate<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "EvaluatedCandidate", "candidate", &self.candidate, "evaluation",
            &&self.evaluation)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for EvaluatedCandidate<'tcx> {
    #[inline]
    fn clone(&self) -> EvaluatedCandidate<'tcx> {
        EvaluatedCandidate {
            candidate: ::core::clone::Clone::clone(&self.candidate),
            evaluation: ::core::clone::Clone::clone(&self.evaluation),
        }
    }
}Clone)]
187struct EvaluatedCandidate<'tcx> {
188    candidate: SelectionCandidate<'tcx>,
189    evaluation: EvaluationResult,
190}
191
192impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
193    pub fn new(infcx: &'cx InferCtxt<'tcx>) -> SelectionContext<'cx, 'tcx> {
194        SelectionContext {
195            infcx,
196            freshener: TypeFreshener::new(infcx),
197            intercrate_ambiguity_causes: None,
198            query_mode: TraitQueryMode::Standard,
199        }
200    }
201
202    pub fn with_query_mode(
203        infcx: &'cx InferCtxt<'tcx>,
204        query_mode: TraitQueryMode,
205    ) -> SelectionContext<'cx, 'tcx> {
206        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:206",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(206u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "query_mode"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("with_query_mode")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&query_mode)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?query_mode, "with_query_mode");
207        SelectionContext { query_mode, ..SelectionContext::new(infcx) }
208    }
209
210    /// Enables tracking of intercrate ambiguity causes. See
211    /// the documentation of [`Self::intercrate_ambiguity_causes`] for more.
212    pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
213        if !self.infcx.typing_mode().is_coherence() {
    ::core::panicking::panic("assertion failed: self.infcx.typing_mode().is_coherence()")
};assert!(self.infcx.typing_mode().is_coherence());
214        if !self.intercrate_ambiguity_causes.is_none() {
    ::core::panicking::panic("assertion failed: self.intercrate_ambiguity_causes.is_none()")
};assert!(self.intercrate_ambiguity_causes.is_none());
215
216        self.intercrate_ambiguity_causes = Some(FxIndexSet::default());
217        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:217",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(217u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("selcx: enable_tracking_intercrate_ambiguity_causes")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
218    }
219
220    /// Gets the intercrate ambiguity causes collected since tracking
221    /// was enabled and disables tracking at the same time. If
222    /// tracking is not enabled, just returns an empty vector.
223    pub fn take_intercrate_ambiguity_causes(
224        &mut self,
225    ) -> FxIndexSet<IntercrateAmbiguityCause<'tcx>> {
226        if !self.infcx.typing_mode().is_coherence() {
    ::core::panicking::panic("assertion failed: self.infcx.typing_mode().is_coherence()")
};assert!(self.infcx.typing_mode().is_coherence());
227
228        self.intercrate_ambiguity_causes.take().unwrap_or_default()
229    }
230
231    pub fn tcx(&self) -> TyCtxt<'tcx> {
232        self.infcx.tcx
233    }
234
235    ///////////////////////////////////////////////////////////////////////////
236    // Selection
237    //
238    // The selection phase tries to identify *how* an obligation will
239    // be resolved. For example, it will identify which impl or
240    // parameter bound is to be used. The process can be inconclusive
241    // if the self type in the obligation is not fully inferred. Selection
242    // can result in an error in one of two ways:
243    //
244    // 1. If no applicable impl or parameter bound can be found.
245    // 2. If the output type parameters in the obligation do not match
246    //    those specified by the impl/bound. For example, if the obligation
247    //    is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
248    //    `impl<T> Iterable<T> for Vec<T>`, than an error would result.
249
250    /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
251    /// type environment by performing unification.
252    x;#[instrument(level = "debug", skip(self), ret)]
253    pub fn poly_select(
254        &mut self,
255        obligation: &PolyTraitObligation<'tcx>,
256    ) -> SelectionResult<'tcx, Selection<'tcx>> {
257        assert!(!self.infcx.next_trait_solver());
258
259        let candidate = match self.select_from_obligation(obligation) {
260            Err(SelectionError::Overflow(OverflowError::Canonical)) => {
261                // In standard mode, overflow must have been caught and reported
262                // earlier.
263                assert!(self.query_mode == TraitQueryMode::Canonical);
264                return Err(SelectionError::Overflow(OverflowError::Canonical));
265            }
266            Err(e) => {
267                return Err(e);
268            }
269            Ok(None) => {
270                return Ok(None);
271            }
272            Ok(Some(candidate)) => candidate,
273        };
274
275        match self.confirm_candidate(obligation, candidate) {
276            Err(SelectionError::Overflow(OverflowError::Canonical)) => {
277                assert!(self.query_mode == TraitQueryMode::Canonical);
278                Err(SelectionError::Overflow(OverflowError::Canonical))
279            }
280            Err(e) => Err(e),
281            Ok(candidate) => Ok(Some(candidate)),
282        }
283    }
284
285    pub fn select(
286        &mut self,
287        obligation: &TraitObligation<'tcx>,
288    ) -> SelectionResult<'tcx, Selection<'tcx>> {
289        if self.infcx.next_trait_solver() {
290            return self.infcx.select_in_new_trait_solver(obligation);
291        }
292
293        self.poly_select(&Obligation {
294            cause: obligation.cause.clone(),
295            param_env: obligation.param_env,
296            predicate: ty::Binder::dummy(obligation.predicate),
297            recursion_depth: obligation.recursion_depth,
298        })
299    }
300
301    fn select_from_obligation(
302        &mut self,
303        obligation: &PolyTraitObligation<'tcx>,
304    ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
305        if true {
    if !!obligation.predicate.has_escaping_bound_vars() {
        ::core::panicking::panic("assertion failed: !obligation.predicate.has_escaping_bound_vars()")
    };
};debug_assert!(!obligation.predicate.has_escaping_bound_vars());
306
307        let pec = &ProvisionalEvaluationCache::default();
308        let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
309
310        self.candidate_from_obligation(&stack)
311    }
312
313    x;#[instrument(level = "debug", skip(self), ret)]
314    fn candidate_from_obligation<'o>(
315        &mut self,
316        stack: &TraitObligationStack<'o, 'tcx>,
317    ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
318        debug_assert!(!self.infcx.next_trait_solver());
319        // Watch out for overflow. This intentionally bypasses (and does
320        // not update) the cache.
321        self.check_recursion_limit(stack.obligation, stack.obligation)?;
322
323        // Check the cache. Note that we freshen the trait-ref
324        // separately rather than using `stack.fresh_trait_pred` --
325        // this is because we want the unbound variables to be
326        // replaced with fresh types starting from index 0.
327        let cache_fresh_trait_pred =
328            stack.obligation.predicate.fold_with(&mut TypeFreshener::new(self.infcx));
329        debug!(?cache_fresh_trait_pred);
330        debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
331
332        if let Some(c) =
333            self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred)
334        {
335            debug!("CACHE HIT");
336            return c;
337        }
338
339        // If no match, compute result and insert into cache.
340        //
341        // FIXME(nikomatsakis) -- this cache is not taking into
342        // account cycles that may have occurred in forming the
343        // candidate. I don't know of any specific problems that
344        // result but it seems awfully suspicious.
345        let (candidate, dep_node) =
346            self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
347
348        debug!("CACHE MISS");
349        self.insert_candidate_cache(
350            stack.obligation.param_env,
351            cache_fresh_trait_pred,
352            dep_node,
353            candidate.clone(),
354        );
355        candidate
356    }
357
358    fn candidate_from_obligation_no_cache<'o>(
359        &mut self,
360        stack: &TraitObligationStack<'o, 'tcx>,
361    ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
362        if let Err(conflict) = self.is_knowable(stack) {
363            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:363",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(363u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coherence stage: not knowable")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("coherence stage: not knowable");
364            if self.intercrate_ambiguity_causes.is_some() {
365                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:365",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(365u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("evaluate_stack: intercrate_ambiguity_causes is some")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("evaluate_stack: intercrate_ambiguity_causes is some");
366                // Heuristics: show the diagnostics when there are no candidates in crate.
367                if let Ok(candidate_set) = self.assemble_candidates(stack) {
368                    let mut no_candidates_apply = true;
369
370                    for c in candidate_set.vec.iter() {
371                        if self.evaluate_candidate(stack, c)?.may_apply() {
372                            no_candidates_apply = false;
373                            break;
374                        }
375                    }
376
377                    if !candidate_set.ambiguous && no_candidates_apply {
378                        let trait_ref = self.infcx.resolve_vars_if_possible(
379                            stack.obligation.predicate.skip_binder().trait_ref,
380                        );
381                        if !trait_ref.references_error() {
382                            let self_ty = trait_ref.self_ty();
383                            let self_ty = self_ty.has_concrete_skeleton().then(|| self_ty);
384                            let cause = if let Conflict::Upstream = conflict {
385                                IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_ref, self_ty }
386                            } else {
387                                IntercrateAmbiguityCause::DownstreamCrate { trait_ref, self_ty }
388                            };
389                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:389",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(389u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message", "cause"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("evaluate_stack: pushing cause")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&cause) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?cause, "evaluate_stack: pushing cause");
390                            self.intercrate_ambiguity_causes.as_mut().unwrap().insert(cause);
391                        }
392                    }
393                }
394            }
395            return Ok(None);
396        }
397
398        let candidate_set = self.assemble_candidates(stack)?;
399
400        if candidate_set.ambiguous {
401            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:401",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(401u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("candidate set contains ambig")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("candidate set contains ambig");
402            return Ok(None);
403        }
404
405        let candidates = candidate_set.vec;
406
407        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:407",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(407u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message", "stack",
                                        "candidates"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("assembled {0} candidates",
                                                    candidates.len()) as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&stack) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&candidates)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?stack, ?candidates, "assembled {} candidates", candidates.len());
408
409        // At this point, we know that each of the entries in the
410        // candidate set is *individually* applicable. Now we have to
411        // figure out if they contain mutual incompatibilities. This
412        // frequently arises if we have an unconstrained input type --
413        // for example, we are looking for `$0: Eq` where `$0` is some
414        // unconstrained type variable. In that case, we'll get a
415        // candidate which assumes $0 == int, one that assumes `$0 ==
416        // usize`, etc. This spells an ambiguity.
417
418        let mut candidates = self.filter_impls(candidates, stack.obligation);
419
420        // If there is more than one candidate, first winnow them down
421        // by considering extra conditions (nested obligations and so
422        // forth). We don't winnow if there is exactly one
423        // candidate. This is a relatively minor distinction but it
424        // can lead to better inference and error-reporting. An
425        // example would be if there was an impl:
426        //
427        //     impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
428        //
429        // and we were to see some code `foo.push_clone()` where `boo`
430        // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
431        // we were to winnow, we'd wind up with zero candidates.
432        // Instead, we select the right impl now but report "`Bar` does
433        // not implement `Clone`".
434        if candidates.len() == 1 {
435            return self.filter_reservation_impls(candidates.pop().unwrap());
436        }
437
438        // Winnow, but record the exact outcome of evaluation, which
439        // is needed for specialization. Propagate overflow if it occurs.
440        let candidates = candidates
441            .into_iter()
442            .map(|c| match self.evaluate_candidate(stack, &c) {
443                Ok(eval) if eval.may_apply() => {
444                    Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
445                }
446                Ok(_) => Ok(None),
447                Err(OverflowError::Canonical) => {
448                    Err(SelectionError::Overflow(OverflowError::Canonical))
449                }
450                Err(OverflowError::Error(e)) => {
451                    Err(SelectionError::Overflow(OverflowError::Error(e)))
452                }
453            })
454            .flat_map(Result::transpose)
455            .collect::<Result<Vec<_>, _>>()?;
456
457        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:457",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(457u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message", "stack",
                                        "candidates"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("{0} potentially applicable candidates",
                                                    candidates.len()) as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&stack) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&candidates)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?stack, ?candidates, "{} potentially applicable candidates", candidates.len());
458        // If there are *NO* candidates, then there are no impls --
459        // that we know of, anyway. Note that in the case where there
460        // are unbound type variables within the obligation, it might
461        // be the case that you could still satisfy the obligation
462        // from another crate by instantiating the type variables with
463        // a type from another crate that does have an impl. This case
464        // is checked for in `evaluate_stack` (and hence users
465        // who might care about this case, like coherence, should use
466        // that function).
467        if candidates.is_empty() {
468            // If there's an error type, 'downgrade' our result from
469            // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
470            // emitting additional spurious errors, since we're guaranteed
471            // to have emitted at least one.
472            if stack.obligation.predicate.references_error() {
473                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:473",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(473u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "stack.obligation.predicate"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("found error type in predicate, treating as ambiguous")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&stack.obligation.predicate)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?stack.obligation.predicate, "found error type in predicate, treating as ambiguous");
474                Ok(None)
475            } else {
476                Err(SelectionError::Unimplemented)
477            }
478        } else {
479            let has_non_region_infer = stack.obligation.predicate.has_non_region_infer();
480            let candidate_preference_mode =
481                CandidatePreferenceMode::compute(self.tcx(), stack.obligation.predicate.def_id());
482            if let Some(candidate) =
483                self.winnow_candidates(has_non_region_infer, candidate_preference_mode, candidates)
484            {
485                self.filter_reservation_impls(candidate)
486            } else {
487                Ok(None)
488            }
489        }
490    }
491
492    ///////////////////////////////////////////////////////////////////////////
493    // EVALUATION
494    //
495    // Tests whether an obligation can be selected or whether an impl
496    // can be applied to particular types. It skips the "confirmation"
497    // step and hence completely ignores output type parameters.
498    //
499    // The result is "true" if the obligation *may* hold and "false" if
500    // we can be sure it does not.
501
502    /// Evaluates whether the obligation `obligation` can be satisfied
503    /// and returns an `EvaluationResult`. This is meant for the
504    /// *initial* call.
505    ///
506    /// Do not use this directly, use `infcx.evaluate_obligation` instead.
507    pub fn evaluate_root_obligation(
508        &mut self,
509        obligation: &PredicateObligation<'tcx>,
510    ) -> Result<EvaluationResult, OverflowError> {
511        if true {
    if !!self.infcx.next_trait_solver() {
        ::core::panicking::panic("assertion failed: !self.infcx.next_trait_solver()")
    };
};debug_assert!(!self.infcx.next_trait_solver());
512        self.evaluation_probe(|this| {
513            let goal =
514                this.infcx.resolve_vars_if_possible((obligation.predicate, obligation.param_env));
515            let mut result = this.evaluate_predicate_recursively(
516                TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
517                obligation.clone(),
518            )?;
519            // If the predicate has done any inference, then downgrade the
520            // result to ambiguous.
521            if this.infcx.resolve_vars_if_possible(goal) != goal {
522                result = result.max(EvaluatedToAmbig);
523            }
524            Ok(result)
525        })
526    }
527
528    /// Computes the evaluation result of `op`, discarding any constraints.
529    ///
530    /// This also runs for leak check to allow higher ranked region errors to impact
531    /// selection. By default it checks for leaks from all universes created inside of
532    /// `op`, but this can be overwritten if necessary.
533    fn evaluation_probe(
534        &mut self,
535        op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
536    ) -> Result<EvaluationResult, OverflowError> {
537        self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
538            let outer_universe = self.infcx.universe();
539            let result = op(self)?;
540
541            match self.infcx.leak_check(outer_universe, Some(snapshot)) {
542                Ok(()) => {}
543                Err(_) => return Ok(EvaluatedToErr),
544            }
545
546            if self.infcx.opaque_types_added_in_snapshot(snapshot) {
547                return Ok(result.max(EvaluatedToOkModuloOpaqueTypes));
548            }
549
550            if self.infcx.region_constraints_added_in_snapshot(snapshot) {
551                Ok(result.max(EvaluatedToOkModuloRegions))
552            } else {
553                Ok(result)
554            }
555        })
556    }
557
558    /// Evaluates the predicates in `predicates` recursively. This may
559    /// guide inference. If this is not desired, run it inside of a
560    /// is run within an inference probe.
561    /// `probe`.
562    #[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("evaluate_predicates_recursively",
                                    "rustc_trait_selection::traits::select",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(562u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&["predicates"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicates)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<EvaluationResult, OverflowError> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut result = EvaluatedToOk;
            for mut obligation in predicates {
                obligation.set_depth_from_parent(stack.depth());
                let eval =
                    self.evaluate_predicate_recursively(stack,
                            obligation.clone())?;
                if let EvaluatedToErr = eval {
                    return Ok(EvaluatedToErr);
                } else { result = cmp::max(result, eval); }
            }
            Ok(result)
        }
    }
}#[instrument(skip(self, stack), level = "debug")]
563    fn evaluate_predicates_recursively<'o, I>(
564        &mut self,
565        stack: TraitObligationStackList<'o, 'tcx>,
566        predicates: I,
567    ) -> Result<EvaluationResult, OverflowError>
568    where
569        I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
570    {
571        let mut result = EvaluatedToOk;
572        for mut obligation in predicates {
573            obligation.set_depth_from_parent(stack.depth());
574            let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
575            if let EvaluatedToErr = eval {
576                // fast-path - EvaluatedToErr is the top of the lattice,
577                // so we don't need to look on the other predicates.
578                return Ok(EvaluatedToErr);
579            } else {
580                result = cmp::max(result, eval);
581            }
582        }
583        Ok(result)
584    }
585
586    x;#[instrument(
587        level = "debug",
588        skip(self, previous_stack),
589        fields(previous_stack = ?previous_stack.head())
590        ret,
591    )]
592    fn evaluate_predicate_recursively<'o>(
593        &mut self,
594        previous_stack: TraitObligationStackList<'o, 'tcx>,
595        obligation: PredicateObligation<'tcx>,
596    ) -> Result<EvaluationResult, OverflowError> {
597        debug_assert!(!self.infcx.next_trait_solver());
598        // `previous_stack` stores a `PolyTraitObligation`, while `obligation` is
599        // a `PredicateObligation`. These are distinct types, so we can't
600        // use any `Option` combinator method that would force them to be
601        // the same.
602        match previous_stack.head() {
603            Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
604            None => self.check_recursion_limit(&obligation, &obligation)?,
605        }
606
607        if sizedness_fast_path(self.tcx(), obligation.predicate, obligation.param_env) {
608            return Ok(EvaluatedToOk);
609        }
610
611        ensure_sufficient_stack(|| {
612            let bound_predicate = obligation.predicate.kind();
613            match bound_predicate.skip_binder() {
614                ty::PredicateKind::Clause(ty::ClauseKind::Trait(t)) => {
615                    let t = bound_predicate.rebind(t);
616                    debug_assert!(!t.has_escaping_bound_vars());
617                    let obligation = obligation.with(self.tcx(), t);
618                    self.evaluate_trait_predicate_recursively(previous_stack, obligation)
619                }
620
621                ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(data)) => {
622                    self.infcx.enter_forall(bound_predicate.rebind(data), |data| {
623                        match effects::evaluate_host_effect_obligation(
624                            self,
625                            &obligation.with(self.tcx(), data),
626                        ) {
627                            Ok(nested) => {
628                                self.evaluate_predicates_recursively(previous_stack, nested)
629                            }
630                            Err(effects::EvaluationFailure::Ambiguous) => Ok(EvaluatedToAmbig),
631                            Err(effects::EvaluationFailure::NoSolution) => Ok(EvaluatedToErr),
632                        }
633                    })
634                }
635
636                ty::PredicateKind::Subtype(p) => {
637                    let p = bound_predicate.rebind(p);
638                    // Does this code ever run?
639                    match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
640                        Ok(Ok(InferOk { obligations, .. })) => {
641                            self.evaluate_predicates_recursively(previous_stack, obligations)
642                        }
643                        Ok(Err(_)) => Ok(EvaluatedToErr),
644                        Err(..) => Ok(EvaluatedToAmbig),
645                    }
646                }
647
648                ty::PredicateKind::Coerce(p) => {
649                    let p = bound_predicate.rebind(p);
650                    // Does this code ever run?
651                    match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
652                        Ok(Ok(InferOk { obligations, .. })) => {
653                            self.evaluate_predicates_recursively(previous_stack, obligations)
654                        }
655                        Ok(Err(_)) => Ok(EvaluatedToErr),
656                        Err(..) => Ok(EvaluatedToAmbig),
657                    }
658                }
659
660                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
661                    if term.is_trivially_wf(self.tcx()) {
662                        return Ok(EvaluatedToOk);
663                    }
664
665                    // So, there is a bit going on here. First, `WellFormed` predicates
666                    // are coinductive, like trait predicates with auto traits.
667                    // This means that we need to detect if we have recursively
668                    // evaluated `WellFormed(X)`. Otherwise, we would run into
669                    // a "natural" overflow error.
670                    //
671                    // Now, the next question is whether we need to do anything
672                    // special with caching. Considering the following tree:
673                    // - `WF(Foo<T>)`
674                    //   - `Bar<T>: Send`
675                    //     - `WF(Foo<T>)`
676                    //   - `Foo<T>: Trait`
677                    // In this case, the innermost `WF(Foo<T>)` should return
678                    // `EvaluatedToOk`, since it's coinductive. Then if
679                    // `Bar<T>: Send` is resolved to `EvaluatedToOk`, it can be
680                    // inserted into a cache (because without thinking about `WF`
681                    // goals, it isn't in a cycle). If `Foo<T>: Trait` later doesn't
682                    // hold, then `Bar<T>: Send` shouldn't hold. Therefore, we
683                    // *do* need to keep track of coinductive cycles.
684
685                    let cache = previous_stack.cache;
686                    let dfn = cache.next_dfn();
687
688                    for stack_term in previous_stack.cache.wf_args.borrow().iter().rev() {
689                        if stack_term.0 != term {
690                            continue;
691                        }
692                        debug!("WellFormed({:?}) on stack", term);
693                        if let Some(stack) = previous_stack.head {
694                            // Okay, let's imagine we have two different stacks:
695                            //   `T: NonAutoTrait -> WF(T) -> T: NonAutoTrait`
696                            //   `WF(T) -> T: NonAutoTrait -> WF(T)`
697                            // Because of this, we need to check that all
698                            // predicates between the WF goals are coinductive.
699                            // Otherwise, we can say that `T: NonAutoTrait` is
700                            // true.
701                            // Let's imagine we have a predicate stack like
702                            //         `Foo: Bar -> WF(T) -> T: NonAutoTrait -> T: Auto`
703                            // depth   ^1                    ^2                 ^3
704                            // and the current predicate is `WF(T)`. `wf_args`
705                            // would contain `(T, 1)`. We want to check all
706                            // trait predicates greater than `1`. The previous
707                            // stack would be `T: Auto`.
708                            let cycle = stack.iter().take_while(|s| s.depth > stack_term.1);
709                            let tcx = self.tcx();
710                            let cycle = cycle.map(|stack| stack.obligation.predicate.upcast(tcx));
711                            if self.coinductive_match(cycle) {
712                                stack.update_reached_depth(stack_term.1);
713                                return Ok(EvaluatedToOk);
714                            } else {
715                                return Ok(EvaluatedToAmbigStackDependent);
716                            }
717                        }
718                        return Ok(EvaluatedToOk);
719                    }
720
721                    match wf::obligations(
722                        self.infcx,
723                        obligation.param_env,
724                        obligation.cause.body_id,
725                        obligation.recursion_depth + 1,
726                        term,
727                        obligation.cause.span,
728                    ) {
729                        Some(obligations) => {
730                            cache.wf_args.borrow_mut().push((term, previous_stack.depth()));
731                            let result =
732                                self.evaluate_predicates_recursively(previous_stack, obligations);
733                            cache.wf_args.borrow_mut().pop();
734
735                            let result = result?;
736
737                            if !result.must_apply_modulo_regions() {
738                                cache.on_failure(dfn);
739                            }
740
741                            cache.on_completion(dfn);
742
743                            Ok(result)
744                        }
745                        None => Ok(EvaluatedToAmbig),
746                    }
747                }
748
749                ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(pred)) => {
750                    // A global type with no free lifetimes or generic parameters
751                    // outlives anything.
752                    if pred.0.has_free_regions()
753                        || pred.0.has_bound_regions()
754                        || pred.0.has_non_region_infer()
755                        || pred.0.has_non_region_infer()
756                    {
757                        Ok(EvaluatedToOkModuloRegions)
758                    } else {
759                        Ok(EvaluatedToOk)
760                    }
761                }
762
763                ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..)) => {
764                    // We do not consider region relationships when evaluating trait matches.
765                    Ok(EvaluatedToOkModuloRegions)
766                }
767
768                ty::PredicateKind::DynCompatible(trait_def_id) => {
769                    if self.tcx().is_dyn_compatible(trait_def_id) {
770                        Ok(EvaluatedToOk)
771                    } else {
772                        Ok(EvaluatedToErr)
773                    }
774                }
775
776                ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
777                    let data = bound_predicate.rebind(data);
778                    let project_obligation = obligation.with(self.tcx(), data);
779                    match project::poly_project_and_unify_term(self, &project_obligation) {
780                        ProjectAndUnifyResult::Holds(mut subobligations) => {
781                            'compute_res: {
782                                // If we've previously marked this projection as 'complete', then
783                                // use the final cached result (either `EvaluatedToOk` or
784                                // `EvaluatedToOkModuloRegions`), and skip re-evaluating the
785                                // sub-obligations.
786                                if let Some(key) =
787                                    ProjectionCacheKey::from_poly_projection_obligation(
788                                        self,
789                                        &project_obligation,
790                                    )
791                                    && let Some(cached_res) = self
792                                        .infcx
793                                        .inner
794                                        .borrow_mut()
795                                        .projection_cache()
796                                        .is_complete(key)
797                                {
798                                    break 'compute_res Ok(cached_res);
799                                }
800
801                                // Need to explicitly set the depth of nested goals here as
802                                // projection obligations can cycle by themselves and in
803                                // `evaluate_predicates_recursively` we only add the depth
804                                // for parent trait goals because only these get added to the
805                                // `TraitObligationStackList`.
806                                for subobligation in subobligations.iter_mut() {
807                                    subobligation.set_depth_from_parent(obligation.recursion_depth);
808                                }
809                                let res = self.evaluate_predicates_recursively(
810                                    previous_stack,
811                                    subobligations,
812                                );
813                                if let Ok(eval_rslt) = res
814                                    && (eval_rslt == EvaluatedToOk
815                                        || eval_rslt == EvaluatedToOkModuloRegions)
816                                    && let Some(key) =
817                                        ProjectionCacheKey::from_poly_projection_obligation(
818                                            self,
819                                            &project_obligation,
820                                        )
821                                {
822                                    // If the result is something that we can cache, then mark this
823                                    // entry as 'complete'. This will allow us to skip evaluating the
824                                    // subobligations at all the next time we evaluate the projection
825                                    // predicate.
826                                    self.infcx
827                                        .inner
828                                        .borrow_mut()
829                                        .projection_cache()
830                                        .complete(key, eval_rslt);
831                                }
832                                res
833                            }
834                        }
835                        ProjectAndUnifyResult::FailedNormalization => Ok(EvaluatedToAmbig),
836                        ProjectAndUnifyResult::Recursive => Ok(EvaluatedToAmbigStackDependent),
837                        ProjectAndUnifyResult::MismatchedProjectionTypes(_) => Ok(EvaluatedToErr),
838                    }
839                }
840
841                ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(symbol)) => {
842                    if may_use_unstable_feature(self.infcx, obligation.param_env, symbol) {
843                        Ok(EvaluatedToOk)
844                    } else {
845                        Ok(EvaluatedToAmbig)
846                    }
847                }
848
849                ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(uv)) => {
850                    match const_evaluatable::is_const_evaluatable(
851                        self.infcx,
852                        uv,
853                        obligation.param_env,
854                        obligation.cause.span,
855                    ) {
856                        Ok(()) => Ok(EvaluatedToOk),
857                        Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
858                        Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
859                        Err(_) => Ok(EvaluatedToErr),
860                    }
861                }
862
863                ty::PredicateKind::ConstEquate(c1, c2) => {
864                    let tcx = self.tcx();
865                    assert!(
866                        tcx.features().generic_const_exprs(),
867                        "`ConstEquate` without a feature gate: {c1:?} {c2:?}",
868                    );
869
870                    {
871                        let c1 = tcx.expand_abstract_consts(c1);
872                        let c2 = tcx.expand_abstract_consts(c2);
873                        debug!(
874                            "evaluate_predicate_recursively: equating consts:\nc1= {:?}\nc2= {:?}",
875                            c1, c2
876                        );
877
878                        use rustc_hir::def::DefKind;
879                        match (c1.kind(), c2.kind()) {
880                            (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b))
881                                if a.def == b.def
882                                    && matches!(
883                                        tcx.def_kind(a.def),
884                                        DefKind::AssocConst { .. }
885                                    ) =>
886                            {
887                                if let Ok(InferOk { obligations, value: () }) = self
888                                    .infcx
889                                    .at(&obligation.cause, obligation.param_env)
890                                    // Can define opaque types as this is only reachable with
891                                    // `generic_const_exprs`
892                                    .eq(
893                                        DefineOpaqueTypes::Yes,
894                                        ty::AliasTerm::from_unevaluated_const(tcx, a),
895                                        ty::AliasTerm::from_unevaluated_const(tcx, b),
896                                    )
897                                {
898                                    return self.evaluate_predicates_recursively(
899                                        previous_stack,
900                                        obligations,
901                                    );
902                                }
903                            }
904                            (_, ty::ConstKind::Unevaluated(_))
905                            | (ty::ConstKind::Unevaluated(_), _) => (),
906                            (_, _) => {
907                                if let Ok(InferOk { obligations, value: () }) = self
908                                    .infcx
909                                    .at(&obligation.cause, obligation.param_env)
910                                    // Can define opaque types as this is only reachable with
911                                    // `generic_const_exprs`
912                                    .eq(DefineOpaqueTypes::Yes, c1, c2)
913                                {
914                                    return self.evaluate_predicates_recursively(
915                                        previous_stack,
916                                        obligations,
917                                    );
918                                }
919                            }
920                        }
921                    }
922
923                    let evaluate = |c: ty::Const<'tcx>| {
924                        if let ty::ConstKind::Unevaluated(_) = c.kind() {
925                            match crate::traits::try_evaluate_const(
926                                self.infcx,
927                                c,
928                                obligation.param_env,
929                            ) {
930                                Ok(val) => Ok(val),
931                                Err(e) => Err(e),
932                            }
933                        } else {
934                            Ok(c)
935                        }
936                    };
937
938                    match (evaluate(c1), evaluate(c2)) {
939                        (Ok(c1), Ok(c2)) => {
940                            match self.infcx.at(&obligation.cause, obligation.param_env).eq(
941                                // Can define opaque types as this is only reachable with
942                                // `generic_const_exprs`
943                                DefineOpaqueTypes::Yes,
944                                c1,
945                                c2,
946                            ) {
947                                Ok(inf_ok) => self.evaluate_predicates_recursively(
948                                    previous_stack,
949                                    inf_ok.into_obligations(),
950                                ),
951                                Err(_) => Ok(EvaluatedToErr),
952                            }
953                        }
954                        (Err(EvaluateConstErr::InvalidConstParamTy(..)), _)
955                        | (_, Err(EvaluateConstErr::InvalidConstParamTy(..))) => Ok(EvaluatedToErr),
956                        (Err(EvaluateConstErr::EvaluationFailure(..)), _)
957                        | (_, Err(EvaluateConstErr::EvaluationFailure(..))) => Ok(EvaluatedToErr),
958                        (Err(EvaluateConstErr::HasGenericsOrInfers), _)
959                        | (_, Err(EvaluateConstErr::HasGenericsOrInfers)) => {
960                            if c1.has_non_region_infer() || c2.has_non_region_infer() {
961                                Ok(EvaluatedToAmbig)
962                            } else {
963                                // Two different constants using generic parameters ~> error.
964                                Ok(EvaluatedToErr)
965                            }
966                        }
967                    }
968                }
969                ty::PredicateKind::NormalizesTo(..) => {
970                    bug!("NormalizesTo is only used by the new solver")
971                }
972                ty::PredicateKind::AliasRelate(..) => {
973                    bug!("AliasRelate is only used by the new solver")
974                }
975                ty::PredicateKind::Ambiguous => Ok(EvaluatedToAmbig),
976                ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
977                    let ct = self.infcx.shallow_resolve_const(ct);
978                    let ct_ty = match ct.kind() {
979                        ty::ConstKind::Infer(_) => {
980                            return Ok(EvaluatedToAmbig);
981                        }
982                        ty::ConstKind::Error(_) => return Ok(EvaluatedToOk),
983                        ty::ConstKind::Value(cv) => cv.ty,
984                        ty::ConstKind::Unevaluated(uv) => self
985                            .tcx()
986                            .type_of(uv.def)
987                            .instantiate(self.tcx(), uv.args)
988                            .skip_norm_wip(),
989                        // FIXME(generic_const_exprs): See comment in `fulfill.rs`
990                        ty::ConstKind::Expr(_) => return Ok(EvaluatedToOk),
991                        ty::ConstKind::Placeholder(_) => {
992                            bug!("placeholder const {:?} in old solver", ct)
993                        }
994                        ty::ConstKind::Bound(_, _) => bug!("escaping bound vars in {:?}", ct),
995                        ty::ConstKind::Param(param_ct) => {
996                            param_ct.find_const_ty_from_env(obligation.param_env)
997                        }
998                    };
999
1000                    match self.infcx.at(&obligation.cause, obligation.param_env).eq(
1001                        // Only really exercised by generic_const_exprs
1002                        DefineOpaqueTypes::Yes,
1003                        ct_ty,
1004                        ty,
1005                    ) {
1006                        Ok(inf_ok) => self.evaluate_predicates_recursively(
1007                            previous_stack,
1008                            inf_ok.into_obligations(),
1009                        ),
1010                        Err(_) => Ok(EvaluatedToErr),
1011                    }
1012                }
1013            }
1014        })
1015    }
1016
1017    x;#[instrument(skip(self, previous_stack), level = "debug", ret)]
1018    fn evaluate_trait_predicate_recursively<'o>(
1019        &mut self,
1020        previous_stack: TraitObligationStackList<'o, 'tcx>,
1021        mut obligation: PolyTraitObligation<'tcx>,
1022    ) -> Result<EvaluationResult, OverflowError> {
1023        if !self.infcx.typing_mode().is_coherence()
1024            && obligation.is_global()
1025            && obligation.param_env.caller_bounds().iter().all(|bound| bound.has_param())
1026        {
1027            // If a param env has no global bounds, global obligations do not
1028            // depend on its particular value in order to work, so we can clear
1029            // out the param env and get better caching.
1030            debug!("in global");
1031            obligation.param_env = ty::ParamEnv::empty();
1032        }
1033
1034        let stack = self.push_stack(previous_stack, &obligation);
1035        let fresh_trait_pred = stack.fresh_trait_pred;
1036        let param_env = obligation.param_env;
1037
1038        debug!(?fresh_trait_pred);
1039
1040        // If a trait predicate is in the (local or global) evaluation cache,
1041        // then we know it holds without cycles.
1042        if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
1043            debug!("CACHE HIT");
1044            return Ok(result);
1045        }
1046
1047        if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
1048            debug!("PROVISIONAL CACHE HIT");
1049            stack.update_reached_depth(result.reached_depth);
1050            return Ok(result.result);
1051        }
1052
1053        // Check if this is a match for something already on the
1054        // stack. If so, we don't want to insert the result into the
1055        // main cache (it is cycle dependent) nor the provisional
1056        // cache (which is meant for things that have completed but
1057        // for a "backedge" -- this result *is* the backedge).
1058        if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
1059            return Ok(cycle_result);
1060        }
1061
1062        let (result, dep_node) = self.in_task(|this| {
1063            let mut result = this.evaluate_stack(&stack)?;
1064
1065            // fix issue #103563, we don't normalize
1066            // nested obligations which produced by `TraitDef` candidate
1067            // (i.e. using bounds on assoc items as assumptions).
1068            // because we don't have enough information to
1069            // normalize these obligations before evaluating.
1070            // so we will try to normalize the obligation and evaluate again.
1071            // we will replace it with new solver in the future.
1072            if EvaluationResult::EvaluatedToErr == result
1073                && fresh_trait_pred.has_aliases()
1074                && fresh_trait_pred.is_global()
1075            {
1076                let mut nested_obligations = PredicateObligations::new();
1077                let predicate = normalize_with_depth_to(
1078                    this,
1079                    param_env,
1080                    obligation.cause.clone(),
1081                    obligation.recursion_depth + 1,
1082                    obligation.predicate,
1083                    &mut nested_obligations,
1084                );
1085                if predicate != obligation.predicate {
1086                    let mut nested_result = EvaluationResult::EvaluatedToOk;
1087                    for obligation in nested_obligations {
1088                        nested_result = cmp::max(
1089                            this.evaluate_predicate_recursively(previous_stack, obligation)?,
1090                            nested_result,
1091                        );
1092                    }
1093
1094                    if nested_result.must_apply_modulo_regions() {
1095                        let obligation = obligation.with(this.tcx(), predicate);
1096                        result = cmp::max(
1097                            nested_result,
1098                            this.evaluate_trait_predicate_recursively(previous_stack, obligation)?,
1099                        );
1100                    }
1101                }
1102            }
1103
1104            Ok::<_, OverflowError>(result)
1105        });
1106
1107        let result = result?;
1108
1109        if !result.must_apply_modulo_regions() {
1110            stack.cache().on_failure(stack.dfn);
1111        }
1112
1113        let reached_depth = stack.reached_depth.get();
1114        if reached_depth >= stack.depth {
1115            debug!("CACHE MISS");
1116            self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
1117            stack.cache().on_completion(stack.dfn);
1118        } else if let Some(_guar) = self.infcx.tainted_by_errors() {
1119            // When an error has occurred, we allow global caching of results even if they
1120            // appear stack-dependent. This prevents exponential re-evaluation of cycles
1121            // in the presence of errors, avoiding compiler hangs like #150907.
1122            // This is safe because compilation will fail anyway.
1123            debug!("CACHE MISS (tainted by errors)");
1124            self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
1125            stack.cache().on_completion(stack.dfn);
1126        } else {
1127            debug!("PROVISIONAL");
1128            debug!(
1129                "caching provisionally because {:?} \
1130                 is a cycle participant (at depth {}, reached depth {})",
1131                fresh_trait_pred, stack.depth, reached_depth,
1132            );
1133
1134            stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_pred, result);
1135        }
1136
1137        Ok(result)
1138    }
1139
1140    /// If there is any previous entry on the stack that precisely
1141    /// matches this obligation, then we can assume that the
1142    /// obligation is satisfied for now (still all other conditions
1143    /// must be met of course). One obvious case this comes up is
1144    /// marker traits like `Send`. Think of a linked list:
1145    ///
1146    ///     struct List<T> { data: T, next: Option<Box<List<T>>> }
1147    ///
1148    /// `Box<List<T>>` will be `Send` if `T` is `Send` and
1149    /// `Option<Box<List<T>>>` is `Send`, and in turn
1150    /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
1151    /// `Send`.
1152    ///
1153    /// Note that we do this comparison using the `fresh_trait_pred`
1154    /// fields. Because these have all been freshened using
1155    /// `self.freshener`, we can be sure that (a) this will not
1156    /// affect the inferencer state and (b) that if we see two
1157    /// fresh regions with the same index, they refer to the same
1158    /// unbound type variable.
1159    fn check_evaluation_cycle(
1160        &mut self,
1161        stack: &TraitObligationStack<'_, 'tcx>,
1162    ) -> Option<EvaluationResult> {
1163        if let Some(cycle_depth) = stack
1164            .iter()
1165            .skip(1) // Skip top-most frame.
1166            .find(|prev| {
1167                stack.obligation.param_env == prev.obligation.param_env
1168                    && stack.fresh_trait_pred == prev.fresh_trait_pred
1169            })
1170            .map(|stack| stack.depth)
1171        {
1172            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1172",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1172u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("evaluate_stack --> recursive at depth {0}",
                                                    cycle_depth) as &dyn Value))])
            });
    } else { ; }
};debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
1173
1174            // If we have a stack like `A B C D E A`, where the top of
1175            // the stack is the final `A`, then this will iterate over
1176            // `A, E, D, C, B` -- i.e., all the participants apart
1177            // from the cycle head. We mark them as participating in a
1178            // cycle. This suppresses caching for those nodes. See
1179            // `in_cycle` field for more details.
1180            stack.update_reached_depth(cycle_depth);
1181
1182            // Subtle: when checking for a coinductive cycle, we do
1183            // not compare using the "freshened trait refs" (which
1184            // have erased regions) but rather the fully explicit
1185            // trait refs. This is important because it's only a cycle
1186            // if the regions match exactly.
1187            let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
1188            let tcx = self.tcx();
1189            let cycle = cycle.map(|stack| stack.obligation.predicate.upcast(tcx));
1190            if self.coinductive_match(cycle) {
1191                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1191",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1191u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("evaluate_stack --> recursive, coinductive")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("evaluate_stack --> recursive, coinductive");
1192                Some(EvaluatedToOk)
1193            } else {
1194                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1194",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1194u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("evaluate_stack --> recursive, inductive")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("evaluate_stack --> recursive, inductive");
1195                Some(EvaluatedToAmbigStackDependent)
1196            }
1197        } else {
1198            None
1199        }
1200    }
1201
1202    fn evaluate_stack<'o>(
1203        &mut self,
1204        stack: &TraitObligationStack<'o, 'tcx>,
1205    ) -> Result<EvaluationResult, OverflowError> {
1206        if true {
    if !!self.infcx.next_trait_solver() {
        ::core::panicking::panic("assertion failed: !self.infcx.next_trait_solver()")
    };
};debug_assert!(!self.infcx.next_trait_solver());
1207        // In intercrate mode, whenever any of the generics are unbound,
1208        // there can always be an impl. Even if there are no impls in
1209        // this crate, perhaps the type would be unified with
1210        // something from another crate that does provide an impl.
1211        //
1212        // In intra mode, we must still be conservative. The reason is
1213        // that we want to avoid cycles. Imagine an impl like:
1214        //
1215        //     impl<T:Eq> Eq for Vec<T>
1216        //
1217        // and a trait reference like `$0 : Eq` where `$0` is an
1218        // unbound variable. When we evaluate this trait-reference, we
1219        // will unify `$0` with `Vec<$1>` (for some fresh variable
1220        // `$1`), on the condition that `$1 : Eq`. We will then wind
1221        // up with many candidates (since that are other `Eq` impls
1222        // that apply) and try to winnow things down. This results in
1223        // a recursive evaluation that `$1 : Eq` -- as you can
1224        // imagine, this is just where we started. To avoid that, we
1225        // check for unbound variables and return an ambiguous (hence possible)
1226        // match if we've seen this trait before.
1227        //
1228        // This suffices to allow chains like `FnMut` implemented in
1229        // terms of `Fn` etc, but we could probably make this more
1230        // precise still.
1231        let unbound_input_types =
1232            stack.fresh_trait_pred.skip_binder().trait_ref.args.types().any(|ty| ty.is_fresh());
1233
1234        if unbound_input_types
1235            && stack.iter().skip(1).any(|prev| {
1236                stack.obligation.param_env == prev.obligation.param_env
1237                    && self.match_fresh_trait_preds(stack.fresh_trait_pred, prev.fresh_trait_pred)
1238            })
1239        {
1240            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1240",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1240u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("evaluate_stack --> unbound argument, recursive --> giving up")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("evaluate_stack --> unbound argument, recursive --> giving up");
1241            return Ok(EvaluatedToAmbigStackDependent);
1242        }
1243
1244        match self.candidate_from_obligation(stack) {
1245            Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1246            Ok(None) => Ok(EvaluatedToAmbig),
1247            Err(SelectionError::Overflow(OverflowError::Canonical)) => {
1248                Err(OverflowError::Canonical)
1249            }
1250            Err(..) => Ok(EvaluatedToErr),
1251        }
1252    }
1253
1254    /// For defaulted traits, we use a co-inductive strategy to solve, so
1255    /// that recursion is ok. This routine returns `true` if the top of the
1256    /// stack (`cycle[0]`):
1257    ///
1258    /// - is a coinductive trait: an auto-trait or `Sized`,
1259    /// - it also appears in the backtrace at some position `X`,
1260    /// - all the predicates at positions `X..` between `X` and the top are
1261    ///   also coinductive traits.
1262    pub(crate) fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
1263    where
1264        I: Iterator<Item = ty::Predicate<'tcx>>,
1265    {
1266        cycle.all(|p| match p.kind().skip_binder() {
1267            ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => {
1268                self.infcx.tcx.trait_is_coinductive(data.def_id())
1269            }
1270            ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => {
1271                // FIXME(generic_const_exprs): GCE needs well-formedness predicates to be
1272                // coinductive, but GCE is on the way out anyways, so this should eventually
1273                // be replaced with `false`.
1274                self.infcx.tcx.features().generic_const_exprs()
1275            }
1276            _ => false,
1277        })
1278    }
1279
1280    /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
1281    /// obligations are met. Returns whether `candidate` remains viable after this further
1282    /// scrutiny.
1283    x;#[instrument(
1284        level = "debug",
1285        skip(self, stack),
1286        fields(depth = stack.obligation.recursion_depth),
1287        ret
1288    )]
1289    fn evaluate_candidate<'o>(
1290        &mut self,
1291        stack: &TraitObligationStack<'o, 'tcx>,
1292        candidate: &SelectionCandidate<'tcx>,
1293    ) -> Result<EvaluationResult, OverflowError> {
1294        let mut result = self.evaluation_probe(|this| {
1295            match this.confirm_candidate(stack.obligation, candidate.clone()) {
1296                Ok(selection) => {
1297                    debug!(?selection);
1298                    this.evaluate_predicates_recursively(
1299                        stack.list(),
1300                        selection.nested_obligations().into_iter(),
1301                    )
1302                }
1303                Err(..) => Ok(EvaluatedToErr),
1304            }
1305        })?;
1306
1307        // If we erased any lifetimes, then we want to use
1308        // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
1309        // as your final result. The result will be cached using
1310        // the freshened trait predicate as a key, so we need
1311        // our result to be correct by *any* choice of original lifetimes,
1312        // not just the lifetime choice for this particular (non-erased)
1313        // predicate.
1314        // See issue #80691
1315        if stack.fresh_trait_pred.has_erased_regions() {
1316            result = result.max(EvaluatedToOkModuloRegions);
1317        }
1318
1319        Ok(result)
1320    }
1321
1322    fn check_evaluation_cache(
1323        &self,
1324        param_env: ty::ParamEnv<'tcx>,
1325        trait_pred: ty::PolyTraitPredicate<'tcx>,
1326    ) -> Option<EvaluationResult> {
1327        let infcx = self.infcx;
1328        let tcx = infcx.tcx;
1329        if self.can_use_global_caches(param_env, trait_pred) {
1330            let key = (infcx.typing_env(param_env), trait_pred);
1331            if let Some(res) = tcx.evaluation_cache.get(&key, tcx) {
1332                Some(res)
1333            } else {
1334                if true {
    match (&infcx.evaluation_cache.get(&(param_env, trait_pred), tcx), &None)
        {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(infcx.evaluation_cache.get(&(param_env, trait_pred), tcx), None);
1335                None
1336            }
1337        } else {
1338            self.infcx.evaluation_cache.get(&(param_env, trait_pred), tcx)
1339        }
1340    }
1341
1342    fn insert_evaluation_cache(
1343        &mut self,
1344        param_env: ty::ParamEnv<'tcx>,
1345        trait_pred: ty::PolyTraitPredicate<'tcx>,
1346        dep_node: DepNodeIndex,
1347        result: EvaluationResult,
1348    ) {
1349        // Avoid caching results that depend on more than just the trait-ref
1350        // - the stack can create recursion.
1351        if result.is_stack_dependent() {
1352            return;
1353        }
1354
1355        let infcx = self.infcx;
1356        let tcx = infcx.tcx;
1357        if self.can_use_global_caches(param_env, trait_pred) {
1358            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1358",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1358u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "trait_pred", "result"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("insert_evaluation_cache global")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&trait_pred)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&result) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?trait_pred, ?result, "insert_evaluation_cache global");
1359            // This may overwrite the cache with the same value
1360            tcx.evaluation_cache.insert(
1361                (infcx.typing_env(param_env), trait_pred),
1362                dep_node,
1363                result,
1364            );
1365            return;
1366        } else {
1367            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1367",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1367u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "trait_pred", "result"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("insert_evaluation_cache local")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&trait_pred)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&result) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?trait_pred, ?result, "insert_evaluation_cache local");
1368            self.infcx.evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1369        }
1370    }
1371
1372    fn check_recursion_depth<T>(
1373        &self,
1374        depth: usize,
1375        error_obligation: &Obligation<'tcx, T>,
1376    ) -> Result<(), OverflowError>
1377    where
1378        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + Clone,
1379    {
1380        if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1381            match self.query_mode {
1382                TraitQueryMode::Standard => {
1383                    if let Some(e) = self.infcx.tainted_by_errors() {
1384                        return Err(OverflowError::Error(e));
1385                    }
1386                    self.infcx.err_ctxt().report_overflow_obligation(error_obligation, true);
1387                }
1388                TraitQueryMode::Canonical => {
1389                    return Err(OverflowError::Canonical);
1390                }
1391            }
1392        }
1393        Ok(())
1394    }
1395
1396    /// Checks that the recursion limit has not been exceeded.
1397    ///
1398    /// The weird return type of this function allows it to be used with the `try` (`?`)
1399    /// operator within certain functions.
1400    #[inline(always)]
1401    fn check_recursion_limit<T: Display + TypeFoldable<TyCtxt<'tcx>>, V>(
1402        &self,
1403        obligation: &Obligation<'tcx, T>,
1404        error_obligation: &Obligation<'tcx, V>,
1405    ) -> Result<(), OverflowError>
1406    where
1407        V: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + Clone,
1408    {
1409        self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1410    }
1411
1412    fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1413    where
1414        OP: FnOnce(&mut Self) -> R,
1415    {
1416        self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self))
1417    }
1418
1419    /// filter_impls filters candidates that have a positive impl for a negative
1420    /// goal and a negative impl for a positive goal
1421    #[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("filter_impls",
                                    "rustc_trait_selection::traits::select",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1421u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&["obligation"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Vec<SelectionCandidate<'tcx>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1427",
                                    "rustc_trait_selection::traits::select",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1427u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("{0:#?}",
                                                                candidates) as &dyn Value))])
                        });
                } else { ; }
            };
            let tcx = self.tcx();
            let mut result = Vec::with_capacity(candidates.len());
            for candidate in candidates {
                if let ImplCandidate(def_id) = candidate {
                    match (tcx.impl_polarity(def_id), obligation.polarity()) {
                        (ty::ImplPolarity::Reservation, _) |
                            (ty::ImplPolarity::Positive,
                            ty::PredicatePolarity::Positive) |
                            (ty::ImplPolarity::Negative,
                            ty::PredicatePolarity::Negative) => {
                            result.push(candidate);
                        }
                        _ => {}
                    }
                } else { result.push(candidate); }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1446",
                                    "rustc_trait_selection::traits::select",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1446u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("{0:#?}",
                                                                result) as &dyn Value))])
                        });
                } else { ; }
            };
            result
        }
    }
}#[instrument(level = "debug", skip(self, candidates))]
1422    fn filter_impls(
1423        &mut self,
1424        candidates: Vec<SelectionCandidate<'tcx>>,
1425        obligation: &PolyTraitObligation<'tcx>,
1426    ) -> Vec<SelectionCandidate<'tcx>> {
1427        trace!("{candidates:#?}");
1428        let tcx = self.tcx();
1429        let mut result = Vec::with_capacity(candidates.len());
1430
1431        for candidate in candidates {
1432            if let ImplCandidate(def_id) = candidate {
1433                match (tcx.impl_polarity(def_id), obligation.polarity()) {
1434                    (ty::ImplPolarity::Reservation, _)
1435                    | (ty::ImplPolarity::Positive, ty::PredicatePolarity::Positive)
1436                    | (ty::ImplPolarity::Negative, ty::PredicatePolarity::Negative) => {
1437                        result.push(candidate);
1438                    }
1439                    _ => {}
1440                }
1441            } else {
1442                result.push(candidate);
1443            }
1444        }
1445
1446        trace!("{result:#?}");
1447        result
1448    }
1449
1450    /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1451    #[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("filter_reservation_impls",
                                    "rustc_trait_selection::traits::select",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1451u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&["candidate"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    SelectionResult<'tcx, SelectionCandidate<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            if let ImplCandidate(def_id) = candidate &&
                    let ty::ImplPolarity::Reservation =
                        tcx.impl_polarity(def_id) {
                if let Some(intercrate_ambiguity_clauses) =
                        &mut self.intercrate_ambiguity_causes {
                    let message =
                        {
                            {
                                'done:
                                    {
                                    for i in
                                        ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
                                        #[allow(unused_imports)]
                                        use rustc_hir::attrs::AttributeKind::*;
                                        let i: &rustc_hir::Attribute = i;
                                        match i {
                                            rustc_hir::Attribute::Parsed(RustcReservationImpl(_,
                                                message)) => {
                                                break 'done Some(*message);
                                            }
                                            rustc_hir::Attribute::Unparsed(..) =>
                                                {}
                                                #[deny(unreachable_patterns)]
                                                _ => {}
                                        }
                                    }
                                    None
                                }
                            }
                        };
                    if let Some(message) = message {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1464",
                                                "rustc_trait_selection::traits::select",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                                ::tracing_core::__macro_support::Option::Some(1464u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("filter_reservation_impls: reservation impl ambiguity on {0:?}",
                                                                            def_id) as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        intercrate_ambiguity_clauses.insert(IntercrateAmbiguityCause::ReservationImpl {
                                message,
                            });
                    }
                }
                return Ok(None);
            }
            Ok(Some(candidate))
        }
    }
}#[instrument(level = "debug", skip(self))]
1452    fn filter_reservation_impls(
1453        &mut self,
1454        candidate: SelectionCandidate<'tcx>,
1455    ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1456        let tcx = self.tcx();
1457        // Treat reservation impls as ambiguity.
1458        if let ImplCandidate(def_id) = candidate
1459            && let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id)
1460        {
1461            if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1462                let message = find_attr!(tcx, def_id, RustcReservationImpl(_, message) => *message);
1463                if let Some(message) = message {
1464                    debug!(
1465                        "filter_reservation_impls: \
1466                                 reservation impl ambiguity on {:?}",
1467                        def_id
1468                    );
1469                    intercrate_ambiguity_clauses
1470                        .insert(IntercrateAmbiguityCause::ReservationImpl { message });
1471                }
1472            }
1473            return Ok(None);
1474        }
1475        Ok(Some(candidate))
1476    }
1477
1478    fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Result<(), Conflict> {
1479        let obligation = &stack.obligation;
1480        match self.infcx.typing_mode() {
1481            TypingMode::Coherence => {}
1482            TypingMode::Analysis { .. }
1483            | TypingMode::Borrowck { .. }
1484            | TypingMode::PostBorrowckAnalysis { .. }
1485            | TypingMode::PostAnalysis => return Ok(()),
1486        }
1487
1488        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1488",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1488u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("is_knowable()")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("is_knowable()");
1489
1490        let predicate = self.infcx.resolve_vars_if_possible(obligation.predicate);
1491
1492        // Okay to skip binder because of the nature of the
1493        // trait-ref-is-knowable check, which does not care about
1494        // bound regions.
1495        let trait_ref = predicate.skip_binder().trait_ref;
1496
1497        coherence::trait_ref_is_knowable(self.infcx, trait_ref, |ty| Ok::<_, !>(ty)).into_ok()
1498    }
1499
1500    /// Returns `true` if the global caches can be used.
1501    fn can_use_global_caches(
1502        &self,
1503        param_env: ty::ParamEnv<'tcx>,
1504        pred: ty::PolyTraitPredicate<'tcx>,
1505    ) -> bool {
1506        // If there are any inference variables in the `ParamEnv`, then we
1507        // always use a cache local to this particular scope. Otherwise, we
1508        // switch to a global cache.
1509        if param_env.has_infer() || pred.has_infer() {
1510            return false;
1511        }
1512
1513        match self.infcx.typing_mode() {
1514            // Avoid using the global cache during coherence and just rely
1515            // on the local cache. It is really just a simplification to
1516            // avoid us having to fear that coherence results "pollute"
1517            // the master cache. Since coherence executes pretty quickly,
1518            // it's not worth going to more trouble to increase the
1519            // hit-rate, I don't think.
1520            TypingMode::Coherence => false,
1521            // Avoid using the global cache when we're defining opaque types
1522            // as their hidden type may impact the result of candidate selection.
1523            //
1524            // HACK: This is still theoretically unsound. Goals can indirectly rely
1525            // on opaques in the defining scope, and it's easier to do so with TAIT.
1526            // However, if we disqualify *all* goals from being cached, perf suffers.
1527            // This is likely fixed by better caching in general in the new solver.
1528            // See: <https://github.com/rust-lang/rust/issues/132064>.
1529            TypingMode::Analysis {
1530                defining_opaque_types_and_generators: defining_opaque_types,
1531            }
1532            | TypingMode::Borrowck { defining_opaque_types } => {
1533                defining_opaque_types.is_empty()
1534                    || (!pred.has_opaque_types() && !pred.has_coroutines())
1535            }
1536            // The hidden types of `defined_opaque_types` is not local to the current
1537            // inference context, so we can freely move this to the global cache.
1538            TypingMode::PostBorrowckAnalysis { .. } => true,
1539            // The global cache is only used if there are no opaque types in
1540            // the defining scope or we're outside of analysis.
1541            //
1542            // FIXME(#132279): This is still incorrect as we treat opaque types
1543            // and default associated items differently between these two modes.
1544            TypingMode::PostAnalysis => true,
1545        }
1546    }
1547
1548    fn check_candidate_cache(
1549        &mut self,
1550        param_env: ty::ParamEnv<'tcx>,
1551        cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1552    ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1553        let infcx = self.infcx;
1554        let tcx = infcx.tcx;
1555        let pred = cache_fresh_trait_pred.skip_binder();
1556
1557        if self.can_use_global_caches(param_env, cache_fresh_trait_pred) {
1558            if let Some(res) = tcx.selection_cache.get(&(infcx.typing_env(param_env), pred), tcx) {
1559                return Some(res);
1560            } else if truecfg!(debug_assertions) {
1561                match infcx.selection_cache.get(&(param_env, pred), tcx) {
1562                    None | Some(Err(SelectionError::Overflow(OverflowError::Canonical))) => {}
1563                    res => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected local cache result: {0:?}",
        res))bug!("unexpected local cache result: {res:?}"),
1564                }
1565            }
1566        }
1567
1568        // Subtle: we need to check the local cache even if we're able to use the
1569        // global cache as we don't cache overflow in the global cache but need to
1570        // cache it as otherwise rustdoc hangs when compiling diesel.
1571        infcx.selection_cache.get(&(param_env, pred), tcx)
1572    }
1573
1574    /// Determines whether can we safely cache the result
1575    /// of selecting an obligation. This is almost always `true`,
1576    /// except when dealing with certain `ParamCandidate`s.
1577    ///
1578    /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1579    /// since it was usually produced directly from a `DefId`. However,
1580    /// certain cases (currently only librustdoc's blanket impl finder),
1581    /// a `ParamEnv` may be explicitly constructed with inference types.
1582    /// When this is the case, we do *not* want to cache the resulting selection
1583    /// candidate. This is due to the fact that it might not always be possible
1584    /// to equate the obligation's trait ref and the candidate's trait ref,
1585    /// if more constraints end up getting added to an inference variable.
1586    ///
1587    /// Because of this, we always want to re-run the full selection
1588    /// process for our obligation the next time we see it, since
1589    /// we might end up picking a different `SelectionCandidate` (or none at all).
1590    fn can_cache_candidate(
1591        &self,
1592        result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1593    ) -> bool {
1594        match result {
1595            Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.has_infer(),
1596            _ => true,
1597        }
1598    }
1599
1600    #[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("insert_candidate_cache",
                                    "rustc_trait_selection::traits::select",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1600u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&["candidate"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let infcx = self.infcx;
            let tcx = infcx.tcx;
            let pred = cache_fresh_trait_pred.skip_binder();
            if !self.can_cache_candidate(&candidate) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1613",
                                        "rustc_trait_selection::traits::select",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1613u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                        ::tracing_core::field::FieldSet::new(&["message", "pred",
                                                        "candidate"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("insert_candidate_cache - candidate is not cacheable")
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&pred) as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&candidate)
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                return;
            }
            if self.can_use_global_caches(param_env, cache_fresh_trait_pred) {
                if let Err(SelectionError::Overflow(OverflowError::Canonical))
                        = candidate
                    {} else {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1621",
                                            "rustc_trait_selection::traits::select",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(1621u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                            ::tracing_core::field::FieldSet::new(&["message", "pred",
                                                            "candidate"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("insert_candidate_cache global")
                                                                as &dyn Value)),
                                                    (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&pred) as
                                                                &dyn Value)),
                                                    (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&candidate)
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    if true {
                        if !!candidate.has_infer() {
                            ::core::panicking::panic("assertion failed: !candidate.has_infer()")
                        };
                    };
                    tcx.selection_cache.insert((infcx.typing_env(param_env),
                            pred), dep_node, candidate);
                    return;
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:1634",
                                    "rustc_trait_selection::traits::select",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1634u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&["message", "pred",
                                                    "candidate"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("insert_candidate_cache local")
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&pred) as
                                                        &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&candidate)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            self.infcx.selection_cache.insert((param_env, pred), dep_node,
                candidate);
        }
    }
}#[instrument(skip(self, param_env, cache_fresh_trait_pred, dep_node), level = "debug")]
1601    fn insert_candidate_cache(
1602        &mut self,
1603        param_env: ty::ParamEnv<'tcx>,
1604        cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1605        dep_node: DepNodeIndex,
1606        candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1607    ) {
1608        let infcx = self.infcx;
1609        let tcx = infcx.tcx;
1610        let pred = cache_fresh_trait_pred.skip_binder();
1611
1612        if !self.can_cache_candidate(&candidate) {
1613            debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1614            return;
1615        }
1616
1617        if self.can_use_global_caches(param_env, cache_fresh_trait_pred) {
1618            if let Err(SelectionError::Overflow(OverflowError::Canonical)) = candidate {
1619                // Don't cache overflow globally; we only produce this in certain modes.
1620            } else {
1621                debug!(?pred, ?candidate, "insert_candidate_cache global");
1622                debug_assert!(!candidate.has_infer());
1623
1624                // This may overwrite the cache with the same value.
1625                tcx.selection_cache.insert(
1626                    (infcx.typing_env(param_env), pred),
1627                    dep_node,
1628                    candidate,
1629                );
1630                return;
1631            }
1632        }
1633
1634        debug!(?pred, ?candidate, "insert_candidate_cache local");
1635        self.infcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1636    }
1637
1638    /// Looks at the item bounds of the projection or opaque type.
1639    /// If this is a nested rigid projection, such as
1640    /// `<<T as Tr1>::Assoc as Tr2>::Assoc`, consider the item bounds
1641    /// on both `Tr1::Assoc` and `Tr2::Assoc`, since we may encounter
1642    /// relative bounds on both via the `associated_type_bounds` feature.
1643    pub(super) fn for_each_item_bound<T>(
1644        &mut self,
1645        mut self_ty: Ty<'tcx>,
1646        mut for_each: impl FnMut(
1647            &mut Self,
1648            ty::Clause<'tcx>,
1649            usize,
1650            AliasBoundKind,
1651        ) -> ControlFlow<T, ()>,
1652        on_ambiguity: impl FnOnce(),
1653    ) -> ControlFlow<T, ()> {
1654        let mut idx = 0;
1655        let mut alias_bound_kind = AliasBoundKind::SelfBounds;
1656
1657        loop {
1658            let (alias_ty, def_id) = match *self_ty.kind() {
1659                ty::Alias(
1660                    alias_ty @ ty::AliasTy {
1661                        kind: ty::Projection { def_id } | ty::Opaque { def_id },
1662                        ..
1663                    },
1664                ) => (alias_ty, def_id),
1665                ty::Infer(ty::TyVar(_)) => {
1666                    on_ambiguity();
1667                    return ControlFlow::Continue(());
1668                }
1669                _ => return ControlFlow::Continue(()),
1670            };
1671
1672            // HACK: On subsequent recursions, we only care about bounds that don't
1673            // share the same type as `self_ty`. This is because for truly rigid
1674            // projections, we will never be able to equate, e.g. `<T as Tr>::A`
1675            // with `<<T as Tr>::A as Tr>::A`.
1676            let relevant_bounds = if alias_bound_kind == AliasBoundKind::NonSelfBounds {
1677                self.tcx().item_non_self_bounds(def_id)
1678            } else {
1679                self.tcx().item_self_bounds(def_id)
1680            };
1681
1682            for bound in relevant_bounds.instantiate(self.tcx(), alias_ty.args).skip_norm_wip() {
1683                for_each(self, bound, idx, alias_bound_kind)?;
1684                idx += 1;
1685            }
1686
1687            if #[allow(non_exhaustive_omitted_patterns)] match alias_ty.kind {
    ty::Projection { .. } => true,
    _ => false,
}matches!(alias_ty.kind, ty::Projection { .. }) {
1688                self_ty = alias_ty.self_ty();
1689            } else {
1690                return ControlFlow::Continue(());
1691            }
1692
1693            alias_bound_kind = AliasBoundKind::NonSelfBounds;
1694        }
1695    }
1696
1697    /// Equates the trait in `obligation` with trait bound. If the two traits
1698    /// can be equated and the normalized trait bound doesn't contain inference
1699    /// variables or placeholders, the normalized bound is returned.
1700    fn match_normalize_trait_ref(
1701        &mut self,
1702        obligation: &PolyTraitObligation<'tcx>,
1703        placeholder_trait_ref: ty::TraitRef<'tcx>,
1704        trait_bound: ty::PolyTraitRef<'tcx>,
1705    ) -> Result<Option<ty::TraitRef<'tcx>>, ()> {
1706        if true {
    if !!placeholder_trait_ref.has_escaping_bound_vars() {
        ::core::panicking::panic("assertion failed: !placeholder_trait_ref.has_escaping_bound_vars()")
    };
};debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1707        if placeholder_trait_ref.def_id != trait_bound.def_id() {
1708            // Avoid unnecessary normalization
1709            return Err(());
1710        }
1711
1712        let drcx = DeepRejectCtxt::relate_rigid_rigid(self.infcx.tcx);
1713        let obligation_args = obligation.predicate.skip_binder().trait_ref.args;
1714        if !drcx.args_may_unify(obligation_args, trait_bound.skip_binder().args) {
1715            return Err(());
1716        }
1717
1718        let trait_bound = self.infcx.instantiate_binder_with_fresh_vars(
1719            obligation.cause.span,
1720            HigherRankedType,
1721            trait_bound,
1722        );
1723        let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1724            normalize_with_depth(
1725                self,
1726                obligation.param_env,
1727                obligation.cause.clone(),
1728                obligation.recursion_depth + 1,
1729                trait_bound,
1730            )
1731        });
1732        self.infcx
1733            .at(&obligation.cause, obligation.param_env)
1734            .eq(DefineOpaqueTypes::No, placeholder_trait_ref, trait_bound)
1735            .map(|InferOk { obligations: _, value: () }| {
1736                // This method is called within a probe, so we can't have
1737                // inference variables and placeholders escape.
1738                if !trait_bound.has_infer() && !trait_bound.has_placeholders() {
1739                    Some(trait_bound)
1740                } else {
1741                    None
1742                }
1743            })
1744            .map_err(|_| ())
1745    }
1746
1747    fn where_clause_may_apply<'o>(
1748        &mut self,
1749        stack: &TraitObligationStack<'o, 'tcx>,
1750        where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1751    ) -> Result<EvaluationResult, OverflowError> {
1752        self.evaluation_probe(|this| {
1753            match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1754                Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1755                Err(()) => Ok(EvaluatedToErr),
1756            }
1757        })
1758    }
1759
1760    /// Return `Yes` if the obligation's predicate type applies to the env_predicate, and
1761    /// `No` if it does not. Return `Ambiguous` in the case that the projection type is a GAT,
1762    /// and applying this env_predicate constrains any of the obligation's GAT parameters.
1763    ///
1764    /// This behavior is a somewhat of a hack to prevent over-constraining inference variables
1765    /// in cases like #91762.
1766    pub(super) fn match_projection_projections(
1767        &mut self,
1768        obligation: &ProjectionTermObligation<'tcx>,
1769        env_predicate: PolyProjectionPredicate<'tcx>,
1770        potentially_unnormalized_candidates: bool,
1771    ) -> ProjectionMatchesProjection {
1772        if true {
    match (&obligation.predicate.def_id(), &env_predicate.item_def_id()) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(obligation.predicate.def_id(), env_predicate.item_def_id());
1773
1774        let mut nested_obligations = PredicateObligations::new();
1775        let infer_predicate = self.infcx.instantiate_binder_with_fresh_vars(
1776            obligation.cause.span,
1777            BoundRegionConversionTime::HigherRankedType,
1778            env_predicate,
1779        );
1780        let infer_projection = if potentially_unnormalized_candidates {
1781            ensure_sufficient_stack(|| {
1782                normalize_with_depth_to(
1783                    self,
1784                    obligation.param_env,
1785                    obligation.cause.clone(),
1786                    obligation.recursion_depth + 1,
1787                    infer_predicate.projection_term,
1788                    &mut nested_obligations,
1789                )
1790            })
1791        } else {
1792            infer_predicate.projection_term
1793        };
1794
1795        let is_match = self
1796            .infcx
1797            .at(&obligation.cause, obligation.param_env)
1798            .eq(DefineOpaqueTypes::No, obligation.predicate, infer_projection)
1799            .is_ok_and(|InferOk { obligations, value: () }| {
1800                self.evaluate_predicates_recursively(
1801                    TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1802                    nested_obligations.into_iter().chain(obligations),
1803                )
1804                .is_ok_and(|res| res.may_apply())
1805            });
1806
1807        if is_match {
1808            let generics = self.tcx().generics_of(obligation.predicate.def_id());
1809            // FIXME(generic_associated_types): Addresses aggressive inference in #92917.
1810            // If this type is a GAT, and of the GAT args resolve to something new,
1811            // that means that we must have newly inferred something about the GAT.
1812            // We should give up in that case.
1813            //
1814            // This only detects one layer of inference, which is probably not what we actually
1815            // want, but fixing it causes some ambiguity:
1816            // <https://github.com/rust-lang/rust/issues/125196>.
1817            if !generics.is_own_empty()
1818                && obligation.predicate.args[generics.parent_count..].iter().any(|&p| {
1819                    p.has_non_region_infer()
1820                        && match p.kind() {
1821                            ty::GenericArgKind::Const(ct) => {
1822                                self.infcx.shallow_resolve_const(ct) != ct
1823                            }
1824                            ty::GenericArgKind::Type(ty) => self.infcx.shallow_resolve(ty) != ty,
1825                            ty::GenericArgKind::Lifetime(_) => false,
1826                        }
1827                })
1828            {
1829                ProjectionMatchesProjection::Ambiguous
1830            } else {
1831                ProjectionMatchesProjection::Yes
1832            }
1833        } else {
1834            ProjectionMatchesProjection::No
1835        }
1836    }
1837}
1838
1839/// ## Winnowing
1840///
1841/// Winnowing is the process of attempting to resolve ambiguity by
1842/// probing further. During the winnowing process, we unify all
1843/// type variables and then we also attempt to evaluate recursive
1844/// bounds to see if they are satisfied.
1845impl<'tcx> SelectionContext<'_, 'tcx> {
1846    /// If there are multiple ways to prove a trait goal, we make some
1847    /// *fairly arbitrary* choices about which candidate is actually used.
1848    ///
1849    /// For more details, look at the implementation of this method :)
1850    x;#[instrument(level = "debug", skip(self), ret)]
1851    fn winnow_candidates(
1852        &mut self,
1853        has_non_region_infer: bool,
1854        candidate_preference_mode: CandidatePreferenceMode,
1855        mut candidates: Vec<EvaluatedCandidate<'tcx>>,
1856    ) -> Option<SelectionCandidate<'tcx>> {
1857        if candidates.len() == 1 {
1858            return Some(candidates.pop().unwrap().candidate);
1859        }
1860
1861        // We prefer `Sized` candidates over everything.
1862        let mut sized_candidates =
1863            candidates.iter().filter(|c| matches!(c.candidate, SizedCandidate));
1864        if let Some(sized_candidate) = sized_candidates.next() {
1865            // There should only ever be a single sized candidate
1866            // as they would otherwise overlap.
1867            debug_assert_eq!(sized_candidates.next(), None);
1868            // Only prefer the built-in `Sized` candidate if its nested goals are certain.
1869            // Otherwise, we may encounter failure later on if inference causes this candidate
1870            // to not hold, but a where clause would've applied instead.
1871            if sized_candidate.evaluation.must_apply_modulo_regions() {
1872                return Some(sized_candidate.candidate.clone());
1873            } else {
1874                return None;
1875            }
1876        }
1877
1878        // Before we consider where-bounds, we have to deduplicate them here and also
1879        // drop where-bounds in case the same where-bound exists without bound vars.
1880        // This is necessary as elaborating super-trait bounds may result in duplicates.
1881        'search_victim: loop {
1882            for (i, this) in candidates.iter().enumerate() {
1883                let ParamCandidate(this) = this.candidate else { continue };
1884                for (j, other) in candidates.iter().enumerate() {
1885                    if i == j {
1886                        continue;
1887                    }
1888
1889                    let ParamCandidate(other) = other.candidate else { continue };
1890                    if this == other {
1891                        candidates.remove(j);
1892                        continue 'search_victim;
1893                    }
1894
1895                    if this.skip_binder().trait_ref == other.skip_binder().trait_ref
1896                        && this.skip_binder().polarity == other.skip_binder().polarity
1897                        && !this.skip_binder().trait_ref.has_escaping_bound_vars()
1898                    {
1899                        candidates.remove(j);
1900                        continue 'search_victim;
1901                    }
1902                }
1903            }
1904
1905            break;
1906        }
1907
1908        let mut alias_bounds = candidates.iter().filter_map(|c| {
1909            if let ProjectionCandidate { idx, kind } = c.candidate {
1910                Some((idx, kind))
1911            } else {
1912                None
1913            }
1914        });
1915        // Extract non-nested alias bound candidates, will be preferred over where bounds if
1916        // we're proving an auto-trait, sizedness trait or default trait.
1917        if matches!(candidate_preference_mode, CandidatePreferenceMode::Marker) {
1918            match alias_bounds
1919                .clone()
1920                .filter_map(|(idx, kind)| (kind == AliasBoundKind::SelfBounds).then_some(idx))
1921                .try_reduce(|c1, c2| if has_non_region_infer { None } else { Some(c1.min(c2)) })
1922            {
1923                Some(Some(idx)) => {
1924                    return Some(ProjectionCandidate { idx, kind: AliasBoundKind::SelfBounds });
1925                }
1926                Some(None) => {}
1927                None => return None,
1928            }
1929        }
1930
1931        // The next highest priority is for non-global where-bounds. However, while we don't
1932        // prefer global where-clauses here, we do bail with ambiguity when encountering both
1933        // a global and a non-global where-clause.
1934        //
1935        // Our handling of where-bounds is generally fairly messy but necessary for backwards
1936        // compatibility, see #50825 for why we need to handle global where-bounds like this.
1937        let is_global = |c: ty::PolyTraitPredicate<'tcx>| c.is_global() && !c.has_bound_vars();
1938        let param_candidates = candidates
1939            .iter()
1940            .filter_map(|c| if let ParamCandidate(p) = c.candidate { Some(p) } else { None });
1941        let mut has_global_bounds = false;
1942        let mut param_candidate = None;
1943        for c in param_candidates {
1944            if is_global(c) {
1945                has_global_bounds = true;
1946            } else if param_candidate.replace(c).is_some() {
1947                // Ambiguity, two potentially different where-clauses
1948                return None;
1949            }
1950        }
1951        if let Some(predicate) = param_candidate {
1952            // Ambiguity, a global and a non-global where-bound.
1953            if has_global_bounds {
1954                return None;
1955            } else {
1956                return Some(ParamCandidate(predicate));
1957            }
1958        }
1959
1960        // Prefer alias-bounds over blanket impls for rigid associated types. This is
1961        // fairly arbitrary but once again necessary for backwards compatibility.
1962        // If there are multiple applicable candidates which don't affect type inference,
1963        // choose the one with the lowest index.
1964        match alias_bounds.try_reduce(|(c1, k1), (c2, k2)| {
1965            if has_non_region_infer {
1966                None
1967            } else if c1 < c2 {
1968                Some((c1, k1))
1969            } else {
1970                Some((c2, k2))
1971            }
1972        }) {
1973            Some(Some((idx, kind))) => return Some(ProjectionCandidate { idx, kind }),
1974            Some(None) => {}
1975            None => return None,
1976        }
1977
1978        // Need to prioritize builtin trait object impls as `<dyn Any as Any>::type_id`
1979        // should use the vtable method and not the method provided by the user-defined
1980        // impl `impl<T: ?Sized> Any for T { .. }`. This really shouldn't exist but is
1981        // necessary due to #57893. We again arbitrarily prefer the applicable candidate
1982        // with the lowest index.
1983        //
1984        // We do not want to use these impls to guide inference in case a user-written impl
1985        // may also apply.
1986        let object_bound = candidates
1987            .iter()
1988            .filter_map(|c| if let ObjectCandidate(i) = c.candidate { Some(i) } else { None })
1989            .try_reduce(|c1, c2| if has_non_region_infer { None } else { Some(c1.min(c2)) });
1990        match object_bound {
1991            Some(Some(index)) => {
1992                return if has_non_region_infer
1993                    && candidates.iter().any(|c| matches!(c.candidate, ImplCandidate(_)))
1994                {
1995                    None
1996                } else {
1997                    Some(ObjectCandidate(index))
1998                };
1999            }
2000            Some(None) => {}
2001            None => return None,
2002        }
2003        // Same for upcasting.
2004        let upcast_bound = candidates
2005            .iter()
2006            .filter_map(|c| {
2007                if let TraitUpcastingUnsizeCandidate(i) = c.candidate { Some(i) } else { None }
2008            })
2009            .try_reduce(|c1, c2| if has_non_region_infer { None } else { Some(c1.min(c2)) });
2010        match upcast_bound {
2011            Some(Some(index)) => return Some(TraitUpcastingUnsizeCandidate(index)),
2012            Some(None) => {}
2013            None => return None,
2014        }
2015
2016        // Finally, handle overlapping user-written impls.
2017        let impls = candidates.iter().filter_map(|c| {
2018            if let ImplCandidate(def_id) = c.candidate {
2019                Some((def_id, c.evaluation))
2020            } else {
2021                None
2022            }
2023        });
2024        let mut impl_candidate = None;
2025        for c in impls {
2026            if let Some(prev) = impl_candidate.replace(c) {
2027                if self.prefer_lhs_over_victim(has_non_region_infer, c, prev.0) {
2028                    // Ok, prefer `c` over the previous entry
2029                } else if self.prefer_lhs_over_victim(has_non_region_infer, prev, c.0) {
2030                    // Ok, keep `prev` instead of the new entry
2031                    impl_candidate = Some(prev);
2032                } else {
2033                    // Ambiguity, two potentially different where-clauses
2034                    return None;
2035                }
2036            }
2037        }
2038        if let Some((def_id, _evaluation)) = impl_candidate {
2039            // Don't use impl candidates which overlap with other candidates.
2040            // This should pretty much only ever happen with malformed impls.
2041            if candidates.iter().all(|c| match c.candidate {
2042                SizedCandidate
2043                | BuiltinCandidate
2044                | TransmutabilityCandidate
2045                | AutoImplCandidate
2046                | ClosureCandidate { .. }
2047                | AsyncClosureCandidate
2048                | AsyncFnKindHelperCandidate
2049                | CoroutineCandidate
2050                | FutureCandidate
2051                | IteratorCandidate
2052                | AsyncIteratorCandidate
2053                | FnPointerCandidate
2054                | TraitAliasCandidate
2055                | TraitUpcastingUnsizeCandidate(_)
2056                | BuiltinObjectCandidate
2057                | BuiltinUnsizeCandidate
2058                | BikeshedGuaranteedNoDropCandidate => false,
2059                // Non-global param candidates have already been handled, global
2060                // where-bounds get ignored.
2061                ParamCandidate(_) | ImplCandidate(_) => true,
2062                ProjectionCandidate { .. } | ObjectCandidate(_) => unreachable!(),
2063            }) {
2064                return Some(ImplCandidate(def_id));
2065            } else {
2066                return None;
2067            }
2068        }
2069
2070        if candidates.len() == 1 {
2071            Some(candidates.pop().unwrap().candidate)
2072        } else {
2073            // Also try ignoring all global where-bounds and check whether we end
2074            // with a unique candidate in this case.
2075            let mut not_a_global_where_bound = candidates
2076                .into_iter()
2077                .filter(|c| !matches!(c.candidate, ParamCandidate(p) if is_global(p)));
2078            not_a_global_where_bound
2079                .next()
2080                .map(|c| c.candidate)
2081                .filter(|_| not_a_global_where_bound.next().is_none())
2082        }
2083    }
2084
2085    fn prefer_lhs_over_victim(
2086        &self,
2087        has_non_region_infer: bool,
2088        (lhs, lhs_evaluation): (DefId, EvaluationResult),
2089        victim: DefId,
2090    ) -> bool {
2091        let tcx = self.tcx();
2092        // See if we can toss out `victim` based on specialization.
2093        //
2094        // While this requires us to know *for sure* that the `lhs` impl applies
2095        // we still use modulo regions here. This is fine as specialization currently
2096        // assumes that specializing impls have to be always applicable, meaning that
2097        // the only allowed region constraints may be constraints also present on the default impl.
2098        if lhs_evaluation.must_apply_modulo_regions() {
2099            if tcx.specializes((lhs, victim)) {
2100                return true;
2101            }
2102        }
2103
2104        match tcx.impls_are_allowed_to_overlap(lhs, victim) {
2105            // For candidates which already reference errors it doesn't really
2106            // matter what we do 🤷
2107            Some(ty::ImplOverlapKind::Permitted { marker: false }) => {
2108                lhs_evaluation.must_apply_considering_regions()
2109            }
2110            Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
2111                // Subtle: If the predicate we are evaluating has inference
2112                // variables, do *not* allow discarding candidates due to
2113                // marker trait impls.
2114                //
2115                // Without this restriction, we could end up accidentally
2116                // constraining inference variables based on an arbitrarily
2117                // chosen trait impl.
2118                //
2119                // Imagine we have the following code:
2120                //
2121                // ```rust
2122                // #[marker] trait MyTrait {}
2123                // impl MyTrait for u8 {}
2124                // impl MyTrait for bool {}
2125                // ```
2126                //
2127                // And we are evaluating the predicate `<_#0t as MyTrait>`.
2128                //
2129                // During selection, we will end up with one candidate for each
2130                // impl of `MyTrait`. If we were to discard one impl in favor
2131                // of the other, we would be left with one candidate, causing
2132                // us to "successfully" select the predicate, unifying
2133                // _#0t with (for example) `u8`.
2134                //
2135                // However, we have no reason to believe that this unification
2136                // is correct - we've essentially just picked an arbitrary
2137                // *possibility* for _#0t, and required that this be the *only*
2138                // possibility.
2139                //
2140                // Eventually, we will either:
2141                // 1) Unify all inference variables in the predicate through
2142                // some other means (e.g. type-checking of a function). We will
2143                // then be in a position to drop marker trait candidates
2144                // without constraining inference variables (since there are
2145                // none left to constrain)
2146                // 2) Be left with some unconstrained inference variables. We
2147                // will then correctly report an inference error, since the
2148                // existence of multiple marker trait impls tells us nothing
2149                // about which one should actually apply.
2150                !has_non_region_infer && lhs_evaluation.must_apply_considering_regions()
2151            }
2152            None => false,
2153        }
2154    }
2155}
2156
2157impl<'tcx> SelectionContext<'_, 'tcx> {
2158    fn sizedness_conditions(
2159        &mut self,
2160        self_ty: Ty<'tcx>,
2161        sizedness: SizedTraitKind,
2162    ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
2163        match self_ty.kind() {
2164            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2165            | ty::Uint(_)
2166            | ty::Int(_)
2167            | ty::Bool
2168            | ty::Float(_)
2169            | ty::FnDef(..)
2170            | ty::FnPtr(..)
2171            | ty::RawPtr(..)
2172            | ty::Char
2173            | ty::Ref(..)
2174            | ty::Coroutine(..)
2175            | ty::CoroutineWitness(..)
2176            | ty::Array(..)
2177            | ty::Closure(..)
2178            | ty::CoroutineClosure(..)
2179            | ty::Never
2180            | ty::Error(_) => ty::Binder::dummy(::alloc::vec::Vec::new()vec![]),
2181
2182            ty::Str | ty::Slice(_) | ty::Dynamic(..) => match sizedness {
2183                SizedTraitKind::Sized => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("tried to assemble `Sized` for unsized type")));
}unreachable!("tried to assemble `Sized` for unsized type"),
2184                SizedTraitKind::MetaSized => ty::Binder::dummy(::alloc::vec::Vec::new()vec![]),
2185            },
2186
2187            ty::Foreign(..) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("tried to assemble `Sized` for unsized type")));
}unreachable!("tried to assemble `Sized` for unsized type"),
2188
2189            ty::Tuple(tys) => {
2190                ty::Binder::dummy(tys.last().map_or_else(Vec::new, |&last| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [last]))vec![last]))
2191            }
2192
2193            ty::Pat(ty, _) => ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [*ty]))vec![*ty]),
2194
2195            ty::Adt(def, args) => {
2196                if let Some(crit) = def.sizedness_constraint(self.tcx(), sizedness) {
2197                    ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [crit.instantiate(self.tcx(), args).skip_norm_wip()]))vec![crit.instantiate(self.tcx(), args).skip_norm_wip()])
2198                } else {
2199                    ty::Binder::dummy(::alloc::vec::Vec::new()vec![])
2200                }
2201            }
2202
2203            ty::UnsafeBinder(binder_ty) => binder_ty.map_bound(|ty| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ty]))vec![ty]),
2204
2205            ty::Alias(..)
2206            | ty::Param(_)
2207            | ty::Placeholder(..)
2208            | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
2209            | ty::Bound(..) => {
2210                ::rustc_middle::util::bug::bug_fmt(format_args!("asked to assemble `Sized` of unexpected type: {0:?}",
        self_ty));bug!("asked to assemble `Sized` of unexpected type: {:?}", self_ty);
2211            }
2212        }
2213    }
2214
2215    fn copy_clone_conditions(&mut self, self_ty: Ty<'tcx>) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
2216        match *self_ty.kind() {
2217            ty::FnDef(..) | ty::FnPtr(..) | ty::Error(_) => ty::Binder::dummy(::alloc::vec::Vec::new()vec![]),
2218
2219            ty::Uint(_)
2220            | ty::Int(_)
2221            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2222            | ty::Bool
2223            | ty::Float(_)
2224            | ty::Char
2225            | ty::RawPtr(..)
2226            | ty::Never
2227            | ty::Ref(_, _, hir::Mutability::Not)
2228            | ty::Array(..) => {
2229                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("tried to assemble `Sized` for type with libcore-provided impl")));
}unreachable!("tried to assemble `Sized` for type with libcore-provided impl")
2230            }
2231
2232            // FIXME(unsafe_binder): Should we conditionally
2233            // (i.e. universally) implement copy/clone?
2234            ty::UnsafeBinder(_) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("tried to assemble `Sized` for unsafe binder")));
}unreachable!("tried to assemble `Sized` for unsafe binder"),
2235
2236            ty::Tuple(tys) => {
2237                // (*) binder moved here
2238                ty::Binder::dummy(tys.iter().collect())
2239            }
2240
2241            ty::Pat(ty, _) => {
2242                // (*) binder moved here
2243                ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ty]))vec![ty])
2244            }
2245
2246            ty::Coroutine(def_id, args) => match self.tcx().coroutine_movability(def_id) {
2247                hir::Movability::Static => {
2248                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("tried to assemble `Clone` for static coroutine")));
}unreachable!("tried to assemble `Clone` for static coroutine")
2249                }
2250                hir::Movability::Movable => {
2251                    if self.tcx().features().coroutine_clone() {
2252                        ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [args.as_coroutine().tupled_upvars_ty(),
                Ty::new_coroutine_witness_for_coroutine(self.tcx(), def_id,
                    args)]))vec![
2253                            args.as_coroutine().tupled_upvars_ty(),
2254                            Ty::new_coroutine_witness_for_coroutine(self.tcx(), def_id, args),
2255                        ])
2256                    } else {
2257                        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("tried to assemble `Clone` for coroutine without enabled feature")));
}unreachable!(
2258                            "tried to assemble `Clone` for coroutine without enabled feature"
2259                        )
2260                    }
2261                }
2262            },
2263
2264            ty::CoroutineWitness(def_id, args) => self
2265                .infcx
2266                .tcx
2267                .coroutine_hidden_types(def_id)
2268                .instantiate(self.infcx.tcx, args)
2269                .skip_norm_wip()
2270                .map_bound(|witness| witness.types.to_vec()),
2271
2272            ty::Closure(_, args) => ty::Binder::dummy(args.as_closure().upvar_tys().to_vec()),
2273
2274            ty::CoroutineClosure(_, args) => {
2275                ty::Binder::dummy(args.as_coroutine_closure().upvar_tys().to_vec())
2276            }
2277
2278            ty::Foreign(..)
2279            | ty::Str
2280            | ty::Slice(_)
2281            | ty::Dynamic(..)
2282            | ty::Adt(..)
2283            | ty::Alias(..)
2284            | ty::Param(..)
2285            | ty::Placeholder(..)
2286            | ty::Bound(..)
2287            | ty::Ref(_, _, ty::Mutability::Mut)
2288            | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2289                ::rustc_middle::util::bug::bug_fmt(format_args!("asked to assemble builtin bounds of unexpected type: {0:?}",
        self_ty));bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2290            }
2291        }
2292    }
2293
2294    fn coroutine_is_gen(&mut self, self_ty: Ty<'tcx>) -> bool {
2295        #[allow(non_exhaustive_omitted_patterns)] match *self_ty.kind() {
    ty::Coroutine(did, ..) if self.tcx().coroutine_is_gen(did) => true,
    _ => false,
}matches!(*self_ty.kind(), ty::Coroutine(did, ..)
2296            if self.tcx().coroutine_is_gen(did))
2297    }
2298
2299    /// For default impls, we need to break apart a type into its
2300    /// "constituent types" -- meaning, the types that it contains.
2301    ///
2302    /// Here are some (simple) examples:
2303    ///
2304    /// ```ignore (illustrative)
2305    /// (i32, u32) -> [i32, u32]
2306    /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2307    /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2308    /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2309    /// ```
2310    x;#[instrument(level = "debug", skip(self), ret)]
2311    fn constituent_types_for_auto_trait(
2312        &self,
2313        t: Ty<'tcx>,
2314    ) -> Result<ty::Binder<'tcx, AutoImplConstituents<'tcx>>, SelectionError<'tcx>> {
2315        Ok(match *t.kind() {
2316            ty::Uint(_)
2317            | ty::Int(_)
2318            | ty::Bool
2319            | ty::Float(_)
2320            | ty::FnDef(..)
2321            | ty::FnPtr(..)
2322            | ty::Error(_)
2323            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2324            | ty::Never
2325            | ty::Char => {
2326                ty::Binder::dummy(AutoImplConstituents { types: vec![], assumptions: vec![] })
2327            }
2328
2329            // This branch is only for `experimental_default_bounds`.
2330            // Other foreign types were rejected earlier in
2331            // `assemble_candidates_from_auto_impls`.
2332            ty::Foreign(..) => {
2333                ty::Binder::dummy(AutoImplConstituents { types: vec![], assumptions: vec![] })
2334            }
2335
2336            ty::UnsafeBinder(ty) => {
2337                ty.map_bound(|ty| AutoImplConstituents { types: vec![ty], assumptions: vec![] })
2338            }
2339
2340            // Treat this like `struct str([u8]);`
2341            ty::Str => ty::Binder::dummy(AutoImplConstituents {
2342                types: vec![Ty::new_slice(self.tcx(), self.tcx().types.u8)],
2343                assumptions: vec![],
2344            }),
2345
2346            ty::Placeholder(..)
2347            | ty::Dynamic(..)
2348            | ty::Param(..)
2349            | ty::Alias(ty::AliasTy {
2350                kind: ty::Projection { .. } | ty::Inherent { .. } | ty::Free { .. },
2351                ..
2352            })
2353            | ty::Bound(..)
2354            | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2355                bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2356            }
2357
2358            ty::RawPtr(element_ty, _) | ty::Ref(_, element_ty, _) => {
2359                ty::Binder::dummy(AutoImplConstituents {
2360                    types: vec![element_ty],
2361                    assumptions: vec![],
2362                })
2363            }
2364
2365            ty::Pat(ty, _) | ty::Array(ty, _) | ty::Slice(ty) => {
2366                ty::Binder::dummy(AutoImplConstituents { types: vec![ty], assumptions: vec![] })
2367            }
2368
2369            ty::Tuple(tys) => {
2370                // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2371                ty::Binder::dummy(AutoImplConstituents {
2372                    types: tys.iter().collect(),
2373                    assumptions: vec![],
2374                })
2375            }
2376
2377            ty::Closure(_, args) => {
2378                let ty = self.infcx.shallow_resolve(args.as_closure().tupled_upvars_ty());
2379                ty::Binder::dummy(AutoImplConstituents { types: vec![ty], assumptions: vec![] })
2380            }
2381
2382            ty::CoroutineClosure(_, args) => {
2383                let ty = self.infcx.shallow_resolve(args.as_coroutine_closure().tupled_upvars_ty());
2384                ty::Binder::dummy(AutoImplConstituents { types: vec![ty], assumptions: vec![] })
2385            }
2386
2387            ty::Coroutine(def_id, args) => {
2388                let ty = self.infcx.shallow_resolve(args.as_coroutine().tupled_upvars_ty());
2389                let tcx = self.tcx();
2390                let witness = Ty::new_coroutine_witness_for_coroutine(tcx, def_id, args);
2391                ty::Binder::dummy(AutoImplConstituents {
2392                    types: vec![ty, witness],
2393                    assumptions: vec![],
2394                })
2395            }
2396
2397            ty::CoroutineWitness(def_id, args) => self
2398                .infcx
2399                .tcx
2400                .coroutine_hidden_types(def_id)
2401                .instantiate(self.infcx.tcx, args)
2402                .skip_norm_wip()
2403                .map_bound(|witness| AutoImplConstituents {
2404                    types: witness.types.to_vec(),
2405                    assumptions: witness.assumptions.to_vec(),
2406                }),
2407
2408            // For `PhantomData<T>`, we pass `T`.
2409            ty::Adt(def, args) if def.is_phantom_data() => {
2410                ty::Binder::dummy(AutoImplConstituents {
2411                    types: args.types().collect(),
2412                    assumptions: vec![],
2413                })
2414            }
2415
2416            ty::Adt(def, args) => ty::Binder::dummy(AutoImplConstituents {
2417                types: def.all_fields().map(|f| f.ty(self.tcx(), args)).collect(),
2418                assumptions: vec![],
2419            }),
2420
2421            ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
2422                if self.infcx.can_define_opaque_ty(def_id) {
2423                    unreachable!()
2424                } else {
2425                    // We can resolve the opaque type to its hidden type,
2426                    // which enforces a DAG between the functions requiring
2427                    // the auto trait bounds in question.
2428                    let ty = self.tcx().type_of_opaque(def_id);
2429                    ty::Binder::dummy(AutoImplConstituents {
2430                        types: vec![ty.instantiate(self.tcx(), args).skip_norm_wip()],
2431                        assumptions: vec![],
2432                    })
2433                }
2434            }
2435        })
2436    }
2437
2438    fn collect_predicates_for_types(
2439        &mut self,
2440        param_env: ty::ParamEnv<'tcx>,
2441        cause: ObligationCause<'tcx>,
2442        recursion_depth: usize,
2443        trait_def_id: DefId,
2444        types: Vec<Ty<'tcx>>,
2445    ) -> PredicateObligations<'tcx> {
2446        // Because the types were potentially derived from
2447        // higher-ranked obligations they may reference late-bound
2448        // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2449        // yield a type like `for<'a> &'a i32`. In general, we
2450        // maintain the invariant that we never manipulate bound
2451        // regions, so we have to process these bound regions somehow.
2452        //
2453        // The strategy is to:
2454        //
2455        // 1. Instantiate those regions to placeholder regions (e.g.,
2456        //    `for<'a> &'a i32` becomes `&0 i32`.
2457        // 2. Produce something like `&'0 i32 : Copy`
2458        // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2459
2460        types
2461            .into_iter()
2462            .flat_map(|placeholder_ty| {
2463                let Normalized { value: normalized_ty, mut obligations } =
2464                    ensure_sufficient_stack(|| {
2465                        normalize_with_depth(
2466                            self,
2467                            param_env,
2468                            cause.clone(),
2469                            recursion_depth,
2470                            placeholder_ty,
2471                        )
2472                    });
2473
2474                let tcx = self.tcx();
2475                let trait_ref = if tcx.generics_of(trait_def_id).own_params.len() == 1 {
2476                    ty::TraitRef::new(tcx, trait_def_id, [normalized_ty])
2477                } else {
2478                    // If this is an ill-formed auto/built-in trait, then synthesize
2479                    // new error args for the missing generics.
2480                    let err_args = ty::GenericArgs::extend_with_error(
2481                        tcx,
2482                        trait_def_id,
2483                        &[normalized_ty.into()],
2484                    );
2485                    ty::TraitRef::new_from_args(tcx, trait_def_id, err_args)
2486                };
2487
2488                let obligation = Obligation::new(self.tcx(), cause.clone(), param_env, trait_ref);
2489                obligations.push(obligation);
2490                obligations
2491            })
2492            .collect()
2493    }
2494
2495    ///////////////////////////////////////////////////////////////////////////
2496    // Matching
2497    //
2498    // Matching is a common path used for both evaluation and
2499    // confirmation. It basically unifies types that appear in impls
2500    // and traits. This does affect the surrounding environment;
2501    // therefore, when used during evaluation, match routines must be
2502    // run inside of a `probe()` so that their side-effects are
2503    // contained.
2504
2505    fn rematch_impl(
2506        &mut self,
2507        impl_def_id: DefId,
2508        obligation: &PolyTraitObligation<'tcx>,
2509    ) -> Normalized<'tcx, GenericArgsRef<'tcx>> {
2510        let impl_trait_header = self.tcx().impl_trait_header(impl_def_id);
2511        match self.match_impl(impl_def_id, impl_trait_header, obligation) {
2512            Ok(args) => args,
2513            Err(()) => {
2514                let predicate = self.infcx.resolve_vars_if_possible(obligation.predicate);
2515                ::rustc_middle::util::bug::bug_fmt(format_args!("impl {0:?} was matchable against {1:?} but now is not",
        impl_def_id, predicate))bug!("impl {impl_def_id:?} was matchable against {predicate:?} but now is not")
2516            }
2517        }
2518    }
2519
2520    x;#[instrument(level = "debug", skip(self), ret)]
2521    fn match_impl(
2522        &mut self,
2523        impl_def_id: DefId,
2524        impl_trait_header: ty::ImplTraitHeader<'tcx>,
2525        obligation: &PolyTraitObligation<'tcx>,
2526    ) -> Result<Normalized<'tcx, GenericArgsRef<'tcx>>, ()> {
2527        let placeholder_obligation =
2528            self.infcx.enter_forall_and_leak_universe(obligation.predicate);
2529        let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2530
2531        let impl_args = self.infcx.fresh_args_for_item(obligation.cause.span, impl_def_id);
2532
2533        let trait_ref =
2534            impl_trait_header.trait_ref.instantiate(self.tcx(), impl_args).skip_norm_wip();
2535        debug!(?impl_trait_header);
2536
2537        let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2538            ensure_sufficient_stack(|| {
2539                normalize_with_depth(
2540                    self,
2541                    obligation.param_env,
2542                    obligation.cause.clone(),
2543                    obligation.recursion_depth + 1,
2544                    trait_ref,
2545                )
2546            });
2547
2548        debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2549
2550        let cause = ObligationCause::new(
2551            obligation.cause.span,
2552            obligation.cause.body_id,
2553            ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2554        );
2555
2556        let InferOk { obligations, .. } = self
2557            .infcx
2558            .at(&cause, obligation.param_env)
2559            .eq(DefineOpaqueTypes::No, placeholder_obligation_trait_ref, impl_trait_ref)
2560            .map_err(|e| {
2561                debug!("match_impl: failed eq_trait_refs due to `{}`", e.to_string(self.tcx()))
2562            })?;
2563        nested_obligations.extend(obligations);
2564
2565        if impl_trait_header.polarity == ty::ImplPolarity::Reservation
2566            && !self.infcx.typing_mode().is_coherence()
2567        {
2568            debug!("reservation impls only apply in intercrate mode");
2569            return Err(());
2570        }
2571
2572        Ok(Normalized { value: impl_args, obligations: nested_obligations })
2573    }
2574
2575    fn match_upcast_principal(
2576        &mut self,
2577        obligation: &PolyTraitObligation<'tcx>,
2578        unnormalized_upcast_principal: ty::PolyTraitRef<'tcx>,
2579        a_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2580        b_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2581        a_region: ty::Region<'tcx>,
2582        b_region: ty::Region<'tcx>,
2583    ) -> SelectionResult<'tcx, PredicateObligations<'tcx>> {
2584        let tcx = self.tcx();
2585        let mut nested = PredicateObligations::new();
2586
2587        // We may upcast to auto traits that are either explicitly listed in
2588        // the object type's bounds, or implied by the principal trait ref's
2589        // supertraits.
2590        let a_auto_traits: FxIndexSet<DefId> = a_data
2591            .auto_traits()
2592            .chain(a_data.principal_def_id().into_iter().flat_map(|principal_def_id| {
2593                elaborate::supertrait_def_ids(tcx, principal_def_id)
2594                    .filter(|def_id| tcx.trait_is_auto(*def_id))
2595            }))
2596            .collect();
2597
2598        let upcast_principal = normalize_with_depth_to(
2599            self,
2600            obligation.param_env,
2601            obligation.cause.clone(),
2602            obligation.recursion_depth + 1,
2603            unnormalized_upcast_principal,
2604            &mut nested,
2605        );
2606
2607        for bound in b_data {
2608            match bound.skip_binder() {
2609                // Check that a_ty's supertrait (upcast_principal) is compatible
2610                // with the target (b_ty).
2611                ty::ExistentialPredicate::Trait(target_principal) => {
2612                    let hr_source_principal = upcast_principal.map_bound(|trait_ref| {
2613                        ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
2614                    });
2615                    let hr_target_principal = bound.rebind(target_principal);
2616
2617                    nested.extend(
2618                        self.infcx
2619                            .enter_forall(hr_target_principal, |target_principal| {
2620                                let source_principal =
2621                                    self.infcx.instantiate_binder_with_fresh_vars(
2622                                        obligation.cause.span,
2623                                        HigherRankedType,
2624                                        hr_source_principal,
2625                                    );
2626                                self.infcx.at(&obligation.cause, obligation.param_env).eq_trace(
2627                                    DefineOpaqueTypes::Yes,
2628                                    ToTrace::to_trace(
2629                                        &obligation.cause,
2630                                        hr_target_principal,
2631                                        hr_source_principal,
2632                                    ),
2633                                    target_principal,
2634                                    source_principal,
2635                                )
2636                            })
2637                            .map_err(|_| SelectionError::Unimplemented)?
2638                            .into_obligations(),
2639                    );
2640                }
2641                // Check that b_ty's projection is satisfied by exactly one of
2642                // a_ty's projections. First, we look through the list to see if
2643                // any match. If not, error. Then, if *more* than one matches, we
2644                // return ambiguity. Otherwise, if exactly one matches, equate
2645                // it with b_ty's projection.
2646                ty::ExistentialPredicate::Projection(target_projection) => {
2647                    let hr_target_projection = bound.rebind(target_projection);
2648
2649                    let mut matching_projections =
2650                        a_data.projection_bounds().filter(|&hr_source_projection| {
2651                            // Eager normalization means that we can just use can_eq
2652                            // here instead of equating and processing obligations.
2653                            hr_source_projection.item_def_id() == hr_target_projection.item_def_id()
2654                                && self.infcx.probe(|_| {
2655                                    self.infcx
2656                                        .enter_forall(hr_target_projection, |target_projection| {
2657                                            let source_projection =
2658                                                self.infcx.instantiate_binder_with_fresh_vars(
2659                                                    obligation.cause.span,
2660                                                    HigherRankedType,
2661                                                    hr_source_projection,
2662                                                );
2663                                            self.infcx
2664                                                .at(&obligation.cause, obligation.param_env)
2665                                                .eq_trace(
2666                                                    DefineOpaqueTypes::Yes,
2667                                                    ToTrace::to_trace(
2668                                                        &obligation.cause,
2669                                                        hr_target_projection,
2670                                                        hr_source_projection,
2671                                                    ),
2672                                                    target_projection,
2673                                                    source_projection,
2674                                                )
2675                                        })
2676                                        .is_ok()
2677                                })
2678                        });
2679
2680                    let Some(hr_source_projection) = matching_projections.next() else {
2681                        return Err(SelectionError::Unimplemented);
2682                    };
2683                    if matching_projections.next().is_some() {
2684                        return Ok(None);
2685                    }
2686                    nested.extend(
2687                        self.infcx
2688                            .enter_forall(hr_target_projection, |target_projection| {
2689                                let source_projection =
2690                                    self.infcx.instantiate_binder_with_fresh_vars(
2691                                        obligation.cause.span,
2692                                        HigherRankedType,
2693                                        hr_source_projection,
2694                                    );
2695                                self.infcx.at(&obligation.cause, obligation.param_env).eq_trace(
2696                                    DefineOpaqueTypes::Yes,
2697                                    ToTrace::to_trace(
2698                                        &obligation.cause,
2699                                        hr_target_projection,
2700                                        hr_source_projection,
2701                                    ),
2702                                    target_projection,
2703                                    source_projection,
2704                                )
2705                            })
2706                            .map_err(|_| SelectionError::Unimplemented)?
2707                            .into_obligations(),
2708                    );
2709                }
2710                // Check that b_ty's auto traits are present in a_ty's bounds.
2711                ty::ExistentialPredicate::AutoTrait(def_id) => {
2712                    if !a_auto_traits.contains(&def_id) {
2713                        return Err(SelectionError::Unimplemented);
2714                    }
2715                }
2716            }
2717        }
2718
2719        nested.push(Obligation::with_depth(
2720            tcx,
2721            obligation.cause.clone(),
2722            obligation.recursion_depth + 1,
2723            obligation.param_env,
2724            ty::Binder::dummy(ty::OutlivesPredicate(a_region, b_region)),
2725        ));
2726
2727        Ok(Some(nested))
2728    }
2729
2730    /// Normalize `where_clause_trait_ref` and try to match it against
2731    /// `obligation`. If successful, return any predicates that
2732    /// result from the normalization.
2733    fn match_where_clause_trait_ref(
2734        &mut self,
2735        obligation: &PolyTraitObligation<'tcx>,
2736        where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2737    ) -> Result<PredicateObligations<'tcx>, ()> {
2738        self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2739    }
2740
2741    /// Returns `Ok` if `poly_trait_ref` being true implies that the
2742    /// obligation is satisfied.
2743    #[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("match_poly_trait_ref",
                                    "rustc_trait_selection::traits::select",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2743u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&["obligation",
                                                    "poly_trait_ref"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&poly_trait_ref)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<PredicateObligations<'tcx>, ()> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let predicate =
                self.infcx.enter_forall_and_leak_universe(obligation.predicate);
            let trait_ref =
                self.infcx.instantiate_binder_with_fresh_vars(obligation.cause.span,
                    HigherRankedType, poly_trait_ref);
            self.infcx.at(&obligation.cause,
                            obligation.param_env).eq(DefineOpaqueTypes::No,
                        predicate.trait_ref,
                        trait_ref).map(|InferOk { obligations, .. }|
                        obligations).map_err(|_| ())
        }
    }
}#[instrument(skip(self), level = "debug")]
2744    fn match_poly_trait_ref(
2745        &mut self,
2746        obligation: &PolyTraitObligation<'tcx>,
2747        poly_trait_ref: ty::PolyTraitRef<'tcx>,
2748    ) -> Result<PredicateObligations<'tcx>, ()> {
2749        let predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
2750        let trait_ref = self.infcx.instantiate_binder_with_fresh_vars(
2751            obligation.cause.span,
2752            HigherRankedType,
2753            poly_trait_ref,
2754        );
2755        self.infcx
2756            .at(&obligation.cause, obligation.param_env)
2757            .eq(DefineOpaqueTypes::No, predicate.trait_ref, trait_ref)
2758            .map(|InferOk { obligations, .. }| obligations)
2759            .map_err(|_| ())
2760    }
2761
2762    ///////////////////////////////////////////////////////////////////////////
2763    // Miscellany
2764
2765    fn match_fresh_trait_preds(
2766        &self,
2767        previous: ty::PolyTraitPredicate<'tcx>,
2768        current: ty::PolyTraitPredicate<'tcx>,
2769    ) -> bool {
2770        let mut matcher = _match::MatchAgainstFreshVars::new(self.tcx());
2771        matcher.relate(previous, current).is_ok()
2772    }
2773
2774    fn push_stack<'o>(
2775        &mut self,
2776        previous_stack: TraitObligationStackList<'o, 'tcx>,
2777        obligation: &'o PolyTraitObligation<'tcx>,
2778    ) -> TraitObligationStack<'o, 'tcx> {
2779        let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
2780
2781        let dfn = previous_stack.cache.next_dfn();
2782        let depth = previous_stack.depth() + 1;
2783        TraitObligationStack {
2784            obligation,
2785            fresh_trait_pred,
2786            reached_depth: Cell::new(depth),
2787            previous: previous_stack,
2788            dfn,
2789            depth,
2790        }
2791    }
2792
2793    #[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("closure_trait_ref_unnormalized",
                                    "rustc_trait_selection::traits::select",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2793u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&["self_ty",
                                                    "fn_trait_def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_trait_def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ty::PolyTraitRef<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty::Closure(_, args) =
                *self_ty.kind() else {
                    ::rustc_middle::util::bug::bug_fmt(format_args!("expected closure, found {0}",
                            self_ty));
                };
            let closure_sig = args.as_closure().sig();
            closure_trait_ref_and_return_type(self.tcx(), fn_trait_def_id,
                    self_ty, closure_sig,
                    util::TupleArgumentsFlag::No).map_bound(|(trait_ref, _)|
                    trait_ref)
        }
    }
}#[instrument(skip(self), level = "debug")]
2794    fn closure_trait_ref_unnormalized(
2795        &mut self,
2796        self_ty: Ty<'tcx>,
2797        fn_trait_def_id: DefId,
2798    ) -> ty::PolyTraitRef<'tcx> {
2799        let ty::Closure(_, args) = *self_ty.kind() else {
2800            bug!("expected closure, found {self_ty}");
2801        };
2802        let closure_sig = args.as_closure().sig();
2803
2804        closure_trait_ref_and_return_type(
2805            self.tcx(),
2806            fn_trait_def_id,
2807            self_ty,
2808            closure_sig,
2809            util::TupleArgumentsFlag::No,
2810        )
2811        .map_bound(|(trait_ref, _)| trait_ref)
2812    }
2813
2814    /// Returns the obligations that are implied by instantiating an
2815    /// impl or trait. The obligations are instantiated and fully
2816    /// normalized. This is used when confirming an impl or default
2817    /// impl.
2818    #[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("impl_or_trait_obligations",
                                    "rustc_trait_selection::traits::select",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2818u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&["recursion_depth",
                                                    "def_id", "args", "parent_trait_pred"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&recursion_depth as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_trait_pred)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PredicateObligations<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let predicates = tcx.predicates_of(def_id);
            match (&predicates.parent, &None) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
            let predicates = predicates.instantiate_own(tcx, args);
            let mut obligations =
                PredicateObligations::with_capacity(predicates.len());
            for (index, (predicate, span)) in
                predicates.into_iter().enumerate() {
                let cause =
                    if tcx.is_lang_item(parent_trait_pred.def_id(),
                            LangItem::CoerceUnsized) {
                        cause.clone()
                    } else {
                        cause.clone().derived_cause(parent_trait_pred,
                            |derived|
                                {
                                    ObligationCauseCode::ImplDerived(Box::new(ImplDerivedCause {
                                                derived,
                                                impl_or_alias_def_id: def_id,
                                                impl_def_predicate_index: Some(index),
                                                span,
                                            }))
                                })
                    };
                let clause =
                    normalize_with_depth_to(self, param_env, cause.clone(),
                        recursion_depth, predicate.skip_norm_wip(),
                        &mut obligations);
                obligations.push(Obligation {
                        cause,
                        recursion_depth,
                        param_env,
                        predicate: clause.as_predicate(),
                    });
            }
            if tcx.def_kind(def_id) == (DefKind::Impl { of_trait: true }) {
                for clause in
                    tcx.impl_super_outlives(def_id).iter_instantiated(tcx,
                            args).map(Unnormalized::skip_norm_wip) {
                    let clause =
                        normalize_with_depth_to(self, param_env, cause.clone(),
                            recursion_depth, clause, &mut obligations);
                    obligations.push(Obligation {
                            cause: cause.clone(),
                            recursion_depth,
                            param_env,
                            predicate: clause.as_predicate(),
                        });
                }
            }
            obligations
        }
    }
}#[instrument(level = "debug", skip(self, cause, param_env))]
2819    fn impl_or_trait_obligations(
2820        &mut self,
2821        cause: &ObligationCause<'tcx>,
2822        recursion_depth: usize,
2823        param_env: ty::ParamEnv<'tcx>,
2824        def_id: DefId,              // of impl or trait
2825        args: GenericArgsRef<'tcx>, // for impl or trait
2826        parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2827    ) -> PredicateObligations<'tcx> {
2828        let tcx = self.tcx();
2829
2830        // To allow for one-pass evaluation of the nested obligation,
2831        // each predicate must be preceded by the obligations required
2832        // to normalize it.
2833        // for example, if we have:
2834        //    impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2835        // the impl will have the following predicates:
2836        //    <V as Iterator>::Item = U,
2837        //    U: Iterator, U: Sized,
2838        //    V: Iterator, V: Sized,
2839        //    <U as Iterator>::Item: Copy
2840        // When we instantiate, say, `V => IntoIter<u32>, U => $0`, the last
2841        // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2842        // `$1: Copy`, so we must ensure the obligations are emitted in
2843        // that order.
2844        let predicates = tcx.predicates_of(def_id);
2845        assert_eq!(predicates.parent, None);
2846        let predicates = predicates.instantiate_own(tcx, args);
2847        let mut obligations = PredicateObligations::with_capacity(predicates.len());
2848        for (index, (predicate, span)) in predicates.into_iter().enumerate() {
2849            let cause = if tcx.is_lang_item(parent_trait_pred.def_id(), LangItem::CoerceUnsized) {
2850                cause.clone()
2851            } else {
2852                cause.clone().derived_cause(parent_trait_pred, |derived| {
2853                    ObligationCauseCode::ImplDerived(Box::new(ImplDerivedCause {
2854                        derived,
2855                        impl_or_alias_def_id: def_id,
2856                        impl_def_predicate_index: Some(index),
2857                        span,
2858                    }))
2859                })
2860            };
2861            let clause = normalize_with_depth_to(
2862                self,
2863                param_env,
2864                cause.clone(),
2865                recursion_depth,
2866                predicate.skip_norm_wip(),
2867                &mut obligations,
2868            );
2869            obligations.push(Obligation {
2870                cause,
2871                recursion_depth,
2872                param_env,
2873                predicate: clause.as_predicate(),
2874            });
2875        }
2876
2877        // Register any outlives obligations from the trait here, cc #124336.
2878        if tcx.def_kind(def_id) == (DefKind::Impl { of_trait: true }) {
2879            for clause in tcx
2880                .impl_super_outlives(def_id)
2881                .iter_instantiated(tcx, args)
2882                .map(Unnormalized::skip_norm_wip)
2883            {
2884                let clause = normalize_with_depth_to(
2885                    self,
2886                    param_env,
2887                    cause.clone(),
2888                    recursion_depth,
2889                    clause,
2890                    &mut obligations,
2891                );
2892                obligations.push(Obligation {
2893                    cause: cause.clone(),
2894                    recursion_depth,
2895                    param_env,
2896                    predicate: clause.as_predicate(),
2897                });
2898            }
2899        }
2900
2901        obligations
2902    }
2903
2904    pub(super) fn should_stall_coroutine(&self, def_id: DefId) -> bool {
2905        match self.infcx.typing_mode() {
2906            TypingMode::Analysis { defining_opaque_types_and_generators: stalled_generators } => {
2907                def_id.as_local().is_some_and(|def_id| stalled_generators.contains(&def_id))
2908            }
2909            TypingMode::Coherence
2910            | TypingMode::PostAnalysis
2911            | TypingMode::Borrowck { defining_opaque_types: _ }
2912            | TypingMode::PostBorrowckAnalysis { defined_opaque_types: _ } => false,
2913        }
2914    }
2915}
2916
2917impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2918    fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2919        TraitObligationStackList::with(self)
2920    }
2921
2922    fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2923        self.previous.cache
2924    }
2925
2926    fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2927        self.list()
2928    }
2929
2930    /// Indicates that attempting to evaluate this stack entry
2931    /// required accessing something from the stack at depth `reached_depth`.
2932    fn update_reached_depth(&self, reached_depth: usize) {
2933        if !(self.depth >= reached_depth) {
    {
        ::core::panicking::panic_fmt(format_args!("invoked `update_reached_depth` with something under this stack: self.depth={0} reached_depth={1}",
                self.depth, reached_depth));
    }
};assert!(
2934            self.depth >= reached_depth,
2935            "invoked `update_reached_depth` with something under this stack: \
2936             self.depth={} reached_depth={}",
2937            self.depth,
2938            reached_depth,
2939        );
2940        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:2940",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2940u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "reached_depth"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("update_reached_depth")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&reached_depth as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(reached_depth, "update_reached_depth");
2941        let mut p = self;
2942        while reached_depth < p.depth {
2943            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:2943",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2943u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "p.fresh_trait_pred"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("update_reached_depth: marking as cycle participant")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&p.fresh_trait_pred)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
2944            p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2945            p = p.previous.head.unwrap();
2946        }
2947    }
2948}
2949
2950/// The "provisional evaluation cache" is used to store intermediate cache results
2951/// when solving auto traits. Auto traits are unusual in that they can support
2952/// cycles. So, for example, a "proof tree" like this would be ok:
2953///
2954/// - `Foo<T>: Send` :-
2955///   - `Bar<T>: Send` :-
2956///     - `Foo<T>: Send` -- cycle, but ok
2957///   - `Baz<T>: Send`
2958///
2959/// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2960/// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2961/// For non-auto traits, this cycle would be an error, but for auto traits (because
2962/// they are coinductive) it is considered ok.
2963///
2964/// However, there is a complication: at the point where we have
2965/// "proven" `Bar<T>: Send`, we have in fact only proven it
2966/// *provisionally*. In particular, we proved that `Bar<T>: Send`
2967/// *under the assumption* that `Foo<T>: Send`. But what if we later
2968/// find out this assumption is wrong?  Specifically, we could
2969/// encounter some kind of error proving `Baz<T>: Send`. In that case,
2970/// `Bar<T>: Send` didn't turn out to be true.
2971///
2972/// In Issue #60010, we found a bug in rustc where it would cache
2973/// these intermediate results. This was fixed in #60444 by disabling
2974/// *all* caching for things involved in a cycle -- in our example,
2975/// that would mean we don't cache that `Bar<T>: Send`. But this led
2976/// to large slowdowns.
2977///
2978/// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2979/// first requires proving `Bar<T>: Send` (which is true:
2980///
2981/// - `Foo<T>: Send` :-
2982///   - `Bar<T>: Send` :-
2983///     - `Foo<T>: Send` -- cycle, but ok
2984///   - `Baz<T>: Send`
2985///     - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2986///     - `*const T: Send` -- but what if we later encounter an error?
2987///
2988/// The *provisional evaluation cache* resolves this issue. It stores
2989/// cache results that we've proven but which were involved in a cycle
2990/// in some way. We track the minimal stack depth (i.e., the
2991/// farthest from the top of the stack) that we are dependent on.
2992/// The idea is that the cache results within are all valid -- so long as
2993/// none of the nodes in between the current node and the node at that minimum
2994/// depth result in an error (in which case the cached results are just thrown away).
2995///
2996/// During evaluation, we consult this provisional cache and rely on
2997/// it. Accessing a cached value is considered equivalent to accessing
2998/// a result at `reached_depth`, so it marks the *current* solution as
2999/// provisional as well. If an error is encountered, we toss out any
3000/// provisional results added from the subtree that encountered the
3001/// error. When we pop the node at `reached_depth` from the stack, we
3002/// can commit all the things that remain in the provisional cache.
3003struct ProvisionalEvaluationCache<'tcx> {
3004    /// next "depth first number" to issue -- just a counter
3005    dfn: Cell<usize>,
3006
3007    /// Map from cache key to the provisionally evaluated thing.
3008    /// The cache entries contain the result but also the DFN in which they
3009    /// were added. The DFN is used to clear out values on failure.
3010    ///
3011    /// Imagine we have a stack like:
3012    ///
3013    /// - `A B C` and we add a cache for the result of C (DFN 2)
3014    /// - Then we have a stack `A B D` where `D` has DFN 3
3015    /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
3016    /// - `E` generates various cache entries which have cyclic dependencies on `B`
3017    ///   - `A B D E F` and so forth
3018    ///   - the DFN of `F` for example would be 5
3019    /// - then we determine that `E` is in error -- we will then clear
3020    ///   all cache values whose DFN is >= 4 -- in this case, that
3021    ///   means the cached value for `F`.
3022    map: RefCell<FxIndexMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
3023
3024    /// The stack of terms that we assume to be well-formed because a `WF(term)` predicate
3025    /// is on the stack above (and because of wellformedness is coinductive).
3026    /// In an "ideal" world, this would share a stack with trait predicates in
3027    /// `TraitObligationStack`. However, trait predicates are *much* hotter than
3028    /// `WellFormed` predicates, and it's very likely that the additional matches
3029    /// will have a perf effect. The value here is the well-formed `GenericArg`
3030    /// and the depth of the trait predicate *above* that well-formed predicate.
3031    wf_args: RefCell<Vec<(ty::Term<'tcx>, usize)>>,
3032}
3033
3034/// A cache value for the provisional cache: contains the depth-first
3035/// number (DFN) and result.
3036#[derive(#[automatically_derived]
impl ::core::marker::Copy for ProvisionalEvaluation { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ProvisionalEvaluation {
    #[inline]
    fn clone(&self) -> ProvisionalEvaluation {
        let _: ::core::clone::AssertParamIsClone<usize>;
        let _: ::core::clone::AssertParamIsClone<EvaluationResult>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ProvisionalEvaluation {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "ProvisionalEvaluation", "from_dfn", &self.from_dfn,
            "reached_depth", &self.reached_depth, "result", &&self.result)
    }
}Debug)]
3037struct ProvisionalEvaluation {
3038    from_dfn: usize,
3039    reached_depth: usize,
3040    result: EvaluationResult,
3041}
3042
3043impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
3044    fn default() -> Self {
3045        Self { dfn: Cell::new(0), map: Default::default(), wf_args: Default::default() }
3046    }
3047}
3048
3049impl<'tcx> ProvisionalEvaluationCache<'tcx> {
3050    /// Get the next DFN in sequence (basically a counter).
3051    fn next_dfn(&self) -> usize {
3052        let result = self.dfn.get();
3053        self.dfn.set(result + 1);
3054        result
3055    }
3056
3057    /// Check the provisional cache for any result for
3058    /// `fresh_trait_pred`. If there is a hit, then you must consider
3059    /// it an access to the stack slots at depth
3060    /// `reached_depth` (from the returned value).
3061    fn get_provisional(
3062        &self,
3063        fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
3064    ) -> Option<ProvisionalEvaluation> {
3065        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:3065",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(3065u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "fresh_trait_pred"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("get_provisional = {0:#?}",
                                                    self.map.borrow().get(&fresh_trait_pred)) as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&fresh_trait_pred)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(
3066            ?fresh_trait_pred,
3067            "get_provisional = {:#?}",
3068            self.map.borrow().get(&fresh_trait_pred),
3069        );
3070        Some(*self.map.borrow().get(&fresh_trait_pred)?)
3071    }
3072
3073    /// Insert a provisional result into the cache. The result came
3074    /// from the node with the given DFN. It accessed a minimum depth
3075    /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
3076    /// and resulted in `result`.
3077    fn insert_provisional(
3078        &self,
3079        from_dfn: usize,
3080        reached_depth: usize,
3081        fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
3082        result: EvaluationResult,
3083    ) {
3084        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:3084",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(3084u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "from_dfn", "fresh_trait_pred", "result"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("insert_provisional")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&from_dfn)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&fresh_trait_pred)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&result) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
3085
3086        let mut map = self.map.borrow_mut();
3087
3088        // Subtle: when we complete working on the DFN `from_dfn`, anything
3089        // that remains in the provisional cache must be dependent on some older
3090        // stack entry than `from_dfn`. We have to update their depth with our transitive
3091        // depth in that case or else it would be referring to some popped note.
3092        //
3093        // Example:
3094        // A (reached depth 0)
3095        //   ...
3096        //      B // depth 1 -- reached depth = 0
3097        //          C // depth 2 -- reached depth = 1 (should be 0)
3098        //              B
3099        //          A // depth 0
3100        //   D (reached depth 1)
3101        //      C (cache -- reached depth = 2)
3102        for (_k, v) in &mut *map {
3103            if v.from_dfn >= from_dfn {
3104                v.reached_depth = reached_depth.min(v.reached_depth);
3105            }
3106        }
3107
3108        map.insert(fresh_trait_pred, ProvisionalEvaluation { from_dfn, reached_depth, result });
3109    }
3110
3111    /// Invoked when the node with dfn `dfn` does not get a successful
3112    /// result. This will clear out any provisional cache entries
3113    /// that were added since `dfn` was created. This is because the
3114    /// provisional entries are things which must assume that the
3115    /// things on the stack at the time of their creation succeeded --
3116    /// since the failing node is presently at the top of the stack,
3117    /// these provisional entries must either depend on it or some
3118    /// ancestor of it.
3119    fn on_failure(&self, dfn: usize) {
3120        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:3120",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(3120u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message", "dfn"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("on_failure")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&dfn) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?dfn, "on_failure");
3121        self.map.borrow_mut().retain(|key, eval| {
3122            if !eval.from_dfn >= dfn {
3123                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:3123",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(3123u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("on_failure: removing {0:?}",
                                                    key) as &dyn Value))])
            });
    } else { ; }
};debug!("on_failure: removing {:?}", key);
3124                false
3125            } else {
3126                true
3127            }
3128        });
3129    }
3130
3131    /// Invoked when the node at depth `depth` completed without
3132    /// depending on anything higher in the stack (if that completion
3133    /// was a failure, then `on_failure` should have been invoked
3134    /// already).
3135    ///
3136    /// Note that we may still have provisional cache items remaining
3137    /// in the cache when this is done. For example, if there is a
3138    /// cycle:
3139    ///
3140    /// * A depends on...
3141    ///     * B depends on A
3142    ///     * C depends on...
3143    ///         * D depends on C
3144    ///     * ...
3145    ///
3146    /// Then as we complete the C node we will have a provisional cache
3147    /// with results for A, B, C, and D. This method would clear out
3148    /// the C and D results, but leave A and B provisional.
3149    ///
3150    /// This is determined based on the DFN: we remove any provisional
3151    /// results created since `dfn` started (e.g., in our example, dfn
3152    /// would be 2, representing the C node, and hence we would
3153    /// remove the result for D, which has DFN 3, but not the results for
3154    /// A and B, which have DFNs 0 and 1 respectively).
3155    ///
3156    /// Note that we *do not* attempt to cache these cycle participants
3157    /// in the evaluation cache. Doing so would require carefully computing
3158    /// the correct `DepNode` to store in the cache entry:
3159    /// cycle participants may implicitly depend on query results
3160    /// related to other participants in the cycle, due to our logic
3161    /// which examines the evaluation stack.
3162    ///
3163    /// We used to try to perform this caching,
3164    /// but it lead to multiple incremental compilation ICEs
3165    /// (see #92987 and #96319), and was very hard to understand.
3166    /// Fortunately, removing the caching didn't seem to
3167    /// have a performance impact in practice.
3168    fn on_completion(&self, dfn: usize) {
3169        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:3169",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(3169u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message", "dfn"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("on_completion")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&dfn) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?dfn, "on_completion");
3170        self.map.borrow_mut().retain(|fresh_trait_pred, eval| {
3171            if eval.from_dfn >= dfn {
3172                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/select/mod.rs:3172",
                        "rustc_trait_selection::traits::select",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/select/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(3172u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "fresh_trait_pred", "eval"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("on_completion")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&fresh_trait_pred)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&eval) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?fresh_trait_pred, ?eval, "on_completion");
3173                return false;
3174            }
3175            true
3176        });
3177    }
3178}
3179
3180#[derive(#[automatically_derived]
impl<'o, 'tcx> ::core::marker::Copy for TraitObligationStackList<'o, 'tcx> { }Copy, #[automatically_derived]
impl<'o, 'tcx> ::core::clone::Clone for TraitObligationStackList<'o, 'tcx> {
    #[inline]
    fn clone(&self) -> TraitObligationStackList<'o, 'tcx> {
        let _:
                ::core::clone::AssertParamIsClone<&'o ProvisionalEvaluationCache<'tcx>>;
        let _:
                ::core::clone::AssertParamIsClone<Option<&'o TraitObligationStack<'o,
                'tcx>>>;
        *self
    }
}Clone)]
3181struct TraitObligationStackList<'o, 'tcx> {
3182    cache: &'o ProvisionalEvaluationCache<'tcx>,
3183    head: Option<&'o TraitObligationStack<'o, 'tcx>>,
3184}
3185
3186impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
3187    fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3188        TraitObligationStackList { cache, head: None }
3189    }
3190
3191    fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3192        TraitObligationStackList { cache: r.cache(), head: Some(r) }
3193    }
3194
3195    fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3196        self.head
3197    }
3198
3199    fn depth(&self) -> usize {
3200        if let Some(head) = self.head { head.depth } else { 0 }
3201    }
3202}
3203
3204impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
3205    type Item = &'o TraitObligationStack<'o, 'tcx>;
3206
3207    fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3208        let o = self.head?;
3209        *self = o.previous;
3210        Some(o)
3211    }
3212}
3213
3214impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
3215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3216        f.write_fmt(format_args!("TraitObligationStack({0:?})", self.obligation))write!(f, "TraitObligationStack({:?})", self.obligation)
3217    }
3218}
3219
3220pub(crate) enum ProjectionMatchesProjection {
3221    Yes,
3222    Ambiguous,
3223    No,
3224}
3225
3226#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for AutoImplConstituents<'tcx> {
    #[inline]
    fn clone(&self) -> AutoImplConstituents<'tcx> {
        AutoImplConstituents {
            types: ::core::clone::Clone::clone(&self.types),
            assumptions: ::core::clone::Clone::clone(&self.assumptions),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for AutoImplConstituents<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "AutoImplConstituents", "types", &self.types, "assumptions",
            &&self.assumptions)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for AutoImplConstituents<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        AutoImplConstituents {
                            types: __binding_0, assumptions: __binding_1 } => {
                            AutoImplConstituents {
                                types: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                assumptions: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    AutoImplConstituents {
                        types: __binding_0, assumptions: __binding_1 } => {
                        AutoImplConstituents {
                            types: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            assumptions: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for AutoImplConstituents<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    AutoImplConstituents {
                        types: ref __binding_0, assumptions: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
3227pub(crate) struct AutoImplConstituents<'tcx> {
3228    pub types: Vec<Ty<'tcx>>,
3229    pub assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
3230}