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 use self::EvaluationResult::*;
6 use self::SelectionCandidate::*;
8 use super::coherence::{self, Conflict};
9 use super::const_evaluatable;
11 use super::project::normalize_with_depth_to;
12 use super::project::ProjectionTyObligation;
14 use super::util::{closure_trait_ref_and_return_type, predicate_for_trait_def};
16 use super::DerivedObligationCause;
17 use super::Obligation;
18 use super::ObligationCauseCode;
20 use super::SelectionResult;
21 use super::TraitQueryMode;
22 use super::{Normalized, ProjectionCacheKey};
23 use super::{ObligationCause, PredicateObligation, TraitObligation};
24 use super::{Overflow, SelectionError, Unimplemented};
26 use crate::infer::{InferCtxt, InferOk, TypeFreshener};
27 use crate::traits::error_reporting::InferCtxtExt;
28 use crate::traits::project::ProjectionCacheKeyExt;
29 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
30 use rustc_data_structures::stack::ensure_sufficient_stack;
31 use rustc_errors::ErrorReported;
33 use rustc_hir::def_id::DefId;
34 use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
35 use rustc_middle::mir::interpret::ErrorHandled;
36 use rustc_middle::ty::fast_reject;
37 use rustc_middle::ty::print::with_no_trimmed_paths;
38 use rustc_middle::ty::relate::TypeRelation;
39 use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef};
40 use rustc_middle::ty::{self, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate};
41 use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable, WithConstness};
42 use rustc_span::symbol::sym;
44 use std::cell::{Cell, RefCell};
46 use std::fmt::{self, Display};
50 pub use rustc_middle::traits::select::*;
52 mod candidate_assembly;
55 #[derive(Clone, Debug)]
56 pub enum IntercrateAmbiguityCause {
57 DownstreamCrate { trait_desc: String, self_desc: Option<String> },
58 UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
59 ReservationImpl { message: String },
62 impl IntercrateAmbiguityCause {
63 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
64 /// See #23980 for details.
65 pub fn add_intercrate_ambiguity_hint(&self, err: &mut rustc_errors::DiagnosticBuilder<'_>) {
66 err.note(&self.intercrate_ambiguity_hint());
69 pub fn intercrate_ambiguity_hint(&self) -> String {
71 &IntercrateAmbiguityCause::DownstreamCrate { ref trait_desc, ref self_desc } => {
72 let self_desc = if let &Some(ref ty) = self_desc {
73 format!(" for type `{}`", ty)
77 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
79 &IntercrateAmbiguityCause::UpstreamCrateUpdate { ref trait_desc, ref self_desc } => {
80 let self_desc = if let &Some(ref ty) = self_desc {
81 format!(" for type `{}`", ty)
86 "upstream crates may add a new impl of trait `{}`{} \
91 &IntercrateAmbiguityCause::ReservationImpl { ref message } => message.clone(),
96 pub struct SelectionContext<'cx, 'tcx> {
97 infcx: &'cx InferCtxt<'cx, 'tcx>,
99 /// Freshener used specifically for entries on the obligation
100 /// stack. This ensures that all entries on the stack at one time
101 /// will have the same set of placeholder entries, which is
102 /// important for checking for trait bounds that recursively
103 /// require themselves.
104 freshener: TypeFreshener<'cx, 'tcx>,
106 /// If `true`, indicates that the evaluation should be conservative
107 /// and consider the possibility of types outside this crate.
108 /// This comes up primarily when resolving ambiguity. Imagine
109 /// there is some trait reference `$0: Bar` where `$0` is an
110 /// inference variable. If `intercrate` is true, then we can never
111 /// say for sure that this reference is not implemented, even if
112 /// there are *no impls at all for `Bar`*, because `$0` could be
113 /// bound to some type that in a downstream crate that implements
114 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
115 /// though, we set this to false, because we are only interested
116 /// in types that the user could actually have written --- in
117 /// other words, we consider `$0: Bar` to be unimplemented if
118 /// there is no type that the user could *actually name* that
119 /// would satisfy it. This avoids crippling inference, basically.
122 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
124 /// Controls whether or not to filter out negative impls when selecting.
125 /// This is used in librustdoc to distinguish between the lack of an impl
126 /// and a negative impl
127 allow_negative_impls: bool,
129 /// The mode that trait queries run in, which informs our error handling
130 /// policy. In essence, canonicalized queries need their errors propagated
131 /// rather than immediately reported because we do not have accurate spans.
132 query_mode: TraitQueryMode,
135 // A stack that walks back up the stack frame.
136 struct TraitObligationStack<'prev, 'tcx> {
137 obligation: &'prev TraitObligation<'tcx>,
139 /// The trait ref from `obligation` but "freshened" with the
140 /// selection-context's freshener. Used to check for recursion.
141 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
143 /// Starts out equal to `depth` -- if, during evaluation, we
144 /// encounter a cycle, then we will set this flag to the minimum
145 /// depth of that cycle for all participants in the cycle. These
146 /// participants will then forego caching their results. This is
147 /// not the most efficient solution, but it addresses #60010. The
148 /// problem we are trying to prevent:
150 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
151 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
152 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
154 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
155 /// is `EvaluatedToOk`; this is because they were only considered
156 /// ok on the premise that if `A: AutoTrait` held, but we indeed
157 /// encountered a problem (later on) with `A: AutoTrait. So we
158 /// currently set a flag on the stack node for `B: AutoTrait` (as
159 /// well as the second instance of `A: AutoTrait`) to suppress
162 /// This is a simple, targeted fix. A more-performant fix requires
163 /// deeper changes, but would permit more caching: we could
164 /// basically defer caching until we have fully evaluated the
165 /// tree, and then cache the entire tree at once. In any case, the
166 /// performance impact here shouldn't be so horrible: every time
167 /// this is hit, we do cache at least one trait, so we only
168 /// evaluate each member of a cycle up to N times, where N is the
169 /// length of the cycle. This means the performance impact is
170 /// bounded and we shouldn't have any terrible worst-cases.
171 reached_depth: Cell<usize>,
173 previous: TraitObligationStackList<'prev, 'tcx>,
175 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
178 /// The depth-first number of this node in the search graph -- a
179 /// pre-order index. Basically, a freshly incremented counter.
183 struct SelectionCandidateSet<'tcx> {
184 // A list of candidates that definitely apply to the current
185 // obligation (meaning: types unify).
186 vec: Vec<SelectionCandidate<'tcx>>,
188 // If `true`, then there were candidates that might or might
189 // not have applied, but we couldn't tell. This occurs when some
190 // of the input types are type variables, in which case there are
191 // various "builtin" rules that might or might not trigger.
195 #[derive(PartialEq, Eq, Debug, Clone)]
196 struct EvaluatedCandidate<'tcx> {
197 candidate: SelectionCandidate<'tcx>,
198 evaluation: EvaluationResult,
201 /// When does the builtin impl for `T: Trait` apply?
202 enum BuiltinImplConditions<'tcx> {
203 /// The impl is conditional on `T1, T2, ...: Trait`.
204 Where(ty::Binder<Vec<Ty<'tcx>>>),
205 /// There is no built-in impl. There may be some other
206 /// candidate (a where-clause or user-defined impl).
208 /// It is unknown whether there is an impl.
212 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
213 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
216 freshener: infcx.freshener(),
218 intercrate_ambiguity_causes: None,
219 allow_negative_impls: false,
220 query_mode: TraitQueryMode::Standard,
224 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
227 freshener: infcx.freshener(),
229 intercrate_ambiguity_causes: None,
230 allow_negative_impls: false,
231 query_mode: TraitQueryMode::Standard,
235 pub fn with_negative(
236 infcx: &'cx InferCtxt<'cx, 'tcx>,
237 allow_negative_impls: bool,
238 ) -> SelectionContext<'cx, 'tcx> {
239 debug!(?allow_negative_impls, "with_negative");
242 freshener: infcx.freshener(),
244 intercrate_ambiguity_causes: None,
245 allow_negative_impls,
246 query_mode: TraitQueryMode::Standard,
250 pub fn with_query_mode(
251 infcx: &'cx InferCtxt<'cx, 'tcx>,
252 query_mode: TraitQueryMode,
253 ) -> SelectionContext<'cx, 'tcx> {
254 debug!(?query_mode, "with_query_mode");
257 freshener: infcx.freshener(),
259 intercrate_ambiguity_causes: None,
260 allow_negative_impls: false,
265 /// Enables tracking of intercrate ambiguity causes. These are
266 /// used in coherence to give improved diagnostics. We don't do
267 /// this until we detect a coherence error because it can lead to
268 /// false overflow results (#47139) and because it costs
269 /// computation time.
270 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
271 assert!(self.intercrate);
272 assert!(self.intercrate_ambiguity_causes.is_none());
273 self.intercrate_ambiguity_causes = Some(vec![]);
274 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
277 /// Gets the intercrate ambiguity causes collected since tracking
278 /// was enabled and disables tracking at the same time. If
279 /// tracking is not enabled, just returns an empty vector.
280 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
281 assert!(self.intercrate);
282 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
285 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
289 pub fn tcx(&self) -> TyCtxt<'tcx> {
293 ///////////////////////////////////////////////////////////////////////////
296 // The selection phase tries to identify *how* an obligation will
297 // be resolved. For example, it will identify which impl or
298 // parameter bound is to be used. The process can be inconclusive
299 // if the self type in the obligation is not fully inferred. Selection
300 // can result in an error in one of two ways:
302 // 1. If no applicable impl or parameter bound can be found.
303 // 2. If the output type parameters in the obligation do not match
304 // those specified by the impl/bound. For example, if the obligation
305 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
306 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
308 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
309 /// type environment by performing unification.
310 #[instrument(level = "debug", skip(self))]
313 obligation: &TraitObligation<'tcx>,
314 ) -> SelectionResult<'tcx, Selection<'tcx>> {
315 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
317 let pec = &ProvisionalEvaluationCache::default();
318 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
320 let candidate = match self.candidate_from_obligation(&stack) {
321 Err(SelectionError::Overflow) => {
322 // In standard mode, overflow must have been caught and reported
324 assert!(self.query_mode == TraitQueryMode::Canonical);
325 return Err(SelectionError::Overflow);
333 Ok(Some(candidate)) => candidate,
336 match self.confirm_candidate(obligation, candidate) {
337 Err(SelectionError::Overflow) => {
338 assert!(self.query_mode == TraitQueryMode::Canonical);
339 Err(SelectionError::Overflow)
349 ///////////////////////////////////////////////////////////////////////////
352 // Tests whether an obligation can be selected or whether an impl
353 // can be applied to particular types. It skips the "confirmation"
354 // step and hence completely ignores output type parameters.
356 // The result is "true" if the obligation *may* hold and "false" if
357 // we can be sure it does not.
359 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
360 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
361 debug!(?obligation, "predicate_may_hold_fatal");
363 // This fatal query is a stopgap that should only be used in standard mode,
364 // where we do not expect overflow to be propagated.
365 assert!(self.query_mode == TraitQueryMode::Standard);
367 self.evaluate_root_obligation(obligation)
368 .expect("Overflow should be caught earlier in standard query mode")
372 /// Evaluates whether the obligation `obligation` can be satisfied
373 /// and returns an `EvaluationResult`. This is meant for the
375 pub fn evaluate_root_obligation(
377 obligation: &PredicateObligation<'tcx>,
378 ) -> Result<EvaluationResult, OverflowError> {
379 self.evaluation_probe(|this| {
380 this.evaluate_predicate_recursively(
381 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
389 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
390 ) -> Result<EvaluationResult, OverflowError> {
391 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
392 let result = op(self)?;
394 match self.infcx.leak_check(true, snapshot) {
396 Err(_) => return Ok(EvaluatedToErr),
399 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
401 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
406 /// Evaluates the predicates in `predicates` recursively. Note that
407 /// this applies projections in the predicates, and therefore
408 /// is run within an inference probe.
409 fn evaluate_predicates_recursively<'o, I>(
411 stack: TraitObligationStackList<'o, 'tcx>,
413 ) -> Result<EvaluationResult, OverflowError>
415 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
417 let mut result = EvaluatedToOk;
418 debug!(?predicates, "evaluate_predicates_recursively");
419 for obligation in predicates {
420 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
421 if let EvaluatedToErr = eval {
422 // fast-path - EvaluatedToErr is the top of the lattice,
423 // so we don't need to look on the other predicates.
424 return Ok(EvaluatedToErr);
426 result = cmp::max(result, eval);
434 skip(self, previous_stack),
435 fields(previous_stack = ?previous_stack.head())
437 fn evaluate_predicate_recursively<'o>(
439 previous_stack: TraitObligationStackList<'o, 'tcx>,
440 obligation: PredicateObligation<'tcx>,
441 ) -> Result<EvaluationResult, OverflowError> {
442 // `previous_stack` stores a `TraitObligation`, while `obligation` is
443 // a `PredicateObligation`. These are distinct types, so we can't
444 // use any `Option` combinator method that would force them to be
446 match previous_stack.head() {
447 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
448 None => self.check_recursion_limit(&obligation, &obligation)?,
451 let result = ensure_sufficient_stack(|| {
452 match obligation.predicate.skip_binders() {
453 ty::PredicateAtom::Trait(t, _) => {
454 let t = ty::Binder::bind(t);
455 debug_assert!(!t.has_escaping_bound_vars());
456 let obligation = obligation.with(t);
457 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
460 ty::PredicateAtom::Subtype(p) => {
461 let p = ty::Binder::bind(p);
462 // Does this code ever run?
463 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
464 Some(Ok(InferOk { mut obligations, .. })) => {
465 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
466 self.evaluate_predicates_recursively(
468 obligations.into_iter(),
471 Some(Err(_)) => Ok(EvaluatedToErr),
472 None => Ok(EvaluatedToAmbig),
476 ty::PredicateAtom::WellFormed(arg) => match wf::obligations(
478 obligation.param_env,
479 obligation.cause.body_id,
480 obligation.recursion_depth + 1,
482 obligation.cause.span,
484 Some(mut obligations) => {
485 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
486 self.evaluate_predicates_recursively(previous_stack, obligations)
488 None => Ok(EvaluatedToAmbig),
491 ty::PredicateAtom::TypeOutlives(..) | ty::PredicateAtom::RegionOutlives(..) => {
492 // We do not consider region relationships when evaluating trait matches.
493 Ok(EvaluatedToOkModuloRegions)
496 ty::PredicateAtom::ObjectSafe(trait_def_id) => {
497 if self.tcx().is_object_safe(trait_def_id) {
504 ty::PredicateAtom::Projection(data) => {
505 let data = ty::Binder::bind(data);
506 let project_obligation = obligation.with(data);
507 match project::poly_project_and_unify_type(self, &project_obligation) {
508 Ok(Ok(Some(mut subobligations))) => {
509 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
511 .evaluate_predicates_recursively(previous_stack, subobligations);
513 ProjectionCacheKey::from_poly_projection_predicate(self, data)
515 self.infcx.inner.borrow_mut().projection_cache().complete(key);
519 Ok(Ok(None)) => Ok(EvaluatedToAmbig),
520 // EvaluatedToRecur might also be acceptable here, but use
521 // Unknown for now because it means that we won't dismiss a
522 // selection candidate solely because it has a projection
523 // cycle. This is closest to the previous behavior of
524 // immediately erroring.
525 Ok(Err(project::InProgress)) => Ok(EvaluatedToUnknown),
526 Err(_) => Ok(EvaluatedToErr),
530 ty::PredicateAtom::ClosureKind(_, closure_substs, kind) => {
531 match self.infcx.closure_kind(closure_substs) {
532 Some(closure_kind) => {
533 if closure_kind.extends(kind) {
539 None => Ok(EvaluatedToAmbig),
543 ty::PredicateAtom::ConstEvaluatable(def_id, substs) => {
544 match const_evaluatable::is_const_evaluatable(
548 obligation.param_env,
549 obligation.cause.span,
551 Ok(()) => Ok(EvaluatedToOk),
552 Err(ErrorHandled::TooGeneric) => Ok(EvaluatedToAmbig),
553 Err(_) => Ok(EvaluatedToErr),
557 ty::PredicateAtom::ConstEquate(c1, c2) => {
558 debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
560 let evaluate = |c: &'tcx ty::Const<'tcx>| {
561 if let ty::ConstKind::Unevaluated(def, substs, promoted) = c.val {
564 obligation.param_env,
568 Some(obligation.cause.span),
570 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty))
576 match (evaluate(c1), evaluate(c2)) {
577 (Ok(c1), Ok(c2)) => {
580 .at(&obligation.cause, obligation.param_env)
583 Ok(_) => Ok(EvaluatedToOk),
584 Err(_) => Ok(EvaluatedToErr),
587 (Err(ErrorHandled::Reported(ErrorReported)), _)
588 | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
589 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
591 obligation.cause.span(self.tcx()),
592 "ConstEquate: const_eval_resolve returned an unexpected error"
595 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
600 ty::PredicateAtom::TypeWellFormedFromEnv(..) => {
601 bug!("TypeWellFormedFromEnv is only used for chalk")
611 fn evaluate_trait_predicate_recursively<'o>(
613 previous_stack: TraitObligationStackList<'o, 'tcx>,
614 mut obligation: TraitObligation<'tcx>,
615 ) -> Result<EvaluationResult, OverflowError> {
616 debug!(?obligation, "evaluate_trait_predicate_recursively");
619 && obligation.is_global()
620 && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst())
622 // If a param env has no global bounds, global obligations do not
623 // depend on its particular value in order to work, so we can clear
624 // out the param env and get better caching.
625 debug!("evaluate_trait_predicate_recursively - in global");
626 obligation.param_env = obligation.param_env.without_caller_bounds();
629 let stack = self.push_stack(previous_stack, &obligation);
630 let fresh_trait_ref = stack.fresh_trait_ref;
632 debug!(?fresh_trait_ref);
634 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
635 debug!(?result, "CACHE HIT");
639 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
640 debug!(?result, "PROVISIONAL CACHE HIT");
641 stack.update_reached_depth(stack.cache().current_reached_depth());
645 // Check if this is a match for something already on the
646 // stack. If so, we don't want to insert the result into the
647 // main cache (it is cycle dependent) nor the provisional
648 // cache (which is meant for things that have completed but
649 // for a "backedge" -- this result *is* the backedge).
650 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
651 return Ok(cycle_result);
654 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
655 let result = result?;
657 if !result.must_apply_modulo_regions() {
658 stack.cache().on_failure(stack.dfn);
661 let reached_depth = stack.reached_depth.get();
662 if reached_depth >= stack.depth {
663 debug!(?result, "CACHE MISS");
664 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
666 stack.cache().on_completion(stack.depth, |fresh_trait_ref, provisional_result| {
667 self.insert_evaluation_cache(
668 obligation.param_env,
671 provisional_result.max(result),
675 debug!(?result, "PROVISIONAL");
677 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
678 is a cycle participant (at depth {}, reached depth {})",
679 fresh_trait_ref, stack.depth, reached_depth,
682 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
688 /// If there is any previous entry on the stack that precisely
689 /// matches this obligation, then we can assume that the
690 /// obligation is satisfied for now (still all other conditions
691 /// must be met of course). One obvious case this comes up is
692 /// marker traits like `Send`. Think of a linked list:
694 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
696 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
697 /// `Option<Box<List<T>>>` is `Send`, and in turn
698 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
701 /// Note that we do this comparison using the `fresh_trait_ref`
702 /// fields. Because these have all been freshened using
703 /// `self.freshener`, we can be sure that (a) this will not
704 /// affect the inferencer state and (b) that if we see two
705 /// fresh regions with the same index, they refer to the same
706 /// unbound type variable.
707 fn check_evaluation_cycle(
709 stack: &TraitObligationStack<'_, 'tcx>,
710 ) -> Option<EvaluationResult> {
711 if let Some(cycle_depth) = stack
713 .skip(1) // Skip top-most frame.
715 stack.obligation.param_env == prev.obligation.param_env
716 && stack.fresh_trait_ref == prev.fresh_trait_ref
718 .map(|stack| stack.depth)
720 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
722 // If we have a stack like `A B C D E A`, where the top of
723 // the stack is the final `A`, then this will iterate over
724 // `A, E, D, C, B` -- i.e., all the participants apart
725 // from the cycle head. We mark them as participating in a
726 // cycle. This suppresses caching for those nodes. See
727 // `in_cycle` field for more details.
728 stack.update_reached_depth(cycle_depth);
730 // Subtle: when checking for a coinductive cycle, we do
731 // not compare using the "freshened trait refs" (which
732 // have erased regions) but rather the fully explicit
733 // trait refs. This is important because it's only a cycle
734 // if the regions match exactly.
735 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
736 let tcx = self.tcx();
738 cycle.map(|stack| stack.obligation.predicate.without_const().to_predicate(tcx));
739 if self.coinductive_match(cycle) {
740 debug!("evaluate_stack --> recursive, coinductive");
743 debug!("evaluate_stack --> recursive, inductive");
744 Some(EvaluatedToRecur)
751 fn evaluate_stack<'o>(
753 stack: &TraitObligationStack<'o, 'tcx>,
754 ) -> Result<EvaluationResult, OverflowError> {
755 // In intercrate mode, whenever any of the generics are unbound,
756 // there can always be an impl. Even if there are no impls in
757 // this crate, perhaps the type would be unified with
758 // something from another crate that does provide an impl.
760 // In intra mode, we must still be conservative. The reason is
761 // that we want to avoid cycles. Imagine an impl like:
763 // impl<T:Eq> Eq for Vec<T>
765 // and a trait reference like `$0 : Eq` where `$0` is an
766 // unbound variable. When we evaluate this trait-reference, we
767 // will unify `$0` with `Vec<$1>` (for some fresh variable
768 // `$1`), on the condition that `$1 : Eq`. We will then wind
769 // up with many candidates (since that are other `Eq` impls
770 // that apply) and try to winnow things down. This results in
771 // a recursive evaluation that `$1 : Eq` -- as you can
772 // imagine, this is just where we started. To avoid that, we
773 // check for unbound variables and return an ambiguous (hence possible)
774 // match if we've seen this trait before.
776 // This suffices to allow chains like `FnMut` implemented in
777 // terms of `Fn` etc, but we could probably make this more
779 let unbound_input_types =
780 stack.fresh_trait_ref.skip_binder().substs.types().any(|ty| ty.is_fresh());
781 // This check was an imperfect workaround for a bug in the old
782 // intercrate mode; it should be removed when that goes away.
783 if unbound_input_types && self.intercrate {
784 debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
785 // Heuristics: show the diagnostics when there are no candidates in crate.
786 if self.intercrate_ambiguity_causes.is_some() {
787 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
788 if let Ok(candidate_set) = self.assemble_candidates(stack) {
789 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
790 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
791 let self_ty = trait_ref.self_ty();
793 with_no_trimmed_paths(|| IntercrateAmbiguityCause::DownstreamCrate {
794 trait_desc: trait_ref.print_only_trait_path().to_string(),
795 self_desc: if self_ty.has_concrete_skeleton() {
796 Some(self_ty.to_string())
802 debug!(?cause, "evaluate_stack: pushing cause");
803 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
807 return Ok(EvaluatedToAmbig);
809 if unbound_input_types
810 && stack.iter().skip(1).any(|prev| {
811 stack.obligation.param_env == prev.obligation.param_env
812 && self.match_fresh_trait_refs(
813 stack.fresh_trait_ref,
814 prev.fresh_trait_ref,
815 prev.obligation.param_env,
819 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
820 return Ok(EvaluatedToUnknown);
823 match self.candidate_from_obligation(stack) {
824 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
825 Ok(None) => Ok(EvaluatedToAmbig),
826 Err(Overflow) => Err(OverflowError),
827 Err(..) => Ok(EvaluatedToErr),
831 /// For defaulted traits, we use a co-inductive strategy to solve, so
832 /// that recursion is ok. This routine returns `true` if the top of the
833 /// stack (`cycle[0]`):
835 /// - is a defaulted trait,
836 /// - it also appears in the backtrace at some position `X`,
837 /// - all the predicates at positions `X..` between `X` and the top are
838 /// also defaulted traits.
839 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
841 I: Iterator<Item = ty::Predicate<'tcx>>,
843 let mut cycle = cycle;
844 cycle.all(|predicate| self.coinductive_predicate(predicate))
847 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
848 let result = match predicate.skip_binders() {
849 ty::PredicateAtom::Trait(ref data, _) => self.tcx().trait_is_auto(data.def_id()),
852 debug!(?predicate, ?result, "coinductive_predicate");
856 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
857 /// obligations are met. Returns whether `candidate` remains viable after this further
862 fields(depth = stack.obligation.recursion_depth)
864 fn evaluate_candidate<'o>(
866 stack: &TraitObligationStack<'o, 'tcx>,
867 candidate: &SelectionCandidate<'tcx>,
868 ) -> Result<EvaluationResult, OverflowError> {
869 let result = self.evaluation_probe(|this| {
870 let candidate = (*candidate).clone();
871 match this.confirm_candidate(stack.obligation, candidate) {
874 this.evaluate_predicates_recursively(
876 selection.nested_obligations().into_iter(),
879 Err(..) => Ok(EvaluatedToErr),
886 fn check_evaluation_cache(
888 param_env: ty::ParamEnv<'tcx>,
889 trait_ref: ty::PolyTraitRef<'tcx>,
890 ) -> Option<EvaluationResult> {
891 let tcx = self.tcx();
892 if self.can_use_global_caches(param_env) {
893 if let Some(res) = tcx.evaluation_cache.get(¶m_env.and(trait_ref), tcx) {
897 self.infcx.evaluation_cache.get(¶m_env.and(trait_ref), tcx)
900 fn insert_evaluation_cache(
902 param_env: ty::ParamEnv<'tcx>,
903 trait_ref: ty::PolyTraitRef<'tcx>,
904 dep_node: DepNodeIndex,
905 result: EvaluationResult,
907 // Avoid caching results that depend on more than just the trait-ref
908 // - the stack can create recursion.
909 if result.is_stack_dependent() {
913 if self.can_use_global_caches(param_env) {
914 if !trait_ref.needs_infer() {
915 debug!(?trait_ref, ?result, "insert_evaluation_cache global");
916 // This may overwrite the cache with the same value
917 // FIXME: Due to #50507 this overwrites the different values
918 // This should be changed to use HashMapExt::insert_same
919 // when that is fixed
920 self.tcx().evaluation_cache.insert(param_env.and(trait_ref), dep_node, result);
925 debug!(?trait_ref, ?result, "insert_evaluation_cache");
926 self.infcx.evaluation_cache.insert(param_env.and(trait_ref), dep_node, result);
929 /// For various reasons, it's possible for a subobligation
930 /// to have a *lower* recursion_depth than the obligation used to create it.
931 /// Projection sub-obligations may be returned from the projection cache,
932 /// which results in obligations with an 'old' `recursion_depth`.
933 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
934 /// subobligations without taking in a 'parent' depth, causing the
935 /// generated subobligations to have a `recursion_depth` of `0`.
937 /// To ensure that obligation_depth never decreasees, we force all subobligations
938 /// to have at least the depth of the original obligation.
939 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
944 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
947 /// Checks that the recursion limit has not been exceeded.
949 /// The weird return type of this function allows it to be used with the `try` (`?`)
950 /// operator within certain functions.
951 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
953 obligation: &Obligation<'tcx, T>,
954 error_obligation: &Obligation<'tcx, V>,
955 ) -> Result<(), OverflowError> {
956 if !self.infcx.tcx.sess.recursion_limit().value_within_limit(obligation.recursion_depth) {
957 match self.query_mode {
958 TraitQueryMode::Standard => {
959 self.infcx().report_overflow_error(error_obligation, true);
961 TraitQueryMode::Canonical => {
962 return Err(OverflowError);
969 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
971 OP: FnOnce(&mut Self) -> R,
973 let (result, dep_node) =
974 self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || op(self));
975 self.tcx().dep_graph.read_index(dep_node);
979 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
980 fn filter_negative_and_reservation_impls(
982 candidate: SelectionCandidate<'tcx>,
983 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
984 if let ImplCandidate(def_id) = candidate {
985 let tcx = self.tcx();
986 match tcx.impl_polarity(def_id) {
987 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
988 return Err(Unimplemented);
990 ty::ImplPolarity::Reservation => {
991 if let Some(intercrate_ambiguity_clauses) =
992 &mut self.intercrate_ambiguity_causes
994 let attrs = tcx.get_attrs(def_id);
995 let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
996 let value = attr.and_then(|a| a.value_str());
997 if let Some(value) = value {
999 "filter_negative_and_reservation_impls: \
1000 reservation impl ambiguity on {:?}",
1003 intercrate_ambiguity_clauses.push(
1004 IntercrateAmbiguityCause::ReservationImpl {
1005 message: value.to_string(),
1018 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1019 debug!("is_knowable(intercrate={:?})", self.intercrate);
1021 if !self.intercrate {
1025 let obligation = &stack.obligation;
1026 let predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1028 // Okay to skip binder because of the nature of the
1029 // trait-ref-is-knowable check, which does not care about
1031 let trait_ref = predicate.skip_binder().trait_ref;
1033 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1036 /// Returns `true` if the global caches can be used.
1037 /// Do note that if the type itself is not in the
1038 /// global tcx, the local caches will be used.
1039 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1040 // If there are any inference variables in the `ParamEnv`, then we
1041 // always use a cache local to this particular scope. Otherwise, we
1042 // switch to a global cache.
1043 if param_env.needs_infer() {
1047 // Avoid using the master cache during coherence and just rely
1048 // on the local cache. This effectively disables caching
1049 // during coherence. It is really just a simplification to
1050 // avoid us having to fear that coherence results "pollute"
1051 // the master cache. Since coherence executes pretty quickly,
1052 // it's not worth going to more trouble to increase the
1053 // hit-rate, I don't think.
1054 if self.intercrate {
1058 // Otherwise, we can use the global cache.
1062 fn check_candidate_cache(
1064 param_env: ty::ParamEnv<'tcx>,
1065 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1066 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1067 let tcx = self.tcx();
1068 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1069 if self.can_use_global_caches(param_env) {
1070 if let Some(res) = tcx.selection_cache.get(¶m_env.and(*trait_ref), tcx) {
1074 self.infcx.selection_cache.get(¶m_env.and(*trait_ref), tcx)
1077 /// Determines whether can we safely cache the result
1078 /// of selecting an obligation. This is almost always `true`,
1079 /// except when dealing with certain `ParamCandidate`s.
1081 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1082 /// since it was usually produced directly from a `DefId`. However,
1083 /// certain cases (currently only librustdoc's blanket impl finder),
1084 /// a `ParamEnv` may be explicitly constructed with inference types.
1085 /// When this is the case, we do *not* want to cache the resulting selection
1086 /// candidate. This is due to the fact that it might not always be possible
1087 /// to equate the obligation's trait ref and the candidate's trait ref,
1088 /// if more constraints end up getting added to an inference variable.
1090 /// Because of this, we always want to re-run the full selection
1091 /// process for our obligation the next time we see it, since
1092 /// we might end up picking a different `SelectionCandidate` (or none at all).
1093 fn can_cache_candidate(
1095 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1098 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1103 fn insert_candidate_cache(
1105 param_env: ty::ParamEnv<'tcx>,
1106 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1107 dep_node: DepNodeIndex,
1108 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1110 let tcx = self.tcx();
1111 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1113 if !self.can_cache_candidate(&candidate) {
1114 debug!(?trait_ref, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1118 if self.can_use_global_caches(param_env) {
1119 if let Err(Overflow) = candidate {
1120 // Don't cache overflow globally; we only produce this in certain modes.
1121 } else if !trait_ref.needs_infer() {
1122 if !candidate.needs_infer() {
1123 debug!(?trait_ref, ?candidate, "insert_candidate_cache global");
1124 // This may overwrite the cache with the same value.
1125 tcx.selection_cache.insert(param_env.and(trait_ref), dep_node, candidate);
1131 debug!(?trait_ref, ?candidate, "insert_candidate_cache local");
1132 self.infcx.selection_cache.insert(param_env.and(trait_ref), dep_node, candidate);
1135 /// Matches a predicate against the bounds of its self type.
1137 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1138 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1139 /// `Baz` bound. We return indexes into the list returned by
1140 /// `tcx.item_bounds` for any applicable bounds.
1141 fn match_projection_obligation_against_definition_bounds(
1143 obligation: &TraitObligation<'tcx>,
1144 ) -> smallvec::SmallVec<[usize; 2]> {
1145 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1146 let placeholder_trait_predicate =
1147 self.infcx().replace_bound_vars_with_placeholders(&poly_trait_predicate);
1149 ?placeholder_trait_predicate,
1150 "match_projection_obligation_against_definition_bounds"
1153 let tcx = self.infcx.tcx;
1154 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1155 ty::Projection(ref data) => (data.item_def_id, data.substs),
1156 ty::Opaque(def_id, substs) => (def_id, substs),
1159 obligation.cause.span,
1160 "match_projection_obligation_against_definition_bounds() called \
1161 but self-ty is not a projection: {:?}",
1162 placeholder_trait_predicate.trait_ref.self_ty()
1166 let bounds = tcx.item_bounds(def_id).subst(tcx, substs);
1168 // The bounds returned by `item_bounds` may contain duplicates after
1169 // normalization, so try to deduplicate when possible to avoid
1170 // unnecessary ambiguity.
1171 let mut distinct_normalized_bounds = FxHashSet::default();
1173 let matching_bounds = bounds
1176 .filter_map(|(idx, bound)| {
1177 if let ty::PredicateAtom::Trait(pred, _) = bound.skip_binders() {
1178 let bound = ty::Binder::bind(pred.trait_ref);
1179 if self.infcx.probe(|_| {
1180 match self.match_projection(
1183 placeholder_trait_predicate.trait_ref,
1186 Ok(Some(normalized_trait))
1187 if distinct_normalized_bounds.insert(normalized_trait) =>
1201 debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds");
1205 /// Equates the trait in `obligation` with trait bound. If the two traits
1206 /// can be equated and the normalized trait bound doesn't contain inference
1207 /// variables or placeholders, the normalized bound is returned.
1208 fn match_projection(
1210 obligation: &TraitObligation<'tcx>,
1211 trait_bound: ty::PolyTraitRef<'tcx>,
1212 placeholder_trait_ref: ty::TraitRef<'tcx>,
1213 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1214 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1215 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1216 // Avoid unnecessary normalization
1220 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1221 project::normalize_with_depth(
1223 obligation.param_env,
1224 obligation.cause.clone(),
1225 obligation.recursion_depth + 1,
1230 .at(&obligation.cause, obligation.param_env)
1231 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1232 .map(|InferOk { obligations: _, value: () }| {
1233 // This method is called within a probe, so we can't have
1234 // inference variables and placeholders escape.
1235 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1244 fn evaluate_where_clause<'o>(
1246 stack: &TraitObligationStack<'o, 'tcx>,
1247 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1248 ) -> Result<EvaluationResult, OverflowError> {
1249 self.evaluation_probe(|this| {
1250 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1251 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1252 Err(()) => Ok(EvaluatedToErr),
1257 pub(super) fn match_projection_projections(
1259 obligation: &ProjectionTyObligation<'tcx>,
1260 obligation_trait_ref: &ty::TraitRef<'tcx>,
1261 data: &PolyProjectionPredicate<'tcx>,
1262 potentially_unnormalized_candidates: bool,
1264 let mut nested_obligations = Vec::new();
1265 let projection_ty = if potentially_unnormalized_candidates {
1266 ensure_sufficient_stack(|| {
1267 project::normalize_with_depth_to(
1269 obligation.param_env,
1270 obligation.cause.clone(),
1271 obligation.recursion_depth + 1,
1272 &data.map_bound_ref(|data| data.projection_ty),
1273 &mut nested_obligations,
1277 data.map_bound_ref(|data| data.projection_ty)
1280 // FIXME(generic_associated_types): Compare the whole projections
1281 let data_poly_trait_ref = projection_ty.map_bound(|proj| proj.trait_ref(self.tcx()));
1282 let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
1284 .at(&obligation.cause, obligation.param_env)
1285 .sup(obligation_poly_trait_ref, data_poly_trait_ref)
1286 .map_or(false, |InferOk { obligations, value: () }| {
1287 self.evaluate_predicates_recursively(
1288 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1289 nested_obligations.into_iter().chain(obligations),
1291 .map_or(false, |res| res.may_apply())
1295 ///////////////////////////////////////////////////////////////////////////
1298 // Winnowing is the process of attempting to resolve ambiguity by
1299 // probing further. During the winnowing process, we unify all
1300 // type variables and then we also attempt to evaluate recursive
1301 // bounds to see if they are satisfied.
1303 /// Returns `true` if `victim` should be dropped in favor of
1304 /// `other`. Generally speaking we will drop duplicate
1305 /// candidates and prefer where-clause candidates.
1307 /// See the comment for "SelectionCandidate" for more details.
1308 fn candidate_should_be_dropped_in_favor_of(
1310 victim: &EvaluatedCandidate<'tcx>,
1311 other: &EvaluatedCandidate<'tcx>,
1314 if victim.candidate == other.candidate {
1318 // Check if a bound would previously have been removed when normalizing
1319 // the param_env so that it can be given the lowest priority. See
1320 // #50825 for the motivation for this.
1322 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
1324 // (*) Prefer `BuiltinCandidate { has_nested: false }` and `DiscriminantKindCandidate`
1325 // to anything else.
1327 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1328 // lifetime of a variable.
1329 match (&other.candidate, &victim.candidate) {
1330 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1332 "default implementations shouldn't be recorded \
1333 when there are other valid candidates"
1338 (BuiltinCandidate { has_nested: false } | DiscriminantKindCandidate, _) => true,
1339 (_, BuiltinCandidate { has_nested: false } | DiscriminantKindCandidate) => false,
1341 (ParamCandidate(..), ParamCandidate(..)) => false,
1343 // Global bounds from the where clause should be ignored
1344 // here (see issue #50825). Otherwise, we have a where
1345 // clause so don't go around looking for impls.
1346 // Arbitrarily give param candidates priority
1347 // over projection and object candidates.
1349 ParamCandidate(ref cand),
1352 | GeneratorCandidate
1353 | FnPointerCandidate
1354 | BuiltinObjectCandidate
1355 | BuiltinUnsizeCandidate
1356 | BuiltinCandidate { .. }
1357 | TraitAliasCandidate(..)
1359 | ProjectionCandidate(_),
1360 ) => !is_global(cand),
1361 (ObjectCandidate | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1362 // Prefer these to a global where-clause bound
1363 // (see issue #50825).
1369 | GeneratorCandidate
1370 | FnPointerCandidate
1371 | BuiltinObjectCandidate
1372 | BuiltinUnsizeCandidate
1373 | BuiltinCandidate { has_nested: true }
1374 | TraitAliasCandidate(..),
1375 ParamCandidate(ref cand),
1377 // Prefer these to a global where-clause bound
1378 // (see issue #50825).
1379 is_global(cand) && other.evaluation.must_apply_modulo_regions()
1382 (ProjectionCandidate(i), ProjectionCandidate(j)) => {
1383 // Arbitrarily pick the first candidate for backwards
1384 // compatibility reasons. Don't let this affect inference.
1385 i > j && !needs_infer
1387 (ObjectCandidate, ObjectCandidate) => bug!("Duplicate object candidate"),
1388 (ObjectCandidate, ProjectionCandidate(_))
1389 | (ProjectionCandidate(_), ObjectCandidate) => {
1390 bug!("Have both object and projection candidate")
1393 // Arbitrarily give projection and object candidates priority.
1395 ObjectCandidate | ProjectionCandidate(_),
1398 | GeneratorCandidate
1399 | FnPointerCandidate
1400 | BuiltinObjectCandidate
1401 | BuiltinUnsizeCandidate
1402 | BuiltinCandidate { .. }
1403 | TraitAliasCandidate(..),
1409 | GeneratorCandidate
1410 | FnPointerCandidate
1411 | BuiltinObjectCandidate
1412 | BuiltinUnsizeCandidate
1413 | BuiltinCandidate { .. }
1414 | TraitAliasCandidate(..),
1415 ObjectCandidate | ProjectionCandidate(_),
1418 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1419 // See if we can toss out `victim` based on specialization.
1420 // This requires us to know *for sure* that the `other` impl applies
1421 // i.e., `EvaluatedToOk`.
1422 if other.evaluation.must_apply_modulo_regions() {
1423 let tcx = self.tcx();
1424 if tcx.specializes((other_def, victim_def)) {
1427 return match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1428 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1429 // Subtle: If the predicate we are evaluating has inference
1430 // variables, do *not* allow discarding candidates due to
1431 // marker trait impls.
1433 // Without this restriction, we could end up accidentally
1434 // constrainting inference variables based on an arbitrarily
1435 // chosen trait impl.
1437 // Imagine we have the following code:
1440 // #[marker] trait MyTrait {}
1441 // impl MyTrait for u8 {}
1442 // impl MyTrait for bool {}
1445 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1447 // During selection, we will end up with one candidate for each
1448 // impl of `MyTrait`. If we were to discard one impl in favor
1449 // of the other, we would be left with one candidate, causing
1450 // us to "successfully" select the predicate, unifying
1451 // _#0t with (for example) `u8`.
1453 // However, we have no reason to believe that this unification
1454 // is correct - we've essentially just picked an arbitrary
1455 // *possibility* for _#0t, and required that this be the *only*
1458 // Eventually, we will either:
1459 // 1) Unify all inference variables in the predicate through
1460 // some other means (e.g. type-checking of a function). We will
1461 // then be in a position to drop marker trait candidates
1462 // without constraining inference variables (since there are
1463 // none left to constrin)
1464 // 2) Be left with some unconstrained inference variables. We
1465 // will then correctly report an inference error, since the
1466 // existence of multiple marker trait impls tells us nothing
1467 // about which one should actually apply.
1478 // Everything else is ambiguous
1482 | GeneratorCandidate
1483 | FnPointerCandidate
1484 | BuiltinObjectCandidate
1485 | BuiltinUnsizeCandidate
1486 | BuiltinCandidate { has_nested: true }
1487 | TraitAliasCandidate(..),
1490 | GeneratorCandidate
1491 | FnPointerCandidate
1492 | BuiltinObjectCandidate
1493 | BuiltinUnsizeCandidate
1494 | BuiltinCandidate { has_nested: true }
1495 | TraitAliasCandidate(..),
1500 fn sized_conditions(
1502 obligation: &TraitObligation<'tcx>,
1503 ) -> BuiltinImplConditions<'tcx> {
1504 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1506 // NOTE: binder moved to (*)
1507 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1509 match self_ty.kind() {
1510 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1521 | ty::GeneratorWitness(..)
1526 // safe for everything
1527 Where(ty::Binder::dummy(Vec::new()))
1530 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1533 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
1536 ty::Adt(def, substs) => {
1537 let sized_crit = def.sized_constraint(self.tcx());
1538 // (*) binder moved here
1539 Where(ty::Binder::bind(
1540 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect(),
1544 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1545 ty::Infer(ty::TyVar(_)) => Ambiguous,
1549 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1550 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1555 fn copy_clone_conditions(
1557 obligation: &TraitObligation<'tcx>,
1558 ) -> BuiltinImplConditions<'tcx> {
1559 // NOTE: binder moved to (*)
1560 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1562 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1564 match self_ty.kind() {
1565 ty::Infer(ty::IntVar(_))
1566 | ty::Infer(ty::FloatVar(_))
1569 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1578 | ty::Ref(_, _, hir::Mutability::Not) => {
1579 // Implementations provided in libcore
1587 | ty::GeneratorWitness(..)
1589 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1591 ty::Array(element_ty, _) => {
1592 // (*) binder moved here
1593 Where(ty::Binder::bind(vec![element_ty]))
1597 // (*) binder moved here
1598 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
1601 ty::Closure(_, substs) => {
1602 // (*) binder moved here
1603 Where(ty::Binder::bind(substs.as_closure().upvar_tys().collect()))
1606 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1607 // Fallback to whatever user-defined impls exist in this case.
1611 ty::Infer(ty::TyVar(_)) => {
1612 // Unbound type variable. Might or might not have
1613 // applicable impls and so forth, depending on what
1614 // those type variables wind up being bound to.
1620 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1621 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1626 /// For default impls, we need to break apart a type into its
1627 /// "constituent types" -- meaning, the types that it contains.
1629 /// Here are some (simple) examples:
1632 /// (i32, u32) -> [i32, u32]
1633 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1634 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1635 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1637 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
1647 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1649 | ty::Char => Vec::new(),
1655 | ty::Projection(..)
1657 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1658 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1661 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1665 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
1667 ty::Tuple(ref tys) => {
1668 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1669 tys.iter().map(|k| k.expect_ty()).collect()
1672 ty::Closure(_, ref substs) => substs.as_closure().upvar_tys().collect(),
1674 ty::Generator(_, ref substs, _) => {
1675 let witness = substs.as_generator().witness();
1676 substs.as_generator().upvar_tys().chain(iter::once(witness)).collect()
1679 ty::GeneratorWitness(types) => {
1680 // This is sound because no regions in the witness can refer to
1681 // the binder outside the witness. So we'll effectivly reuse
1682 // the implicit binder around the witness.
1683 types.skip_binder().to_vec()
1686 // For `PhantomData<T>`, we pass `T`.
1687 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
1689 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
1691 ty::Opaque(def_id, substs) => {
1692 // We can resolve the `impl Trait` to its concrete type,
1693 // which enforces a DAG between the functions requiring
1694 // the auto trait bounds in question.
1695 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
1700 fn collect_predicates_for_types(
1702 param_env: ty::ParamEnv<'tcx>,
1703 cause: ObligationCause<'tcx>,
1704 recursion_depth: usize,
1705 trait_def_id: DefId,
1706 types: ty::Binder<Vec<Ty<'tcx>>>,
1707 ) -> Vec<PredicateObligation<'tcx>> {
1708 // Because the types were potentially derived from
1709 // higher-ranked obligations they may reference late-bound
1710 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
1711 // yield a type like `for<'a> &'a i32`. In general, we
1712 // maintain the invariant that we never manipulate bound
1713 // regions, so we have to process these bound regions somehow.
1715 // The strategy is to:
1717 // 1. Instantiate those regions to placeholder regions (e.g.,
1718 // `for<'a> &'a i32` becomes `&0 i32`.
1719 // 2. Produce something like `&'0 i32 : Copy`
1720 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
1723 .skip_binder() // binder moved -\
1726 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
1728 self.infcx.commit_unconditionally(|_| {
1729 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(&ty);
1730 let Normalized { value: normalized_ty, mut obligations } =
1731 ensure_sufficient_stack(|| {
1732 project::normalize_with_depth(
1740 let placeholder_obligation = predicate_for_trait_def(
1749 obligations.push(placeholder_obligation);
1756 ///////////////////////////////////////////////////////////////////////////
1759 // Matching is a common path used for both evaluation and
1760 // confirmation. It basically unifies types that appear in impls
1761 // and traits. This does affect the surrounding environment;
1762 // therefore, when used during evaluation, match routines must be
1763 // run inside of a `probe()` so that their side-effects are
1769 obligation: &TraitObligation<'tcx>,
1770 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
1771 match self.match_impl(impl_def_id, obligation) {
1772 Ok(substs) => substs,
1775 "Impl {:?} was matchable against {:?} but now is not",
1786 obligation: &TraitObligation<'tcx>,
1787 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
1788 debug!(?impl_def_id, ?obligation, "match_impl");
1789 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
1791 // Before we create the substitutions and everything, first
1792 // consider a "quick reject". This avoids creating more types
1793 // and so forth that we need to.
1794 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
1798 let placeholder_obligation =
1799 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
1800 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
1802 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
1804 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
1806 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
1807 ensure_sufficient_stack(|| {
1808 project::normalize_with_depth(
1810 obligation.param_env,
1811 obligation.cause.clone(),
1812 obligation.recursion_depth + 1,
1817 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
1819 let InferOk { obligations, .. } = self
1821 .at(&obligation.cause, obligation.param_env)
1822 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
1823 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
1824 nested_obligations.extend(obligations);
1827 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
1829 debug!("match_impl: reservation impls only apply in intercrate mode");
1833 debug!(?impl_substs, "match_impl: success");
1834 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
1837 fn fast_reject_trait_refs(
1839 obligation: &TraitObligation<'_>,
1840 impl_trait_ref: &ty::TraitRef<'_>,
1842 // We can avoid creating type variables and doing the full
1843 // substitution if we find that any of the input types, when
1844 // simplified, do not match.
1846 obligation.predicate.skip_binder().trait_ref.substs.iter().zip(impl_trait_ref.substs).any(
1847 |(obligation_arg, impl_arg)| {
1848 match (obligation_arg.unpack(), impl_arg.unpack()) {
1849 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
1850 let simplified_obligation_ty =
1851 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
1852 let simplified_impl_ty =
1853 fast_reject::simplify_type(self.tcx(), impl_ty, false);
1855 simplified_obligation_ty.is_some()
1856 && simplified_impl_ty.is_some()
1857 && simplified_obligation_ty != simplified_impl_ty
1859 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
1860 // Lifetimes can never cause a rejection.
1863 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
1864 // Conservatively ignore consts (i.e. assume they might
1865 // unify later) until we have `fast_reject` support for
1866 // them (if we'll ever need it, even).
1869 _ => unreachable!(),
1875 /// Normalize `where_clause_trait_ref` and try to match it against
1876 /// `obligation`. If successful, return any predicates that
1877 /// result from the normalization. Normalization is necessary
1878 /// because where-clauses are stored in the parameter environment
1880 fn match_where_clause_trait_ref(
1882 obligation: &TraitObligation<'tcx>,
1883 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1884 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
1885 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
1888 /// Returns `Ok` if `poly_trait_ref` being true implies that the
1889 /// obligation is satisfied.
1890 fn match_poly_trait_ref(
1892 obligation: &TraitObligation<'tcx>,
1893 poly_trait_ref: ty::PolyTraitRef<'tcx>,
1894 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
1895 debug!(?obligation, ?poly_trait_ref, "match_poly_trait_ref");
1898 .at(&obligation.cause, obligation.param_env)
1899 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
1900 .map(|InferOk { obligations, .. }| obligations)
1904 ///////////////////////////////////////////////////////////////////////////
1907 fn match_fresh_trait_refs(
1909 previous: ty::PolyTraitRef<'tcx>,
1910 current: ty::PolyTraitRef<'tcx>,
1911 param_env: ty::ParamEnv<'tcx>,
1913 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
1914 matcher.relate(previous, current).is_ok()
1919 previous_stack: TraitObligationStackList<'o, 'tcx>,
1920 obligation: &'o TraitObligation<'tcx>,
1921 ) -> TraitObligationStack<'o, 'tcx> {
1922 let fresh_trait_ref =
1923 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
1925 let dfn = previous_stack.cache.next_dfn();
1926 let depth = previous_stack.depth() + 1;
1927 TraitObligationStack {
1930 reached_depth: Cell::new(depth),
1931 previous: previous_stack,
1937 fn closure_trait_ref_unnormalized(
1939 obligation: &TraitObligation<'tcx>,
1940 substs: SubstsRef<'tcx>,
1941 ) -> ty::PolyTraitRef<'tcx> {
1942 debug!(?obligation, ?substs, "closure_trait_ref_unnormalized");
1943 let closure_sig = substs.as_closure().sig();
1945 debug!(?closure_sig);
1947 // (1) Feels icky to skip the binder here, but OTOH we know
1948 // that the self-type is an unboxed closure type and hence is
1949 // in fact unparameterized (or at least does not reference any
1950 // regions bound in the obligation). Still probably some
1951 // refactoring could make this nicer.
1952 closure_trait_ref_and_return_type(
1954 obligation.predicate.def_id(),
1955 obligation.predicate.skip_binder().self_ty(), // (1)
1957 util::TupleArgumentsFlag::No,
1959 .map_bound(|(trait_ref, _)| trait_ref)
1962 fn generator_trait_ref_unnormalized(
1964 obligation: &TraitObligation<'tcx>,
1965 substs: SubstsRef<'tcx>,
1966 ) -> ty::PolyTraitRef<'tcx> {
1967 let gen_sig = substs.as_generator().poly_sig();
1969 // (1) Feels icky to skip the binder here, but OTOH we know
1970 // that the self-type is an generator type and hence is
1971 // in fact unparameterized (or at least does not reference any
1972 // regions bound in the obligation). Still probably some
1973 // refactoring could make this nicer.
1975 super::util::generator_trait_ref_and_outputs(
1977 obligation.predicate.def_id(),
1978 obligation.predicate.skip_binder().self_ty(), // (1)
1981 .map_bound(|(trait_ref, ..)| trait_ref)
1984 /// Returns the obligations that are implied by instantiating an
1985 /// impl or trait. The obligations are substituted and fully
1986 /// normalized. This is used when confirming an impl or default
1988 fn impl_or_trait_obligations(
1990 cause: ObligationCause<'tcx>,
1991 recursion_depth: usize,
1992 param_env: ty::ParamEnv<'tcx>,
1993 def_id: DefId, // of impl or trait
1994 substs: SubstsRef<'tcx>, // for impl or trait
1995 ) -> Vec<PredicateObligation<'tcx>> {
1996 debug!(?def_id, "impl_or_trait_obligations");
1997 let tcx = self.tcx();
1999 // To allow for one-pass evaluation of the nested obligation,
2000 // each predicate must be preceded by the obligations required
2002 // for example, if we have:
2003 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2004 // the impl will have the following predicates:
2005 // <V as Iterator>::Item = U,
2006 // U: Iterator, U: Sized,
2007 // V: Iterator, V: Sized,
2008 // <U as Iterator>::Item: Copy
2009 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2010 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2011 // `$1: Copy`, so we must ensure the obligations are emitted in
2013 let predicates = tcx.predicates_of(def_id);
2014 assert_eq!(predicates.parent, None);
2015 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2016 for (predicate, _) in predicates.predicates {
2017 let predicate = normalize_with_depth_to(
2022 &predicate.subst(tcx, substs),
2025 obligations.push(Obligation {
2026 cause: cause.clone(),
2033 // We are performing deduplication here to avoid exponential blowups
2034 // (#38528) from happening, but the real cause of the duplication is
2035 // unknown. What we know is that the deduplication avoids exponential
2036 // amount of predicates being propagated when processing deeply nested
2039 // This code is hot enough that it's worth avoiding the allocation
2040 // required for the FxHashSet when possible. Special-casing lengths 0,
2041 // 1 and 2 covers roughly 75-80% of the cases.
2042 if obligations.len() <= 1 {
2043 // No possibility of duplicates.
2044 } else if obligations.len() == 2 {
2045 // Only two elements. Drop the second if they are equal.
2046 if obligations[0] == obligations[1] {
2047 obligations.truncate(1);
2050 // Three or more elements. Use a general deduplication process.
2051 let mut seen = FxHashSet::default();
2052 obligations.retain(|i| seen.insert(i.clone()));
2059 trait TraitObligationExt<'tcx> {
2062 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2063 ) -> ObligationCause<'tcx>;
2066 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2069 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2070 ) -> ObligationCause<'tcx> {
2072 * Creates a cause for obligations that are derived from
2073 * `obligation` by a recursive search (e.g., for a builtin
2074 * bound, or eventually a `auto trait Foo`). If `obligation`
2075 * is itself a derived obligation, this is just a clone, but
2076 * otherwise we create a "derived obligation" cause so as to
2077 * keep track of the original root obligation for error
2081 let obligation = self;
2083 // NOTE(flaper87): As of now, it keeps track of the whole error
2084 // chain. Ideally, we should have a way to configure this either
2085 // by using -Z verbose or just a CLI argument.
2086 let derived_cause = DerivedObligationCause {
2087 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2088 parent_code: Rc::new(obligation.cause.code.clone()),
2090 let derived_code = variant(derived_cause);
2091 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2095 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2096 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2097 TraitObligationStackList::with(self)
2100 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2104 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2108 /// Indicates that attempting to evaluate this stack entry
2109 /// required accessing something from the stack at depth `reached_depth`.
2110 fn update_reached_depth(&self, reached_depth: usize) {
2112 self.depth > reached_depth,
2113 "invoked `update_reached_depth` with something under this stack: \
2114 self.depth={} reached_depth={}",
2118 debug!(reached_depth, "update_reached_depth");
2120 while reached_depth < p.depth {
2121 debug!(?p.fresh_trait_ref, "update_reached_depth: marking as cycle participant");
2122 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2123 p = p.previous.head.unwrap();
2128 /// The "provisional evaluation cache" is used to store intermediate cache results
2129 /// when solving auto traits. Auto traits are unusual in that they can support
2130 /// cycles. So, for example, a "proof tree" like this would be ok:
2132 /// - `Foo<T>: Send` :-
2133 /// - `Bar<T>: Send` :-
2134 /// - `Foo<T>: Send` -- cycle, but ok
2135 /// - `Baz<T>: Send`
2137 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2138 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2139 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2140 /// they are coinductive) it is considered ok.
2142 /// However, there is a complication: at the point where we have
2143 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2144 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2145 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2146 /// find out this assumption is wrong? Specifically, we could
2147 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2148 /// `Bar<T>: Send` didn't turn out to be true.
2150 /// In Issue #60010, we found a bug in rustc where it would cache
2151 /// these intermediate results. This was fixed in #60444 by disabling
2152 /// *all* caching for things involved in a cycle -- in our example,
2153 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2154 /// to large slowdowns.
2156 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2157 /// first requires proving `Bar<T>: Send` (which is true:
2159 /// - `Foo<T>: Send` :-
2160 /// - `Bar<T>: Send` :-
2161 /// - `Foo<T>: Send` -- cycle, but ok
2162 /// - `Baz<T>: Send`
2163 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2164 /// - `*const T: Send` -- but what if we later encounter an error?
2166 /// The *provisional evaluation cache* resolves this issue. It stores
2167 /// cache results that we've proven but which were involved in a cycle
2168 /// in some way. We track the minimal stack depth (i.e., the
2169 /// farthest from the top of the stack) that we are dependent on.
2170 /// The idea is that the cache results within are all valid -- so long as
2171 /// none of the nodes in between the current node and the node at that minimum
2172 /// depth result in an error (in which case the cached results are just thrown away).
2174 /// During evaluation, we consult this provisional cache and rely on
2175 /// it. Accessing a cached value is considered equivalent to accessing
2176 /// a result at `reached_depth`, so it marks the *current* solution as
2177 /// provisional as well. If an error is encountered, we toss out any
2178 /// provisional results added from the subtree that encountered the
2179 /// error. When we pop the node at `reached_depth` from the stack, we
2180 /// can commit all the things that remain in the provisional cache.
2181 struct ProvisionalEvaluationCache<'tcx> {
2182 /// next "depth first number" to issue -- just a counter
2185 /// Stores the "coldest" depth (bottom of stack) reached by any of
2186 /// the evaluation entries. The idea here is that all things in the provisional
2187 /// cache are always dependent on *something* that is colder in the stack:
2188 /// therefore, if we add a new entry that is dependent on something *colder still*,
2189 /// we have to modify the depth for all entries at once.
2193 /// Imagine we have a stack `A B C D E` (with `E` being the top of
2194 /// the stack). We cache something with depth 2, which means that
2195 /// it was dependent on C. Then we pop E but go on and process a
2196 /// new node F: A B C D F. Now F adds something to the cache with
2197 /// depth 1, meaning it is dependent on B. Our original cache
2198 /// entry is also dependent on B, because there is a path from E
2199 /// to C and then from C to F and from F to B.
2200 reached_depth: Cell<usize>,
2202 /// Map from cache key to the provisionally evaluated thing.
2203 /// The cache entries contain the result but also the DFN in which they
2204 /// were added. The DFN is used to clear out values on failure.
2206 /// Imagine we have a stack like:
2208 /// - `A B C` and we add a cache for the result of C (DFN 2)
2209 /// - Then we have a stack `A B D` where `D` has DFN 3
2210 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2211 /// - `E` generates various cache entries which have cyclic dependices on `B`
2212 /// - `A B D E F` and so forth
2213 /// - the DFN of `F` for example would be 5
2214 /// - then we determine that `E` is in error -- we will then clear
2215 /// all cache values whose DFN is >= 4 -- in this case, that
2216 /// means the cached value for `F`.
2217 map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
2220 /// A cache value for the provisional cache: contains the depth-first
2221 /// number (DFN) and result.
2222 #[derive(Copy, Clone, Debug)]
2223 struct ProvisionalEvaluation {
2225 result: EvaluationResult,
2228 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2229 fn default() -> Self {
2230 Self { dfn: Cell::new(0), reached_depth: Cell::new(usize::MAX), map: Default::default() }
2234 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2235 /// Get the next DFN in sequence (basically a counter).
2236 fn next_dfn(&self) -> usize {
2237 let result = self.dfn.get();
2238 self.dfn.set(result + 1);
2242 /// Check the provisional cache for any result for
2243 /// `fresh_trait_ref`. If there is a hit, then you must consider
2244 /// it an access to the stack slots at depth
2245 /// `self.current_reached_depth()` and above.
2246 fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
2249 reached_depth = ?self.reached_depth.get(),
2250 "get_provisional = {:#?}",
2251 self.map.borrow().get(&fresh_trait_ref),
2253 Some(self.map.borrow().get(&fresh_trait_ref)?.result)
2256 /// Current value of the `reached_depth` counter -- all the
2257 /// provisional cache entries are dependent on the item at this
2259 fn current_reached_depth(&self) -> usize {
2260 self.reached_depth.get()
2263 /// Insert a provisional result into the cache. The result came
2264 /// from the node with the given DFN. It accessed a minimum depth
2265 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
2266 /// and resulted in `result`.
2267 fn insert_provisional(
2270 reached_depth: usize,
2271 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
2272 result: EvaluationResult,
2274 debug!(?from_dfn, ?reached_depth, ?fresh_trait_ref, ?result, "insert_provisional");
2275 let r_d = self.reached_depth.get();
2276 self.reached_depth.set(r_d.min(reached_depth));
2278 debug!(reached_depth = self.reached_depth.get());
2280 self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
2283 /// Invoked when the node with dfn `dfn` does not get a successful
2284 /// result. This will clear out any provisional cache entries
2285 /// that were added since `dfn` was created. This is because the
2286 /// provisional entries are things which must assume that the
2287 /// things on the stack at the time of their creation succeeded --
2288 /// since the failing node is presently at the top of the stack,
2289 /// these provisional entries must either depend on it or some
2291 fn on_failure(&self, dfn: usize) {
2292 debug!(?dfn, "on_failure");
2293 self.map.borrow_mut().retain(|key, eval| {
2294 if !eval.from_dfn >= dfn {
2295 debug!("on_failure: removing {:?}", key);
2303 /// Invoked when the node at depth `depth` completed without
2304 /// depending on anything higher in the stack (if that completion
2305 /// was a failure, then `on_failure` should have been invoked
2306 /// already). The callback `op` will be invoked for each
2307 /// provisional entry that we can now confirm.
2311 mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
2313 debug!(?depth, reached_depth = ?self.reached_depth.get(), "on_completion");
2315 if self.reached_depth.get() < depth {
2316 debug!("on_completion: did not yet reach depth to complete");
2320 for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
2321 debug!(?fresh_trait_ref, ?eval, "on_completion");
2323 op(fresh_trait_ref, eval.result);
2326 self.reached_depth.set(usize::MAX);
2330 #[derive(Copy, Clone)]
2331 struct TraitObligationStackList<'o, 'tcx> {
2332 cache: &'o ProvisionalEvaluationCache<'tcx>,
2333 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2336 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2337 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2338 TraitObligationStackList { cache, head: None }
2341 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2342 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2345 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2349 fn depth(&self) -> usize {
2350 if let Some(head) = self.head { head.depth } else { 0 }
2354 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2355 type Item = &'o TraitObligationStack<'o, 'tcx>;
2357 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2368 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2370 write!(f, "TraitObligationStack({:?})", self.obligation)