rustc_trait_selection/traits/select/
mod.rs

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