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::assert_matches::assert_matches;
6use std::cell::{Cell, RefCell};
7use std::fmt::{self, Display};
8use std::ops::ControlFlow;
9use std::{cmp, iter};
10
11use hir::def::DefKind;
12use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
13use rustc_data_structures::stack::ensure_sufficient_stack;
14use rustc_errors::{Diag, EmissionGuarantee};
15use rustc_hir as hir;
16use rustc_hir::LangItem;
17use rustc_hir::def_id::DefId;
18use rustc_infer::infer::BoundRegionConversionTime::{self, HigherRankedType};
19use rustc_infer::infer::DefineOpaqueTypes;
20use rustc_infer::infer::at::ToTrace;
21use rustc_infer::infer::relate::TypeRelation;
22use rustc_infer::traits::{PredicateObligations, TraitObligation};
23use rustc_middle::bug;
24use rustc_middle::dep_graph::{DepNodeIndex, dep_kinds};
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, GenericArgsRef, PolyProjectionPredicate, Ty, TyCtxt, TypeFoldable, TypeVisitableExt,
31    TypingMode, Upcast,
32};
33use rustc_span::{Symbol, sym};
34use rustc_type_ir::elaborate;
35use tracing::{debug, instrument, trace};
36
37use self::EvaluationResult::*;
38use self::SelectionCandidate::*;
39use super::coherence::{self, Conflict};
40use super::project::ProjectionTermObligation;
41use super::util::closure_trait_ref_and_return_type;
42use super::{
43    ImplDerivedCause, Normalized, Obligation, ObligationCause, ObligationCauseCode, Overflow,
44    PolyTraitObligation, PredicateObligation, Selection, SelectionError, SelectionResult,
45    TraitQueryMode, const_evaluatable, project, util, wf,
46};
47use crate::error_reporting::InferCtxtErrorExt;
48use crate::infer::{InferCtxt, InferOk, TypeFreshener};
49use crate::solve::InferCtxtSelectExt as _;
50use crate::traits::normalize::{normalize_with_depth, normalize_with_depth_to};
51use crate::traits::project::{ProjectAndUnifyResult, ProjectionCacheKeyExt};
52use crate::traits::{EvaluateConstErr, ProjectionCacheKey, Unimplemented, effects};
53
54mod _match;
55mod candidate_assembly;
56mod confirmation;
57
58#[derive(Clone, Debug, Eq, PartialEq, Hash)]
59pub enum IntercrateAmbiguityCause<'tcx> {
60    DownstreamCrate { trait_ref: ty::TraitRef<'tcx>, self_ty: Option<Ty<'tcx>> },
61    UpstreamCrateUpdate { trait_ref: ty::TraitRef<'tcx>, self_ty: Option<Ty<'tcx>> },
62    ReservationImpl { message: Symbol },
63}
64
65impl<'tcx> IntercrateAmbiguityCause<'tcx> {
66    /// Emits notes when the overlap is caused by complex intercrate ambiguities.
67    /// See #23980 for details.
68    pub fn add_intercrate_ambiguity_hint<G: EmissionGuarantee>(&self, err: &mut Diag<'_, G>) {
69        err.note(self.intercrate_ambiguity_hint());
70    }
71
72    pub fn intercrate_ambiguity_hint(&self) -> String {
73        with_no_trimmed_paths!(match self {
74            IntercrateAmbiguityCause::DownstreamCrate { trait_ref, self_ty } => {
75                format!(
76                    "downstream crates may implement trait `{trait_desc}`{self_desc}",
77                    trait_desc = trait_ref.print_trait_sugared(),
78                    self_desc = if let Some(self_ty) = self_ty {
79                        format!(" for type `{self_ty}`")
80                    } else {
81                        String::new()
82                    }
83                )
84            }
85            IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_ref, self_ty } => {
86                format!(
87                    "upstream crates may add a new impl of trait `{trait_desc}`{self_desc} \
88                in future versions",
89                    trait_desc = trait_ref.print_trait_sugared(),
90                    self_desc = if let Some(self_ty) = self_ty {
91                        format!(" for type `{self_ty}`")
92                    } else {
93                        String::new()
94                    }
95                )
96            }
97            IntercrateAmbiguityCause::ReservationImpl { message } => message.to_string(),
98        })
99    }
100}
101
102pub struct SelectionContext<'cx, 'tcx> {
103    pub infcx: &'cx InferCtxt<'tcx>,
104
105    /// Freshener used specifically for entries on the obligation
106    /// stack. This ensures that all entries on the stack at one time
107    /// will have the same set of placeholder entries, which is
108    /// important for checking for trait bounds that recursively
109    /// require themselves.
110    freshener: TypeFreshener<'cx, 'tcx>,
111
112    /// If `intercrate` is set, we remember predicates which were
113    /// considered ambiguous because of impls potentially added in other crates.
114    /// This is used in coherence to give improved diagnostics.
115    /// We don't do his until we detect a coherence error because it can
116    /// lead to false overflow results (#47139) and because always
117    /// computing it may negatively impact performance.
118    intercrate_ambiguity_causes: Option<FxIndexSet<IntercrateAmbiguityCause<'tcx>>>,
119
120    /// The mode that trait queries run in, which informs our error handling
121    /// policy. In essence, canonicalized queries need their errors propagated
122    /// rather than immediately reported because we do not have accurate spans.
123    query_mode: TraitQueryMode,
124}
125
126// A stack that walks back up the stack frame.
127struct TraitObligationStack<'prev, 'tcx> {
128    obligation: &'prev PolyTraitObligation<'tcx>,
129
130    /// The trait predicate from `obligation` but "freshened" with the
131    /// selection-context's freshener. Used to check for recursion.
132    fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
133
134    /// Starts out equal to `depth` -- if, during evaluation, we
135    /// encounter a cycle, then we will set this flag to the minimum
136    /// depth of that cycle for all participants in the cycle. These
137    /// participants will then forego caching their results. This is
138    /// not the most efficient solution, but it addresses #60010. The
139    /// problem we are trying to prevent:
140    ///
141    /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
142    /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
143    /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
144    ///
145    /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
146    /// is `EvaluatedToOk`; this is because they were only considered
147    /// ok on the premise that if `A: AutoTrait` held, but we indeed
148    /// encountered a problem (later on) with `A: AutoTrait`. So we
149    /// currently set a flag on the stack node for `B: AutoTrait` (as
150    /// well as the second instance of `A: AutoTrait`) to suppress
151    /// caching.
152    ///
153    /// This is a simple, targeted fix. A more-performant fix requires
154    /// deeper changes, but would permit more caching: we could
155    /// basically defer caching until we have fully evaluated the
156    /// tree, and then cache the entire tree at once. In any case, the
157    /// performance impact here shouldn't be so horrible: every time
158    /// this is hit, we do cache at least one trait, so we only
159    /// evaluate each member of a cycle up to N times, where N is the
160    /// length of the cycle. This means the performance impact is
161    /// bounded and we shouldn't have any terrible worst-cases.
162    reached_depth: Cell<usize>,
163
164    previous: TraitObligationStackList<'prev, 'tcx>,
165
166    /// The number of parent frames plus one (thus, the topmost frame has depth 1).
167    depth: usize,
168
169    /// The depth-first number of this node in the search graph -- a
170    /// pre-order index. Basically, a freshly incremented counter.
171    dfn: usize,
172}
173
174struct SelectionCandidateSet<'tcx> {
175    /// A list of candidates that definitely apply to the current
176    /// obligation (meaning: types unify).
177    vec: Vec<SelectionCandidate<'tcx>>,
178
179    /// If `true`, then there were candidates that might or might
180    /// not have applied, but we couldn't tell. This occurs when some
181    /// of the input types are type variables, in which case there are
182    /// various "builtin" rules that might or might not trigger.
183    ambiguous: bool,
184}
185
186#[derive(PartialEq, Eq, Debug, Clone)]
187struct EvaluatedCandidate<'tcx> {
188    candidate: SelectionCandidate<'tcx>,
189    evaluation: EvaluationResult,
190}
191
192/// When does the builtin impl for `T: Trait` apply?
193#[derive(Debug)]
194enum BuiltinImplConditions<'tcx> {
195    /// The impl is conditional on `T1, T2, ...: Trait`.
196    Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
197    /// There is no built-in impl. There may be some other
198    /// candidate (a where-clause or user-defined impl).
199    None,
200    /// It is unknown whether there is an impl.
201    Ambiguous,
202}
203
204impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
205    pub fn new(infcx: &'cx InferCtxt<'tcx>) -> SelectionContext<'cx, 'tcx> {
206        SelectionContext {
207            infcx,
208            freshener: infcx.freshener(),
209            intercrate_ambiguity_causes: None,
210            query_mode: TraitQueryMode::Standard,
211        }
212    }
213
214    pub fn with_query_mode(
215        infcx: &'cx InferCtxt<'tcx>,
216        query_mode: TraitQueryMode,
217    ) -> SelectionContext<'cx, 'tcx> {
218        debug!(?query_mode, "with_query_mode");
219        SelectionContext { query_mode, ..SelectionContext::new(infcx) }
220    }
221
222    /// Enables tracking of intercrate ambiguity causes. See
223    /// the documentation of [`Self::intercrate_ambiguity_causes`] for more.
224    pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
225        assert_matches!(self.infcx.typing_mode(), TypingMode::Coherence);
226        assert!(self.intercrate_ambiguity_causes.is_none());
227        self.intercrate_ambiguity_causes = Some(FxIndexSet::default());
228        debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
229    }
230
231    /// Gets the intercrate ambiguity causes collected since tracking
232    /// was enabled and disables tracking at the same time. If
233    /// tracking is not enabled, just returns an empty vector.
234    pub fn take_intercrate_ambiguity_causes(
235        &mut self,
236    ) -> FxIndexSet<IntercrateAmbiguityCause<'tcx>> {
237        assert_matches!(self.infcx.typing_mode(), TypingMode::Coherence);
238        self.intercrate_ambiguity_causes.take().unwrap_or_default()
239    }
240
241    pub fn tcx(&self) -> TyCtxt<'tcx> {
242        self.infcx.tcx
243    }
244
245    ///////////////////////////////////////////////////////////////////////////
246    // Selection
247    //
248    // The selection phase tries to identify *how* an obligation will
249    // be resolved. For example, it will identify which impl or
250    // parameter bound is to be used. The process can be inconclusive
251    // if the self type in the obligation is not fully inferred. Selection
252    // can result in an error in one of two ways:
253    //
254    // 1. If no applicable impl or parameter bound can be found.
255    // 2. If the output type parameters in the obligation do not match
256    //    those specified by the impl/bound. For example, if the obligation
257    //    is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
258    //    `impl<T> Iterable<T> for Vec<T>`, than an error would result.
259
260    /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
261    /// type environment by performing unification.
262    #[instrument(level = "debug", skip(self), ret)]
263    pub fn poly_select(
264        &mut self,
265        obligation: &PolyTraitObligation<'tcx>,
266    ) -> SelectionResult<'tcx, Selection<'tcx>> {
267        if self.infcx.next_trait_solver() {
268            return self.infcx.select_in_new_trait_solver(obligation);
269        }
270
271        let candidate = match self.select_from_obligation(obligation) {
272            Err(SelectionError::Overflow(OverflowError::Canonical)) => {
273                // In standard mode, overflow must have been caught and reported
274                // earlier.
275                assert!(self.query_mode == TraitQueryMode::Canonical);
276                return Err(SelectionError::Overflow(OverflowError::Canonical));
277            }
278            Err(e) => {
279                return Err(e);
280            }
281            Ok(None) => {
282                return Ok(None);
283            }
284            Ok(Some(candidate)) => candidate,
285        };
286
287        match self.confirm_candidate(obligation, candidate) {
288            Err(SelectionError::Overflow(OverflowError::Canonical)) => {
289                assert!(self.query_mode == TraitQueryMode::Canonical);
290                Err(SelectionError::Overflow(OverflowError::Canonical))
291            }
292            Err(e) => Err(e),
293            Ok(candidate) => Ok(Some(candidate)),
294        }
295    }
296
297    pub fn select(
298        &mut self,
299        obligation: &TraitObligation<'tcx>,
300    ) -> SelectionResult<'tcx, Selection<'tcx>> {
301        self.poly_select(&Obligation {
302            cause: obligation.cause.clone(),
303            param_env: obligation.param_env,
304            predicate: ty::Binder::dummy(obligation.predicate),
305            recursion_depth: obligation.recursion_depth,
306        })
307    }
308
309    fn select_from_obligation(
310        &mut self,
311        obligation: &PolyTraitObligation<'tcx>,
312    ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
313        debug_assert!(!obligation.predicate.has_escaping_bound_vars());
314
315        let pec = &ProvisionalEvaluationCache::default();
316        let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
317
318        self.candidate_from_obligation(&stack)
319    }
320
321    #[instrument(level = "debug", skip(self), ret)]
322    fn candidate_from_obligation<'o>(
323        &mut self,
324        stack: &TraitObligationStack<'o, 'tcx>,
325    ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
326        debug_assert!(!self.infcx.next_trait_solver());
327        // Watch out for overflow. This intentionally bypasses (and does
328        // not update) the cache.
329        self.check_recursion_limit(stack.obligation, stack.obligation)?;
330
331        // Check the cache. Note that we freshen the trait-ref
332        // separately rather than using `stack.fresh_trait_ref` --
333        // this is because we want the unbound variables to be
334        // replaced with fresh types starting from index 0.
335        let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate);
336        debug!(?cache_fresh_trait_pred);
337        debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
338
339        if let Some(c) =
340            self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred)
341        {
342            debug!("CACHE HIT");
343            return c;
344        }
345
346        // If no match, compute result and insert into cache.
347        //
348        // FIXME(nikomatsakis) -- this cache is not taking into
349        // account cycles that may have occurred in forming the
350        // candidate. I don't know of any specific problems that
351        // result but it seems awfully suspicious.
352        let (candidate, dep_node) =
353            self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
354
355        debug!("CACHE MISS");
356        self.insert_candidate_cache(
357            stack.obligation.param_env,
358            cache_fresh_trait_pred,
359            dep_node,
360            candidate.clone(),
361        );
362        candidate
363    }
364
365    fn candidate_from_obligation_no_cache<'o>(
366        &mut self,
367        stack: &TraitObligationStack<'o, 'tcx>,
368    ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
369        if let Err(conflict) = self.is_knowable(stack) {
370            debug!("coherence stage: not knowable");
371            if self.intercrate_ambiguity_causes.is_some() {
372                debug!("evaluate_stack: intercrate_ambiguity_causes is some");
373                // Heuristics: show the diagnostics when there are no candidates in crate.
374                if let Ok(candidate_set) = self.assemble_candidates(stack) {
375                    let mut no_candidates_apply = true;
376
377                    for c in candidate_set.vec.iter() {
378                        if self.evaluate_candidate(stack, c)?.may_apply() {
379                            no_candidates_apply = false;
380                            break;
381                        }
382                    }
383
384                    if !candidate_set.ambiguous && no_candidates_apply {
385                        let trait_ref = self.infcx.resolve_vars_if_possible(
386                            stack.obligation.predicate.skip_binder().trait_ref,
387                        );
388                        if !trait_ref.references_error() {
389                            let self_ty = trait_ref.self_ty();
390                            let self_ty = self_ty.has_concrete_skeleton().then(|| self_ty);
391                            let cause = if let Conflict::Upstream = conflict {
392                                IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_ref, self_ty }
393                            } else {
394                                IntercrateAmbiguityCause::DownstreamCrate { trait_ref, self_ty }
395                            };
396                            debug!(?cause, "evaluate_stack: pushing cause");
397                            self.intercrate_ambiguity_causes.as_mut().unwrap().insert(cause);
398                        }
399                    }
400                }
401            }
402            return Ok(None);
403        }
404
405        let candidate_set = self.assemble_candidates(stack)?;
406
407        if candidate_set.ambiguous {
408            debug!("candidate set contains ambig");
409            return Ok(None);
410        }
411
412        let candidates = candidate_set.vec;
413
414        debug!(?stack, ?candidates, "assembled {} candidates", candidates.len());
415
416        // At this point, we know that each of the entries in the
417        // candidate set is *individually* applicable. Now we have to
418        // figure out if they contain mutual incompatibilities. This
419        // frequently arises if we have an unconstrained input type --
420        // for example, we are looking for `$0: Eq` where `$0` is some
421        // unconstrained type variable. In that case, we'll get a
422        // candidate which assumes $0 == int, one that assumes `$0 ==
423        // usize`, etc. This spells an ambiguity.
424
425        let mut candidates = self.filter_impls(candidates, stack.obligation);
426
427        // If there is more than one candidate, first winnow them down
428        // by considering extra conditions (nested obligations and so
429        // forth). We don't winnow if there is exactly one
430        // candidate. This is a relatively minor distinction but it
431        // can lead to better inference and error-reporting. An
432        // example would be if there was an impl:
433        //
434        //     impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
435        //
436        // and we were to see some code `foo.push_clone()` where `boo`
437        // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
438        // we were to winnow, we'd wind up with zero candidates.
439        // Instead, we select the right impl now but report "`Bar` does
440        // not implement `Clone`".
441        if candidates.len() == 1 {
442            return self.filter_reservation_impls(candidates.pop().unwrap());
443        }
444
445        // Winnow, but record the exact outcome of evaluation, which
446        // is needed for specialization. Propagate overflow if it occurs.
447        let candidates = candidates
448            .into_iter()
449            .map(|c| match self.evaluate_candidate(stack, &c) {
450                Ok(eval) if eval.may_apply() => {
451                    Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
452                }
453                Ok(_) => Ok(None),
454                Err(OverflowError::Canonical) => Err(Overflow(OverflowError::Canonical)),
455                Err(OverflowError::Error(e)) => Err(Overflow(OverflowError::Error(e))),
456            })
457            .flat_map(Result::transpose)
458            .collect::<Result<Vec<_>, _>>()?;
459
460        debug!(?stack, ?candidates, "{} potentially applicable candidates", candidates.len());
461        // If there are *NO* candidates, then there are no impls --
462        // that we know of, anyway. Note that in the case where there
463        // are unbound type variables within the obligation, it might
464        // be the case that you could still satisfy the obligation
465        // from another crate by instantiating the type variables with
466        // a type from another crate that does have an impl. This case
467        // is checked for in `evaluate_stack` (and hence users
468        // who might care about this case, like coherence, should use
469        // that function).
470        if candidates.is_empty() {
471            // If there's an error type, 'downgrade' our result from
472            // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
473            // emitting additional spurious errors, since we're guaranteed
474            // to have emitted at least one.
475            if stack.obligation.predicate.references_error() {
476                debug!(?stack.obligation.predicate, "found error type in predicate, treating as ambiguous");
477                Ok(None)
478            } else {
479                Err(Unimplemented)
480            }
481        } else {
482            let has_non_region_infer = stack.obligation.predicate.has_non_region_infer();
483            if let Some(candidate) = self.winnow_candidates(has_non_region_infer, candidates) {
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        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    #[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    #[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        ensure_sufficient_stack(|| {
607            let bound_predicate = obligation.predicate.kind();
608            match bound_predicate.skip_binder() {
609                ty::PredicateKind::Clause(ty::ClauseKind::Trait(t)) => {
610                    let t = bound_predicate.rebind(t);
611                    debug_assert!(!t.has_escaping_bound_vars());
612                    let obligation = obligation.with(self.tcx(), t);
613                    self.evaluate_trait_predicate_recursively(previous_stack, obligation)
614                }
615
616                ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(data)) => {
617                    self.infcx.enter_forall(bound_predicate.rebind(data), |data| {
618                        match effects::evaluate_host_effect_obligation(
619                            self,
620                            &obligation.with(self.tcx(), data),
621                        ) {
622                            Ok(nested) => {
623                                self.evaluate_predicates_recursively(previous_stack, nested)
624                            }
625                            Err(effects::EvaluationFailure::Ambiguous) => Ok(EvaluatedToAmbig),
626                            Err(effects::EvaluationFailure::NoSolution) => Ok(EvaluatedToErr),
627                        }
628                    })
629                }
630
631                ty::PredicateKind::Subtype(p) => {
632                    let p = bound_predicate.rebind(p);
633                    // Does this code ever run?
634                    match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
635                        Ok(Ok(InferOk { obligations, .. })) => {
636                            self.evaluate_predicates_recursively(previous_stack, obligations)
637                        }
638                        Ok(Err(_)) => Ok(EvaluatedToErr),
639                        Err(..) => Ok(EvaluatedToAmbig),
640                    }
641                }
642
643                ty::PredicateKind::Coerce(p) => {
644                    let p = bound_predicate.rebind(p);
645                    // Does this code ever run?
646                    match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
647                        Ok(Ok(InferOk { obligations, .. })) => {
648                            self.evaluate_predicates_recursively(previous_stack, obligations)
649                        }
650                        Ok(Err(_)) => Ok(EvaluatedToErr),
651                        Err(..) => Ok(EvaluatedToAmbig),
652                    }
653                }
654
655                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
656                    // So, there is a bit going on here. First, `WellFormed` predicates
657                    // are coinductive, like trait predicates with auto traits.
658                    // This means that we need to detect if we have recursively
659                    // evaluated `WellFormed(X)`. Otherwise, we would run into
660                    // a "natural" overflow error.
661                    //
662                    // Now, the next question is whether we need to do anything
663                    // special with caching. Considering the following tree:
664                    // - `WF(Foo<T>)`
665                    //   - `Bar<T>: Send`
666                    //     - `WF(Foo<T>)`
667                    //   - `Foo<T>: Trait`
668                    // In this case, the innermost `WF(Foo<T>)` should return
669                    // `EvaluatedToOk`, since it's coinductive. Then if
670                    // `Bar<T>: Send` is resolved to `EvaluatedToOk`, it can be
671                    // inserted into a cache (because without thinking about `WF`
672                    // goals, it isn't in a cycle). If `Foo<T>: Trait` later doesn't
673                    // hold, then `Bar<T>: Send` shouldn't hold. Therefore, we
674                    // *do* need to keep track of coinductive cycles.
675
676                    let cache = previous_stack.cache;
677                    let dfn = cache.next_dfn();
678
679                    for stack_arg in previous_stack.cache.wf_args.borrow().iter().rev() {
680                        if stack_arg.0 != arg {
681                            continue;
682                        }
683                        debug!("WellFormed({:?}) on stack", arg);
684                        if let Some(stack) = previous_stack.head {
685                            // Okay, let's imagine we have two different stacks:
686                            //   `T: NonAutoTrait -> WF(T) -> T: NonAutoTrait`
687                            //   `WF(T) -> T: NonAutoTrait -> WF(T)`
688                            // Because of this, we need to check that all
689                            // predicates between the WF goals are coinductive.
690                            // Otherwise, we can say that `T: NonAutoTrait` is
691                            // true.
692                            // Let's imagine we have a predicate stack like
693                            //         `Foo: Bar -> WF(T) -> T: NonAutoTrait -> T: Auto`
694                            // depth   ^1                    ^2                 ^3
695                            // and the current predicate is `WF(T)`. `wf_args`
696                            // would contain `(T, 1)`. We want to check all
697                            // trait predicates greater than `1`. The previous
698                            // stack would be `T: Auto`.
699                            let cycle = stack.iter().take_while(|s| s.depth > stack_arg.1);
700                            let tcx = self.tcx();
701                            let cycle = cycle.map(|stack| stack.obligation.predicate.upcast(tcx));
702                            if self.coinductive_match(cycle) {
703                                stack.update_reached_depth(stack_arg.1);
704                                return Ok(EvaluatedToOk);
705                            } else {
706                                return Ok(EvaluatedToAmbigStackDependent);
707                            }
708                        }
709                        return Ok(EvaluatedToOk);
710                    }
711
712                    match wf::obligations(
713                        self.infcx,
714                        obligation.param_env,
715                        obligation.cause.body_id,
716                        obligation.recursion_depth + 1,
717                        arg,
718                        obligation.cause.span,
719                    ) {
720                        Some(obligations) => {
721                            cache.wf_args.borrow_mut().push((arg, previous_stack.depth()));
722                            let result =
723                                self.evaluate_predicates_recursively(previous_stack, obligations);
724                            cache.wf_args.borrow_mut().pop();
725
726                            let result = result?;
727
728                            if !result.must_apply_modulo_regions() {
729                                cache.on_failure(dfn);
730                            }
731
732                            cache.on_completion(dfn);
733
734                            Ok(result)
735                        }
736                        None => Ok(EvaluatedToAmbig),
737                    }
738                }
739
740                ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(pred)) => {
741                    // A global type with no free lifetimes or generic parameters
742                    // outlives anything.
743                    if pred.0.has_free_regions()
744                        || pred.0.has_bound_regions()
745                        || pred.0.has_non_region_infer()
746                        || pred.0.has_non_region_infer()
747                    {
748                        Ok(EvaluatedToOkModuloRegions)
749                    } else {
750                        Ok(EvaluatedToOk)
751                    }
752                }
753
754                ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..)) => {
755                    // We do not consider region relationships when evaluating trait matches.
756                    Ok(EvaluatedToOkModuloRegions)
757                }
758
759                ty::PredicateKind::DynCompatible(trait_def_id) => {
760                    if self.tcx().is_dyn_compatible(trait_def_id) {
761                        Ok(EvaluatedToOk)
762                    } else {
763                        Ok(EvaluatedToErr)
764                    }
765                }
766
767                ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
768                    let data = bound_predicate.rebind(data);
769                    let project_obligation = obligation.with(self.tcx(), data);
770                    match project::poly_project_and_unify_term(self, &project_obligation) {
771                        ProjectAndUnifyResult::Holds(mut subobligations) => {
772                            'compute_res: {
773                                // If we've previously marked this projection as 'complete', then
774                                // use the final cached result (either `EvaluatedToOk` or
775                                // `EvaluatedToOkModuloRegions`), and skip re-evaluating the
776                                // sub-obligations.
777                                if let Some(key) =
778                                    ProjectionCacheKey::from_poly_projection_obligation(
779                                        self,
780                                        &project_obligation,
781                                    )
782                                {
783                                    if let Some(cached_res) = self
784                                        .infcx
785                                        .inner
786                                        .borrow_mut()
787                                        .projection_cache()
788                                        .is_complete(key)
789                                    {
790                                        break 'compute_res Ok(cached_res);
791                                    }
792                                }
793
794                                // Need to explicitly set the depth of nested goals here as
795                                // projection obligations can cycle by themselves and in
796                                // `evaluate_predicates_recursively` we only add the depth
797                                // for parent trait goals because only these get added to the
798                                // `TraitObligationStackList`.
799                                for subobligation in subobligations.iter_mut() {
800                                    subobligation.set_depth_from_parent(obligation.recursion_depth);
801                                }
802                                let res = self.evaluate_predicates_recursively(
803                                    previous_stack,
804                                    subobligations,
805                                );
806                                if let Ok(eval_rslt) = res
807                                    && (eval_rslt == EvaluatedToOk
808                                        || eval_rslt == EvaluatedToOkModuloRegions)
809                                    && let Some(key) =
810                                        ProjectionCacheKey::from_poly_projection_obligation(
811                                            self,
812                                            &project_obligation,
813                                        )
814                                {
815                                    // If the result is something that we can cache, then mark this
816                                    // entry as 'complete'. This will allow us to skip evaluating the
817                                    // subobligations at all the next time we evaluate the projection
818                                    // predicate.
819                                    self.infcx
820                                        .inner
821                                        .borrow_mut()
822                                        .projection_cache()
823                                        .complete(key, eval_rslt);
824                                }
825                                res
826                            }
827                        }
828                        ProjectAndUnifyResult::FailedNormalization => Ok(EvaluatedToAmbig),
829                        ProjectAndUnifyResult::Recursive => Ok(EvaluatedToAmbigStackDependent),
830                        ProjectAndUnifyResult::MismatchedProjectionTypes(_) => Ok(EvaluatedToErr),
831                    }
832                }
833
834                ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(uv)) => {
835                    match const_evaluatable::is_const_evaluatable(
836                        self.infcx,
837                        uv,
838                        obligation.param_env,
839                        obligation.cause.span,
840                    ) {
841                        Ok(()) => Ok(EvaluatedToOk),
842                        Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
843                        Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
844                        Err(_) => Ok(EvaluatedToErr),
845                    }
846                }
847
848                ty::PredicateKind::ConstEquate(c1, c2) => {
849                    let tcx = self.tcx();
850                    assert!(
851                        tcx.features().generic_const_exprs(),
852                        "`ConstEquate` without a feature gate: {c1:?} {c2:?}",
853                    );
854
855                    {
856                        let c1 = tcx.expand_abstract_consts(c1);
857                        let c2 = tcx.expand_abstract_consts(c2);
858                        debug!(
859                            "evaluate_predicate_recursively: equating consts:\nc1= {:?}\nc2= {:?}",
860                            c1, c2
861                        );
862
863                        use rustc_hir::def::DefKind;
864                        match (c1.kind(), c2.kind()) {
865                            (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b))
866                                if a.def == b.def && tcx.def_kind(a.def) == DefKind::AssocConst =>
867                            {
868                                if let Ok(InferOk { obligations, value: () }) = self
869                                    .infcx
870                                    .at(&obligation.cause, obligation.param_env)
871                                    // Can define opaque types as this is only reachable with
872                                    // `generic_const_exprs`
873                                    .eq(
874                                        DefineOpaqueTypes::Yes,
875                                        ty::AliasTerm::from(a),
876                                        ty::AliasTerm::from(b),
877                                    )
878                                {
879                                    return self.evaluate_predicates_recursively(
880                                        previous_stack,
881                                        obligations,
882                                    );
883                                }
884                            }
885                            (_, ty::ConstKind::Unevaluated(_))
886                            | (ty::ConstKind::Unevaluated(_), _) => (),
887                            (_, _) => {
888                                if let Ok(InferOk { obligations, value: () }) = self
889                                    .infcx
890                                    .at(&obligation.cause, obligation.param_env)
891                                    // Can define opaque types as this is only reachable with
892                                    // `generic_const_exprs`
893                                    .eq(DefineOpaqueTypes::Yes, c1, c2)
894                                {
895                                    return self.evaluate_predicates_recursively(
896                                        previous_stack,
897                                        obligations,
898                                    );
899                                }
900                            }
901                        }
902                    }
903
904                    let evaluate = |c: ty::Const<'tcx>| {
905                        if let ty::ConstKind::Unevaluated(_) = c.kind() {
906                            match crate::traits::try_evaluate_const(
907                                self.infcx,
908                                c,
909                                obligation.param_env,
910                            ) {
911                                Ok(val) => Ok(val),
912                                Err(e) => Err(e),
913                            }
914                        } else {
915                            Ok(c)
916                        }
917                    };
918
919                    match (evaluate(c1), evaluate(c2)) {
920                        (Ok(c1), Ok(c2)) => {
921                            match self.infcx.at(&obligation.cause, obligation.param_env).eq(
922                                // Can define opaque types as this is only reachable with
923                                // `generic_const_exprs`
924                                DefineOpaqueTypes::Yes,
925                                c1,
926                                c2,
927                            ) {
928                                Ok(inf_ok) => self.evaluate_predicates_recursively(
929                                    previous_stack,
930                                    inf_ok.into_obligations(),
931                                ),
932                                Err(_) => Ok(EvaluatedToErr),
933                            }
934                        }
935                        (Err(EvaluateConstErr::InvalidConstParamTy(..)), _)
936                        | (_, Err(EvaluateConstErr::InvalidConstParamTy(..))) => Ok(EvaluatedToErr),
937                        (Err(EvaluateConstErr::EvaluationFailure(..)), _)
938                        | (_, Err(EvaluateConstErr::EvaluationFailure(..))) => Ok(EvaluatedToErr),
939                        (Err(EvaluateConstErr::HasGenericsOrInfers), _)
940                        | (_, Err(EvaluateConstErr::HasGenericsOrInfers)) => {
941                            if c1.has_non_region_infer() || c2.has_non_region_infer() {
942                                Ok(EvaluatedToAmbig)
943                            } else {
944                                // Two different constants using generic parameters ~> error.
945                                Ok(EvaluatedToErr)
946                            }
947                        }
948                    }
949                }
950                ty::PredicateKind::NormalizesTo(..) => {
951                    bug!("NormalizesTo is only used by the new solver")
952                }
953                ty::PredicateKind::AliasRelate(..) => {
954                    bug!("AliasRelate is only used by the new solver")
955                }
956                ty::PredicateKind::Ambiguous => Ok(EvaluatedToAmbig),
957                ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
958                    let ct = self.infcx.shallow_resolve_const(ct);
959                    let ct_ty = match ct.kind() {
960                        ty::ConstKind::Infer(_) => {
961                            return Ok(EvaluatedToAmbig);
962                        }
963                        ty::ConstKind::Error(_) => return Ok(EvaluatedToOk),
964                        ty::ConstKind::Value(cv) => cv.ty,
965                        ty::ConstKind::Unevaluated(uv) => {
966                            self.tcx().type_of(uv.def).instantiate(self.tcx(), uv.args)
967                        }
968                        // FIXME(generic_const_exprs): See comment in `fulfill.rs`
969                        ty::ConstKind::Expr(_) => return Ok(EvaluatedToOk),
970                        ty::ConstKind::Placeholder(_) => {
971                            bug!("placeholder const {:?} in old solver", ct)
972                        }
973                        ty::ConstKind::Bound(_, _) => bug!("escaping bound vars in {:?}", ct),
974                        ty::ConstKind::Param(param_ct) => {
975                            param_ct.find_ty_from_env(obligation.param_env)
976                        }
977                    };
978
979                    match self.infcx.at(&obligation.cause, obligation.param_env).eq(
980                        // Only really exercised by generic_const_exprs
981                        DefineOpaqueTypes::Yes,
982                        ct_ty,
983                        ty,
984                    ) {
985                        Ok(inf_ok) => self.evaluate_predicates_recursively(
986                            previous_stack,
987                            inf_ok.into_obligations(),
988                        ),
989                        Err(_) => Ok(EvaluatedToErr),
990                    }
991                }
992            }
993        })
994    }
995
996    #[instrument(skip(self, previous_stack), level = "debug", ret)]
997    fn evaluate_trait_predicate_recursively<'o>(
998        &mut self,
999        previous_stack: TraitObligationStackList<'o, 'tcx>,
1000        mut obligation: PolyTraitObligation<'tcx>,
1001    ) -> Result<EvaluationResult, OverflowError> {
1002        if !matches!(self.infcx.typing_mode(), TypingMode::Coherence)
1003            && obligation.is_global()
1004            && obligation.param_env.caller_bounds().iter().all(|bound| bound.has_param())
1005        {
1006            // If a param env has no global bounds, global obligations do not
1007            // depend on its particular value in order to work, so we can clear
1008            // out the param env and get better caching.
1009            debug!("in global");
1010            obligation.param_env = ty::ParamEnv::empty();
1011        }
1012
1013        let stack = self.push_stack(previous_stack, &obligation);
1014        let fresh_trait_pred = stack.fresh_trait_pred;
1015        let param_env = obligation.param_env;
1016
1017        debug!(?fresh_trait_pred);
1018
1019        // If a trait predicate is in the (local or global) evaluation cache,
1020        // then we know it holds without cycles.
1021        if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
1022            debug!("CACHE HIT");
1023            return Ok(result);
1024        }
1025
1026        if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
1027            debug!("PROVISIONAL CACHE HIT");
1028            stack.update_reached_depth(result.reached_depth);
1029            return Ok(result.result);
1030        }
1031
1032        // Check if this is a match for something already on the
1033        // stack. If so, we don't want to insert the result into the
1034        // main cache (it is cycle dependent) nor the provisional
1035        // cache (which is meant for things that have completed but
1036        // for a "backedge" -- this result *is* the backedge).
1037        if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
1038            return Ok(cycle_result);
1039        }
1040
1041        let (result, dep_node) = self.in_task(|this| {
1042            let mut result = this.evaluate_stack(&stack)?;
1043
1044            // fix issue #103563, we don't normalize
1045            // nested obligations which produced by `TraitDef` candidate
1046            // (i.e. using bounds on assoc items as assumptions).
1047            // because we don't have enough information to
1048            // normalize these obligations before evaluating.
1049            // so we will try to normalize the obligation and evaluate again.
1050            // we will replace it with new solver in the future.
1051            if EvaluationResult::EvaluatedToErr == result
1052                && fresh_trait_pred.has_aliases()
1053                && fresh_trait_pred.is_global()
1054            {
1055                let mut nested_obligations = PredicateObligations::new();
1056                let predicate = normalize_with_depth_to(
1057                    this,
1058                    param_env,
1059                    obligation.cause.clone(),
1060                    obligation.recursion_depth + 1,
1061                    obligation.predicate,
1062                    &mut nested_obligations,
1063                );
1064                if predicate != obligation.predicate {
1065                    let mut nested_result = EvaluationResult::EvaluatedToOk;
1066                    for obligation in nested_obligations {
1067                        nested_result = cmp::max(
1068                            this.evaluate_predicate_recursively(previous_stack, obligation)?,
1069                            nested_result,
1070                        );
1071                    }
1072
1073                    if nested_result.must_apply_modulo_regions() {
1074                        let obligation = obligation.with(this.tcx(), predicate);
1075                        result = cmp::max(
1076                            nested_result,
1077                            this.evaluate_trait_predicate_recursively(previous_stack, obligation)?,
1078                        );
1079                    }
1080                }
1081            }
1082
1083            Ok::<_, OverflowError>(result)
1084        });
1085
1086        let result = result?;
1087
1088        if !result.must_apply_modulo_regions() {
1089            stack.cache().on_failure(stack.dfn);
1090        }
1091
1092        let reached_depth = stack.reached_depth.get();
1093        if reached_depth >= stack.depth {
1094            debug!("CACHE MISS");
1095            self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
1096            stack.cache().on_completion(stack.dfn);
1097        } else {
1098            debug!("PROVISIONAL");
1099            debug!(
1100                "caching provisionally because {:?} \
1101                 is a cycle participant (at depth {}, reached depth {})",
1102                fresh_trait_pred, stack.depth, reached_depth,
1103            );
1104
1105            stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_pred, result);
1106        }
1107
1108        Ok(result)
1109    }
1110
1111    /// If there is any previous entry on the stack that precisely
1112    /// matches this obligation, then we can assume that the
1113    /// obligation is satisfied for now (still all other conditions
1114    /// must be met of course). One obvious case this comes up is
1115    /// marker traits like `Send`. Think of a linked list:
1116    ///
1117    ///     struct List<T> { data: T, next: Option<Box<List<T>>> }
1118    ///
1119    /// `Box<List<T>>` will be `Send` if `T` is `Send` and
1120    /// `Option<Box<List<T>>>` is `Send`, and in turn
1121    /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
1122    /// `Send`.
1123    ///
1124    /// Note that we do this comparison using the `fresh_trait_ref`
1125    /// fields. Because these have all been freshened using
1126    /// `self.freshener`, we can be sure that (a) this will not
1127    /// affect the inferencer state and (b) that if we see two
1128    /// fresh regions with the same index, they refer to the same
1129    /// unbound type variable.
1130    fn check_evaluation_cycle(
1131        &mut self,
1132        stack: &TraitObligationStack<'_, 'tcx>,
1133    ) -> Option<EvaluationResult> {
1134        if let Some(cycle_depth) = stack
1135            .iter()
1136            .skip(1) // Skip top-most frame.
1137            .find(|prev| {
1138                stack.obligation.param_env == prev.obligation.param_env
1139                    && stack.fresh_trait_pred == prev.fresh_trait_pred
1140            })
1141            .map(|stack| stack.depth)
1142        {
1143            debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
1144
1145            // If we have a stack like `A B C D E A`, where the top of
1146            // the stack is the final `A`, then this will iterate over
1147            // `A, E, D, C, B` -- i.e., all the participants apart
1148            // from the cycle head. We mark them as participating in a
1149            // cycle. This suppresses caching for those nodes. See
1150            // `in_cycle` field for more details.
1151            stack.update_reached_depth(cycle_depth);
1152
1153            // Subtle: when checking for a coinductive cycle, we do
1154            // not compare using the "freshened trait refs" (which
1155            // have erased regions) but rather the fully explicit
1156            // trait refs. This is important because it's only a cycle
1157            // if the regions match exactly.
1158            let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
1159            let tcx = self.tcx();
1160            let cycle = cycle.map(|stack| stack.obligation.predicate.upcast(tcx));
1161            if self.coinductive_match(cycle) {
1162                debug!("evaluate_stack --> recursive, coinductive");
1163                Some(EvaluatedToOk)
1164            } else {
1165                debug!("evaluate_stack --> recursive, inductive");
1166                Some(EvaluatedToAmbigStackDependent)
1167            }
1168        } else {
1169            None
1170        }
1171    }
1172
1173    fn evaluate_stack<'o>(
1174        &mut self,
1175        stack: &TraitObligationStack<'o, 'tcx>,
1176    ) -> Result<EvaluationResult, OverflowError> {
1177        debug_assert!(!self.infcx.next_trait_solver());
1178        // In intercrate mode, whenever any of the generics are unbound,
1179        // there can always be an impl. Even if there are no impls in
1180        // this crate, perhaps the type would be unified with
1181        // something from another crate that does provide an impl.
1182        //
1183        // In intra mode, we must still be conservative. The reason is
1184        // that we want to avoid cycles. Imagine an impl like:
1185        //
1186        //     impl<T:Eq> Eq for Vec<T>
1187        //
1188        // and a trait reference like `$0 : Eq` where `$0` is an
1189        // unbound variable. When we evaluate this trait-reference, we
1190        // will unify `$0` with `Vec<$1>` (for some fresh variable
1191        // `$1`), on the condition that `$1 : Eq`. We will then wind
1192        // up with many candidates (since that are other `Eq` impls
1193        // that apply) and try to winnow things down. This results in
1194        // a recursive evaluation that `$1 : Eq` -- as you can
1195        // imagine, this is just where we started. To avoid that, we
1196        // check for unbound variables and return an ambiguous (hence possible)
1197        // match if we've seen this trait before.
1198        //
1199        // This suffices to allow chains like `FnMut` implemented in
1200        // terms of `Fn` etc, but we could probably make this more
1201        // precise still.
1202        let unbound_input_types =
1203            stack.fresh_trait_pred.skip_binder().trait_ref.args.types().any(|ty| ty.is_fresh());
1204
1205        if unbound_input_types
1206            && stack.iter().skip(1).any(|prev| {
1207                stack.obligation.param_env == prev.obligation.param_env
1208                    && self.match_fresh_trait_refs(stack.fresh_trait_pred, prev.fresh_trait_pred)
1209            })
1210        {
1211            debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
1212            return Ok(EvaluatedToAmbigStackDependent);
1213        }
1214
1215        match self.candidate_from_obligation(stack) {
1216            Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1217            Ok(None) => Ok(EvaluatedToAmbig),
1218            Err(Overflow(OverflowError::Canonical)) => Err(OverflowError::Canonical),
1219            Err(..) => Ok(EvaluatedToErr),
1220        }
1221    }
1222
1223    /// For defaulted traits, we use a co-inductive strategy to solve, so
1224    /// that recursion is ok. This routine returns `true` if the top of the
1225    /// stack (`cycle[0]`):
1226    ///
1227    /// - is a coinductive trait: an auto-trait or `Sized`,
1228    /// - it also appears in the backtrace at some position `X`,
1229    /// - all the predicates at positions `X..` between `X` and the top are
1230    ///   also coinductive traits.
1231    pub(crate) fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
1232    where
1233        I: Iterator<Item = ty::Predicate<'tcx>>,
1234    {
1235        cycle.all(|p| match p.kind().skip_binder() {
1236            ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => {
1237                self.infcx.tcx.trait_is_coinductive(data.def_id())
1238            }
1239            ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => true,
1240            _ => false,
1241        })
1242    }
1243
1244    /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
1245    /// obligations are met. Returns whether `candidate` remains viable after this further
1246    /// scrutiny.
1247    #[instrument(
1248        level = "debug",
1249        skip(self, stack),
1250        fields(depth = stack.obligation.recursion_depth),
1251        ret
1252    )]
1253    fn evaluate_candidate<'o>(
1254        &mut self,
1255        stack: &TraitObligationStack<'o, 'tcx>,
1256        candidate: &SelectionCandidate<'tcx>,
1257    ) -> Result<EvaluationResult, OverflowError> {
1258        let mut result = self.evaluation_probe(|this| {
1259            match this.confirm_candidate(stack.obligation, candidate.clone()) {
1260                Ok(selection) => {
1261                    debug!(?selection);
1262                    this.evaluate_predicates_recursively(
1263                        stack.list(),
1264                        selection.nested_obligations().into_iter(),
1265                    )
1266                }
1267                Err(..) => Ok(EvaluatedToErr),
1268            }
1269        })?;
1270
1271        // If we erased any lifetimes, then we want to use
1272        // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
1273        // as your final result. The result will be cached using
1274        // the freshened trait predicate as a key, so we need
1275        // our result to be correct by *any* choice of original lifetimes,
1276        // not just the lifetime choice for this particular (non-erased)
1277        // predicate.
1278        // See issue #80691
1279        if stack.fresh_trait_pred.has_erased_regions() {
1280            result = result.max(EvaluatedToOkModuloRegions);
1281        }
1282
1283        Ok(result)
1284    }
1285
1286    fn check_evaluation_cache(
1287        &self,
1288        param_env: ty::ParamEnv<'tcx>,
1289        trait_pred: ty::PolyTraitPredicate<'tcx>,
1290    ) -> Option<EvaluationResult> {
1291        let infcx = self.infcx;
1292        let tcx = infcx.tcx;
1293        if self.can_use_global_caches(param_env, trait_pred) {
1294            let key = (infcx.typing_env(param_env), trait_pred);
1295            if let Some(res) = tcx.evaluation_cache.get(&key, tcx) {
1296                Some(res)
1297            } else {
1298                debug_assert_eq!(infcx.evaluation_cache.get(&(param_env, trait_pred), tcx), None);
1299                None
1300            }
1301        } else {
1302            self.infcx.evaluation_cache.get(&(param_env, trait_pred), tcx)
1303        }
1304    }
1305
1306    fn insert_evaluation_cache(
1307        &mut self,
1308        param_env: ty::ParamEnv<'tcx>,
1309        trait_pred: ty::PolyTraitPredicate<'tcx>,
1310        dep_node: DepNodeIndex,
1311        result: EvaluationResult,
1312    ) {
1313        // Avoid caching results that depend on more than just the trait-ref
1314        // - the stack can create recursion.
1315        if result.is_stack_dependent() {
1316            return;
1317        }
1318
1319        let infcx = self.infcx;
1320        let tcx = infcx.tcx;
1321        if self.can_use_global_caches(param_env, trait_pred) {
1322            debug!(?trait_pred, ?result, "insert_evaluation_cache global");
1323            // This may overwrite the cache with the same value
1324            tcx.evaluation_cache.insert(
1325                (infcx.typing_env(param_env), trait_pred),
1326                dep_node,
1327                result,
1328            );
1329            return;
1330        } else {
1331            debug!(?trait_pred, ?result, "insert_evaluation_cache local");
1332            self.infcx.evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1333        }
1334    }
1335
1336    fn check_recursion_depth<T>(
1337        &self,
1338        depth: usize,
1339        error_obligation: &Obligation<'tcx, T>,
1340    ) -> Result<(), OverflowError>
1341    where
1342        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + Clone,
1343    {
1344        if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1345            match self.query_mode {
1346                TraitQueryMode::Standard => {
1347                    if let Some(e) = self.infcx.tainted_by_errors() {
1348                        return Err(OverflowError::Error(e));
1349                    }
1350                    self.infcx.err_ctxt().report_overflow_obligation(error_obligation, true);
1351                }
1352                TraitQueryMode::Canonical => {
1353                    return Err(OverflowError::Canonical);
1354                }
1355            }
1356        }
1357        Ok(())
1358    }
1359
1360    /// Checks that the recursion limit has not been exceeded.
1361    ///
1362    /// The weird return type of this function allows it to be used with the `try` (`?`)
1363    /// operator within certain functions.
1364    #[inline(always)]
1365    fn check_recursion_limit<T: Display + TypeFoldable<TyCtxt<'tcx>>, V>(
1366        &self,
1367        obligation: &Obligation<'tcx, T>,
1368        error_obligation: &Obligation<'tcx, V>,
1369    ) -> Result<(), OverflowError>
1370    where
1371        V: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + Clone,
1372    {
1373        self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1374    }
1375
1376    fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1377    where
1378        OP: FnOnce(&mut Self) -> R,
1379    {
1380        self.tcx().dep_graph.with_anon_task(self.tcx(), dep_kinds::TraitSelect, || op(self))
1381    }
1382
1383    /// filter_impls filters candidates that have a positive impl for a negative
1384    /// goal and a negative impl for a positive goal
1385    #[instrument(level = "debug", skip(self, candidates))]
1386    fn filter_impls(
1387        &mut self,
1388        candidates: Vec<SelectionCandidate<'tcx>>,
1389        obligation: &PolyTraitObligation<'tcx>,
1390    ) -> Vec<SelectionCandidate<'tcx>> {
1391        trace!("{candidates:#?}");
1392        let tcx = self.tcx();
1393        let mut result = Vec::with_capacity(candidates.len());
1394
1395        for candidate in candidates {
1396            if let ImplCandidate(def_id) = candidate {
1397                match (tcx.impl_polarity(def_id), obligation.polarity()) {
1398                    (ty::ImplPolarity::Reservation, _)
1399                    | (ty::ImplPolarity::Positive, ty::PredicatePolarity::Positive)
1400                    | (ty::ImplPolarity::Negative, ty::PredicatePolarity::Negative) => {
1401                        result.push(candidate);
1402                    }
1403                    _ => {}
1404                }
1405            } else {
1406                result.push(candidate);
1407            }
1408        }
1409
1410        trace!("{result:#?}");
1411        result
1412    }
1413
1414    /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1415    #[instrument(level = "debug", skip(self))]
1416    fn filter_reservation_impls(
1417        &mut self,
1418        candidate: SelectionCandidate<'tcx>,
1419    ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1420        let tcx = self.tcx();
1421        // Treat reservation impls as ambiguity.
1422        if let ImplCandidate(def_id) = candidate {
1423            if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
1424                if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1425                    let message = tcx
1426                        .get_attr(def_id, sym::rustc_reservation_impl)
1427                        .and_then(|a| a.value_str());
1428                    if let Some(message) = message {
1429                        debug!(
1430                            "filter_reservation_impls: \
1431                                 reservation impl ambiguity on {:?}",
1432                            def_id
1433                        );
1434                        intercrate_ambiguity_clauses
1435                            .insert(IntercrateAmbiguityCause::ReservationImpl { message });
1436                    }
1437                }
1438                return Ok(None);
1439            }
1440        }
1441        Ok(Some(candidate))
1442    }
1443
1444    fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Result<(), Conflict> {
1445        let obligation = &stack.obligation;
1446        match self.infcx.typing_mode() {
1447            TypingMode::Coherence => {}
1448            TypingMode::Analysis { .. }
1449            | TypingMode::PostBorrowckAnalysis { .. }
1450            | TypingMode::PostAnalysis => return Ok(()),
1451        }
1452
1453        debug!("is_knowable()");
1454
1455        let predicate = self.infcx.resolve_vars_if_possible(obligation.predicate);
1456
1457        // Okay to skip binder because of the nature of the
1458        // trait-ref-is-knowable check, which does not care about
1459        // bound regions.
1460        let trait_ref = predicate.skip_binder().trait_ref;
1461
1462        coherence::trait_ref_is_knowable(self.infcx, trait_ref, |ty| Ok::<_, !>(ty)).into_ok()
1463    }
1464
1465    /// Returns `true` if the global caches can be used.
1466    fn can_use_global_caches(
1467        &self,
1468        param_env: ty::ParamEnv<'tcx>,
1469        pred: ty::PolyTraitPredicate<'tcx>,
1470    ) -> bool {
1471        // If there are any inference variables in the `ParamEnv`, then we
1472        // always use a cache local to this particular scope. Otherwise, we
1473        // switch to a global cache.
1474        if param_env.has_infer() || pred.has_infer() {
1475            return false;
1476        }
1477
1478        match self.infcx.typing_mode() {
1479            // Avoid using the global cache during coherence and just rely
1480            // on the local cache. It is really just a simplification to
1481            // avoid us having to fear that coherence results "pollute"
1482            // the master cache. Since coherence executes pretty quickly,
1483            // it's not worth going to more trouble to increase the
1484            // hit-rate, I don't think.
1485            TypingMode::Coherence => false,
1486            // Avoid using the global cache when we're defining opaque types
1487            // as their hidden type may impact the result of candidate selection.
1488            //
1489            // HACK: This is still theoretically unsound. Goals can indirectly rely
1490            // on opaques in the defining scope, and it's easier to do so with TAIT.
1491            // However, if we disqualify *all* goals from being cached, perf suffers.
1492            // This is likely fixed by better caching in general in the new solver.
1493            // See: <https://github.com/rust-lang/rust/issues/132064>.
1494            TypingMode::Analysis { defining_opaque_types } => {
1495                defining_opaque_types.is_empty() || !pred.has_opaque_types()
1496            }
1497            // The hidden types of `defined_opaque_types` is not local to the current
1498            // inference context, so we can freely move this to the global cache.
1499            TypingMode::PostBorrowckAnalysis { .. } => true,
1500            // The global cache is only used if there are no opaque types in
1501            // the defining scope or we're outside of analysis.
1502            //
1503            // FIXME(#132279): This is still incorrect as we treat opaque types
1504            // and default associated items differently between these two modes.
1505            TypingMode::PostAnalysis => true,
1506        }
1507    }
1508
1509    fn check_candidate_cache(
1510        &mut self,
1511        param_env: ty::ParamEnv<'tcx>,
1512        cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1513    ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1514        let infcx = self.infcx;
1515        let tcx = infcx.tcx;
1516        let pred = cache_fresh_trait_pred.skip_binder();
1517
1518        if self.can_use_global_caches(param_env, cache_fresh_trait_pred) {
1519            if let Some(res) = tcx.selection_cache.get(&(infcx.typing_env(param_env), pred), tcx) {
1520                return Some(res);
1521            } else if cfg!(debug_assertions) {
1522                match infcx.selection_cache.get(&(param_env, pred), tcx) {
1523                    None | Some(Err(Overflow(OverflowError::Canonical))) => {}
1524                    res => bug!("unexpected local cache result: {res:?}"),
1525                }
1526            }
1527        }
1528
1529        // Subtle: we need to check the local cache even if we're able to use the
1530        // global cache as we don't cache overflow in the global cache but need to
1531        // cache it as otherwise rustdoc hangs when compiling diesel.
1532        infcx.selection_cache.get(&(param_env, pred), tcx)
1533    }
1534
1535    /// Determines whether can we safely cache the result
1536    /// of selecting an obligation. This is almost always `true`,
1537    /// except when dealing with certain `ParamCandidate`s.
1538    ///
1539    /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1540    /// since it was usually produced directly from a `DefId`. However,
1541    /// certain cases (currently only librustdoc's blanket impl finder),
1542    /// a `ParamEnv` may be explicitly constructed with inference types.
1543    /// When this is the case, we do *not* want to cache the resulting selection
1544    /// candidate. This is due to the fact that it might not always be possible
1545    /// to equate the obligation's trait ref and the candidate's trait ref,
1546    /// if more constraints end up getting added to an inference variable.
1547    ///
1548    /// Because of this, we always want to re-run the full selection
1549    /// process for our obligation the next time we see it, since
1550    /// we might end up picking a different `SelectionCandidate` (or none at all).
1551    fn can_cache_candidate(
1552        &self,
1553        result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1554    ) -> bool {
1555        match result {
1556            Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.has_infer(),
1557            _ => true,
1558        }
1559    }
1560
1561    #[instrument(skip(self, param_env, cache_fresh_trait_pred, dep_node), level = "debug")]
1562    fn insert_candidate_cache(
1563        &mut self,
1564        param_env: ty::ParamEnv<'tcx>,
1565        cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1566        dep_node: DepNodeIndex,
1567        candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1568    ) {
1569        let infcx = self.infcx;
1570        let tcx = infcx.tcx;
1571        let pred = cache_fresh_trait_pred.skip_binder();
1572
1573        if !self.can_cache_candidate(&candidate) {
1574            debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1575            return;
1576        }
1577
1578        if self.can_use_global_caches(param_env, cache_fresh_trait_pred) {
1579            if let Err(Overflow(OverflowError::Canonical)) = candidate {
1580                // Don't cache overflow globally; we only produce this in certain modes.
1581            } else {
1582                debug!(?pred, ?candidate, "insert_candidate_cache global");
1583                debug_assert!(!candidate.has_infer());
1584
1585                // This may overwrite the cache with the same value.
1586                tcx.selection_cache.insert(
1587                    (infcx.typing_env(param_env), pred),
1588                    dep_node,
1589                    candidate,
1590                );
1591                return;
1592            }
1593        }
1594
1595        debug!(?pred, ?candidate, "insert_candidate_cache local");
1596        self.infcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1597    }
1598
1599    /// Looks at the item bounds of the projection or opaque type.
1600    /// If this is a nested rigid projection, such as
1601    /// `<<T as Tr1>::Assoc as Tr2>::Assoc`, consider the item bounds
1602    /// on both `Tr1::Assoc` and `Tr2::Assoc`, since we may encounter
1603    /// relative bounds on both via the `associated_type_bounds` feature.
1604    pub(super) fn for_each_item_bound<T>(
1605        &mut self,
1606        mut self_ty: Ty<'tcx>,
1607        mut for_each: impl FnMut(&mut Self, ty::Clause<'tcx>, usize) -> ControlFlow<T, ()>,
1608        on_ambiguity: impl FnOnce(),
1609    ) -> ControlFlow<T, ()> {
1610        let mut idx = 0;
1611        let mut in_parent_alias_type = false;
1612
1613        loop {
1614            let (kind, alias_ty) = match *self_ty.kind() {
1615                ty::Alias(kind @ (ty::Projection | ty::Opaque), alias_ty) => (kind, alias_ty),
1616                ty::Infer(ty::TyVar(_)) => {
1617                    on_ambiguity();
1618                    return ControlFlow::Continue(());
1619                }
1620                _ => return ControlFlow::Continue(()),
1621            };
1622
1623            // HACK: On subsequent recursions, we only care about bounds that don't
1624            // share the same type as `self_ty`. This is because for truly rigid
1625            // projections, we will never be able to equate, e.g. `<T as Tr>::A`
1626            // with `<<T as Tr>::A as Tr>::A`.
1627            let relevant_bounds = if in_parent_alias_type {
1628                self.tcx().item_non_self_bounds(alias_ty.def_id)
1629            } else {
1630                self.tcx().item_self_bounds(alias_ty.def_id)
1631            };
1632
1633            for bound in relevant_bounds.instantiate(self.tcx(), alias_ty.args) {
1634                for_each(self, bound, idx)?;
1635                idx += 1;
1636            }
1637
1638            if kind == ty::Projection {
1639                self_ty = alias_ty.self_ty();
1640            } else {
1641                return ControlFlow::Continue(());
1642            }
1643
1644            in_parent_alias_type = true;
1645        }
1646    }
1647
1648    /// Equates the trait in `obligation` with trait bound. If the two traits
1649    /// can be equated and the normalized trait bound doesn't contain inference
1650    /// variables or placeholders, the normalized bound is returned.
1651    fn match_normalize_trait_ref(
1652        &mut self,
1653        obligation: &PolyTraitObligation<'tcx>,
1654        placeholder_trait_ref: ty::TraitRef<'tcx>,
1655        trait_bound: ty::PolyTraitRef<'tcx>,
1656    ) -> Result<Option<ty::TraitRef<'tcx>>, ()> {
1657        debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1658        if placeholder_trait_ref.def_id != trait_bound.def_id() {
1659            // Avoid unnecessary normalization
1660            return Err(());
1661        }
1662
1663        let trait_bound = self.infcx.instantiate_binder_with_fresh_vars(
1664            obligation.cause.span,
1665            HigherRankedType,
1666            trait_bound,
1667        );
1668        let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1669            normalize_with_depth(
1670                self,
1671                obligation.param_env,
1672                obligation.cause.clone(),
1673                obligation.recursion_depth + 1,
1674                trait_bound,
1675            )
1676        });
1677        self.infcx
1678            .at(&obligation.cause, obligation.param_env)
1679            .eq(DefineOpaqueTypes::No, placeholder_trait_ref, trait_bound)
1680            .map(|InferOk { obligations: _, value: () }| {
1681                // This method is called within a probe, so we can't have
1682                // inference variables and placeholders escape.
1683                if !trait_bound.has_infer() && !trait_bound.has_placeholders() {
1684                    Some(trait_bound)
1685                } else {
1686                    None
1687                }
1688            })
1689            .map_err(|_| ())
1690    }
1691
1692    fn where_clause_may_apply<'o>(
1693        &mut self,
1694        stack: &TraitObligationStack<'o, 'tcx>,
1695        where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1696    ) -> Result<EvaluationResult, OverflowError> {
1697        self.evaluation_probe(|this| {
1698            match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1699                Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1700                Err(()) => Ok(EvaluatedToErr),
1701            }
1702        })
1703    }
1704
1705    /// Return `Yes` if the obligation's predicate type applies to the env_predicate, and
1706    /// `No` if it does not. Return `Ambiguous` in the case that the projection type is a GAT,
1707    /// and applying this env_predicate constrains any of the obligation's GAT parameters.
1708    ///
1709    /// This behavior is a somewhat of a hack to prevent over-constraining inference variables
1710    /// in cases like #91762.
1711    pub(super) fn match_projection_projections(
1712        &mut self,
1713        obligation: &ProjectionTermObligation<'tcx>,
1714        env_predicate: PolyProjectionPredicate<'tcx>,
1715        potentially_unnormalized_candidates: bool,
1716    ) -> ProjectionMatchesProjection {
1717        debug_assert_eq!(obligation.predicate.def_id, env_predicate.item_def_id());
1718
1719        let mut nested_obligations = PredicateObligations::new();
1720        let infer_predicate = self.infcx.instantiate_binder_with_fresh_vars(
1721            obligation.cause.span,
1722            BoundRegionConversionTime::HigherRankedType,
1723            env_predicate,
1724        );
1725        let infer_projection = if potentially_unnormalized_candidates {
1726            ensure_sufficient_stack(|| {
1727                normalize_with_depth_to(
1728                    self,
1729                    obligation.param_env,
1730                    obligation.cause.clone(),
1731                    obligation.recursion_depth + 1,
1732                    infer_predicate.projection_term,
1733                    &mut nested_obligations,
1734                )
1735            })
1736        } else {
1737            infer_predicate.projection_term
1738        };
1739
1740        let is_match = self
1741            .infcx
1742            .at(&obligation.cause, obligation.param_env)
1743            .eq(DefineOpaqueTypes::No, obligation.predicate, infer_projection)
1744            .is_ok_and(|InferOk { obligations, value: () }| {
1745                self.evaluate_predicates_recursively(
1746                    TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1747                    nested_obligations.into_iter().chain(obligations),
1748                )
1749                .is_ok_and(|res| res.may_apply())
1750            });
1751
1752        if is_match {
1753            let generics = self.tcx().generics_of(obligation.predicate.def_id);
1754            // FIXME(generic-associated-types): Addresses aggressive inference in #92917.
1755            // If this type is a GAT, and of the GAT args resolve to something new,
1756            // that means that we must have newly inferred something about the GAT.
1757            // We should give up in that case.
1758            // FIXME(generic-associated-types): This only detects one layer of inference,
1759            // which is probably not what we actually want, but fixing it causes some ambiguity:
1760            // <https://github.com/rust-lang/rust/issues/125196>.
1761            if !generics.is_own_empty()
1762                && obligation.predicate.args[generics.parent_count..].iter().any(|&p| {
1763                    p.has_non_region_infer()
1764                        && match p.unpack() {
1765                            ty::GenericArgKind::Const(ct) => {
1766                                self.infcx.shallow_resolve_const(ct) != ct
1767                            }
1768                            ty::GenericArgKind::Type(ty) => self.infcx.shallow_resolve(ty) != ty,
1769                            ty::GenericArgKind::Lifetime(_) => false,
1770                        }
1771                })
1772            {
1773                ProjectionMatchesProjection::Ambiguous
1774            } else {
1775                ProjectionMatchesProjection::Yes
1776            }
1777        } else {
1778            ProjectionMatchesProjection::No
1779        }
1780    }
1781}
1782
1783/// ## Winnowing
1784///
1785/// Winnowing is the process of attempting to resolve ambiguity by
1786/// probing further. During the winnowing process, we unify all
1787/// type variables and then we also attempt to evaluate recursive
1788/// bounds to see if they are satisfied.
1789impl<'tcx> SelectionContext<'_, 'tcx> {
1790    /// If there are multiple ways to prove a trait goal, we make some
1791    /// *fairly arbitrary* choices about which candidate is actually used.
1792    ///
1793    /// For more details, look at the implementation of this method :)
1794    #[instrument(level = "debug", skip(self), ret)]
1795    fn winnow_candidates(
1796        &mut self,
1797        has_non_region_infer: bool,
1798        mut candidates: Vec<EvaluatedCandidate<'tcx>>,
1799    ) -> Option<SelectionCandidate<'tcx>> {
1800        if candidates.len() == 1 {
1801            return Some(candidates.pop().unwrap().candidate);
1802        }
1803
1804        // We prefer trivial builtin candidates, i.e. builtin impls without any nested
1805        // requirements, over all others. This is a fix for #53123 and prevents winnowing
1806        // from accidentally extending the lifetime of a variable.
1807        let mut trivial_builtin = candidates
1808            .iter()
1809            .filter(|c| matches!(c.candidate, BuiltinCandidate { has_nested: false }));
1810        if let Some(_trivial) = trivial_builtin.next() {
1811            // There should only ever be a single trivial builtin candidate
1812            // as they would otherwise overlap.
1813            debug_assert_eq!(trivial_builtin.next(), None);
1814            return Some(BuiltinCandidate { has_nested: false });
1815        }
1816
1817        // Before we consider where-bounds, we have to deduplicate them here and also
1818        // drop where-bounds in case the same where-bound exists without bound vars.
1819        // This is necessary as elaborating super-trait bounds may result in duplicates.
1820        'search_victim: loop {
1821            for (i, this) in candidates.iter().enumerate() {
1822                let ParamCandidate(this) = this.candidate else { continue };
1823                for (j, other) in candidates.iter().enumerate() {
1824                    if i == j {
1825                        continue;
1826                    }
1827
1828                    let ParamCandidate(other) = other.candidate else { continue };
1829                    if this == other {
1830                        candidates.remove(j);
1831                        continue 'search_victim;
1832                    }
1833
1834                    if this.skip_binder().trait_ref == other.skip_binder().trait_ref
1835                        && this.skip_binder().polarity == other.skip_binder().polarity
1836                        && !this.skip_binder().trait_ref.has_escaping_bound_vars()
1837                    {
1838                        candidates.remove(j);
1839                        continue 'search_victim;
1840                    }
1841                }
1842            }
1843
1844            break;
1845        }
1846
1847        // The next highest priority is for non-global where-bounds. However, while we don't
1848        // prefer global where-clauses here, we do bail with ambiguity when encountering both
1849        // a global and a non-global where-clause.
1850        //
1851        // Our handling of where-bounds is generally fairly messy but necessary for backwards
1852        // compatibility, see #50825 for why we need to handle global where-bounds like this.
1853        let is_global = |c: ty::PolyTraitPredicate<'tcx>| c.is_global() && !c.has_bound_vars();
1854        let param_candidates = candidates
1855            .iter()
1856            .filter_map(|c| if let ParamCandidate(p) = c.candidate { Some(p) } else { None });
1857        let mut has_global_bounds = false;
1858        let mut param_candidate = None;
1859        for c in param_candidates {
1860            if is_global(c) {
1861                has_global_bounds = true;
1862            } else if param_candidate.replace(c).is_some() {
1863                // Ambiguity, two potentially different where-clauses
1864                return None;
1865            }
1866        }
1867        if let Some(predicate) = param_candidate {
1868            // Ambiguity, a global and a non-global where-bound.
1869            if has_global_bounds {
1870                return None;
1871            } else {
1872                return Some(ParamCandidate(predicate));
1873            }
1874        }
1875
1876        // Prefer alias-bounds over blanket impls for rigid associated types. This is
1877        // fairly arbitrary but once again necessary for backwards compatibility.
1878        // If there are multiple applicable candidates which don't affect type inference,
1879        // choose the one with the lowest index.
1880        let alias_bound = candidates
1881            .iter()
1882            .filter_map(|c| if let ProjectionCandidate(i) = c.candidate { Some(i) } else { None })
1883            .try_reduce(|c1, c2| if has_non_region_infer { None } else { Some(c1.min(c2)) });
1884        match alias_bound {
1885            Some(Some(index)) => return Some(ProjectionCandidate(index)),
1886            Some(None) => {}
1887            None => return None,
1888        }
1889
1890        // Need to prioritize builtin trait object impls as `<dyn Any as Any>::type_id`
1891        // should use the vtable method and not the method provided by the user-defined
1892        // impl `impl<T: ?Sized> Any for T { .. }`. This really shouldn't exist but is
1893        // necessary due to #57893. We again arbitrarily prefer the applicable candidate
1894        // with the lowest index.
1895        let object_bound = candidates
1896            .iter()
1897            .filter_map(|c| if let ObjectCandidate(i) = c.candidate { Some(i) } else { None })
1898            .try_reduce(|c1, c2| if has_non_region_infer { None } else { Some(c1.min(c2)) });
1899        match object_bound {
1900            Some(Some(index)) => return Some(ObjectCandidate(index)),
1901            Some(None) => {}
1902            None => return None,
1903        }
1904        // Same for upcasting.
1905        let upcast_bound = candidates
1906            .iter()
1907            .filter_map(|c| {
1908                if let TraitUpcastingUnsizeCandidate(i) = c.candidate { Some(i) } else { None }
1909            })
1910            .try_reduce(|c1, c2| if has_non_region_infer { None } else { Some(c1.min(c2)) });
1911        match upcast_bound {
1912            Some(Some(index)) => return Some(TraitUpcastingUnsizeCandidate(index)),
1913            Some(None) => {}
1914            None => return None,
1915        }
1916
1917        // Finally, handle overlapping user-written impls.
1918        let impls = candidates.iter().filter_map(|c| {
1919            if let ImplCandidate(def_id) = c.candidate {
1920                Some((def_id, c.evaluation))
1921            } else {
1922                None
1923            }
1924        });
1925        let mut impl_candidate = None;
1926        for c in impls {
1927            if let Some(prev) = impl_candidate.replace(c) {
1928                if self.prefer_lhs_over_victim(has_non_region_infer, c, prev.0) {
1929                    // Ok, prefer `c` over the previous entry
1930                } else if self.prefer_lhs_over_victim(has_non_region_infer, prev, c.0) {
1931                    // Ok, keep `prev` instead of the new entry
1932                    impl_candidate = Some(prev);
1933                } else {
1934                    // Ambiguity, two potentially different where-clauses
1935                    return None;
1936                }
1937            }
1938        }
1939        if let Some((def_id, _evaluation)) = impl_candidate {
1940            // Don't use impl candidates which overlap with other candidates.
1941            // This should pretty much only ever happen with malformed impls.
1942            if candidates.iter().all(|c| match c.candidate {
1943                BuiltinCandidate { has_nested: _ }
1944                | TransmutabilityCandidate
1945                | AutoImplCandidate
1946                | ClosureCandidate { .. }
1947                | AsyncClosureCandidate
1948                | AsyncFnKindHelperCandidate
1949                | CoroutineCandidate
1950                | FutureCandidate
1951                | IteratorCandidate
1952                | AsyncIteratorCandidate
1953                | FnPointerCandidate
1954                | TraitAliasCandidate
1955                | TraitUpcastingUnsizeCandidate(_)
1956                | BuiltinObjectCandidate
1957                | BuiltinUnsizeCandidate
1958                | BikeshedGuaranteedNoDropCandidate => false,
1959                // Non-global param candidates have already been handled, global
1960                // where-bounds get ignored.
1961                ParamCandidate(_) | ImplCandidate(_) => true,
1962                ProjectionCandidate(_) | ObjectCandidate(_) => unreachable!(),
1963            }) {
1964                return Some(ImplCandidate(def_id));
1965            } else {
1966                return None;
1967            }
1968        }
1969
1970        if candidates.len() == 1 {
1971            Some(candidates.pop().unwrap().candidate)
1972        } else {
1973            // Also try ignoring all global where-bounds and check whether we end
1974            // with a unique candidate in this case.
1975            let mut not_a_global_where_bound = candidates
1976                .into_iter()
1977                .filter(|c| !matches!(c.candidate, ParamCandidate(p) if is_global(p)));
1978            not_a_global_where_bound
1979                .next()
1980                .map(|c| c.candidate)
1981                .filter(|_| not_a_global_where_bound.next().is_none())
1982        }
1983    }
1984
1985    fn prefer_lhs_over_victim(
1986        &self,
1987        has_non_region_infer: bool,
1988        (lhs, lhs_evaluation): (DefId, EvaluationResult),
1989        victim: DefId,
1990    ) -> bool {
1991        let tcx = self.tcx();
1992        // See if we can toss out `victim` based on specialization.
1993        //
1994        // While this requires us to know *for sure* that the `lhs` impl applies
1995        // we still use modulo regions here. This is fine as specialization currently
1996        // assumes that specializing impls have to be always applicable, meaning that
1997        // the only allowed region constraints may be constraints also present on the default impl.
1998        if lhs_evaluation.must_apply_modulo_regions() {
1999            if tcx.specializes((lhs, victim)) {
2000                return true;
2001            }
2002        }
2003
2004        match tcx.impls_are_allowed_to_overlap(lhs, victim) {
2005            // For candidates which already reference errors it doesn't really
2006            // matter what we do 🤷
2007            Some(ty::ImplOverlapKind::Permitted { marker: false }) => {
2008                lhs_evaluation.must_apply_considering_regions()
2009            }
2010            Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
2011                // Subtle: If the predicate we are evaluating has inference
2012                // variables, do *not* allow discarding candidates due to
2013                // marker trait impls.
2014                //
2015                // Without this restriction, we could end up accidentally
2016                // constraining inference variables based on an arbitrarily
2017                // chosen trait impl.
2018                //
2019                // Imagine we have the following code:
2020                //
2021                // ```rust
2022                // #[marker] trait MyTrait {}
2023                // impl MyTrait for u8 {}
2024                // impl MyTrait for bool {}
2025                // ```
2026                //
2027                // And we are evaluating the predicate `<_#0t as MyTrait>`.
2028                //
2029                // During selection, we will end up with one candidate for each
2030                // impl of `MyTrait`. If we were to discard one impl in favor
2031                // of the other, we would be left with one candidate, causing
2032                // us to "successfully" select the predicate, unifying
2033                // _#0t with (for example) `u8`.
2034                //
2035                // However, we have no reason to believe that this unification
2036                // is correct - we've essentially just picked an arbitrary
2037                // *possibility* for _#0t, and required that this be the *only*
2038                // possibility.
2039                //
2040                // Eventually, we will either:
2041                // 1) Unify all inference variables in the predicate through
2042                // some other means (e.g. type-checking of a function). We will
2043                // then be in a position to drop marker trait candidates
2044                // without constraining inference variables (since there are
2045                // none left to constrain)
2046                // 2) Be left with some unconstrained inference variables. We
2047                // will then correctly report an inference error, since the
2048                // existence of multiple marker trait impls tells us nothing
2049                // about which one should actually apply.
2050                !has_non_region_infer && lhs_evaluation.must_apply_considering_regions()
2051            }
2052            None => false,
2053        }
2054    }
2055}
2056
2057impl<'tcx> SelectionContext<'_, 'tcx> {
2058    fn sized_conditions(
2059        &mut self,
2060        obligation: &PolyTraitObligation<'tcx>,
2061    ) -> BuiltinImplConditions<'tcx> {
2062        use self::BuiltinImplConditions::{Ambiguous, None, Where};
2063
2064        // NOTE: binder moved to (*)
2065        let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2066
2067        match self_ty.kind() {
2068            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2069            | ty::Uint(_)
2070            | ty::Int(_)
2071            | ty::Bool
2072            | ty::Float(_)
2073            | ty::FnDef(..)
2074            | ty::FnPtr(..)
2075            | ty::RawPtr(..)
2076            | ty::Char
2077            | ty::Ref(..)
2078            | ty::Coroutine(..)
2079            | ty::CoroutineWitness(..)
2080            | ty::Array(..)
2081            | ty::Closure(..)
2082            | ty::CoroutineClosure(..)
2083            | ty::Never
2084            | ty::Dynamic(_, _, ty::DynStar)
2085            | ty::Error(_) => {
2086                // safe for everything
2087                Where(ty::Binder::dummy(Vec::new()))
2088            }
2089
2090            ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2091
2092            ty::Tuple(tys) => Where(
2093                obligation.predicate.rebind(tys.last().map_or_else(Vec::new, |&last| vec![last])),
2094            ),
2095
2096            ty::Pat(ty, _) => Where(obligation.predicate.rebind(vec![*ty])),
2097
2098            ty::Adt(def, args) => {
2099                if let Some(sized_crit) = def.sized_constraint(self.tcx()) {
2100                    // (*) binder moved here
2101                    Where(
2102                        obligation.predicate.rebind(vec![sized_crit.instantiate(self.tcx(), args)]),
2103                    )
2104                } else {
2105                    Where(ty::Binder::dummy(Vec::new()))
2106                }
2107            }
2108
2109            // FIXME(unsafe_binders): This binder needs to be squashed
2110            ty::UnsafeBinder(binder_ty) => Where(binder_ty.map_bound(|ty| vec![ty])),
2111
2112            ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) => None,
2113            ty::Infer(ty::TyVar(_)) => Ambiguous,
2114
2115            // We can make this an ICE if/once we actually instantiate the trait obligation eagerly.
2116            ty::Bound(..) => None,
2117
2118            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2119                bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2120            }
2121        }
2122    }
2123
2124    fn copy_clone_conditions(
2125        &mut self,
2126        obligation: &PolyTraitObligation<'tcx>,
2127    ) -> BuiltinImplConditions<'tcx> {
2128        // NOTE: binder moved to (*)
2129        let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2130
2131        use self::BuiltinImplConditions::{Ambiguous, None, Where};
2132
2133        match *self_ty.kind() {
2134            ty::FnDef(..) | ty::FnPtr(..) | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
2135
2136            ty::Uint(_)
2137            | ty::Int(_)
2138            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2139            | ty::Bool
2140            | ty::Float(_)
2141            | ty::Char
2142            | ty::RawPtr(..)
2143            | ty::Never
2144            | ty::Ref(_, _, hir::Mutability::Not)
2145            | ty::Array(..) => {
2146                // Implementations provided in libcore
2147                None
2148            }
2149
2150            // FIXME(unsafe_binder): Should we conditionally
2151            // (i.e. universally) implement copy/clone?
2152            ty::UnsafeBinder(_) => None,
2153
2154            ty::Dynamic(..)
2155            | ty::Str
2156            | ty::Slice(..)
2157            | ty::Foreign(..)
2158            | ty::Ref(_, _, hir::Mutability::Mut) => None,
2159
2160            ty::Tuple(tys) => {
2161                // (*) binder moved here
2162                Where(obligation.predicate.rebind(tys.iter().collect()))
2163            }
2164
2165            ty::Pat(ty, _) => {
2166                // (*) binder moved here
2167                Where(obligation.predicate.rebind(vec![ty]))
2168            }
2169
2170            ty::Coroutine(coroutine_def_id, args) => {
2171                match self.tcx().coroutine_movability(coroutine_def_id) {
2172                    hir::Movability::Static => None,
2173                    hir::Movability::Movable => {
2174                        if self.tcx().features().coroutine_clone() {
2175                            let resolved_upvars =
2176                                self.infcx.shallow_resolve(args.as_coroutine().tupled_upvars_ty());
2177                            let resolved_witness =
2178                                self.infcx.shallow_resolve(args.as_coroutine().witness());
2179                            if resolved_upvars.is_ty_var() || resolved_witness.is_ty_var() {
2180                                // Not yet resolved.
2181                                Ambiguous
2182                            } else {
2183                                let all = args
2184                                    .as_coroutine()
2185                                    .upvar_tys()
2186                                    .iter()
2187                                    .chain([args.as_coroutine().witness()])
2188                                    .collect::<Vec<_>>();
2189                                Where(obligation.predicate.rebind(all))
2190                            }
2191                        } else {
2192                            None
2193                        }
2194                    }
2195                }
2196            }
2197
2198            ty::CoroutineWitness(def_id, args) => {
2199                let hidden_types = rebind_coroutine_witness_types(
2200                    self.infcx.tcx,
2201                    def_id,
2202                    args,
2203                    obligation.predicate.bound_vars(),
2204                );
2205                Where(hidden_types)
2206            }
2207
2208            ty::Closure(_, args) => {
2209                // (*) binder moved here
2210                let ty = self.infcx.shallow_resolve(args.as_closure().tupled_upvars_ty());
2211                if let ty::Infer(ty::TyVar(_)) = ty.kind() {
2212                    // Not yet resolved.
2213                    Ambiguous
2214                } else {
2215                    Where(obligation.predicate.rebind(args.as_closure().upvar_tys().to_vec()))
2216                }
2217            }
2218
2219            ty::CoroutineClosure(_, args) => {
2220                // (*) binder moved here
2221                let ty = self.infcx.shallow_resolve(args.as_coroutine_closure().tupled_upvars_ty());
2222                if let ty::Infer(ty::TyVar(_)) = ty.kind() {
2223                    // Not yet resolved.
2224                    Ambiguous
2225                } else {
2226                    Where(
2227                        obligation
2228                            .predicate
2229                            .rebind(args.as_coroutine_closure().upvar_tys().to_vec()),
2230                    )
2231                }
2232            }
2233
2234            ty::Adt(..) | ty::Alias(..) | ty::Param(..) | ty::Placeholder(..) => {
2235                // Fallback to whatever user-defined impls exist in this case.
2236                None
2237            }
2238
2239            ty::Infer(ty::TyVar(_)) => {
2240                // Unbound type variable. Might or might not have
2241                // applicable impls and so forth, depending on what
2242                // those type variables wind up being bound to.
2243                Ambiguous
2244            }
2245
2246            // We can make this an ICE if/once we actually instantiate the trait obligation eagerly.
2247            ty::Bound(..) => None,
2248
2249            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2250                bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2251            }
2252        }
2253    }
2254
2255    fn fused_iterator_conditions(
2256        &mut self,
2257        obligation: &PolyTraitObligation<'tcx>,
2258    ) -> BuiltinImplConditions<'tcx> {
2259        let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2260        if let ty::Coroutine(did, ..) = *self_ty.kind()
2261            && self.tcx().coroutine_is_gen(did)
2262        {
2263            BuiltinImplConditions::Where(ty::Binder::dummy(Vec::new()))
2264        } else {
2265            BuiltinImplConditions::None
2266        }
2267    }
2268
2269    /// For default impls, we need to break apart a type into its
2270    /// "constituent types" -- meaning, the types that it contains.
2271    ///
2272    /// Here are some (simple) examples:
2273    ///
2274    /// ```ignore (illustrative)
2275    /// (i32, u32) -> [i32, u32]
2276    /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2277    /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2278    /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2279    /// ```
2280    #[instrument(level = "debug", skip(self), ret)]
2281    fn constituent_types_for_ty(
2282        &self,
2283        t: ty::Binder<'tcx, Ty<'tcx>>,
2284    ) -> Result<ty::Binder<'tcx, Vec<Ty<'tcx>>>, SelectionError<'tcx>> {
2285        Ok(match *t.skip_binder().kind() {
2286            ty::Uint(_)
2287            | ty::Int(_)
2288            | ty::Bool
2289            | ty::Float(_)
2290            | ty::FnDef(..)
2291            | ty::FnPtr(..)
2292            | ty::Error(_)
2293            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2294            | ty::Never
2295            | ty::Char => ty::Binder::dummy(Vec::new()),
2296
2297            // FIXME(unsafe_binders): Squash the double binder for now, I guess.
2298            ty::UnsafeBinder(_) => return Err(SelectionError::Unimplemented),
2299
2300            // Treat this like `struct str([u8]);`
2301            ty::Str => ty::Binder::dummy(vec![Ty::new_slice(self.tcx(), self.tcx().types.u8)]),
2302
2303            ty::Placeholder(..)
2304            | ty::Dynamic(..)
2305            | ty::Param(..)
2306            | ty::Foreign(..)
2307            | ty::Alias(ty::Projection | ty::Inherent | ty::Weak, ..)
2308            | ty::Bound(..)
2309            | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2310                bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2311            }
2312
2313            ty::RawPtr(element_ty, _) | ty::Ref(_, element_ty, _) => t.rebind(vec![element_ty]),
2314
2315            ty::Pat(ty, _) | ty::Array(ty, _) | ty::Slice(ty) => t.rebind(vec![ty]),
2316
2317            ty::Tuple(tys) => {
2318                // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2319                t.rebind(tys.iter().collect())
2320            }
2321
2322            ty::Closure(_, args) => {
2323                let ty = self.infcx.shallow_resolve(args.as_closure().tupled_upvars_ty());
2324                t.rebind(vec![ty])
2325            }
2326
2327            ty::CoroutineClosure(_, args) => {
2328                let ty = self.infcx.shallow_resolve(args.as_coroutine_closure().tupled_upvars_ty());
2329                t.rebind(vec![ty])
2330            }
2331
2332            ty::Coroutine(_, args) => {
2333                let ty = self.infcx.shallow_resolve(args.as_coroutine().tupled_upvars_ty());
2334                let witness = args.as_coroutine().witness();
2335                t.rebind([ty].into_iter().chain(iter::once(witness)).collect())
2336            }
2337
2338            ty::CoroutineWitness(def_id, args) => {
2339                rebind_coroutine_witness_types(self.infcx.tcx, def_id, args, t.bound_vars())
2340            }
2341
2342            // For `PhantomData<T>`, we pass `T`.
2343            ty::Adt(def, args) if def.is_phantom_data() => t.rebind(args.types().collect()),
2344
2345            ty::Adt(def, args) => {
2346                t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), args)).collect())
2347            }
2348
2349            ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
2350                if self.infcx.can_define_opaque_ty(def_id) {
2351                    unreachable!()
2352                } else {
2353                    // We can resolve the `impl Trait` to its concrete type,
2354                    // which enforces a DAG between the functions requiring
2355                    // the auto trait bounds in question.
2356                    match self.tcx().type_of_opaque(def_id) {
2357                        Ok(ty) => t.rebind(vec![ty.instantiate(self.tcx(), args)]),
2358                        Err(_) => {
2359                            return Err(SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id));
2360                        }
2361                    }
2362                }
2363            }
2364        })
2365    }
2366
2367    fn collect_predicates_for_types(
2368        &mut self,
2369        param_env: ty::ParamEnv<'tcx>,
2370        cause: ObligationCause<'tcx>,
2371        recursion_depth: usize,
2372        trait_def_id: DefId,
2373        types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
2374    ) -> PredicateObligations<'tcx> {
2375        // Because the types were potentially derived from
2376        // higher-ranked obligations they may reference late-bound
2377        // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2378        // yield a type like `for<'a> &'a i32`. In general, we
2379        // maintain the invariant that we never manipulate bound
2380        // regions, so we have to process these bound regions somehow.
2381        //
2382        // The strategy is to:
2383        //
2384        // 1. Instantiate those regions to placeholder regions (e.g.,
2385        //    `for<'a> &'a i32` becomes `&0 i32`.
2386        // 2. Produce something like `&'0 i32 : Copy`
2387        // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2388
2389        types
2390            .as_ref()
2391            .skip_binder() // binder moved -\
2392            .iter()
2393            .flat_map(|ty| {
2394                let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(*ty); // <----/
2395
2396                let placeholder_ty = self.infcx.enter_forall_and_leak_universe(ty);
2397                let Normalized { value: normalized_ty, mut obligations } =
2398                    ensure_sufficient_stack(|| {
2399                        normalize_with_depth(
2400                            self,
2401                            param_env,
2402                            cause.clone(),
2403                            recursion_depth,
2404                            placeholder_ty,
2405                        )
2406                    });
2407
2408                let tcx = self.tcx();
2409                let trait_ref = if tcx.generics_of(trait_def_id).own_params.len() == 1 {
2410                    ty::TraitRef::new(tcx, trait_def_id, [normalized_ty])
2411                } else {
2412                    // If this is an ill-formed auto/built-in trait, then synthesize
2413                    // new error args for the missing generics.
2414                    let err_args = ty::GenericArgs::extend_with_error(
2415                        tcx,
2416                        trait_def_id,
2417                        &[normalized_ty.into()],
2418                    );
2419                    ty::TraitRef::new_from_args(tcx, trait_def_id, err_args)
2420                };
2421
2422                let obligation = Obligation::new(self.tcx(), cause.clone(), param_env, trait_ref);
2423                obligations.push(obligation);
2424                obligations
2425            })
2426            .collect()
2427    }
2428
2429    ///////////////////////////////////////////////////////////////////////////
2430    // Matching
2431    //
2432    // Matching is a common path used for both evaluation and
2433    // confirmation. It basically unifies types that appear in impls
2434    // and traits. This does affect the surrounding environment;
2435    // therefore, when used during evaluation, match routines must be
2436    // run inside of a `probe()` so that their side-effects are
2437    // contained.
2438
2439    fn rematch_impl(
2440        &mut self,
2441        impl_def_id: DefId,
2442        obligation: &PolyTraitObligation<'tcx>,
2443    ) -> Normalized<'tcx, GenericArgsRef<'tcx>> {
2444        let impl_trait_header = self.tcx().impl_trait_header(impl_def_id).unwrap();
2445        match self.match_impl(impl_def_id, impl_trait_header, obligation) {
2446            Ok(args) => args,
2447            Err(()) => {
2448                let predicate = self.infcx.resolve_vars_if_possible(obligation.predicate);
2449                bug!("impl {impl_def_id:?} was matchable against {predicate:?} but now is not")
2450            }
2451        }
2452    }
2453
2454    #[instrument(level = "debug", skip(self), ret)]
2455    fn match_impl(
2456        &mut self,
2457        impl_def_id: DefId,
2458        impl_trait_header: ty::ImplTraitHeader<'tcx>,
2459        obligation: &PolyTraitObligation<'tcx>,
2460    ) -> Result<Normalized<'tcx, GenericArgsRef<'tcx>>, ()> {
2461        let placeholder_obligation =
2462            self.infcx.enter_forall_and_leak_universe(obligation.predicate);
2463        let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2464
2465        let impl_args = self.infcx.fresh_args_for_item(obligation.cause.span, impl_def_id);
2466
2467        let trait_ref = impl_trait_header.trait_ref.instantiate(self.tcx(), impl_args);
2468        debug!(?impl_trait_header);
2469
2470        let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2471            ensure_sufficient_stack(|| {
2472                normalize_with_depth(
2473                    self,
2474                    obligation.param_env,
2475                    obligation.cause.clone(),
2476                    obligation.recursion_depth + 1,
2477                    trait_ref,
2478                )
2479            });
2480
2481        debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2482
2483        let cause = ObligationCause::new(
2484            obligation.cause.span,
2485            obligation.cause.body_id,
2486            ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2487        );
2488
2489        let InferOk { obligations, .. } = self
2490            .infcx
2491            .at(&cause, obligation.param_env)
2492            .eq(DefineOpaqueTypes::No, placeholder_obligation_trait_ref, impl_trait_ref)
2493            .map_err(|e| {
2494                debug!("match_impl: failed eq_trait_refs due to `{}`", e.to_string(self.tcx()))
2495            })?;
2496        nested_obligations.extend(obligations);
2497
2498        if impl_trait_header.polarity == ty::ImplPolarity::Reservation
2499            && !matches!(self.infcx.typing_mode(), TypingMode::Coherence)
2500        {
2501            debug!("reservation impls only apply in intercrate mode");
2502            return Err(());
2503        }
2504
2505        Ok(Normalized { value: impl_args, obligations: nested_obligations })
2506    }
2507
2508    fn match_upcast_principal(
2509        &mut self,
2510        obligation: &PolyTraitObligation<'tcx>,
2511        unnormalized_upcast_principal: ty::PolyTraitRef<'tcx>,
2512        a_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2513        b_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2514        a_region: ty::Region<'tcx>,
2515        b_region: ty::Region<'tcx>,
2516    ) -> SelectionResult<'tcx, PredicateObligations<'tcx>> {
2517        let tcx = self.tcx();
2518        let mut nested = PredicateObligations::new();
2519
2520        // We may upcast to auto traits that are either explicitly listed in
2521        // the object type's bounds, or implied by the principal trait ref's
2522        // supertraits.
2523        let a_auto_traits: FxIndexSet<DefId> = a_data
2524            .auto_traits()
2525            .chain(a_data.principal_def_id().into_iter().flat_map(|principal_def_id| {
2526                elaborate::supertrait_def_ids(tcx, principal_def_id)
2527                    .filter(|def_id| tcx.trait_is_auto(*def_id))
2528            }))
2529            .collect();
2530
2531        let upcast_principal = normalize_with_depth_to(
2532            self,
2533            obligation.param_env,
2534            obligation.cause.clone(),
2535            obligation.recursion_depth + 1,
2536            unnormalized_upcast_principal,
2537            &mut nested,
2538        );
2539
2540        for bound in b_data {
2541            match bound.skip_binder() {
2542                // Check that a_ty's supertrait (upcast_principal) is compatible
2543                // with the target (b_ty).
2544                ty::ExistentialPredicate::Trait(target_principal) => {
2545                    let hr_source_principal = upcast_principal.map_bound(|trait_ref| {
2546                        ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
2547                    });
2548                    let hr_target_principal = bound.rebind(target_principal);
2549
2550                    nested.extend(
2551                        self.infcx
2552                            .enter_forall(hr_target_principal, |target_principal| {
2553                                let source_principal =
2554                                    self.infcx.instantiate_binder_with_fresh_vars(
2555                                        obligation.cause.span,
2556                                        HigherRankedType,
2557                                        hr_source_principal,
2558                                    );
2559                                self.infcx.at(&obligation.cause, obligation.param_env).eq_trace(
2560                                    DefineOpaqueTypes::Yes,
2561                                    ToTrace::to_trace(
2562                                        &obligation.cause,
2563                                        hr_target_principal,
2564                                        hr_source_principal,
2565                                    ),
2566                                    target_principal,
2567                                    source_principal,
2568                                )
2569                            })
2570                            .map_err(|_| SelectionError::Unimplemented)?
2571                            .into_obligations(),
2572                    );
2573                }
2574                // Check that b_ty's projection is satisfied by exactly one of
2575                // a_ty's projections. First, we look through the list to see if
2576                // any match. If not, error. Then, if *more* than one matches, we
2577                // return ambiguity. Otherwise, if exactly one matches, equate
2578                // it with b_ty's projection.
2579                ty::ExistentialPredicate::Projection(target_projection) => {
2580                    let hr_target_projection = bound.rebind(target_projection);
2581
2582                    let mut matching_projections =
2583                        a_data.projection_bounds().filter(|&hr_source_projection| {
2584                            // Eager normalization means that we can just use can_eq
2585                            // here instead of equating and processing obligations.
2586                            hr_source_projection.item_def_id() == hr_target_projection.item_def_id()
2587                                && self.infcx.probe(|_| {
2588                                    self.infcx
2589                                        .enter_forall(hr_target_projection, |target_projection| {
2590                                            let source_projection =
2591                                                self.infcx.instantiate_binder_with_fresh_vars(
2592                                                    obligation.cause.span,
2593                                                    HigherRankedType,
2594                                                    hr_source_projection,
2595                                                );
2596                                            self.infcx
2597                                                .at(&obligation.cause, obligation.param_env)
2598                                                .eq_trace(
2599                                                    DefineOpaqueTypes::Yes,
2600                                                    ToTrace::to_trace(
2601                                                        &obligation.cause,
2602                                                        hr_target_projection,
2603                                                        hr_source_projection,
2604                                                    ),
2605                                                    target_projection,
2606                                                    source_projection,
2607                                                )
2608                                        })
2609                                        .is_ok()
2610                                })
2611                        });
2612
2613                    let Some(hr_source_projection) = matching_projections.next() else {
2614                        return Err(SelectionError::Unimplemented);
2615                    };
2616                    if matching_projections.next().is_some() {
2617                        return Ok(None);
2618                    }
2619                    nested.extend(
2620                        self.infcx
2621                            .enter_forall(hr_target_projection, |target_projection| {
2622                                let source_projection =
2623                                    self.infcx.instantiate_binder_with_fresh_vars(
2624                                        obligation.cause.span,
2625                                        HigherRankedType,
2626                                        hr_source_projection,
2627                                    );
2628                                self.infcx.at(&obligation.cause, obligation.param_env).eq_trace(
2629                                    DefineOpaqueTypes::Yes,
2630                                    ToTrace::to_trace(
2631                                        &obligation.cause,
2632                                        hr_target_projection,
2633                                        hr_source_projection,
2634                                    ),
2635                                    target_projection,
2636                                    source_projection,
2637                                )
2638                            })
2639                            .map_err(|_| SelectionError::Unimplemented)?
2640                            .into_obligations(),
2641                    );
2642                }
2643                // Check that b_ty's auto traits are present in a_ty's bounds.
2644                ty::ExistentialPredicate::AutoTrait(def_id) => {
2645                    if !a_auto_traits.contains(&def_id) {
2646                        return Err(SelectionError::Unimplemented);
2647                    }
2648                }
2649            }
2650        }
2651
2652        nested.push(Obligation::with_depth(
2653            tcx,
2654            obligation.cause.clone(),
2655            obligation.recursion_depth + 1,
2656            obligation.param_env,
2657            ty::Binder::dummy(ty::OutlivesPredicate(a_region, b_region)),
2658        ));
2659
2660        Ok(Some(nested))
2661    }
2662
2663    /// Normalize `where_clause_trait_ref` and try to match it against
2664    /// `obligation`. If successful, return any predicates that
2665    /// result from the normalization.
2666    fn match_where_clause_trait_ref(
2667        &mut self,
2668        obligation: &PolyTraitObligation<'tcx>,
2669        where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2670    ) -> Result<PredicateObligations<'tcx>, ()> {
2671        self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2672    }
2673
2674    /// Returns `Ok` if `poly_trait_ref` being true implies that the
2675    /// obligation is satisfied.
2676    #[instrument(skip(self), level = "debug")]
2677    fn match_poly_trait_ref(
2678        &mut self,
2679        obligation: &PolyTraitObligation<'tcx>,
2680        poly_trait_ref: ty::PolyTraitRef<'tcx>,
2681    ) -> Result<PredicateObligations<'tcx>, ()> {
2682        let predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
2683        let trait_ref = self.infcx.instantiate_binder_with_fresh_vars(
2684            obligation.cause.span,
2685            HigherRankedType,
2686            poly_trait_ref,
2687        );
2688        self.infcx
2689            .at(&obligation.cause, obligation.param_env)
2690            .eq(DefineOpaqueTypes::No, predicate.trait_ref, trait_ref)
2691            .map(|InferOk { obligations, .. }| obligations)
2692            .map_err(|_| ())
2693    }
2694
2695    ///////////////////////////////////////////////////////////////////////////
2696    // Miscellany
2697
2698    fn match_fresh_trait_refs(
2699        &self,
2700        previous: ty::PolyTraitPredicate<'tcx>,
2701        current: ty::PolyTraitPredicate<'tcx>,
2702    ) -> bool {
2703        let mut matcher = _match::MatchAgainstFreshVars::new(self.tcx());
2704        matcher.relate(previous, current).is_ok()
2705    }
2706
2707    fn push_stack<'o>(
2708        &mut self,
2709        previous_stack: TraitObligationStackList<'o, 'tcx>,
2710        obligation: &'o PolyTraitObligation<'tcx>,
2711    ) -> TraitObligationStack<'o, 'tcx> {
2712        let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
2713
2714        let dfn = previous_stack.cache.next_dfn();
2715        let depth = previous_stack.depth() + 1;
2716        TraitObligationStack {
2717            obligation,
2718            fresh_trait_pred,
2719            reached_depth: Cell::new(depth),
2720            previous: previous_stack,
2721            dfn,
2722            depth,
2723        }
2724    }
2725
2726    #[instrument(skip(self), level = "debug")]
2727    fn closure_trait_ref_unnormalized(
2728        &mut self,
2729        self_ty: Ty<'tcx>,
2730        fn_trait_def_id: DefId,
2731    ) -> ty::PolyTraitRef<'tcx> {
2732        let ty::Closure(_, args) = *self_ty.kind() else {
2733            bug!("expected closure, found {self_ty}");
2734        };
2735        let closure_sig = args.as_closure().sig();
2736
2737        closure_trait_ref_and_return_type(
2738            self.tcx(),
2739            fn_trait_def_id,
2740            self_ty,
2741            closure_sig,
2742            util::TupleArgumentsFlag::No,
2743        )
2744        .map_bound(|(trait_ref, _)| trait_ref)
2745    }
2746
2747    /// Returns the obligations that are implied by instantiating an
2748    /// impl or trait. The obligations are instantiated and fully
2749    /// normalized. This is used when confirming an impl or default
2750    /// impl.
2751    #[instrument(level = "debug", skip(self, cause, param_env))]
2752    fn impl_or_trait_obligations(
2753        &mut self,
2754        cause: &ObligationCause<'tcx>,
2755        recursion_depth: usize,
2756        param_env: ty::ParamEnv<'tcx>,
2757        def_id: DefId,              // of impl or trait
2758        args: GenericArgsRef<'tcx>, // for impl or trait
2759        parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2760    ) -> PredicateObligations<'tcx> {
2761        let tcx = self.tcx();
2762
2763        // To allow for one-pass evaluation of the nested obligation,
2764        // each predicate must be preceded by the obligations required
2765        // to normalize it.
2766        // for example, if we have:
2767        //    impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2768        // the impl will have the following predicates:
2769        //    <V as Iterator>::Item = U,
2770        //    U: Iterator, U: Sized,
2771        //    V: Iterator, V: Sized,
2772        //    <U as Iterator>::Item: Copy
2773        // When we instantiate, say, `V => IntoIter<u32>, U => $0`, the last
2774        // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2775        // `$1: Copy`, so we must ensure the obligations are emitted in
2776        // that order.
2777        let predicates = tcx.predicates_of(def_id);
2778        assert_eq!(predicates.parent, None);
2779        let predicates = predicates.instantiate_own(tcx, args);
2780        let mut obligations = PredicateObligations::with_capacity(predicates.len());
2781        for (index, (predicate, span)) in predicates.into_iter().enumerate() {
2782            let cause = if tcx.is_lang_item(parent_trait_pred.def_id(), LangItem::CoerceUnsized) {
2783                cause.clone()
2784            } else {
2785                cause.clone().derived_cause(parent_trait_pred, |derived| {
2786                    ObligationCauseCode::ImplDerived(Box::new(ImplDerivedCause {
2787                        derived,
2788                        impl_or_alias_def_id: def_id,
2789                        impl_def_predicate_index: Some(index),
2790                        span,
2791                    }))
2792                })
2793            };
2794            let clause = normalize_with_depth_to(
2795                self,
2796                param_env,
2797                cause.clone(),
2798                recursion_depth,
2799                predicate,
2800                &mut obligations,
2801            );
2802            obligations.push(Obligation {
2803                cause,
2804                recursion_depth,
2805                param_env,
2806                predicate: clause.as_predicate(),
2807            });
2808        }
2809
2810        // Register any outlives obligations from the trait here, cc #124336.
2811        if matches!(tcx.def_kind(def_id), DefKind::Impl { of_trait: true }) {
2812            for clause in tcx.impl_super_outlives(def_id).iter_instantiated(tcx, args) {
2813                let clause = normalize_with_depth_to(
2814                    self,
2815                    param_env,
2816                    cause.clone(),
2817                    recursion_depth,
2818                    clause,
2819                    &mut obligations,
2820                );
2821                obligations.push(Obligation {
2822                    cause: cause.clone(),
2823                    recursion_depth,
2824                    param_env,
2825                    predicate: clause.as_predicate(),
2826                });
2827            }
2828        }
2829
2830        obligations
2831    }
2832}
2833
2834fn rebind_coroutine_witness_types<'tcx>(
2835    tcx: TyCtxt<'tcx>,
2836    def_id: DefId,
2837    args: ty::GenericArgsRef<'tcx>,
2838    bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
2839) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
2840    let bound_coroutine_types = tcx.coroutine_hidden_types(def_id).skip_binder();
2841    let shifted_coroutine_types =
2842        tcx.shift_bound_var_indices(bound_vars.len(), bound_coroutine_types.skip_binder());
2843    ty::Binder::bind_with_vars(
2844        ty::EarlyBinder::bind(shifted_coroutine_types.to_vec()).instantiate(tcx, args),
2845        tcx.mk_bound_variable_kinds_from_iter(
2846            bound_vars.iter().chain(bound_coroutine_types.bound_vars()),
2847        ),
2848    )
2849}
2850
2851impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2852    fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2853        TraitObligationStackList::with(self)
2854    }
2855
2856    fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2857        self.previous.cache
2858    }
2859
2860    fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2861        self.list()
2862    }
2863
2864    /// Indicates that attempting to evaluate this stack entry
2865    /// required accessing something from the stack at depth `reached_depth`.
2866    fn update_reached_depth(&self, reached_depth: usize) {
2867        assert!(
2868            self.depth >= reached_depth,
2869            "invoked `update_reached_depth` with something under this stack: \
2870             self.depth={} reached_depth={}",
2871            self.depth,
2872            reached_depth,
2873        );
2874        debug!(reached_depth, "update_reached_depth");
2875        let mut p = self;
2876        while reached_depth < p.depth {
2877            debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
2878            p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2879            p = p.previous.head.unwrap();
2880        }
2881    }
2882}
2883
2884/// The "provisional evaluation cache" is used to store intermediate cache results
2885/// when solving auto traits. Auto traits are unusual in that they can support
2886/// cycles. So, for example, a "proof tree" like this would be ok:
2887///
2888/// - `Foo<T>: Send` :-
2889///   - `Bar<T>: Send` :-
2890///     - `Foo<T>: Send` -- cycle, but ok
2891///   - `Baz<T>: Send`
2892///
2893/// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2894/// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2895/// For non-auto traits, this cycle would be an error, but for auto traits (because
2896/// they are coinductive) it is considered ok.
2897///
2898/// However, there is a complication: at the point where we have
2899/// "proven" `Bar<T>: Send`, we have in fact only proven it
2900/// *provisionally*. In particular, we proved that `Bar<T>: Send`
2901/// *under the assumption* that `Foo<T>: Send`. But what if we later
2902/// find out this assumption is wrong?  Specifically, we could
2903/// encounter some kind of error proving `Baz<T>: Send`. In that case,
2904/// `Bar<T>: Send` didn't turn out to be true.
2905///
2906/// In Issue #60010, we found a bug in rustc where it would cache
2907/// these intermediate results. This was fixed in #60444 by disabling
2908/// *all* caching for things involved in a cycle -- in our example,
2909/// that would mean we don't cache that `Bar<T>: Send`. But this led
2910/// to large slowdowns.
2911///
2912/// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2913/// first requires proving `Bar<T>: Send` (which is true:
2914///
2915/// - `Foo<T>: Send` :-
2916///   - `Bar<T>: Send` :-
2917///     - `Foo<T>: Send` -- cycle, but ok
2918///   - `Baz<T>: Send`
2919///     - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2920///     - `*const T: Send` -- but what if we later encounter an error?
2921///
2922/// The *provisional evaluation cache* resolves this issue. It stores
2923/// cache results that we've proven but which were involved in a cycle
2924/// in some way. We track the minimal stack depth (i.e., the
2925/// farthest from the top of the stack) that we are dependent on.
2926/// The idea is that the cache results within are all valid -- so long as
2927/// none of the nodes in between the current node and the node at that minimum
2928/// depth result in an error (in which case the cached results are just thrown away).
2929///
2930/// During evaluation, we consult this provisional cache and rely on
2931/// it. Accessing a cached value is considered equivalent to accessing
2932/// a result at `reached_depth`, so it marks the *current* solution as
2933/// provisional as well. If an error is encountered, we toss out any
2934/// provisional results added from the subtree that encountered the
2935/// error. When we pop the node at `reached_depth` from the stack, we
2936/// can commit all the things that remain in the provisional cache.
2937struct ProvisionalEvaluationCache<'tcx> {
2938    /// next "depth first number" to issue -- just a counter
2939    dfn: Cell<usize>,
2940
2941    /// Map from cache key to the provisionally evaluated thing.
2942    /// The cache entries contain the result but also the DFN in which they
2943    /// were added. The DFN is used to clear out values on failure.
2944    ///
2945    /// Imagine we have a stack like:
2946    ///
2947    /// - `A B C` and we add a cache for the result of C (DFN 2)
2948    /// - Then we have a stack `A B D` where `D` has DFN 3
2949    /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2950    /// - `E` generates various cache entries which have cyclic dependencies on `B`
2951    ///   - `A B D E F` and so forth
2952    ///   - the DFN of `F` for example would be 5
2953    /// - then we determine that `E` is in error -- we will then clear
2954    ///   all cache values whose DFN is >= 4 -- in this case, that
2955    ///   means the cached value for `F`.
2956    map: RefCell<FxIndexMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
2957
2958    /// The stack of args that we assume to be true because a `WF(arg)` predicate
2959    /// is on the stack above (and because of wellformedness is coinductive).
2960    /// In an "ideal" world, this would share a stack with trait predicates in
2961    /// `TraitObligationStack`. However, trait predicates are *much* hotter than
2962    /// `WellFormed` predicates, and it's very likely that the additional matches
2963    /// will have a perf effect. The value here is the well-formed `GenericArg`
2964    /// and the depth of the trait predicate *above* that well-formed predicate.
2965    wf_args: RefCell<Vec<(ty::GenericArg<'tcx>, usize)>>,
2966}
2967
2968/// A cache value for the provisional cache: contains the depth-first
2969/// number (DFN) and result.
2970#[derive(Copy, Clone, Debug)]
2971struct ProvisionalEvaluation {
2972    from_dfn: usize,
2973    reached_depth: usize,
2974    result: EvaluationResult,
2975}
2976
2977impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2978    fn default() -> Self {
2979        Self { dfn: Cell::new(0), map: Default::default(), wf_args: Default::default() }
2980    }
2981}
2982
2983impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2984    /// Get the next DFN in sequence (basically a counter).
2985    fn next_dfn(&self) -> usize {
2986        let result = self.dfn.get();
2987        self.dfn.set(result + 1);
2988        result
2989    }
2990
2991    /// Check the provisional cache for any result for
2992    /// `fresh_trait_ref`. If there is a hit, then you must consider
2993    /// it an access to the stack slots at depth
2994    /// `reached_depth` (from the returned value).
2995    fn get_provisional(
2996        &self,
2997        fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2998    ) -> Option<ProvisionalEvaluation> {
2999        debug!(
3000            ?fresh_trait_pred,
3001            "get_provisional = {:#?}",
3002            self.map.borrow().get(&fresh_trait_pred),
3003        );
3004        Some(*self.map.borrow().get(&fresh_trait_pred)?)
3005    }
3006
3007    /// Insert a provisional result into the cache. The result came
3008    /// from the node with the given DFN. It accessed a minimum depth
3009    /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
3010    /// and resulted in `result`.
3011    fn insert_provisional(
3012        &self,
3013        from_dfn: usize,
3014        reached_depth: usize,
3015        fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
3016        result: EvaluationResult,
3017    ) {
3018        debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
3019
3020        let mut map = self.map.borrow_mut();
3021
3022        // Subtle: when we complete working on the DFN `from_dfn`, anything
3023        // that remains in the provisional cache must be dependent on some older
3024        // stack entry than `from_dfn`. We have to update their depth with our transitive
3025        // depth in that case or else it would be referring to some popped note.
3026        //
3027        // Example:
3028        // A (reached depth 0)
3029        //   ...
3030        //      B // depth 1 -- reached depth = 0
3031        //          C // depth 2 -- reached depth = 1 (should be 0)
3032        //              B
3033        //          A // depth 0
3034        //   D (reached depth 1)
3035        //      C (cache -- reached depth = 2)
3036        for (_k, v) in &mut *map {
3037            if v.from_dfn >= from_dfn {
3038                v.reached_depth = reached_depth.min(v.reached_depth);
3039            }
3040        }
3041
3042        map.insert(fresh_trait_pred, ProvisionalEvaluation { from_dfn, reached_depth, result });
3043    }
3044
3045    /// Invoked when the node with dfn `dfn` does not get a successful
3046    /// result. This will clear out any provisional cache entries
3047    /// that were added since `dfn` was created. This is because the
3048    /// provisional entries are things which must assume that the
3049    /// things on the stack at the time of their creation succeeded --
3050    /// since the failing node is presently at the top of the stack,
3051    /// these provisional entries must either depend on it or some
3052    /// ancestor of it.
3053    fn on_failure(&self, dfn: usize) {
3054        debug!(?dfn, "on_failure");
3055        self.map.borrow_mut().retain(|key, eval| {
3056            if !eval.from_dfn >= dfn {
3057                debug!("on_failure: removing {:?}", key);
3058                false
3059            } else {
3060                true
3061            }
3062        });
3063    }
3064
3065    /// Invoked when the node at depth `depth` completed without
3066    /// depending on anything higher in the stack (if that completion
3067    /// was a failure, then `on_failure` should have been invoked
3068    /// already).
3069    ///
3070    /// Note that we may still have provisional cache items remaining
3071    /// in the cache when this is done. For example, if there is a
3072    /// cycle:
3073    ///
3074    /// * A depends on...
3075    ///     * B depends on A
3076    ///     * C depends on...
3077    ///         * D depends on C
3078    ///     * ...
3079    ///
3080    /// Then as we complete the C node we will have a provisional cache
3081    /// with results for A, B, C, and D. This method would clear out
3082    /// the C and D results, but leave A and B provisional.
3083    ///
3084    /// This is determined based on the DFN: we remove any provisional
3085    /// results created since `dfn` started (e.g., in our example, dfn
3086    /// would be 2, representing the C node, and hence we would
3087    /// remove the result for D, which has DFN 3, but not the results for
3088    /// A and B, which have DFNs 0 and 1 respectively).
3089    ///
3090    /// Note that we *do not* attempt to cache these cycle participants
3091    /// in the evaluation cache. Doing so would require carefully computing
3092    /// the correct `DepNode` to store in the cache entry:
3093    /// cycle participants may implicitly depend on query results
3094    /// related to other participants in the cycle, due to our logic
3095    /// which examines the evaluation stack.
3096    ///
3097    /// We used to try to perform this caching,
3098    /// but it lead to multiple incremental compilation ICEs
3099    /// (see #92987 and #96319), and was very hard to understand.
3100    /// Fortunately, removing the caching didn't seem to
3101    /// have a performance impact in practice.
3102    fn on_completion(&self, dfn: usize) {
3103        debug!(?dfn, "on_completion");
3104        self.map.borrow_mut().retain(|fresh_trait_pred, eval| {
3105            if eval.from_dfn >= dfn {
3106                debug!(?fresh_trait_pred, ?eval, "on_completion");
3107                return false;
3108            }
3109            true
3110        });
3111    }
3112}
3113
3114#[derive(Copy, Clone)]
3115struct TraitObligationStackList<'o, 'tcx> {
3116    cache: &'o ProvisionalEvaluationCache<'tcx>,
3117    head: Option<&'o TraitObligationStack<'o, 'tcx>>,
3118}
3119
3120impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
3121    fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3122        TraitObligationStackList { cache, head: None }
3123    }
3124
3125    fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3126        TraitObligationStackList { cache: r.cache(), head: Some(r) }
3127    }
3128
3129    fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3130        self.head
3131    }
3132
3133    fn depth(&self) -> usize {
3134        if let Some(head) = self.head { head.depth } else { 0 }
3135    }
3136}
3137
3138impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
3139    type Item = &'o TraitObligationStack<'o, 'tcx>;
3140
3141    fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3142        let o = self.head?;
3143        *self = o.previous;
3144        Some(o)
3145    }
3146}
3147
3148impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
3149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3150        write!(f, "TraitObligationStack({:?})", self.obligation)
3151    }
3152}
3153
3154pub(crate) enum ProjectionMatchesProjection {
3155    Yes,
3156    Ambiguous,
3157    No,
3158}