1 //! Candidate selection. See the [rustc dev guide] for more information on how this works.
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection
5 // FIXME: The `map` field in ProvisionalEvaluationCache should be changed to
6 // a `FxIndexMap` to avoid query instability, but right now it causes a perf regression. This would be
7 // fixed or at least lightened by the addition of the `drain_filter` method to `FxIndexMap`
8 // Relevant: https://github.com/rust-lang/rust/pull/103723 and https://github.com/bluss/indexmap/issues/242
9 #![allow(rustc::potential_query_instability)]
11 use self::EvaluationResult::*;
12 use self::SelectionCandidate::*;
14 use super::coherence::{self, Conflict};
15 use super::const_evaluatable;
17 use super::project::normalize_with_depth_to;
18 use super::project::ProjectionTyObligation;
20 use super::util::{closure_trait_ref_and_return_type, predicate_for_trait_def};
23 ErrorReporting, ImplDerivedObligation, ImplDerivedObligationCause, Normalized, Obligation,
24 ObligationCause, ObligationCauseCode, Overflow, PredicateObligation, Selection, SelectionError,
25 SelectionResult, TraitObligation, TraitQueryMode,
28 use crate::infer::{InferCtxt, InferOk, TypeFreshener};
29 use crate::traits::error_reporting::TypeErrCtxtExt;
30 use crate::traits::project::ProjectAndUnifyResult;
31 use crate::traits::project::ProjectionCacheKeyExt;
32 use crate::traits::ProjectionCacheKey;
33 use crate::traits::Unimplemented;
34 use rustc_data_structures::fx::FxHashMap;
35 use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
36 use rustc_data_structures::stack::ensure_sufficient_stack;
37 use rustc_errors::Diagnostic;
39 use rustc_hir::def_id::DefId;
40 use rustc_infer::infer::LateBoundRegionConversionTime;
41 use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
42 use rustc_middle::mir::interpret::ErrorHandled;
43 use rustc_middle::ty::abstract_const::NotConstEvaluatable;
44 use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
45 use rustc_middle::ty::fold::BottomUpFolder;
46 use rustc_middle::ty::print::{FmtPrinter, Print};
47 use rustc_middle::ty::relate::TypeRelation;
48 use rustc_middle::ty::SubstsRef;
49 use rustc_middle::ty::{self, EarlyBinder, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate};
50 use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable, TypeVisitable};
51 use rustc_span::symbol::sym;
53 use std::cell::{Cell, RefCell};
55 use std::fmt::{self, Display};
58 pub use rustc_middle::traits::select::*;
59 use rustc_middle::ty::print::with_no_trimmed_paths;
61 mod candidate_assembly;
64 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
65 pub enum IntercrateAmbiguityCause {
66 DownstreamCrate { trait_desc: String, self_desc: Option<String> },
67 UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
68 ReservationImpl { message: String },
71 impl IntercrateAmbiguityCause {
72 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
73 /// See #23980 for details.
74 pub fn add_intercrate_ambiguity_hint(&self, err: &mut Diagnostic) {
75 err.note(&self.intercrate_ambiguity_hint());
78 pub fn intercrate_ambiguity_hint(&self) -> String {
80 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } => {
81 let self_desc = if let Some(ty) = self_desc {
82 format!(" for type `{}`", ty)
86 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
88 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc } => {
89 let self_desc = if let Some(ty) = self_desc {
90 format!(" for type `{}`", ty)
95 "upstream crates may add a new impl of trait `{}`{} \
100 IntercrateAmbiguityCause::ReservationImpl { message } => message.clone(),
105 pub struct SelectionContext<'cx, 'tcx> {
106 pub infcx: &'cx InferCtxt<'tcx>,
108 /// Freshener used specifically for entries on the obligation
109 /// stack. This ensures that all entries on the stack at one time
110 /// will have the same set of placeholder entries, which is
111 /// important for checking for trait bounds that recursively
112 /// require themselves.
113 freshener: TypeFreshener<'cx, 'tcx>,
115 /// If `intercrate` is set, we remember predicates which were
116 /// considered ambiguous because of impls potentially added in other crates.
117 /// This is used in coherence to give improved diagnostics.
118 /// We don't do his until we detect a coherence error because it can
119 /// lead to false overflow results (#47139) and because always
120 /// computing it may negatively impact performance.
121 intercrate_ambiguity_causes: Option<FxIndexSet<IntercrateAmbiguityCause>>,
123 /// The mode that trait queries run in, which informs our error handling
124 /// policy. In essence, canonicalized queries need their errors propagated
125 /// rather than immediately reported because we do not have accurate spans.
126 query_mode: TraitQueryMode,
129 // A stack that walks back up the stack frame.
130 struct TraitObligationStack<'prev, 'tcx> {
131 obligation: &'prev TraitObligation<'tcx>,
133 /// The trait predicate from `obligation` but "freshened" with the
134 /// selection-context's freshener. Used to check for recursion.
135 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
137 /// Starts out equal to `depth` -- if, during evaluation, we
138 /// encounter a cycle, then we will set this flag to the minimum
139 /// depth of that cycle for all participants in the cycle. These
140 /// participants will then forego caching their results. This is
141 /// not the most efficient solution, but it addresses #60010. The
142 /// problem we are trying to prevent:
144 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
145 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
146 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
148 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
149 /// is `EvaluatedToOk`; this is because they were only considered
150 /// ok on the premise that if `A: AutoTrait` held, but we indeed
151 /// encountered a problem (later on) with `A: AutoTrait. So we
152 /// currently set a flag on the stack node for `B: AutoTrait` (as
153 /// well as the second instance of `A: AutoTrait`) to suppress
156 /// This is a simple, targeted fix. A more-performant fix requires
157 /// deeper changes, but would permit more caching: we could
158 /// basically defer caching until we have fully evaluated the
159 /// tree, and then cache the entire tree at once. In any case, the
160 /// performance impact here shouldn't be so horrible: every time
161 /// this is hit, we do cache at least one trait, so we only
162 /// evaluate each member of a cycle up to N times, where N is the
163 /// length of the cycle. This means the performance impact is
164 /// bounded and we shouldn't have any terrible worst-cases.
165 reached_depth: Cell<usize>,
167 previous: TraitObligationStackList<'prev, 'tcx>,
169 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
172 /// The depth-first number of this node in the search graph -- a
173 /// pre-order index. Basically, a freshly incremented counter.
177 struct SelectionCandidateSet<'tcx> {
178 // A list of candidates that definitely apply to the current
179 // obligation (meaning: types unify).
180 vec: Vec<SelectionCandidate<'tcx>>,
182 // If `true`, then there were candidates that might or might
183 // not have applied, but we couldn't tell. This occurs when some
184 // of the input types are type variables, in which case there are
185 // various "builtin" rules that might or might not trigger.
189 #[derive(PartialEq, Eq, Debug, Clone)]
190 struct EvaluatedCandidate<'tcx> {
191 candidate: SelectionCandidate<'tcx>,
192 evaluation: EvaluationResult,
195 /// When does the builtin impl for `T: Trait` apply?
197 enum BuiltinImplConditions<'tcx> {
198 /// The impl is conditional on `T1, T2, ...: Trait`.
199 Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
200 /// There is no built-in impl. There may be some other
201 /// candidate (a where-clause or user-defined impl).
203 /// It is unknown whether there is an impl.
207 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
208 pub fn new(infcx: &'cx InferCtxt<'tcx>) -> SelectionContext<'cx, 'tcx> {
211 freshener: infcx.freshener_keep_static(),
212 intercrate_ambiguity_causes: None,
213 query_mode: TraitQueryMode::Standard,
217 pub fn with_query_mode(
218 infcx: &'cx InferCtxt<'tcx>,
219 query_mode: TraitQueryMode,
220 ) -> SelectionContext<'cx, 'tcx> {
221 debug!(?query_mode, "with_query_mode");
222 SelectionContext { query_mode, ..SelectionContext::new(infcx) }
225 /// Enables tracking of intercrate ambiguity causes. See
226 /// the documentation of [`Self::intercrate_ambiguity_causes`] for more.
227 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
228 assert!(self.is_intercrate());
229 assert!(self.intercrate_ambiguity_causes.is_none());
230 self.intercrate_ambiguity_causes = Some(FxIndexSet::default());
231 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
234 /// Gets the intercrate ambiguity causes collected since tracking
235 /// was enabled and disables tracking at the same time. If
236 /// tracking is not enabled, just returns an empty vector.
237 pub fn take_intercrate_ambiguity_causes(&mut self) -> FxIndexSet<IntercrateAmbiguityCause> {
238 assert!(self.is_intercrate());
239 self.intercrate_ambiguity_causes.take().unwrap_or_default()
242 pub fn tcx(&self) -> TyCtxt<'tcx> {
246 pub fn is_intercrate(&self) -> bool {
247 self.infcx.intercrate
250 ///////////////////////////////////////////////////////////////////////////
253 // The selection phase tries to identify *how* an obligation will
254 // be resolved. For example, it will identify which impl or
255 // parameter bound is to be used. The process can be inconclusive
256 // if the self type in the obligation is not fully inferred. Selection
257 // can result in an error in one of two ways:
259 // 1. If no applicable impl or parameter bound can be found.
260 // 2. If the output type parameters in the obligation do not match
261 // those specified by the impl/bound. For example, if the obligation
262 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
263 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
265 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
266 /// type environment by performing unification.
267 #[instrument(level = "debug", skip(self), ret)]
270 obligation: &TraitObligation<'tcx>,
271 ) -> SelectionResult<'tcx, Selection<'tcx>> {
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
276 assert!(self.query_mode == TraitQueryMode::Canonical);
277 return Err(SelectionError::Overflow(OverflowError::Canonical));
285 Ok(Some(candidate)) => candidate,
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))
294 Ok(candidate) => Ok(Some(candidate)),
298 pub(crate) fn select_from_obligation(
300 obligation: &TraitObligation<'tcx>,
301 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
302 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
304 let pec = &ProvisionalEvaluationCache::default();
305 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
307 self.candidate_from_obligation(&stack)
310 #[instrument(level = "debug", skip(self), ret)]
311 fn candidate_from_obligation<'o>(
313 stack: &TraitObligationStack<'o, 'tcx>,
314 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
315 // Watch out for overflow. This intentionally bypasses (and does
316 // not update) the cache.
317 self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
319 // Check the cache. Note that we freshen the trait-ref
320 // separately rather than using `stack.fresh_trait_ref` --
321 // this is because we want the unbound variables to be
322 // replaced with fresh types starting from index 0.
323 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate);
324 debug!(?cache_fresh_trait_pred);
325 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
328 self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred)
334 // If no match, compute result and insert into cache.
336 // FIXME(nikomatsakis) -- this cache is not taking into
337 // account cycles that may have occurred in forming the
338 // candidate. I don't know of any specific problems that
339 // result but it seems awfully suspicious.
340 let (candidate, dep_node) =
341 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
343 debug!("CACHE MISS");
344 self.insert_candidate_cache(
345 stack.obligation.param_env,
346 cache_fresh_trait_pred,
353 fn candidate_from_obligation_no_cache<'o>(
355 stack: &TraitObligationStack<'o, 'tcx>,
356 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
357 if let Err(conflict) = self.is_knowable(stack) {
358 debug!("coherence stage: not knowable");
359 if self.intercrate_ambiguity_causes.is_some() {
360 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
361 // Heuristics: show the diagnostics when there are no candidates in crate.
362 if let Ok(candidate_set) = self.assemble_candidates(stack) {
363 let mut no_candidates_apply = true;
365 for c in candidate_set.vec.iter() {
366 if self.evaluate_candidate(stack, &c)?.may_apply() {
367 no_candidates_apply = false;
372 if !candidate_set.ambiguous && no_candidates_apply {
373 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
374 let self_ty = trait_ref.self_ty();
375 let (trait_desc, self_desc) = with_no_trimmed_paths!({
376 let trait_desc = trait_ref.print_only_trait_path().to_string();
377 let self_desc = if self_ty.has_concrete_skeleton() {
378 Some(self_ty.to_string())
382 (trait_desc, self_desc)
384 let cause = if let Conflict::Upstream = conflict {
385 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
387 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
389 debug!(?cause, "evaluate_stack: pushing cause");
390 self.intercrate_ambiguity_causes.as_mut().unwrap().insert(cause);
397 let candidate_set = self.assemble_candidates(stack)?;
399 if candidate_set.ambiguous {
400 debug!("candidate set contains ambig");
404 let candidates = candidate_set.vec;
406 debug!(?stack, ?candidates, "assembled {} candidates", candidates.len());
408 // At this point, we know that each of the entries in the
409 // candidate set is *individually* applicable. Now we have to
410 // figure out if they contain mutual incompatibilities. This
411 // frequently arises if we have an unconstrained input type --
412 // for example, we are looking for `$0: Eq` where `$0` is some
413 // unconstrained type variable. In that case, we'll get a
414 // candidate which assumes $0 == int, one that assumes `$0 ==
415 // usize`, etc. This spells an ambiguity.
417 let mut candidates = self.filter_impls(candidates, stack.obligation);
419 // If there is more than one candidate, first winnow them down
420 // by considering extra conditions (nested obligations and so
421 // forth). We don't winnow if there is exactly one
422 // candidate. This is a relatively minor distinction but it
423 // can lead to better inference and error-reporting. An
424 // example would be if there was an impl:
426 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
428 // and we were to see some code `foo.push_clone()` where `boo`
429 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
430 // we were to winnow, we'd wind up with zero candidates.
431 // Instead, we select the right impl now but report "`Bar` does
432 // not implement `Clone`".
433 if candidates.len() == 1 {
434 return self.filter_reservation_impls(candidates.pop().unwrap(), stack.obligation);
437 // Winnow, but record the exact outcome of evaluation, which
438 // is needed for specialization. Propagate overflow if it occurs.
439 let mut candidates = candidates
441 .map(|c| match self.evaluate_candidate(stack, &c) {
442 Ok(eval) if eval.may_apply() => {
443 Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
446 Err(OverflowError::Canonical) => Err(Overflow(OverflowError::Canonical)),
447 Err(OverflowError::ErrorReporting) => Err(ErrorReporting),
448 Err(OverflowError::Error(e)) => Err(Overflow(OverflowError::Error(e))),
450 .flat_map(Result::transpose)
451 .collect::<Result<Vec<_>, _>>()?;
453 debug!(?stack, ?candidates, "winnowed to {} candidates", candidates.len());
455 let needs_infer = stack.obligation.predicate.has_non_region_infer();
457 // If there are STILL multiple candidates, we can further
458 // reduce the list by dropping duplicates -- including
459 // resolving specializations.
460 if candidates.len() > 1 {
462 while i < candidates.len() {
463 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
464 self.candidate_should_be_dropped_in_favor_of(
471 debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
472 candidates.swap_remove(i);
474 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
477 // If there are *STILL* multiple candidates, give up
478 // and report ambiguity.
480 debug!("multiple matches, ambig");
487 // If there are *NO* candidates, then there are no impls --
488 // that we know of, anyway. Note that in the case where there
489 // are unbound type variables within the obligation, it might
490 // be the case that you could still satisfy the obligation
491 // from another crate by instantiating the type variables with
492 // a type from another crate that does have an impl. This case
493 // is checked for in `evaluate_stack` (and hence users
494 // who might care about this case, like coherence, should use
496 if candidates.is_empty() {
497 // If there's an error type, 'downgrade' our result from
498 // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
499 // emitting additional spurious errors, since we're guaranteed
500 // to have emitted at least one.
501 if stack.obligation.predicate.references_error() {
502 debug!(?stack.obligation.predicate, "found error type in predicate, treating as ambiguous");
505 return Err(Unimplemented);
508 // Just one candidate left.
509 self.filter_reservation_impls(candidates.pop().unwrap().candidate, stack.obligation)
512 ///////////////////////////////////////////////////////////////////////////
515 // Tests whether an obligation can be selected or whether an impl
516 // can be applied to particular types. It skips the "confirmation"
517 // step and hence completely ignores output type parameters.
519 // The result is "true" if the obligation *may* hold and "false" if
520 // we can be sure it does not.
522 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
523 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
524 debug!(?obligation, "predicate_may_hold_fatal");
526 // This fatal query is a stopgap that should only be used in standard mode,
527 // where we do not expect overflow to be propagated.
528 assert!(self.query_mode == TraitQueryMode::Standard);
530 self.evaluate_root_obligation(obligation)
531 .expect("Overflow should be caught earlier in standard query mode")
535 /// Evaluates whether the obligation `obligation` can be satisfied
536 /// and returns an `EvaluationResult`. This is meant for the
538 pub fn evaluate_root_obligation(
540 obligation: &PredicateObligation<'tcx>,
541 ) -> Result<EvaluationResult, OverflowError> {
542 self.evaluation_probe(|this| {
543 this.evaluate_predicate_recursively(
544 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
552 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
553 ) -> Result<EvaluationResult, OverflowError> {
554 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
555 let result = op(self)?;
557 match self.infcx.leak_check(true, snapshot) {
559 Err(_) => return Ok(EvaluatedToErr),
562 if self.infcx.opaque_types_added_in_snapshot(snapshot) {
563 return Ok(result.max(EvaluatedToOkModuloOpaqueTypes));
566 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
568 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
573 /// Evaluates the predicates in `predicates` recursively. Note that
574 /// this applies projections in the predicates, and therefore
575 /// is run within an inference probe.
576 #[instrument(skip(self, stack), level = "debug")]
577 fn evaluate_predicates_recursively<'o, I>(
579 stack: TraitObligationStackList<'o, 'tcx>,
581 ) -> Result<EvaluationResult, OverflowError>
583 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
585 let mut result = EvaluatedToOk;
586 for obligation in predicates {
587 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
588 if let EvaluatedToErr = eval {
589 // fast-path - EvaluatedToErr is the top of the lattice,
590 // so we don't need to look on the other predicates.
591 return Ok(EvaluatedToErr);
593 result = cmp::max(result, eval);
601 skip(self, previous_stack),
602 fields(previous_stack = ?previous_stack.head())
605 fn evaluate_predicate_recursively<'o>(
607 previous_stack: TraitObligationStackList<'o, 'tcx>,
608 obligation: PredicateObligation<'tcx>,
609 ) -> Result<EvaluationResult, OverflowError> {
610 // `previous_stack` stores a `TraitObligation`, while `obligation` is
611 // a `PredicateObligation`. These are distinct types, so we can't
612 // use any `Option` combinator method that would force them to be
614 match previous_stack.head() {
615 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
616 None => self.check_recursion_limit(&obligation, &obligation)?,
619 ensure_sufficient_stack(|| {
620 let bound_predicate = obligation.predicate.kind();
621 match bound_predicate.skip_binder() {
622 ty::PredicateKind::Clause(ty::Clause::Trait(t)) => {
623 let t = bound_predicate.rebind(t);
624 debug_assert!(!t.has_escaping_bound_vars());
625 let obligation = obligation.with(self.tcx(), t);
626 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
629 ty::PredicateKind::Subtype(p) => {
630 let p = bound_predicate.rebind(p);
631 // Does this code ever run?
632 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
633 Ok(Ok(InferOk { mut obligations, .. })) => {
634 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
635 self.evaluate_predicates_recursively(
637 obligations.into_iter(),
640 Ok(Err(_)) => Ok(EvaluatedToErr),
641 Err(..) => Ok(EvaluatedToAmbig),
645 ty::PredicateKind::Coerce(p) => {
646 let p = bound_predicate.rebind(p);
647 // Does this code ever run?
648 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
649 Ok(Ok(InferOk { mut obligations, .. })) => {
650 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
651 self.evaluate_predicates_recursively(
653 obligations.into_iter(),
656 Ok(Err(_)) => Ok(EvaluatedToErr),
657 Err(..) => Ok(EvaluatedToAmbig),
661 ty::PredicateKind::WellFormed(arg) => {
662 // So, there is a bit going on here. First, `WellFormed` predicates
663 // are coinductive, like trait predicates with auto traits.
664 // This means that we need to detect if we have recursively
665 // evaluated `WellFormed(X)`. Otherwise, we would run into
666 // a "natural" overflow error.
668 // Now, the next question is whether we need to do anything
669 // special with caching. Considering the following tree:
674 // In this case, the innermost `WF(Foo<T>)` should return
675 // `EvaluatedToOk`, since it's coinductive. Then if
676 // `Bar<T>: Send` is resolved to `EvaluatedToOk`, it can be
677 // inserted into a cache (because without thinking about `WF`
678 // goals, it isn't in a cycle). If `Foo<T>: Trait` later doesn't
679 // hold, then `Bar<T>: Send` shouldn't hold. Therefore, we
680 // *do* need to keep track of coinductive cycles.
682 let cache = previous_stack.cache;
683 let dfn = cache.next_dfn();
685 for stack_arg in previous_stack.cache.wf_args.borrow().iter().rev() {
686 if stack_arg.0 != arg {
689 debug!("WellFormed({:?}) on stack", arg);
690 if let Some(stack) = previous_stack.head {
691 // Okay, let's imagine we have two different stacks:
692 // `T: NonAutoTrait -> WF(T) -> T: NonAutoTrait`
693 // `WF(T) -> T: NonAutoTrait -> WF(T)`
694 // Because of this, we need to check that all
695 // predicates between the WF goals are coinductive.
696 // Otherwise, we can say that `T: NonAutoTrait` is
698 // Let's imagine we have a predicate stack like
699 // `Foo: Bar -> WF(T) -> T: NonAutoTrait -> T: Auto
701 // and the current predicate is `WF(T)`. `wf_args`
702 // would contain `(T, 1)`. We want to check all
703 // trait predicates greater than `1`. The previous
704 // stack would be `T: Auto`.
705 let cycle = stack.iter().take_while(|s| s.depth > stack_arg.1);
706 let tcx = self.tcx();
708 cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
709 if self.coinductive_match(cycle) {
710 stack.update_reached_depth(stack_arg.1);
711 return Ok(EvaluatedToOk);
713 return Ok(EvaluatedToRecur);
716 return Ok(EvaluatedToOk);
719 match wf::obligations(
721 obligation.param_env,
722 obligation.cause.body_id,
723 obligation.recursion_depth + 1,
725 obligation.cause.span,
727 Some(mut obligations) => {
728 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
730 cache.wf_args.borrow_mut().push((arg, previous_stack.depth()));
732 self.evaluate_predicates_recursively(previous_stack, obligations);
733 cache.wf_args.borrow_mut().pop();
735 let result = result?;
737 if !result.must_apply_modulo_regions() {
738 cache.on_failure(dfn);
741 cache.on_completion(dfn);
745 None => Ok(EvaluatedToAmbig),
749 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(pred)) => {
750 // A global type with no late-bound regions can only
751 // contain the "'static" lifetime (any other lifetime
752 // would either be late-bound or local), so it is guaranteed
753 // to outlive any other lifetime
754 if pred.0.is_global() && !pred.0.has_late_bound_regions() {
757 Ok(EvaluatedToOkModuloRegions)
761 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(..)) => {
762 // We do not consider region relationships when evaluating trait matches.
763 Ok(EvaluatedToOkModuloRegions)
766 ty::PredicateKind::ObjectSafe(trait_def_id) => {
767 if self.tcx().is_object_safe(trait_def_id) {
774 ty::PredicateKind::Clause(ty::Clause::Projection(data)) => {
775 let data = bound_predicate.rebind(data);
776 let project_obligation = obligation.with(self.tcx(), data);
777 match project::poly_project_and_unify_type(self, &project_obligation) {
778 ProjectAndUnifyResult::Holds(mut subobligations) => {
780 // If we've previously marked this projection as 'complete', then
781 // use the final cached result (either `EvaluatedToOk` or
782 // `EvaluatedToOkModuloRegions`), and skip re-evaluating the
785 ProjectionCacheKey::from_poly_projection_predicate(self, data)
787 if let Some(cached_res) = self
794 break 'compute_res Ok(cached_res);
799 subobligations.iter_mut(),
800 obligation.recursion_depth,
802 let res = self.evaluate_predicates_recursively(
806 if let Ok(eval_rslt) = res
807 && (eval_rslt == EvaluatedToOk || eval_rslt == EvaluatedToOkModuloRegions)
809 ProjectionCacheKey::from_poly_projection_predicate(
813 // If the result is something that we can cache, then mark this
814 // entry as 'complete'. This will allow us to skip evaluating the
815 // subobligations at all the next time we evaluate the projection
821 .complete(key, eval_rslt);
826 ProjectAndUnifyResult::FailedNormalization => Ok(EvaluatedToAmbig),
827 ProjectAndUnifyResult::Recursive => Ok(EvaluatedToRecur),
828 ProjectAndUnifyResult::MismatchedProjectionTypes(_) => Ok(EvaluatedToErr),
832 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
833 match self.infcx.closure_kind(closure_substs) {
834 Some(closure_kind) => {
835 if closure_kind.extends(kind) {
841 None => Ok(EvaluatedToAmbig),
845 ty::PredicateKind::ConstEvaluatable(uv) => {
846 match const_evaluatable::is_const_evaluatable(
849 obligation.param_env,
850 obligation.cause.span,
852 Ok(()) => Ok(EvaluatedToOk),
853 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
854 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
855 Err(_) => Ok(EvaluatedToErr),
859 ty::PredicateKind::ConstEquate(c1, c2) => {
860 let tcx = self.tcx();
862 tcx.features().generic_const_exprs,
863 "`ConstEquate` without a feature gate: {c1:?} {c2:?}",
867 let c1 = tcx.expand_abstract_consts(c1);
868 let c2 = tcx.expand_abstract_consts(c2);
870 "evalaute_predicate_recursively: equating consts:\nc1= {:?}\nc2= {:?}",
874 use rustc_hir::def::DefKind;
875 use ty::ConstKind::Unevaluated;
876 match (c1.kind(), c2.kind()) {
877 (Unevaluated(a), Unevaluated(b))
878 if a.def.did == b.def.did
879 && tcx.def_kind(a.def.did) == DefKind::AssocConst =>
881 if let Ok(new_obligations) = self
883 .at(&obligation.cause, obligation.param_env)
885 .eq(a.substs, b.substs)
887 let mut obligations = new_obligations.obligations;
889 obligations.iter_mut(),
890 obligation.recursion_depth,
892 return self.evaluate_predicates_recursively(
894 obligations.into_iter(),
898 (_, Unevaluated(_)) | (Unevaluated(_), _) => (),
900 if let Ok(new_obligations) = self
902 .at(&obligation.cause, obligation.param_env)
905 let mut obligations = new_obligations.obligations;
907 obligations.iter_mut(),
908 obligation.recursion_depth,
910 return self.evaluate_predicates_recursively(
912 obligations.into_iter(),
919 let evaluate = |c: ty::Const<'tcx>| {
920 if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() {
921 match self.infcx.try_const_eval_resolve(
922 obligation.param_env,
925 Some(obligation.cause.span),
935 match (evaluate(c1), evaluate(c2)) {
936 (Ok(c1), Ok(c2)) => {
937 match self.infcx.at(&obligation.cause, obligation.param_env).eq(c1, c2)
939 Ok(inf_ok) => self.evaluate_predicates_recursively(
941 inf_ok.into_obligations(),
943 Err(_) => Ok(EvaluatedToErr),
946 (Err(ErrorHandled::Reported(_)), _)
947 | (_, Err(ErrorHandled::Reported(_))) => Ok(EvaluatedToErr),
948 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
949 if c1.has_non_region_infer() || c2.has_non_region_infer() {
952 // Two different constants using generic parameters ~> error.
958 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
959 bug!("TypeWellFormedFromEnv is only used for chalk")
961 ty::PredicateKind::Ambiguous => Ok(EvaluatedToAmbig),
966 #[instrument(skip(self, previous_stack), level = "debug", ret)]
967 fn evaluate_trait_predicate_recursively<'o>(
969 previous_stack: TraitObligationStackList<'o, 'tcx>,
970 mut obligation: TraitObligation<'tcx>,
971 ) -> Result<EvaluationResult, OverflowError> {
972 if !self.is_intercrate()
973 && obligation.is_global()
974 && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst())
976 // If a param env has no global bounds, global obligations do not
977 // depend on its particular value in order to work, so we can clear
978 // out the param env and get better caching.
980 obligation.param_env = obligation.param_env.without_caller_bounds();
983 let stack = self.push_stack(previous_stack, &obligation);
984 let mut fresh_trait_pred = stack.fresh_trait_pred;
985 let mut param_env = obligation.param_env;
987 fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| {
988 pred.remap_constness(&mut param_env);
992 debug!(?fresh_trait_pred);
994 // If a trait predicate is in the (local or global) evaluation cache,
995 // then we know it holds without cycles.
996 if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
1001 if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
1002 debug!("PROVISIONAL CACHE HIT");
1003 stack.update_reached_depth(result.reached_depth);
1004 return Ok(result.result);
1007 // Check if this is a match for something already on the
1008 // stack. If so, we don't want to insert the result into the
1009 // main cache (it is cycle dependent) nor the provisional
1010 // cache (which is meant for things that have completed but
1011 // for a "backedge" -- this result *is* the backedge).
1012 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
1013 return Ok(cycle_result);
1016 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
1017 let result = result?;
1019 if !result.must_apply_modulo_regions() {
1020 stack.cache().on_failure(stack.dfn);
1023 let reached_depth = stack.reached_depth.get();
1024 if reached_depth >= stack.depth {
1025 debug!("CACHE MISS");
1026 self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
1027 stack.cache().on_completion(stack.dfn);
1029 debug!("PROVISIONAL");
1031 "caching provisionally because {:?} \
1032 is a cycle participant (at depth {}, reached depth {})",
1033 fresh_trait_pred, stack.depth, reached_depth,
1036 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_pred, result);
1042 /// If there is any previous entry on the stack that precisely
1043 /// matches this obligation, then we can assume that the
1044 /// obligation is satisfied for now (still all other conditions
1045 /// must be met of course). One obvious case this comes up is
1046 /// marker traits like `Send`. Think of a linked list:
1048 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
1050 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
1051 /// `Option<Box<List<T>>>` is `Send`, and in turn
1052 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
1055 /// Note that we do this comparison using the `fresh_trait_ref`
1056 /// fields. Because these have all been freshened using
1057 /// `self.freshener`, we can be sure that (a) this will not
1058 /// affect the inferencer state and (b) that if we see two
1059 /// fresh regions with the same index, they refer to the same
1060 /// unbound type variable.
1061 fn check_evaluation_cycle(
1063 stack: &TraitObligationStack<'_, 'tcx>,
1064 ) -> Option<EvaluationResult> {
1065 if let Some(cycle_depth) = stack
1067 .skip(1) // Skip top-most frame.
1069 stack.obligation.param_env == prev.obligation.param_env
1070 && stack.fresh_trait_pred == prev.fresh_trait_pred
1072 .map(|stack| stack.depth)
1074 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
1076 // If we have a stack like `A B C D E A`, where the top of
1077 // the stack is the final `A`, then this will iterate over
1078 // `A, E, D, C, B` -- i.e., all the participants apart
1079 // from the cycle head. We mark them as participating in a
1080 // cycle. This suppresses caching for those nodes. See
1081 // `in_cycle` field for more details.
1082 stack.update_reached_depth(cycle_depth);
1084 // Subtle: when checking for a coinductive cycle, we do
1085 // not compare using the "freshened trait refs" (which
1086 // have erased regions) but rather the fully explicit
1087 // trait refs. This is important because it's only a cycle
1088 // if the regions match exactly.
1089 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
1090 let tcx = self.tcx();
1091 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
1092 if self.coinductive_match(cycle) {
1093 debug!("evaluate_stack --> recursive, coinductive");
1096 debug!("evaluate_stack --> recursive, inductive");
1097 Some(EvaluatedToRecur)
1104 fn evaluate_stack<'o>(
1106 stack: &TraitObligationStack<'o, 'tcx>,
1107 ) -> Result<EvaluationResult, OverflowError> {
1108 // In intercrate mode, whenever any of the generics are unbound,
1109 // there can always be an impl. Even if there are no impls in
1110 // this crate, perhaps the type would be unified with
1111 // something from another crate that does provide an impl.
1113 // In intra mode, we must still be conservative. The reason is
1114 // that we want to avoid cycles. Imagine an impl like:
1116 // impl<T:Eq> Eq for Vec<T>
1118 // and a trait reference like `$0 : Eq` where `$0` is an
1119 // unbound variable. When we evaluate this trait-reference, we
1120 // will unify `$0` with `Vec<$1>` (for some fresh variable
1121 // `$1`), on the condition that `$1 : Eq`. We will then wind
1122 // up with many candidates (since that are other `Eq` impls
1123 // that apply) and try to winnow things down. This results in
1124 // a recursive evaluation that `$1 : Eq` -- as you can
1125 // imagine, this is just where we started. To avoid that, we
1126 // check for unbound variables and return an ambiguous (hence possible)
1127 // match if we've seen this trait before.
1129 // This suffices to allow chains like `FnMut` implemented in
1130 // terms of `Fn` etc, but we could probably make this more
1132 let unbound_input_types =
1133 stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh());
1135 if unbound_input_types
1136 && stack.iter().skip(1).any(|prev| {
1137 stack.obligation.param_env == prev.obligation.param_env
1138 && self.match_fresh_trait_refs(
1139 stack.fresh_trait_pred,
1140 prev.fresh_trait_pred,
1141 prev.obligation.param_env,
1145 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
1146 return Ok(EvaluatedToUnknown);
1149 match self.candidate_from_obligation(stack) {
1150 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1151 Ok(None) => Ok(EvaluatedToAmbig),
1152 Err(Overflow(OverflowError::Canonical)) => Err(OverflowError::Canonical),
1153 Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
1154 Err(..) => Ok(EvaluatedToErr),
1158 /// For defaulted traits, we use a co-inductive strategy to solve, so
1159 /// that recursion is ok. This routine returns `true` if the top of the
1160 /// stack (`cycle[0]`):
1162 /// - is a defaulted trait,
1163 /// - it also appears in the backtrace at some position `X`,
1164 /// - all the predicates at positions `X..` between `X` and the top are
1165 /// also defaulted traits.
1166 pub(crate) fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
1168 I: Iterator<Item = ty::Predicate<'tcx>>,
1170 cycle.all(|predicate| self.coinductive_predicate(predicate))
1173 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1174 let result = match predicate.kind().skip_binder() {
1175 ty::PredicateKind::Clause(ty::Clause::Trait(ref data)) => {
1176 self.tcx().trait_is_coinductive(data.def_id())
1178 ty::PredicateKind::WellFormed(_) => true,
1181 debug!(?predicate, ?result, "coinductive_predicate");
1185 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
1186 /// obligations are met. Returns whether `candidate` remains viable after this further
1191 fields(depth = stack.obligation.recursion_depth),
1194 fn evaluate_candidate<'o>(
1196 stack: &TraitObligationStack<'o, 'tcx>,
1197 candidate: &SelectionCandidate<'tcx>,
1198 ) -> Result<EvaluationResult, OverflowError> {
1199 let mut result = self.evaluation_probe(|this| {
1200 let candidate = (*candidate).clone();
1201 match this.confirm_candidate(stack.obligation, candidate) {
1204 this.evaluate_predicates_recursively(
1206 selection.nested_obligations().into_iter(),
1209 Err(..) => Ok(EvaluatedToErr),
1213 // If we erased any lifetimes, then we want to use
1214 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
1215 // as your final result. The result will be cached using
1216 // the freshened trait predicate as a key, so we need
1217 // our result to be correct by *any* choice of original lifetimes,
1218 // not just the lifetime choice for this particular (non-erased)
1221 if stack.fresh_trait_pred.has_erased_regions() {
1222 result = result.max(EvaluatedToOkModuloRegions);
1228 fn check_evaluation_cache(
1230 param_env: ty::ParamEnv<'tcx>,
1231 trait_pred: ty::PolyTraitPredicate<'tcx>,
1232 ) -> Option<EvaluationResult> {
1233 // Neither the global nor local cache is aware of intercrate
1234 // mode, so don't do any caching. In particular, we might
1235 // re-use the same `InferCtxt` with both an intercrate
1236 // and non-intercrate `SelectionContext`
1237 if self.is_intercrate() {
1241 let tcx = self.tcx();
1242 if self.can_use_global_caches(param_env) {
1243 if let Some(res) = tcx.evaluation_cache.get(&(param_env, trait_pred), tcx) {
1247 self.infcx.evaluation_cache.get(&(param_env, trait_pred), tcx)
1250 fn insert_evaluation_cache(
1252 param_env: ty::ParamEnv<'tcx>,
1253 trait_pred: ty::PolyTraitPredicate<'tcx>,
1254 dep_node: DepNodeIndex,
1255 result: EvaluationResult,
1257 // Avoid caching results that depend on more than just the trait-ref
1258 // - the stack can create recursion.
1259 if result.is_stack_dependent() {
1263 // Neither the global nor local cache is aware of intercrate
1264 // mode, so don't do any caching. In particular, we might
1265 // re-use the same `InferCtxt` with both an intercrate
1266 // and non-intercrate `SelectionContext`
1267 if self.is_intercrate() {
1271 if self.can_use_global_caches(param_env) {
1272 if !trait_pred.needs_infer() {
1273 debug!(?trait_pred, ?result, "insert_evaluation_cache global");
1274 // This may overwrite the cache with the same value
1275 // FIXME: Due to #50507 this overwrites the different values
1276 // This should be changed to use HashMapExt::insert_same
1277 // when that is fixed
1278 self.tcx().evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1283 debug!(?trait_pred, ?result, "insert_evaluation_cache");
1284 self.infcx.evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1287 /// For various reasons, it's possible for a subobligation
1288 /// to have a *lower* recursion_depth than the obligation used to create it.
1289 /// Projection sub-obligations may be returned from the projection cache,
1290 /// which results in obligations with an 'old' `recursion_depth`.
1291 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1292 /// subobligations without taking in a 'parent' depth, causing the
1293 /// generated subobligations to have a `recursion_depth` of `0`.
1295 /// To ensure that obligation_depth never decreases, we force all subobligations
1296 /// to have at least the depth of the original obligation.
1297 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1302 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1305 fn check_recursion_depth<T>(
1308 error_obligation: &Obligation<'tcx, T>,
1309 ) -> Result<(), OverflowError>
1312 + TypeFoldable<'tcx>
1313 + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>,
1314 <T as Print<'tcx, FmtPrinter<'tcx, 'tcx>>>::Error: std::fmt::Debug,
1316 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1317 match self.query_mode {
1318 TraitQueryMode::Standard => {
1319 if let Some(e) = self.infcx.tainted_by_errors() {
1320 return Err(OverflowError::Error(e));
1322 self.infcx.err_ctxt().report_overflow_error(error_obligation, true);
1324 TraitQueryMode::Canonical => {
1325 return Err(OverflowError::Canonical);
1332 /// Checks that the recursion limit has not been exceeded.
1334 /// The weird return type of this function allows it to be used with the `try` (`?`)
1335 /// operator within certain functions.
1337 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V>(
1339 obligation: &Obligation<'tcx, T>,
1340 error_obligation: &Obligation<'tcx, V>,
1341 ) -> Result<(), OverflowError>
1344 + TypeFoldable<'tcx>
1345 + Print<'tcx, FmtPrinter<'tcx, 'tcx>, Output = FmtPrinter<'tcx, 'tcx>>,
1346 <V as Print<'tcx, FmtPrinter<'tcx, 'tcx>>>::Error: std::fmt::Debug,
1348 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1351 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1353 OP: FnOnce(&mut Self) -> R,
1355 let (result, dep_node) =
1356 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1357 self.tcx().dep_graph.read_index(dep_node);
1361 /// filter_impls filters constant trait obligations and candidates that have a positive impl
1362 /// for a negative goal and a negative impl for a positive goal
1363 #[instrument(level = "debug", skip(self, candidates))]
1366 candidates: Vec<SelectionCandidate<'tcx>>,
1367 obligation: &TraitObligation<'tcx>,
1368 ) -> Vec<SelectionCandidate<'tcx>> {
1369 trace!("{candidates:#?}");
1370 let tcx = self.tcx();
1371 let mut result = Vec::with_capacity(candidates.len());
1373 for candidate in candidates {
1374 // Respect const trait obligations
1375 if obligation.is_const() {
1378 ImplCandidate(def_id) if tcx.constness(def_id) == hir::Constness::Const => {}
1380 ParamCandidate(trait_pred) if trait_pred.is_const_if_const() => {}
1382 ProjectionCandidate(_, ty::BoundConstness::ConstIfConst) => {}
1384 AutoImplCandidate => {}
1385 // generator / future, this will raise error in other places
1386 // or ignore error with const_async_blocks feature
1387 GeneratorCandidate => {}
1388 FutureCandidate => {}
1389 // FnDef where the function is const
1390 FnPointerCandidate { is_const: true } => {}
1391 ConstDestructCandidate(_) => {}
1393 // reject all other types of candidates
1399 if let ImplCandidate(def_id) = candidate {
1400 if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id)
1401 || obligation.polarity() == tcx.impl_polarity(def_id)
1403 result.push(candidate);
1406 result.push(candidate);
1410 trace!("{result:#?}");
1414 /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1415 #[instrument(level = "debug", skip(self))]
1416 fn filter_reservation_impls(
1418 candidate: SelectionCandidate<'tcx>,
1419 obligation: &TraitObligation<'tcx>,
1420 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1421 let tcx = self.tcx();
1422 // Treat reservation impls as ambiguity.
1423 if let ImplCandidate(def_id) = candidate {
1424 if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
1425 if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1427 .get_attr(def_id, sym::rustc_reservation_impl)
1428 .and_then(|a| a.value_str());
1429 if let Some(value) = value {
1431 "filter_reservation_impls: \
1432 reservation impl ambiguity on {:?}",
1435 intercrate_ambiguity_clauses.insert(
1436 IntercrateAmbiguityCause::ReservationImpl {
1437 message: value.to_string(),
1448 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Result<(), Conflict> {
1449 debug!("is_knowable(intercrate={:?})", self.is_intercrate());
1451 if !self.is_intercrate() || stack.obligation.polarity() == ty::ImplPolarity::Negative {
1455 let obligation = &stack.obligation;
1456 let predicate = self.infcx.resolve_vars_if_possible(obligation.predicate);
1458 // Okay to skip binder because of the nature of the
1459 // trait-ref-is-knowable check, which does not care about
1461 let trait_ref = predicate.skip_binder().trait_ref;
1463 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1466 /// Returns `true` if the global caches can be used.
1467 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1468 // If there are any inference variables in the `ParamEnv`, then we
1469 // always use a cache local to this particular scope. Otherwise, we
1470 // switch to a global cache.
1471 if param_env.needs_infer() {
1475 // Avoid using the master cache during coherence and just rely
1476 // on the local cache. This effectively disables caching
1477 // during coherence. It is really just a simplification to
1478 // avoid us having to fear that coherence results "pollute"
1479 // the master cache. Since coherence executes pretty quickly,
1480 // it's not worth going to more trouble to increase the
1481 // hit-rate, I don't think.
1482 if self.is_intercrate() {
1486 // Otherwise, we can use the global cache.
1490 fn check_candidate_cache(
1492 mut param_env: ty::ParamEnv<'tcx>,
1493 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1494 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1495 // Neither the global nor local cache is aware of intercrate
1496 // mode, so don't do any caching. In particular, we might
1497 // re-use the same `InferCtxt` with both an intercrate
1498 // and non-intercrate `SelectionContext`
1499 if self.is_intercrate() {
1502 let tcx = self.tcx();
1503 let mut pred = cache_fresh_trait_pred.skip_binder();
1504 pred.remap_constness(&mut param_env);
1506 if self.can_use_global_caches(param_env) {
1507 if let Some(res) = tcx.selection_cache.get(&(param_env, pred), tcx) {
1511 self.infcx.selection_cache.get(&(param_env, pred), tcx)
1514 /// Determines whether can we safely cache the result
1515 /// of selecting an obligation. This is almost always `true`,
1516 /// except when dealing with certain `ParamCandidate`s.
1518 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1519 /// since it was usually produced directly from a `DefId`. However,
1520 /// certain cases (currently only librustdoc's blanket impl finder),
1521 /// a `ParamEnv` may be explicitly constructed with inference types.
1522 /// When this is the case, we do *not* want to cache the resulting selection
1523 /// candidate. This is due to the fact that it might not always be possible
1524 /// to equate the obligation's trait ref and the candidate's trait ref,
1525 /// if more constraints end up getting added to an inference variable.
1527 /// Because of this, we always want to re-run the full selection
1528 /// process for our obligation the next time we see it, since
1529 /// we might end up picking a different `SelectionCandidate` (or none at all).
1530 fn can_cache_candidate(
1532 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1534 // Neither the global nor local cache is aware of intercrate
1535 // mode, so don't do any caching. In particular, we might
1536 // re-use the same `InferCtxt` with both an intercrate
1537 // and non-intercrate `SelectionContext`
1538 if self.is_intercrate() {
1542 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1547 #[instrument(skip(self, param_env, cache_fresh_trait_pred, dep_node), level = "debug")]
1548 fn insert_candidate_cache(
1550 mut param_env: ty::ParamEnv<'tcx>,
1551 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1552 dep_node: DepNodeIndex,
1553 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1555 let tcx = self.tcx();
1556 let mut pred = cache_fresh_trait_pred.skip_binder();
1558 pred.remap_constness(&mut param_env);
1560 if !self.can_cache_candidate(&candidate) {
1561 debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1565 if self.can_use_global_caches(param_env) {
1566 if let Err(Overflow(OverflowError::Canonical)) = candidate {
1567 // Don't cache overflow globally; we only produce this in certain modes.
1568 } else if !pred.needs_infer() {
1569 if !candidate.needs_infer() {
1570 debug!(?pred, ?candidate, "insert_candidate_cache global");
1571 // This may overwrite the cache with the same value.
1572 tcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1578 debug!(?pred, ?candidate, "insert_candidate_cache local");
1579 self.infcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1582 /// Matches a predicate against the bounds of its self type.
1584 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1585 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1586 /// `Baz` bound. We return indexes into the list returned by
1587 /// `tcx.item_bounds` for any applicable bounds.
1588 #[instrument(level = "debug", skip(self), ret)]
1589 fn match_projection_obligation_against_definition_bounds(
1591 obligation: &TraitObligation<'tcx>,
1592 ) -> smallvec::SmallVec<[(usize, ty::BoundConstness); 2]> {
1593 let poly_trait_predicate = self.infcx.resolve_vars_if_possible(obligation.predicate);
1594 let placeholder_trait_predicate =
1595 self.infcx.replace_bound_vars_with_placeholders(poly_trait_predicate);
1596 debug!(?placeholder_trait_predicate);
1598 let tcx = self.infcx.tcx;
1599 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1600 ty::Projection(ref data) => (data.item_def_id, data.substs),
1601 ty::Opaque(def_id, substs) => (def_id, substs),
1604 obligation.cause.span,
1605 "match_projection_obligation_against_definition_bounds() called \
1606 but self-ty is not a projection: {:?}",
1607 placeholder_trait_predicate.trait_ref.self_ty()
1611 let bounds = tcx.bound_item_bounds(def_id).subst(tcx, substs);
1613 // The bounds returned by `item_bounds` may contain duplicates after
1614 // normalization, so try to deduplicate when possible to avoid
1615 // unnecessary ambiguity.
1616 let mut distinct_normalized_bounds = FxHashSet::default();
1621 .filter_map(|(idx, bound)| {
1622 let bound_predicate = bound.kind();
1623 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1624 bound_predicate.skip_binder()
1626 let bound = bound_predicate.rebind(pred.trait_ref);
1627 if self.infcx.probe(|_| {
1628 match self.match_normalize_trait_ref(
1631 placeholder_trait_predicate.trait_ref,
1634 Ok(Some(normalized_trait))
1635 if distinct_normalized_bounds.insert(normalized_trait) =>
1642 return Some((idx, pred.constness));
1650 /// Equates the trait in `obligation` with trait bound. If the two traits
1651 /// can be equated and the normalized trait bound doesn't contain inference
1652 /// variables or placeholders, the normalized bound is returned.
1653 fn match_normalize_trait_ref(
1655 obligation: &TraitObligation<'tcx>,
1656 trait_bound: ty::PolyTraitRef<'tcx>,
1657 placeholder_trait_ref: ty::TraitRef<'tcx>,
1658 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1659 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1660 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1661 // Avoid unnecessary normalization
1665 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1666 project::normalize_with_depth(
1668 obligation.param_env,
1669 obligation.cause.clone(),
1670 obligation.recursion_depth + 1,
1675 .at(&obligation.cause, obligation.param_env)
1676 .define_opaque_types(false)
1677 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1678 .map(|InferOk { obligations: _, value: () }| {
1679 // This method is called within a probe, so we can't have
1680 // inference variables and placeholders escape.
1681 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1690 fn where_clause_may_apply<'o>(
1692 stack: &TraitObligationStack<'o, 'tcx>,
1693 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1694 ) -> Result<EvaluationResult, OverflowError> {
1695 self.evaluation_probe(|this| {
1696 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1697 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1698 Err(()) => Ok(EvaluatedToErr),
1703 /// Return `Yes` if the obligation's predicate type applies to the env_predicate, and
1704 /// `No` if it does not. Return `Ambiguous` in the case that the projection type is a GAT,
1705 /// and applying this env_predicate constrains any of the obligation's GAT substitutions.
1707 /// This behavior is a somewhat of a hack to prevent over-constraining inference variables
1708 /// in cases like #91762.
1709 pub(super) fn match_projection_projections(
1711 obligation: &ProjectionTyObligation<'tcx>,
1712 env_predicate: PolyProjectionPredicate<'tcx>,
1713 potentially_unnormalized_candidates: bool,
1714 ) -> ProjectionMatchesProjection {
1715 let mut nested_obligations = Vec::new();
1716 let infer_predicate = self.infcx.replace_bound_vars_with_fresh_vars(
1717 obligation.cause.span,
1718 LateBoundRegionConversionTime::HigherRankedType,
1721 let infer_projection = if potentially_unnormalized_candidates {
1722 ensure_sufficient_stack(|| {
1723 project::normalize_with_depth_to(
1725 obligation.param_env,
1726 obligation.cause.clone(),
1727 obligation.recursion_depth + 1,
1728 infer_predicate.projection_ty,
1729 &mut nested_obligations,
1733 infer_predicate.projection_ty
1738 .at(&obligation.cause, obligation.param_env)
1739 .define_opaque_types(false)
1740 .sup(obligation.predicate, infer_projection)
1741 .map_or(false, |InferOk { obligations, value: () }| {
1742 self.evaluate_predicates_recursively(
1743 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1744 nested_obligations.into_iter().chain(obligations),
1746 .map_or(false, |res| res.may_apply())
1750 let generics = self.tcx().generics_of(obligation.predicate.item_def_id);
1751 // FIXME(generic-associated-types): Addresses aggressive inference in #92917.
1752 // If this type is a GAT, and of the GAT substs resolve to something new,
1753 // that means that we must have newly inferred something about the GAT.
1754 // We should give up in that case.
1755 if !generics.params.is_empty()
1756 && obligation.predicate.substs[generics.parent_count..]
1758 .any(|&p| p.has_non_region_infer() && self.infcx.shallow_resolve(p) != p)
1760 ProjectionMatchesProjection::Ambiguous
1762 ProjectionMatchesProjection::Yes
1765 ProjectionMatchesProjection::No
1769 ///////////////////////////////////////////////////////////////////////////
1772 // Winnowing is the process of attempting to resolve ambiguity by
1773 // probing further. During the winnowing process, we unify all
1774 // type variables and then we also attempt to evaluate recursive
1775 // bounds to see if they are satisfied.
1777 /// Returns `true` if `victim` should be dropped in favor of
1778 /// `other`. Generally speaking we will drop duplicate
1779 /// candidates and prefer where-clause candidates.
1781 /// See the comment for "SelectionCandidate" for more details.
1782 fn candidate_should_be_dropped_in_favor_of(
1784 victim: &EvaluatedCandidate<'tcx>,
1785 other: &EvaluatedCandidate<'tcx>,
1788 if victim.candidate == other.candidate {
1792 // Check if a bound would previously have been removed when normalizing
1793 // the param_env so that it can be given the lowest priority. See
1794 // #50825 for the motivation for this.
1795 let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| {
1796 cand.is_global() && !cand.has_late_bound_regions()
1799 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1800 // `DiscriminantKindCandidate`, `ConstDestructCandidate`
1801 // to anything else.
1803 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1804 // lifetime of a variable.
1805 match (&other.candidate, &victim.candidate) {
1806 (_, AutoImplCandidate) | (AutoImplCandidate, _) => {
1808 "default implementations shouldn't be recorded \
1809 when there are other valid candidates"
1813 // FIXME(@jswrenn): this should probably be more sophisticated
1814 (TransmutabilityCandidate, _) | (_, TransmutabilityCandidate) => false,
1817 (BuiltinCandidate { has_nested: false } | ConstDestructCandidate(_), _) => true,
1818 (_, BuiltinCandidate { has_nested: false } | ConstDestructCandidate(_)) => false,
1820 (ParamCandidate(other), ParamCandidate(victim)) => {
1821 let same_except_bound_vars = other.skip_binder().trait_ref
1822 == victim.skip_binder().trait_ref
1823 && other.skip_binder().constness == victim.skip_binder().constness
1824 && other.skip_binder().polarity == victim.skip_binder().polarity
1825 && !other.skip_binder().trait_ref.has_escaping_bound_vars();
1826 if same_except_bound_vars {
1827 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1828 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1829 // or the current one if tied (they should both evaluate to the same answer). This is
1830 // probably best characterized as a "hack", since we might prefer to just do our
1831 // best to *not* create essentially duplicate candidates in the first place.
1832 other.bound_vars().len() <= victim.bound_vars().len()
1833 } else if other.skip_binder().trait_ref == victim.skip_binder().trait_ref
1834 && victim.skip_binder().constness == ty::BoundConstness::NotConst
1835 && other.skip_binder().polarity == victim.skip_binder().polarity
1837 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1844 // Drop otherwise equivalent non-const fn pointer candidates
1845 (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
1847 // Global bounds from the where clause should be ignored
1848 // here (see issue #50825). Otherwise, we have a where
1849 // clause so don't go around looking for impls.
1850 // Arbitrarily give param candidates priority
1851 // over projection and object candidates.
1853 ParamCandidate(ref cand),
1856 | GeneratorCandidate
1858 | FnPointerCandidate { .. }
1859 | BuiltinObjectCandidate
1860 | BuiltinUnsizeCandidate
1861 | TraitUpcastingUnsizeCandidate(_)
1862 | BuiltinCandidate { .. }
1863 | TraitAliasCandidate
1864 | ObjectCandidate(_)
1865 | ProjectionCandidate(..),
1866 ) => !is_global(cand),
1867 (ObjectCandidate(_) | ProjectionCandidate(..), ParamCandidate(ref cand)) => {
1868 // Prefer these to a global where-clause bound
1869 // (see issue #50825).
1875 | GeneratorCandidate
1877 | FnPointerCandidate { .. }
1878 | BuiltinObjectCandidate
1879 | BuiltinUnsizeCandidate
1880 | TraitUpcastingUnsizeCandidate(_)
1881 | BuiltinCandidate { has_nested: true }
1882 | TraitAliasCandidate,
1883 ParamCandidate(ref cand),
1885 // Prefer these to a global where-clause bound
1886 // (see issue #50825).
1887 is_global(cand) && other.evaluation.must_apply_modulo_regions()
1890 (ProjectionCandidate(i, _), ProjectionCandidate(j, _))
1891 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1892 // Arbitrarily pick the lower numbered candidate for backwards
1893 // compatibility reasons. Don't let this affect inference.
1894 i < j && !needs_infer
1896 (ObjectCandidate(_), ProjectionCandidate(..))
1897 | (ProjectionCandidate(..), ObjectCandidate(_)) => {
1898 bug!("Have both object and projection candidate")
1901 // Arbitrarily give projection and object candidates priority.
1903 ObjectCandidate(_) | ProjectionCandidate(..),
1906 | GeneratorCandidate
1908 | FnPointerCandidate { .. }
1909 | BuiltinObjectCandidate
1910 | BuiltinUnsizeCandidate
1911 | TraitUpcastingUnsizeCandidate(_)
1912 | BuiltinCandidate { .. }
1913 | TraitAliasCandidate,
1919 | GeneratorCandidate
1921 | FnPointerCandidate { .. }
1922 | BuiltinObjectCandidate
1923 | BuiltinUnsizeCandidate
1924 | TraitUpcastingUnsizeCandidate(_)
1925 | BuiltinCandidate { .. }
1926 | TraitAliasCandidate,
1927 ObjectCandidate(_) | ProjectionCandidate(..),
1930 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1931 // See if we can toss out `victim` based on specialization.
1932 // While this requires us to know *for sure* that the `other` impl applies
1933 // we still use modulo regions here.
1935 // This is fine as specialization currently assumes that specializing
1936 // impls have to be always applicable, meaning that the only allowed
1937 // region constraints may be constraints also present on the default impl.
1938 let tcx = self.tcx();
1939 if other.evaluation.must_apply_modulo_regions() {
1940 if tcx.specializes((other_def, victim_def)) {
1945 if other.evaluation.must_apply_considering_regions() {
1946 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1947 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1948 // Subtle: If the predicate we are evaluating has inference
1949 // variables, do *not* allow discarding candidates due to
1950 // marker trait impls.
1952 // Without this restriction, we could end up accidentally
1953 // constraining inference variables based on an arbitrarily
1954 // chosen trait impl.
1956 // Imagine we have the following code:
1959 // #[marker] trait MyTrait {}
1960 // impl MyTrait for u8 {}
1961 // impl MyTrait for bool {}
1964 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1966 // During selection, we will end up with one candidate for each
1967 // impl of `MyTrait`. If we were to discard one impl in favor
1968 // of the other, we would be left with one candidate, causing
1969 // us to "successfully" select the predicate, unifying
1970 // _#0t with (for example) `u8`.
1972 // However, we have no reason to believe that this unification
1973 // is correct - we've essentially just picked an arbitrary
1974 // *possibility* for _#0t, and required that this be the *only*
1977 // Eventually, we will either:
1978 // 1) Unify all inference variables in the predicate through
1979 // some other means (e.g. type-checking of a function). We will
1980 // then be in a position to drop marker trait candidates
1981 // without constraining inference variables (since there are
1982 // none left to constrain)
1983 // 2) Be left with some unconstrained inference variables. We
1984 // will then correctly report an inference error, since the
1985 // existence of multiple marker trait impls tells us nothing
1986 // about which one should actually apply.
1997 // Everything else is ambiguous
2001 | GeneratorCandidate
2003 | FnPointerCandidate { .. }
2004 | BuiltinObjectCandidate
2005 | BuiltinUnsizeCandidate
2006 | TraitUpcastingUnsizeCandidate(_)
2007 | BuiltinCandidate { has_nested: true }
2008 | TraitAliasCandidate,
2011 | GeneratorCandidate
2013 | FnPointerCandidate { .. }
2014 | BuiltinObjectCandidate
2015 | BuiltinUnsizeCandidate
2016 | TraitUpcastingUnsizeCandidate(_)
2017 | BuiltinCandidate { has_nested: true }
2018 | TraitAliasCandidate,
2023 fn sized_conditions(
2025 obligation: &TraitObligation<'tcx>,
2026 ) -> BuiltinImplConditions<'tcx> {
2027 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2029 // NOTE: binder moved to (*)
2030 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2032 match self_ty.kind() {
2033 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2044 | ty::GeneratorWitness(..)
2048 | ty::Dynamic(_, _, ty::DynStar)
2050 // safe for everything
2051 Where(ty::Binder::dummy(Vec::new()))
2054 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2056 ty::Tuple(tys) => Where(
2057 obligation.predicate.rebind(tys.last().map_or_else(Vec::new, |&last| vec![last])),
2060 ty::Adt(def, substs) => {
2061 let sized_crit = def.sized_constraint(self.tcx());
2062 // (*) binder moved here
2063 Where(obligation.predicate.rebind({
2067 .map(|ty| sized_crit.rebind(*ty).subst(self.tcx(), substs))
2072 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2073 ty::Infer(ty::TyVar(_)) => Ambiguous,
2077 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2078 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2083 fn copy_clone_conditions(
2085 obligation: &TraitObligation<'tcx>,
2086 ) -> BuiltinImplConditions<'tcx> {
2087 // NOTE: binder moved to (*)
2088 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2090 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2092 match *self_ty.kind() {
2093 ty::Infer(ty::IntVar(_))
2094 | ty::Infer(ty::FloatVar(_))
2097 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
2106 | ty::Ref(_, _, hir::Mutability::Not)
2107 | ty::Array(..) => {
2108 // Implementations provided in libcore
2115 | ty::Generator(_, _, hir::Movability::Static)
2117 | ty::Ref(_, _, hir::Mutability::Mut) => None,
2120 // (*) binder moved here
2121 Where(obligation.predicate.rebind(tys.iter().collect()))
2124 ty::Generator(_, substs, hir::Movability::Movable) => {
2125 if self.tcx().features().generator_clone {
2126 let resolved_upvars =
2127 self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
2128 let resolved_witness =
2129 self.infcx.shallow_resolve(substs.as_generator().witness());
2130 if resolved_upvars.is_ty_var() || resolved_witness.is_ty_var() {
2131 // Not yet resolved.
2137 .chain(iter::once(substs.as_generator().witness()))
2138 .collect::<Vec<_>>();
2139 Where(obligation.predicate.rebind(all))
2146 ty::GeneratorWitness(binder) => {
2147 let witness_tys = binder.skip_binder();
2148 for witness_ty in witness_tys.iter() {
2149 let resolved = self.infcx.shallow_resolve(witness_ty);
2150 if resolved.is_ty_var() {
2154 // (*) binder moved here
2155 let all_vars = self.tcx().mk_bound_variable_kinds(
2156 obligation.predicate.bound_vars().iter().chain(binder.bound_vars().iter()),
2158 Where(ty::Binder::bind_with_vars(witness_tys.to_vec(), all_vars))
2161 ty::Closure(_, substs) => {
2162 // (*) binder moved here
2163 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
2164 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
2165 // Not yet resolved.
2168 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
2172 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2173 // Fallback to whatever user-defined impls exist in this case.
2177 ty::Infer(ty::TyVar(_)) => {
2178 // Unbound type variable. Might or might not have
2179 // applicable impls and so forth, depending on what
2180 // those type variables wind up being bound to.
2186 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2187 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2192 /// For default impls, we need to break apart a type into its
2193 /// "constituent types" -- meaning, the types that it contains.
2195 /// Here are some (simple) examples:
2197 /// ```ignore (illustrative)
2198 /// (i32, u32) -> [i32, u32]
2199 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2200 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2201 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2203 #[instrument(level = "debug", skip(self), ret)]
2204 fn constituent_types_for_ty(
2206 t: ty::Binder<'tcx, Ty<'tcx>>,
2207 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
2208 match *t.skip_binder().kind() {
2217 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2219 | ty::Char => ty::Binder::dummy(Vec::new()),
2225 | ty::Projection(..)
2227 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2228 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2231 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2232 t.rebind(vec![element_ty])
2235 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
2237 ty::Tuple(ref tys) => {
2238 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2239 t.rebind(tys.iter().collect())
2242 ty::Closure(_, ref substs) => {
2243 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
2247 ty::Generator(_, ref substs, _) => {
2248 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
2249 let witness = substs.as_generator().witness();
2250 t.rebind([ty].into_iter().chain(iter::once(witness)).collect())
2253 ty::GeneratorWitness(types) => {
2254 debug_assert!(!types.has_escaping_bound_vars());
2255 types.map_bound(|types| types.to_vec())
2258 // For `PhantomData<T>`, we pass `T`.
2259 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
2261 ty::Adt(def, substs) => {
2262 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
2265 ty::Opaque(def_id, substs) => {
2266 // We can resolve the `impl Trait` to its concrete type,
2267 // which enforces a DAG between the functions requiring
2268 // the auto trait bounds in question.
2269 t.rebind(vec![self.tcx().bound_type_of(def_id).subst(self.tcx(), substs)])
2274 fn collect_predicates_for_types(
2276 param_env: ty::ParamEnv<'tcx>,
2277 cause: ObligationCause<'tcx>,
2278 recursion_depth: usize,
2279 trait_def_id: DefId,
2280 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
2281 ) -> Vec<PredicateObligation<'tcx>> {
2282 // Because the types were potentially derived from
2283 // higher-ranked obligations they may reference late-bound
2284 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2285 // yield a type like `for<'a> &'a i32`. In general, we
2286 // maintain the invariant that we never manipulate bound
2287 // regions, so we have to process these bound regions somehow.
2289 // The strategy is to:
2291 // 1. Instantiate those regions to placeholder regions (e.g.,
2292 // `for<'a> &'a i32` becomes `&0 i32`.
2293 // 2. Produce something like `&'0 i32 : Copy`
2294 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2298 .skip_binder() // binder moved -\
2301 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(*ty); // <----/
2303 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
2304 let Normalized { value: normalized_ty, mut obligations } =
2305 ensure_sufficient_stack(|| {
2306 project::normalize_with_depth(
2314 let placeholder_obligation = predicate_for_trait_def(
2322 obligations.push(placeholder_obligation);
2328 ///////////////////////////////////////////////////////////////////////////
2331 // Matching is a common path used for both evaluation and
2332 // confirmation. It basically unifies types that appear in impls
2333 // and traits. This does affect the surrounding environment;
2334 // therefore, when used during evaluation, match routines must be
2335 // run inside of a `probe()` so that their side-effects are
2341 obligation: &TraitObligation<'tcx>,
2342 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
2343 let impl_trait_ref = self.tcx().bound_impl_trait_ref(impl_def_id).unwrap();
2344 match self.match_impl(impl_def_id, impl_trait_ref, obligation) {
2345 Ok(substs) => substs,
2347 // FIXME: A rematch may fail when a candidate cache hit occurs
2348 // on thefreshened form of the trait predicate, but the match
2349 // fails for some reason that is not captured in the freshened
2350 // cache key. For example, equating an impl trait ref against
2351 // the placeholder trait ref may fail due the Generalizer relation
2352 // raising a CyclicalTy error due to a sub_root_var relation
2353 // for a variable being generalized...
2354 self.infcx.tcx.sess.delay_span_bug(
2355 obligation.cause.span,
2357 "Impl {:?} was matchable against {:?} but now is not",
2358 impl_def_id, obligation
2361 let value = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2362 let err = self.tcx().ty_error();
2363 let value = value.fold_with(&mut BottomUpFolder {
2369 Normalized { value, obligations: vec![] }
2374 #[instrument(level = "debug", skip(self), ret)]
2378 impl_trait_ref: EarlyBinder<ty::TraitRef<'tcx>>,
2379 obligation: &TraitObligation<'tcx>,
2380 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2381 let placeholder_obligation =
2382 self.infcx.replace_bound_vars_with_placeholders(obligation.predicate);
2383 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2385 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2387 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2389 debug!(?impl_trait_ref);
2391 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2392 ensure_sufficient_stack(|| {
2393 project::normalize_with_depth(
2395 obligation.param_env,
2396 obligation.cause.clone(),
2397 obligation.recursion_depth + 1,
2402 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2404 let cause = ObligationCause::new(
2405 obligation.cause.span,
2406 obligation.cause.body_id,
2407 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2410 let InferOk { obligations, .. } = self
2412 .at(&cause, obligation.param_env)
2413 .define_opaque_types(false)
2414 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2415 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{e}`"))?;
2416 nested_obligations.extend(obligations);
2418 if !self.is_intercrate()
2419 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2421 debug!("reservation impls only apply in intercrate mode");
2425 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2428 fn fast_reject_trait_refs(
2430 obligation: &TraitObligation<'tcx>,
2431 impl_trait_ref: &ty::TraitRef<'tcx>,
2433 // We can avoid creating type variables and doing the full
2434 // substitution if we find that any of the input types, when
2435 // simplified, do not match.
2436 let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsPlaceholder };
2437 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs)
2438 .any(|(obl, imp)| !drcx.generic_args_may_unify(obl, imp))
2441 /// Normalize `where_clause_trait_ref` and try to match it against
2442 /// `obligation`. If successful, return any predicates that
2443 /// result from the normalization.
2444 fn match_where_clause_trait_ref(
2446 obligation: &TraitObligation<'tcx>,
2447 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2448 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2449 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2452 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2453 /// obligation is satisfied.
2454 #[instrument(skip(self), level = "debug")]
2455 fn match_poly_trait_ref(
2457 obligation: &TraitObligation<'tcx>,
2458 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2459 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2461 .at(&obligation.cause, obligation.param_env)
2462 // We don't want predicates for opaque types to just match all other types,
2463 // if there is an obligation on the opaque type, then that obligation must be met
2464 // opaquely. Otherwise we'd match any obligation to the opaque type and then error
2466 .define_opaque_types(false)
2467 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2468 .map(|InferOk { obligations, .. }| obligations)
2472 ///////////////////////////////////////////////////////////////////////////
2475 fn match_fresh_trait_refs(
2477 previous: ty::PolyTraitPredicate<'tcx>,
2478 current: ty::PolyTraitPredicate<'tcx>,
2479 param_env: ty::ParamEnv<'tcx>,
2481 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2482 matcher.relate(previous, current).is_ok()
2487 previous_stack: TraitObligationStackList<'o, 'tcx>,
2488 obligation: &'o TraitObligation<'tcx>,
2489 ) -> TraitObligationStack<'o, 'tcx> {
2490 let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
2492 let dfn = previous_stack.cache.next_dfn();
2493 let depth = previous_stack.depth() + 1;
2494 TraitObligationStack {
2497 reached_depth: Cell::new(depth),
2498 previous: previous_stack,
2504 #[instrument(skip(self), level = "debug")]
2505 fn closure_trait_ref_unnormalized(
2507 obligation: &TraitObligation<'tcx>,
2508 substs: SubstsRef<'tcx>,
2509 ) -> ty::PolyTraitRef<'tcx> {
2510 let closure_sig = substs.as_closure().sig();
2512 debug!(?closure_sig);
2514 // NOTE: The self-type is an unboxed closure type and hence is
2515 // in fact unparameterized (or at least does not reference any
2516 // regions bound in the obligation).
2517 let self_ty = obligation
2521 .expect("unboxed closure type should not capture bound vars from the predicate");
2523 closure_trait_ref_and_return_type(
2525 obligation.predicate.def_id(),
2528 util::TupleArgumentsFlag::No,
2530 .map_bound(|(trait_ref, _)| trait_ref)
2533 /// Returns the obligations that are implied by instantiating an
2534 /// impl or trait. The obligations are substituted and fully
2535 /// normalized. This is used when confirming an impl or default
2537 #[instrument(level = "debug", skip(self, cause, param_env))]
2538 fn impl_or_trait_obligations(
2540 cause: &ObligationCause<'tcx>,
2541 recursion_depth: usize,
2542 param_env: ty::ParamEnv<'tcx>,
2543 def_id: DefId, // of impl or trait
2544 substs: SubstsRef<'tcx>, // for impl or trait
2545 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2546 ) -> Vec<PredicateObligation<'tcx>> {
2547 let tcx = self.tcx();
2549 // To allow for one-pass evaluation of the nested obligation,
2550 // each predicate must be preceded by the obligations required
2552 // for example, if we have:
2553 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2554 // the impl will have the following predicates:
2555 // <V as Iterator>::Item = U,
2556 // U: Iterator, U: Sized,
2557 // V: Iterator, V: Sized,
2558 // <U as Iterator>::Item: Copy
2559 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2560 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2561 // `$1: Copy`, so we must ensure the obligations are emitted in
2563 let predicates = tcx.bound_predicates_of(def_id);
2564 debug!(?predicates);
2565 assert_eq!(predicates.0.parent, None);
2566 let mut obligations = Vec::with_capacity(predicates.0.predicates.len());
2567 for (predicate, span) in predicates.0.predicates {
2569 let cause = cause.clone().derived_cause(parent_trait_pred, |derived| {
2570 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
2572 impl_def_id: def_id,
2576 let predicate = normalize_with_depth_to(
2581 predicates.rebind(*predicate).subst(tcx, substs),
2584 obligations.push(Obligation { cause, recursion_depth, param_env, predicate });
2591 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2592 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2593 TraitObligationStackList::with(self)
2596 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2600 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2604 /// Indicates that attempting to evaluate this stack entry
2605 /// required accessing something from the stack at depth `reached_depth`.
2606 fn update_reached_depth(&self, reached_depth: usize) {
2608 self.depth >= reached_depth,
2609 "invoked `update_reached_depth` with something under this stack: \
2610 self.depth={} reached_depth={}",
2614 debug!(reached_depth, "update_reached_depth");
2616 while reached_depth < p.depth {
2617 debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
2618 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2619 p = p.previous.head.unwrap();
2624 /// The "provisional evaluation cache" is used to store intermediate cache results
2625 /// when solving auto traits. Auto traits are unusual in that they can support
2626 /// cycles. So, for example, a "proof tree" like this would be ok:
2628 /// - `Foo<T>: Send` :-
2629 /// - `Bar<T>: Send` :-
2630 /// - `Foo<T>: Send` -- cycle, but ok
2631 /// - `Baz<T>: Send`
2633 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2634 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2635 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2636 /// they are coinductive) it is considered ok.
2638 /// However, there is a complication: at the point where we have
2639 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2640 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2641 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2642 /// find out this assumption is wrong? Specifically, we could
2643 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2644 /// `Bar<T>: Send` didn't turn out to be true.
2646 /// In Issue #60010, we found a bug in rustc where it would cache
2647 /// these intermediate results. This was fixed in #60444 by disabling
2648 /// *all* caching for things involved in a cycle -- in our example,
2649 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2650 /// to large slowdowns.
2652 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2653 /// first requires proving `Bar<T>: Send` (which is true:
2655 /// - `Foo<T>: Send` :-
2656 /// - `Bar<T>: Send` :-
2657 /// - `Foo<T>: Send` -- cycle, but ok
2658 /// - `Baz<T>: Send`
2659 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2660 /// - `*const T: Send` -- but what if we later encounter an error?
2662 /// The *provisional evaluation cache* resolves this issue. It stores
2663 /// cache results that we've proven but which were involved in a cycle
2664 /// in some way. We track the minimal stack depth (i.e., the
2665 /// farthest from the top of the stack) that we are dependent on.
2666 /// The idea is that the cache results within are all valid -- so long as
2667 /// none of the nodes in between the current node and the node at that minimum
2668 /// depth result in an error (in which case the cached results are just thrown away).
2670 /// During evaluation, we consult this provisional cache and rely on
2671 /// it. Accessing a cached value is considered equivalent to accessing
2672 /// a result at `reached_depth`, so it marks the *current* solution as
2673 /// provisional as well. If an error is encountered, we toss out any
2674 /// provisional results added from the subtree that encountered the
2675 /// error. When we pop the node at `reached_depth` from the stack, we
2676 /// can commit all the things that remain in the provisional cache.
2677 struct ProvisionalEvaluationCache<'tcx> {
2678 /// next "depth first number" to issue -- just a counter
2681 /// Map from cache key to the provisionally evaluated thing.
2682 /// The cache entries contain the result but also the DFN in which they
2683 /// were added. The DFN is used to clear out values on failure.
2685 /// Imagine we have a stack like:
2687 /// - `A B C` and we add a cache for the result of C (DFN 2)
2688 /// - Then we have a stack `A B D` where `D` has DFN 3
2689 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2690 /// - `E` generates various cache entries which have cyclic dependencies on `B`
2691 /// - `A B D E F` and so forth
2692 /// - the DFN of `F` for example would be 5
2693 /// - then we determine that `E` is in error -- we will then clear
2694 /// all cache values whose DFN is >= 4 -- in this case, that
2695 /// means the cached value for `F`.
2696 map: RefCell<FxHashMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
2698 /// The stack of args that we assume to be true because a `WF(arg)` predicate
2699 /// is on the stack above (and because of wellformedness is coinductive).
2700 /// In an "ideal" world, this would share a stack with trait predicates in
2701 /// `TraitObligationStack`. However, trait predicates are *much* hotter than
2702 /// `WellFormed` predicates, and it's very likely that the additional matches
2703 /// will have a perf effect. The value here is the well-formed `GenericArg`
2704 /// and the depth of the trait predicate *above* that well-formed predicate.
2705 wf_args: RefCell<Vec<(ty::GenericArg<'tcx>, usize)>>,
2708 /// A cache value for the provisional cache: contains the depth-first
2709 /// number (DFN) and result.
2710 #[derive(Copy, Clone, Debug)]
2711 struct ProvisionalEvaluation {
2713 reached_depth: usize,
2714 result: EvaluationResult,
2717 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2718 fn default() -> Self {
2719 Self { dfn: Cell::new(0), map: Default::default(), wf_args: Default::default() }
2723 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2724 /// Get the next DFN in sequence (basically a counter).
2725 fn next_dfn(&self) -> usize {
2726 let result = self.dfn.get();
2727 self.dfn.set(result + 1);
2731 /// Check the provisional cache for any result for
2732 /// `fresh_trait_ref`. If there is a hit, then you must consider
2733 /// it an access to the stack slots at depth
2734 /// `reached_depth` (from the returned value).
2737 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2738 ) -> Option<ProvisionalEvaluation> {
2741 "get_provisional = {:#?}",
2742 self.map.borrow().get(&fresh_trait_pred),
2744 Some(*self.map.borrow().get(&fresh_trait_pred)?)
2747 /// Insert a provisional result into the cache. The result came
2748 /// from the node with the given DFN. It accessed a minimum depth
2749 /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
2750 /// and resulted in `result`.
2751 fn insert_provisional(
2754 reached_depth: usize,
2755 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2756 result: EvaluationResult,
2758 debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
2760 let mut map = self.map.borrow_mut();
2762 // Subtle: when we complete working on the DFN `from_dfn`, anything
2763 // that remains in the provisional cache must be dependent on some older
2764 // stack entry than `from_dfn`. We have to update their depth with our transitive
2765 // depth in that case or else it would be referring to some popped note.
2768 // A (reached depth 0)
2770 // B // depth 1 -- reached depth = 0
2771 // C // depth 2 -- reached depth = 1 (should be 0)
2774 // D (reached depth 1)
2775 // C (cache -- reached depth = 2)
2776 for (_k, v) in &mut *map {
2777 if v.from_dfn >= from_dfn {
2778 v.reached_depth = reached_depth.min(v.reached_depth);
2782 map.insert(fresh_trait_pred, ProvisionalEvaluation { from_dfn, reached_depth, result });
2785 /// Invoked when the node with dfn `dfn` does not get a successful
2786 /// result. This will clear out any provisional cache entries
2787 /// that were added since `dfn` was created. This is because the
2788 /// provisional entries are things which must assume that the
2789 /// things on the stack at the time of their creation succeeded --
2790 /// since the failing node is presently at the top of the stack,
2791 /// these provisional entries must either depend on it or some
2793 fn on_failure(&self, dfn: usize) {
2794 debug!(?dfn, "on_failure");
2795 self.map.borrow_mut().retain(|key, eval| {
2796 if !eval.from_dfn >= dfn {
2797 debug!("on_failure: removing {:?}", key);
2805 /// Invoked when the node at depth `depth` completed without
2806 /// depending on anything higher in the stack (if that completion
2807 /// was a failure, then `on_failure` should have been invoked
2810 /// Note that we may still have provisional cache items remaining
2811 /// in the cache when this is done. For example, if there is a
2814 /// * A depends on...
2815 /// * B depends on A
2816 /// * C depends on...
2817 /// * D depends on C
2820 /// Then as we complete the C node we will have a provisional cache
2821 /// with results for A, B, C, and D. This method would clear out
2822 /// the C and D results, but leave A and B provisional.
2824 /// This is determined based on the DFN: we remove any provisional
2825 /// results created since `dfn` started (e.g., in our example, dfn
2826 /// would be 2, representing the C node, and hence we would
2827 /// remove the result for D, which has DFN 3, but not the results for
2828 /// A and B, which have DFNs 0 and 1 respectively).
2830 /// Note that we *do not* attempt to cache these cycle participants
2831 /// in the evaluation cache. Doing so would require carefully computing
2832 /// the correct `DepNode` to store in the cache entry:
2833 /// cycle participants may implicitly depend on query results
2834 /// related to other participants in the cycle, due to our logic
2835 /// which examines the evaluation stack.
2837 /// We used to try to perform this caching,
2838 /// but it lead to multiple incremental compilation ICEs
2839 /// (see #92987 and #96319), and was very hard to understand.
2840 /// Fortunately, removing the caching didn't seem to
2841 /// have a performance impact in practice.
2842 fn on_completion(&self, dfn: usize) {
2843 debug!(?dfn, "on_completion");
2845 for (fresh_trait_pred, eval) in
2846 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2848 debug!(?fresh_trait_pred, ?eval, "on_completion");
2853 #[derive(Copy, Clone)]
2854 struct TraitObligationStackList<'o, 'tcx> {
2855 cache: &'o ProvisionalEvaluationCache<'tcx>,
2856 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2859 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2860 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2861 TraitObligationStackList { cache, head: None }
2864 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2865 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2868 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2872 fn depth(&self) -> usize {
2873 if let Some(head) = self.head { head.depth } else { 0 }
2877 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2878 type Item = &'o TraitObligationStack<'o, 'tcx>;
2880 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2887 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2888 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2889 write!(f, "TraitObligationStack({:?})", self.obligation)
2893 pub enum ProjectionMatchesProjection {