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::{ImplSource, 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, CantBeErased, DeepRejectCtxt, GenericArgsRef,
30    PolyProjectionPredicate, SizedTraitKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt,
31    TypingMode, Unnormalized, Upcast, 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 typing_mode(&self) -> TypingMode<'tcx, CantBeErased> {
203        self.infcx.typing_mode_raw().assert_not_erased()
204    }
205
206    pub fn with_query_mode(
207        infcx: &'cx InferCtxt<'tcx>,
208        query_mode: TraitQueryMode,
209    ) -> SelectionContext<'cx, 'tcx> {
210        {
    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:210",
                        "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(210u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("query_mode")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("query_mode");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("with_query_mode")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&query_mode)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?query_mode, "with_query_mode");
211        SelectionContext { query_mode, ..SelectionContext::new(infcx) }
212    }
213
214    /// Enables tracking of intercrate ambiguity causes. See
215    /// the documentation of [`Self::intercrate_ambiguity_causes`] for more.
216    pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
217        if !self.typing_mode().is_coherence() {
    ::core::panicking::panic("assertion failed: self.typing_mode().is_coherence()")
};assert!(self.typing_mode().is_coherence());
218        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());
219
220        self.intercrate_ambiguity_causes = Some(FxIndexSet::default());
221        {
    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:221",
                        "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(221u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("selcx: enable_tracking_intercrate_ambiguity_causes")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
222    }
223
224    /// Gets the intercrate ambiguity causes collected since tracking
225    /// was enabled and disables tracking at the same time. If
226    /// tracking is not enabled, just returns an empty vector.
227    pub fn take_intercrate_ambiguity_causes(
228        &mut self,
229    ) -> FxIndexSet<IntercrateAmbiguityCause<'tcx>> {
230        if !self.typing_mode().is_coherence() {
    ::core::panicking::panic("assertion failed: self.typing_mode().is_coherence()")
};assert!(self.typing_mode().is_coherence());
231
232        self.intercrate_ambiguity_causes.take().unwrap_or_default()
233    }
234
235    pub fn tcx(&self) -> TyCtxt<'tcx> {
236        self.infcx.tcx
237    }
238
239    ///////////////////////////////////////////////////////////////////////////
240    // Selection
241    //
242    // The selection phase tries to identify *how* an obligation will
243    // be resolved. For example, it will identify which impl or
244    // parameter bound is to be used. The process can be inconclusive
245    // if the self type in the obligation is not fully inferred. Selection
246    // can result in an error in one of two ways:
247    //
248    // 1. If no applicable impl or parameter bound can be found.
249    // 2. If the output type parameters in the obligation do not match
250    //    those specified by the impl/bound. For example, if the obligation
251    //    is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
252    //    `impl<T> Iterable<T> for Vec<T>`, than an error would result.
253
254    /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
255    /// type environment by performing unification.
256    x;#[instrument(level = "debug", skip(self), ret)]
257    pub fn poly_select(
258        &mut self,
259        obligation: &PolyTraitObligation<'tcx>,
260    ) -> SelectionResult<'tcx, Selection<'tcx>> {
261        assert!(!self.infcx.next_trait_solver());
262
263        let candidate = match self.select_from_obligation(obligation) {
264            Err(SelectionError::Overflow(OverflowError::Canonical)) => {
265                // In standard mode, overflow must have been caught and reported
266                // earlier.
267                assert!(self.query_mode == TraitQueryMode::Canonical);
268                return Err(SelectionError::Overflow(OverflowError::Canonical));
269            }
270            Err(e) => {
271                return Err(e);
272            }
273            Ok(None) => {
274                return Ok(None);
275            }
276            Ok(Some(candidate)) => candidate,
277        };
278
279        match self.confirm_candidate(obligation, candidate) {
280            Err(SelectionError::Overflow(OverflowError::Canonical)) => {
281                assert!(self.query_mode == TraitQueryMode::Canonical);
282                Err(SelectionError::Overflow(OverflowError::Canonical))
283            }
284            Err(e) => Err(e),
285            Ok(ImplSource::Builtin(..)) if self.typing_mode().is_reflection() => {
286                // Builtin impls regularly don't satisfy the try_as_dyn requirements, so
287                // we just reject all of them.
288                Err(SelectionError::Unimplemented)
289            }
290            Ok(candidate) => Ok(Some(candidate)),
291        }
292    }
293
294    pub fn select(
295        &mut self,
296        obligation: &TraitObligation<'tcx>,
297    ) -> SelectionResult<'tcx, Selection<'tcx>> {
298        if self.infcx.next_trait_solver() {
299            return self.infcx.select_in_new_trait_solver(obligation);
300        }
301
302        self.poly_select(&Obligation {
303            cause: obligation.cause.clone(),
304            param_env: obligation.param_env,
305            predicate: ty::Binder::dummy(obligation.predicate),
306            recursion_depth: obligation.recursion_depth,
307        })
308    }
309
310    fn select_from_obligation(
311        &mut self,
312        obligation: &PolyTraitObligation<'tcx>,
313    ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
314        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());
315
316        let pec = &ProvisionalEvaluationCache::default();
317        let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
318
319        self.candidate_from_obligation(&stack)
320    }
321
322    x;#[instrument(level = "debug", skip(self), ret)]
323    fn candidate_from_obligation<'o>(
324        &mut self,
325        stack: &TraitObligationStack<'o, 'tcx>,
326    ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
327        debug_assert!(!self.infcx.next_trait_solver());
328        // Watch out for overflow. This intentionally bypasses (and does
329        // not update) the cache.
330        self.check_recursion_limit(stack.obligation, stack.obligation)?;
331
332        // Check the cache. Note that we freshen the trait-ref
333        // separately rather than using `stack.fresh_trait_pred` --
334        // this is because we want the unbound variables to be
335        // replaced with fresh types starting from index 0.
336        let cache_fresh_trait_pred =
337            stack.obligation.predicate.fold_with(&mut TypeFreshener::new(self.infcx));
338        debug!(?cache_fresh_trait_pred);
339        debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
340
341        if let Some(c) =
342            self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred)
343        {
344            debug!("CACHE HIT");
345            return c;
346        }
347
348        // If no match, compute result and insert into cache.
349        //
350        // FIXME(nikomatsakis) -- this cache is not taking into
351        // account cycles that may have occurred in forming the
352        // candidate. I don't know of any specific problems that
353        // result but it seems awfully suspicious.
354        let (candidate, dep_node) =
355            self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
356
357        debug!("CACHE MISS");
358        self.insert_candidate_cache(
359            stack.obligation.param_env,
360            cache_fresh_trait_pred,
361            dep_node,
362            candidate.clone(),
363        );
364        candidate
365    }
366
367    fn candidate_from_obligation_no_cache<'o>(
368        &mut self,
369        stack: &TraitObligationStack<'o, 'tcx>,
370    ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
371        if let Err(conflict) = self.is_knowable(stack) {
372            {
    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:372",
                        "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(372u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coherence stage: not knowable")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coherence stage: not knowable");
373            if self.intercrate_ambiguity_causes.is_some() {
374                {
    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:374",
                        "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(374u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("evaluate_stack: intercrate_ambiguity_causes is some")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("evaluate_stack: intercrate_ambiguity_causes is some");
375                // Heuristics: show the diagnostics when there are no candidates in crate.
376                if let Ok(candidate_set) = self.assemble_candidates(stack) {
377                    let mut no_candidates_apply = true;
378
379                    for c in candidate_set.vec.iter() {
380                        if self.evaluate_candidate(stack, c)?.may_apply() {
381                            no_candidates_apply = false;
382                            break;
383                        }
384                    }
385
386                    if !candidate_set.ambiguous && no_candidates_apply {
387                        let trait_ref = self.infcx.resolve_vars_if_possible(
388                            stack.obligation.predicate.skip_binder().trait_ref,
389                        );
390                        if !trait_ref.references_error() {
391                            let self_ty = trait_ref.self_ty();
392                            let self_ty = self_ty.has_concrete_skeleton().then(|| self_ty);
393                            let cause = if let Conflict::Upstream = conflict {
394                                IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_ref, self_ty }
395                            } else {
396                                IntercrateAmbiguityCause::DownstreamCrate { trait_ref, self_ty }
397                            };
398                            {
    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:398",
                        "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(398u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("cause")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("cause");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("evaluate_stack: pushing cause")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?cause, "evaluate_stack: pushing cause");
399                            self.intercrate_ambiguity_causes.as_mut().unwrap().insert(cause);
400                        }
401                    }
402                }
403            }
404            return Ok(None);
405        }
406
407        let candidate_set = self.assemble_candidates(stack)?;
408
409        if candidate_set.ambiguous {
410            {
    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:410",
                        "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(410u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("candidate set contains ambig")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("candidate set contains ambig");
411            return Ok(None);
412        }
413
414        let candidates = candidate_set.vec;
415
416        {
    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:416",
                        "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(416u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("stack")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("stack");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("candidates")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("candidates");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("assembled {0} candidates",
                                                    candidates.len()) as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&stack)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidates)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?stack, ?candidates, "assembled {} candidates", candidates.len());
417
418        // At this point, we know that each of the entries in the
419        // candidate set is *individually* applicable. Now we have to
420        // figure out if they contain mutual incompatibilities. This
421        // frequently arises if we have an unconstrained input type --
422        // for example, we are looking for `$0: Eq` where `$0` is some
423        // unconstrained type variable. In that case, we'll get a
424        // candidate which assumes $0 == int, one that assumes `$0 ==
425        // usize`, etc. This spells an ambiguity.
426
427        let mut candidates = self.filter_impls(candidates, stack.obligation);
428
429        // If there is more than one candidate, first winnow them down
430        // by considering extra conditions (nested obligations and so
431        // forth). We don't winnow if there is exactly one
432        // candidate. This is a relatively minor distinction but it
433        // can lead to better inference and error-reporting. An
434        // example would be if there was an impl:
435        //
436        //     impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
437        //
438        // and we were to see some code `foo.push_clone()` where `boo`
439        // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
440        // we were to winnow, we'd wind up with zero candidates.
441        // Instead, we select the right impl now but report "`Bar` does
442        // not implement `Clone`".
443        if candidates.len() == 1 {
444            return self.filter_reservation_impls(candidates.pop().unwrap());
445        }
446
447        // Winnow, but record the exact outcome of evaluation, which
448        // is needed for specialization. Propagate overflow if it occurs.
449        let candidates = candidates
450            .into_iter()
451            .map(|c| match self.evaluate_candidate(stack, &c) {
452                Ok(eval) if eval.may_apply() => {
453                    Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
454                }
455                Ok(_) => Ok(None),
456                Err(OverflowError::Canonical) => {
457                    Err(SelectionError::Overflow(OverflowError::Canonical))
458                }
459                Err(OverflowError::Error(e)) => {
460                    Err(SelectionError::Overflow(OverflowError::Error(e)))
461                }
462            })
463            .flat_map(Result::transpose)
464            .collect::<Result<Vec<_>, _>>()?;
465
466        {
    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:466",
                        "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(466u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("stack")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("stack");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("candidates")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("candidates");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0} potentially applicable candidates",
                                                    candidates.len()) as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&stack)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidates)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?stack, ?candidates, "{} potentially applicable candidates", candidates.len());
467        // If there are *NO* candidates, then there are no impls --
468        // that we know of, anyway. Note that in the case where there
469        // are unbound type variables within the obligation, it might
470        // be the case that you could still satisfy the obligation
471        // from another crate by instantiating the type variables with
472        // a type from another crate that does have an impl. This case
473        // is checked for in `evaluate_stack` (and hence users
474        // who might care about this case, like coherence, should use
475        // that function).
476        if candidates.is_empty() {
477            // If there's an error type, 'downgrade' our result from
478            // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
479            // emitting additional spurious errors, since we're guaranteed
480            // to have emitted at least one.
481            if stack.obligation.predicate.references_error() {
482                {
    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:482",
                        "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(482u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("stack.obligation.predicate")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("stack.obligation.predicate");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("found error type in predicate, treating as ambiguous")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&stack.obligation.predicate)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?stack.obligation.predicate, "found error type in predicate, treating as ambiguous");
483                Ok(None)
484            } else {
485                Err(SelectionError::Unimplemented)
486            }
487        } else {
488            let has_non_region_infer = stack.obligation.predicate.has_non_region_infer();
489            let candidate_preference_mode =
490                CandidatePreferenceMode::compute(self.tcx(), stack.obligation.predicate.def_id());
491            if let Some(candidate) =
492                self.winnow_candidates(has_non_region_infer, candidate_preference_mode, candidates)
493            {
494                self.filter_reservation_impls(candidate)
495            } else {
496                Ok(None)
497            }
498        }
499    }
500
501    ///////////////////////////////////////////////////////////////////////////
502    // EVALUATION
503    //
504    // Tests whether an obligation can be selected or whether an impl
505    // can be applied to particular types. It skips the "confirmation"
506    // step and hence completely ignores output type parameters.
507    //
508    // The result is "true" if the obligation *may* hold and "false" if
509    // we can be sure it does not.
510
511    /// Evaluates whether the obligation `obligation` can be satisfied
512    /// and returns an `EvaluationResult`. This is meant for the
513    /// *initial* call.
514    ///
515    /// Do not use this directly, use `infcx.evaluate_obligation` instead.
516    pub fn evaluate_root_obligation(
517        &mut self,
518        obligation: &PredicateObligation<'tcx>,
519    ) -> Result<EvaluationResult, OverflowError> {
520        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());
521        self.evaluation_probe(|this| {
522            let goal =
523                this.infcx.resolve_vars_if_possible((obligation.predicate, obligation.param_env));
524            let mut result = this.evaluate_predicate_recursively(
525                TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
526                obligation.clone(),
527            )?;
528            // If the predicate has done any inference, then downgrade the
529            // result to ambiguous.
530            if this.infcx.resolve_vars_if_possible(goal) != goal {
531                result = result.max(EvaluatedToAmbig);
532            }
533            Ok(result)
534        })
535    }
536
537    /// Computes the evaluation result of `op`, discarding any constraints.
538    ///
539    /// This also runs for leak check to allow higher ranked region errors to impact
540    /// selection. By default it checks for leaks from all universes created inside of
541    /// `op`, but this can be overwritten if necessary.
542    fn evaluation_probe(
543        &mut self,
544        op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
545    ) -> Result<EvaluationResult, OverflowError> {
546        self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
547            let outer_universe = self.infcx.universe();
548            let result = op(self)?;
549
550            match self.infcx.leak_check(outer_universe, Some(snapshot)) {
551                Ok(()) => {}
552                Err(_) => return Ok(EvaluatedToErr),
553            }
554
555            if self.infcx.opaque_types_added_in_snapshot(snapshot) {
556                return Ok(result.max(EvaluatedToOkModuloOpaqueTypes));
557            }
558
559            if self.infcx.region_constraints_added_in_snapshot(snapshot) {
560                Ok(result.max(EvaluatedToOkModuloRegions))
561            } else {
562                Ok(result)
563            }
564        })
565    }
566
567    /// Evaluates the predicates in `predicates` recursively. This may
568    /// guide inference. If this is not desired, run it inside of a
569    /// is run within an inference probe.
570    /// `probe`.
571    #[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(571u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("predicates")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("predicates");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicates)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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:1441",
                                    "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(1441u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0:#?}",
                                                                candidates) as &dyn ::tracing::field::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:1460",
                                    "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(1460u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0:#?}",
                                                                result) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            result
        }
    }
}#[instrument(level = "debug", skip(self, candidates))]
1436    fn filter_impls(
1437        &mut self,
1438        candidates: Vec<SelectionCandidate<'tcx>>,
1439        obligation: &PolyTraitObligation<'tcx>,
1440    ) -> Vec<SelectionCandidate<'tcx>> {
1441        trace!("{candidates:#?}");
1442        let tcx = self.tcx();
1443        let mut result = Vec::with_capacity(candidates.len());
1444
1445        for candidate in candidates {
1446            if let ImplCandidate(def_id) = candidate {
1447                match (tcx.impl_polarity(def_id), obligation.polarity()) {
1448                    (ty::ImplPolarity::Reservation, _)
1449                    | (ty::ImplPolarity::Positive, ty::PredicatePolarity::Positive)
1450                    | (ty::ImplPolarity::Negative, ty::PredicatePolarity::Negative) => {
1451                        result.push(candidate);
1452                    }
1453                    _ => {}
1454                }
1455            } else {
1456                result.push(candidate);
1457            }
1458        }
1459
1460        trace!("{result:#?}");
1461        result
1462    }
1463
1464    /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1465    #[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(1465u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("candidate")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("candidate");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    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")]
2787    fn match_poly_trait_ref(
2788        &mut self,
2789        obligation: &PolyTraitObligation<'tcx>,
2790        poly_trait_ref: ty::PolyTraitRef<'tcx>,
2791    ) -> Result<PredicateObligations<'tcx>, ()> {
2792        let predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
2793        let trait_ref = self.infcx.instantiate_binder_with_fresh_vars(
2794            obligation.cause.span,
2795            HigherRankedType,
2796            poly_trait_ref,
2797        );
2798        self.infcx
2799            .at(&obligation.cause, obligation.param_env)
2800            .eq(DefineOpaqueTypes::No, predicate.trait_ref, trait_ref)
2801            .map(|InferOk { obligations, .. }| obligations)
2802            .map_err(|_| ())
2803    }
2804
2805    ///////////////////////////////////////////////////////////////////////////
2806    // Miscellany
2807
2808    fn match_fresh_trait_preds(
2809        &self,
2810        previous: ty::PolyTraitPredicate<'tcx>,
2811        current: ty::PolyTraitPredicate<'tcx>,
2812    ) -> bool {
2813        let mut matcher = _match::MatchAgainstFreshVars::new(self.tcx());
2814        matcher.relate(previous, current).is_ok()
2815    }
2816
2817    fn push_stack<'o>(
2818        &mut self,
2819        previous_stack: TraitObligationStackList<'o, 'tcx>,
2820        obligation: &'o PolyTraitObligation<'tcx>,
2821    ) -> TraitObligationStack<'o, 'tcx> {
2822        let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
2823
2824        let dfn = previous_stack.cache.next_dfn();
2825        let depth = previous_stack.depth() + 1;
2826        TraitObligationStack {
2827            obligation,
2828            fresh_trait_pred,
2829            reached_depth: Cell::new(depth),
2830            previous: previous_stack,
2831            dfn,
2832            depth,
2833        }
2834    }
2835
2836    #[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(2836u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_trait_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_trait_def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_trait_def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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")]
2837    fn closure_trait_ref_unnormalized(
2838        &mut self,
2839        self_ty: Ty<'tcx>,
2840        fn_trait_def_id: DefId,
2841    ) -> ty::PolyTraitRef<'tcx> {
2842        let ty::Closure(_, args) = *self_ty.kind() else {
2843            bug!("expected closure, found {self_ty}");
2844        };
2845        let closure_sig = args.as_closure().sig();
2846
2847        closure_trait_ref_and_return_type(
2848            self.tcx(),
2849            fn_trait_def_id,
2850            self_ty,
2851            closure_sig,
2852            util::TupleArgumentsFlag::No,
2853        )
2854        .map_bound(|(trait_ref, _)| trait_ref)
2855    }
2856
2857    /// Returns the obligations that are implied by instantiating an
2858    /// impl or trait. The obligations are instantiated and fully
2859    /// normalized. This is used when confirming an impl or default
2860    /// impl.
2861    #[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(2861u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::select"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("recursion_depth")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("recursion_depth");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("args");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("parent_trait_pred")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("parent_trait_pred");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&recursion_depth
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_trait_pred)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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