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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    SelectionResult<'tcx, SelectionCandidate<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            if let ImplCandidate(def_id) = candidate &&
                    let ty::ImplPolarity::Reservation =
                        tcx.impl_polarity(def_id) {
                if let Some(intercrate_ambiguity_clauses) =
                        &mut self.intercrate_ambiguity_causes {
                    let message =
                        {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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