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