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