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};
10 use super::project::normalize_with_depth_to;
12 use super::util::{closure_trait_ref_and_return_type, predicate_for_trait_def};
14 use super::DerivedObligationCause;
15 use super::Obligation;
16 use super::ObligationCauseCode;
18 use super::SelectionResult;
19 use super::TraitQueryMode;
20 use super::{Normalized, ProjectionCacheKey};
21 use super::{ObligationCause, PredicateObligation, TraitObligation};
22 use super::{Overflow, SelectionError, Unimplemented};
24 use crate::infer::{InferCtxt, InferOk, TypeFreshener};
25 use crate::traits::error_reporting::InferCtxtExt;
26 use crate::traits::project::ProjectionCacheKeyExt;
28 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
29 use rustc_data_structures::stack::ensure_sufficient_stack;
30 use rustc_errors::ErrorReported;
32 use rustc_hir::def_id::DefId;
33 use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
34 use rustc_middle::mir::interpret::ErrorHandled;
35 use rustc_middle::ty::fast_reject;
36 use rustc_middle::ty::relate::TypeRelation;
37 use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef};
38 use rustc_middle::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
39 use rustc_span::symbol::sym;
41 use std::cell::{Cell, RefCell};
43 use std::fmt::{self, Display};
47 pub use rustc_middle::traits::select::*;
49 mod candidate_assembly;
52 pub struct SelectionContext<'cx, 'tcx> {
53 infcx: &'cx InferCtxt<'cx, 'tcx>,
55 /// Freshener used specifically for entries on the obligation
56 /// stack. This ensures that all entries on the stack at one time
57 /// will have the same set of placeholder entries, which is
58 /// important for checking for trait bounds that recursively
59 /// require themselves.
60 freshener: TypeFreshener<'cx, 'tcx>,
62 /// If `true`, indicates that the evaluation should be conservative
63 /// and consider the possibility of types outside this crate.
64 /// This comes up primarily when resolving ambiguity. Imagine
65 /// there is some trait reference `$0: Bar` where `$0` is an
66 /// inference variable. If `intercrate` is true, then we can never
67 /// say for sure that this reference is not implemented, even if
68 /// there are *no impls at all for `Bar`*, because `$0` could be
69 /// bound to some type that in a downstream crate that implements
70 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
71 /// though, we set this to false, because we are only interested
72 /// in types that the user could actually have written --- in
73 /// other words, we consider `$0: Bar` to be unimplemented if
74 /// there is no type that the user could *actually name* that
75 /// would satisfy it. This avoids crippling inference, basically.
78 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
80 /// Controls whether or not to filter out negative impls when selecting.
81 /// This is used in librustdoc to distinguish between the lack of an impl
82 /// and a negative impl
83 allow_negative_impls: bool,
85 /// The mode that trait queries run in, which informs our error handling
86 /// policy. In essence, canonicalized queries need their errors propagated
87 /// rather than immediately reported because we do not have accurate spans.
88 query_mode: TraitQueryMode,
91 // A stack that walks back up the stack frame.
92 struct TraitObligationStack<'prev, 'tcx> {
93 obligation: &'prev TraitObligation<'tcx>,
95 /// The trait ref from `obligation` but "freshened" with the
96 /// selection-context's freshener. Used to check for recursion.
97 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
99 /// Starts out equal to `depth` -- if, during evaluation, we
100 /// encounter a cycle, then we will set this flag to the minimum
101 /// depth of that cycle for all participants in the cycle. These
102 /// participants will then forego caching their results. This is
103 /// not the most efficient solution, but it addresses #60010. The
104 /// problem we are trying to prevent:
106 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
107 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
108 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
110 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
111 /// is `EvaluatedToOk`; this is because they were only considered
112 /// ok on the premise that if `A: AutoTrait` held, but we indeed
113 /// encountered a problem (later on) with `A: AutoTrait. So we
114 /// currently set a flag on the stack node for `B: AutoTrait` (as
115 /// well as the second instance of `A: AutoTrait`) to suppress
118 /// This is a simple, targeted fix. A more-performant fix requires
119 /// deeper changes, but would permit more caching: we could
120 /// basically defer caching until we have fully evaluated the
121 /// tree, and then cache the entire tree at once. In any case, the
122 /// performance impact here shouldn't be so horrible: every time
123 /// this is hit, we do cache at least one trait, so we only
124 /// evaluate each member of a cycle up to N times, where N is the
125 /// length of the cycle. This means the performance impact is
126 /// bounded and we shouldn't have any terrible worst-cases.
127 reached_depth: Cell<usize>,
129 previous: TraitObligationStackList<'prev, 'tcx>,
131 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
134 /// The depth-first number of this node in the search graph -- a
135 /// pre-order index. Basically, a freshly incremented counter.
139 struct SelectionCandidateSet<'tcx> {
140 // A list of candidates that definitely apply to the current
141 // obligation (meaning: types unify).
142 vec: Vec<SelectionCandidate<'tcx>>,
144 // If `true`, then there were candidates that might or might
145 // not have applied, but we couldn't tell. This occurs when some
146 // of the input types are type variables, in which case there are
147 // various "builtin" rules that might or might not trigger.
151 #[derive(PartialEq, Eq, Debug, Clone)]
152 struct EvaluatedCandidate<'tcx> {
153 candidate: SelectionCandidate<'tcx>,
154 evaluation: EvaluationResult,
157 /// When does the builtin impl for `T: Trait` apply?
158 enum BuiltinImplConditions<'tcx> {
159 /// The impl is conditional on `T1, T2, ...: Trait`.
160 Where(ty::Binder<Vec<Ty<'tcx>>>),
161 /// There is no built-in impl. There may be some other
162 /// candidate (a where-clause or user-defined impl).
164 /// It is unknown whether there is an impl.
168 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
169 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
172 freshener: infcx.freshener(),
174 intercrate_ambiguity_causes: None,
175 allow_negative_impls: false,
176 query_mode: TraitQueryMode::Standard,
180 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
183 freshener: infcx.freshener(),
185 intercrate_ambiguity_causes: None,
186 allow_negative_impls: false,
187 query_mode: TraitQueryMode::Standard,
191 pub fn with_negative(
192 infcx: &'cx InferCtxt<'cx, 'tcx>,
193 allow_negative_impls: bool,
194 ) -> SelectionContext<'cx, 'tcx> {
195 debug!("with_negative({:?})", allow_negative_impls);
198 freshener: infcx.freshener(),
200 intercrate_ambiguity_causes: None,
201 allow_negative_impls,
202 query_mode: TraitQueryMode::Standard,
206 pub fn with_query_mode(
207 infcx: &'cx InferCtxt<'cx, 'tcx>,
208 query_mode: TraitQueryMode,
209 ) -> SelectionContext<'cx, 'tcx> {
210 debug!("with_query_mode({:?})", query_mode);
213 freshener: infcx.freshener(),
215 intercrate_ambiguity_causes: None,
216 allow_negative_impls: false,
221 /// Enables tracking of intercrate ambiguity causes. These are
222 /// used in coherence to give improved diagnostics. We don't do
223 /// this until we detect a coherence error because it can lead to
224 /// false overflow results (#47139) and because it costs
225 /// computation time.
226 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
227 assert!(self.intercrate);
228 assert!(self.intercrate_ambiguity_causes.is_none());
229 self.intercrate_ambiguity_causes = Some(vec![]);
230 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
233 /// Gets the intercrate ambiguity causes collected since tracking
234 /// was enabled and disables tracking at the same time. If
235 /// tracking is not enabled, just returns an empty vector.
236 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
237 assert!(self.intercrate);
238 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
241 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
245 pub fn tcx(&self) -> TyCtxt<'tcx> {
249 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
253 ///////////////////////////////////////////////////////////////////////////
256 // The selection phase tries to identify *how* an obligation will
257 // be resolved. For example, it will identify which impl or
258 // parameter bound is to be used. The process can be inconclusive
259 // if the self type in the obligation is not fully inferred. Selection
260 // can result in an error in one of two ways:
262 // 1. If no applicable impl or parameter bound can be found.
263 // 2. If the output type parameters in the obligation do not match
264 // those specified by the impl/bound. For example, if the obligation
265 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
266 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
268 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
269 /// type environment by performing unification.
272 obligation: &TraitObligation<'tcx>,
273 ) -> SelectionResult<'tcx, Selection<'tcx>> {
274 debug!("select({:?})", obligation);
275 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
277 let pec = &ProvisionalEvaluationCache::default();
278 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
280 let candidate = match self.candidate_from_obligation(&stack) {
281 Err(SelectionError::Overflow) => {
282 // In standard mode, overflow must have been caught and reported
284 assert!(self.query_mode == TraitQueryMode::Canonical);
285 return Err(SelectionError::Overflow);
293 Ok(Some(candidate)) => candidate,
296 match self.confirm_candidate(obligation, candidate) {
297 Err(SelectionError::Overflow) => {
298 assert!(self.query_mode == TraitQueryMode::Canonical);
299 Err(SelectionError::Overflow)
302 Ok(candidate) => Ok(Some(candidate)),
306 ///////////////////////////////////////////////////////////////////////////
309 // Tests whether an obligation can be selected or whether an impl
310 // can be applied to particular types. It skips the "confirmation"
311 // step and hence completely ignores output type parameters.
313 // The result is "true" if the obligation *may* hold and "false" if
314 // we can be sure it does not.
316 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
317 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
318 debug!("predicate_may_hold_fatal({:?})", obligation);
320 // This fatal query is a stopgap that should only be used in standard mode,
321 // where we do not expect overflow to be propagated.
322 assert!(self.query_mode == TraitQueryMode::Standard);
324 self.evaluate_root_obligation(obligation)
325 .expect("Overflow should be caught earlier in standard query mode")
329 /// Evaluates whether the obligation `obligation` can be satisfied
330 /// and returns an `EvaluationResult`. This is meant for the
332 pub fn evaluate_root_obligation(
334 obligation: &PredicateObligation<'tcx>,
335 ) -> Result<EvaluationResult, OverflowError> {
336 self.evaluation_probe(|this| {
337 this.evaluate_predicate_recursively(
338 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
346 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
347 ) -> Result<EvaluationResult, OverflowError> {
348 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
349 let result = op(self)?;
351 match self.infcx.leak_check(true, snapshot) {
353 Err(_) => return Ok(EvaluatedToErr),
356 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
358 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
363 /// Evaluates the predicates in `predicates` recursively. Note that
364 /// this applies projections in the predicates, and therefore
365 /// is run within an inference probe.
366 fn evaluate_predicates_recursively<'o, I>(
368 stack: TraitObligationStackList<'o, 'tcx>,
370 ) -> Result<EvaluationResult, OverflowError>
372 I: IntoIterator<Item = PredicateObligation<'tcx>>,
374 let mut result = EvaluatedToOk;
375 for obligation in predicates {
376 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
377 debug!("evaluate_predicate_recursively({:?}) = {:?}", obligation, eval);
378 if let EvaluatedToErr = eval {
379 // fast-path - EvaluatedToErr is the top of the lattice,
380 // so we don't need to look on the other predicates.
381 return Ok(EvaluatedToErr);
383 result = cmp::max(result, eval);
389 fn evaluate_predicate_recursively<'o>(
391 previous_stack: TraitObligationStackList<'o, 'tcx>,
392 obligation: PredicateObligation<'tcx>,
393 ) -> Result<EvaluationResult, OverflowError> {
395 "evaluate_predicate_recursively(previous_stack={:?}, obligation={:?})",
396 previous_stack.head(),
400 // `previous_stack` stores a `TraitObligatiom`, while `obligation` is
401 // a `PredicateObligation`. These are distinct types, so we can't
402 // use any `Option` combinator method that would force them to be
404 match previous_stack.head() {
405 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
406 None => self.check_recursion_limit(&obligation, &obligation)?,
409 match obligation.predicate.kind() {
410 &ty::PredicateKind::Trait(t, _) => {
411 debug_assert!(!t.has_escaping_bound_vars());
412 let obligation = obligation.with(t);
413 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
416 &ty::PredicateKind::Subtype(p) => {
417 // Does this code ever run?
418 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
419 Some(Ok(InferOk { mut obligations, .. })) => {
420 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
421 self.evaluate_predicates_recursively(
423 obligations.into_iter(),
426 Some(Err(_)) => Ok(EvaluatedToErr),
427 None => Ok(EvaluatedToAmbig),
431 &ty::PredicateKind::WellFormed(arg) => match wf::obligations(
433 obligation.param_env,
434 obligation.cause.body_id,
436 obligation.cause.span,
438 Some(mut obligations) => {
439 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
440 self.evaluate_predicates_recursively(previous_stack, obligations.into_iter())
442 None => Ok(EvaluatedToAmbig),
445 ty::PredicateKind::TypeOutlives(..) | ty::PredicateKind::RegionOutlives(..) => {
446 // We do not consider region relationships when evaluating trait matches.
447 Ok(EvaluatedToOkModuloRegions)
450 &ty::PredicateKind::ObjectSafe(trait_def_id) => {
451 if self.tcx().is_object_safe(trait_def_id) {
458 &ty::PredicateKind::Projection(data) => {
459 let project_obligation = obligation.with(data);
460 match project::poly_project_and_unify_type(self, &project_obligation) {
461 Ok(Some(mut subobligations)) => {
462 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
463 let result = self.evaluate_predicates_recursively(
465 subobligations.into_iter(),
468 ProjectionCacheKey::from_poly_projection_predicate(self, data)
470 self.infcx.inner.borrow_mut().projection_cache().complete(key);
474 Ok(None) => Ok(EvaluatedToAmbig),
475 Err(_) => Ok(EvaluatedToErr),
479 &ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
480 match self.infcx.closure_kind(closure_substs) {
481 Some(closure_kind) => {
482 if closure_kind.extends(kind) {
488 None => Ok(EvaluatedToAmbig),
492 &ty::PredicateKind::ConstEvaluatable(def_id, substs) => {
493 match self.tcx().const_eval_resolve(
494 obligation.param_env,
500 Ok(_) => Ok(EvaluatedToOk),
501 Err(ErrorHandled::TooGeneric) => Ok(EvaluatedToAmbig),
502 Err(_) => Ok(EvaluatedToErr),
506 ty::PredicateKind::ConstEquate(c1, c2) => {
507 debug!("evaluate_predicate_recursively: equating consts c1={:?} c2={:?}", c1, c2);
509 let evaluate = |c: &'tcx ty::Const<'tcx>| {
510 if let ty::ConstKind::Unevaluated(def_id, substs, promoted) = c.val {
513 obligation.param_env,
517 Some(obligation.cause.span),
519 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty))
525 match (evaluate(c1), evaluate(c2)) {
526 (Ok(c1), Ok(c2)) => {
527 match self.infcx().at(&obligation.cause, obligation.param_env).eq(c1, c2) {
528 Ok(_) => Ok(EvaluatedToOk),
529 Err(_) => Ok(EvaluatedToErr),
532 (Err(ErrorHandled::Reported(ErrorReported)), _)
533 | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
534 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => span_bug!(
535 obligation.cause.span(self.tcx()),
536 "ConstEquate: const_eval_resolve returned an unexpected error"
538 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
546 fn evaluate_trait_predicate_recursively<'o>(
548 previous_stack: TraitObligationStackList<'o, 'tcx>,
549 mut obligation: TraitObligation<'tcx>,
550 ) -> Result<EvaluationResult, OverflowError> {
551 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
554 && obligation.is_global()
555 && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst())
557 // If a param env has no global bounds, global obligations do not
558 // depend on its particular value in order to work, so we can clear
559 // out the param env and get better caching.
560 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
561 obligation.param_env = obligation.param_env.without_caller_bounds();
564 let stack = self.push_stack(previous_stack, &obligation);
565 let fresh_trait_ref = stack.fresh_trait_ref;
566 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
567 debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
571 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
572 debug!("PROVISIONAL CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
573 stack.update_reached_depth(stack.cache().current_reached_depth());
577 // Check if this is a match for something already on the
578 // stack. If so, we don't want to insert the result into the
579 // main cache (it is cycle dependent) nor the provisional
580 // cache (which is meant for things that have completed but
581 // for a "backedge" -- this result *is* the backedge).
582 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
583 return Ok(cycle_result);
586 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
587 let result = result?;
589 if !result.must_apply_modulo_regions() {
590 stack.cache().on_failure(stack.dfn);
593 let reached_depth = stack.reached_depth.get();
594 if reached_depth >= stack.depth {
595 debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
596 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
598 stack.cache().on_completion(stack.depth, |fresh_trait_ref, provisional_result| {
599 self.insert_evaluation_cache(
600 obligation.param_env,
603 provisional_result.max(result),
607 debug!("PROVISIONAL: {:?}={:?}", fresh_trait_ref, result);
609 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
610 is a cycle participant (at depth {}, reached depth {})",
611 fresh_trait_ref, stack.depth, reached_depth,
614 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
620 /// If there is any previous entry on the stack that precisely
621 /// matches this obligation, then we can assume that the
622 /// obligation is satisfied for now (still all other conditions
623 /// must be met of course). One obvious case this comes up is
624 /// marker traits like `Send`. Think of a linked list:
626 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
628 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
629 /// `Option<Box<List<T>>>` is `Send`, and in turn
630 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
633 /// Note that we do this comparison using the `fresh_trait_ref`
634 /// fields. Because these have all been freshened using
635 /// `self.freshener`, we can be sure that (a) this will not
636 /// affect the inferencer state and (b) that if we see two
637 /// fresh regions with the same index, they refer to the same
638 /// unbound type variable.
639 fn check_evaluation_cycle(
641 stack: &TraitObligationStack<'_, 'tcx>,
642 ) -> Option<EvaluationResult> {
643 if let Some(cycle_depth) = stack
645 .skip(1) // Skip top-most frame.
647 stack.obligation.param_env == prev.obligation.param_env
648 && stack.fresh_trait_ref == prev.fresh_trait_ref
650 .map(|stack| stack.depth)
653 "evaluate_stack({:?}) --> recursive at depth {}",
654 stack.fresh_trait_ref, cycle_depth,
657 // If we have a stack like `A B C D E A`, where the top of
658 // the stack is the final `A`, then this will iterate over
659 // `A, E, D, C, B` -- i.e., all the participants apart
660 // from the cycle head. We mark them as participating in a
661 // cycle. This suppresses caching for those nodes. See
662 // `in_cycle` field for more details.
663 stack.update_reached_depth(cycle_depth);
665 // Subtle: when checking for a coinductive cycle, we do
666 // not compare using the "freshened trait refs" (which
667 // have erased regions) but rather the fully explicit
668 // trait refs. This is important because it's only a cycle
669 // if the regions match exactly.
670 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
671 let tcx = self.tcx();
672 let cycle = cycle.map(|stack| {
673 ty::PredicateKind::Trait(stack.obligation.predicate, hir::Constness::NotConst)
676 if self.coinductive_match(cycle) {
677 debug!("evaluate_stack({:?}) --> recursive, coinductive", stack.fresh_trait_ref);
680 debug!("evaluate_stack({:?}) --> recursive, inductive", stack.fresh_trait_ref);
681 Some(EvaluatedToRecur)
688 fn evaluate_stack<'o>(
690 stack: &TraitObligationStack<'o, 'tcx>,
691 ) -> Result<EvaluationResult, OverflowError> {
692 // In intercrate mode, whenever any of the generics are unbound,
693 // there can always be an impl. Even if there are no impls in
694 // this crate, perhaps the type would be unified with
695 // something from another crate that does provide an impl.
697 // In intra mode, we must still be conservative. The reason is
698 // that we want to avoid cycles. Imagine an impl like:
700 // impl<T:Eq> Eq for Vec<T>
702 // and a trait reference like `$0 : Eq` where `$0` is an
703 // unbound variable. When we evaluate this trait-reference, we
704 // will unify `$0` with `Vec<$1>` (for some fresh variable
705 // `$1`), on the condition that `$1 : Eq`. We will then wind
706 // up with many candidates (since that are other `Eq` impls
707 // that apply) and try to winnow things down. This results in
708 // a recursive evaluation that `$1 : Eq` -- as you can
709 // imagine, this is just where we started. To avoid that, we
710 // check for unbound variables and return an ambiguous (hence possible)
711 // match if we've seen this trait before.
713 // This suffices to allow chains like `FnMut` implemented in
714 // terms of `Fn` etc, but we could probably make this more
716 let unbound_input_types =
717 stack.fresh_trait_ref.skip_binder().substs.types().any(|ty| ty.is_fresh());
718 // This check was an imperfect workaround for a bug in the old
719 // intercrate mode; it should be removed when that goes away.
720 if unbound_input_types && self.intercrate {
722 "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
723 stack.fresh_trait_ref
725 // Heuristics: show the diagnostics when there are no candidates in crate.
726 if self.intercrate_ambiguity_causes.is_some() {
727 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
728 if let Ok(candidate_set) = self.assemble_candidates(stack) {
729 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
730 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
731 let self_ty = trait_ref.self_ty();
732 let cause = IntercrateAmbiguityCause::DownstreamCrate {
733 trait_desc: trait_ref.print_only_trait_path().to_string(),
734 self_desc: if self_ty.has_concrete_skeleton() {
735 Some(self_ty.to_string())
740 debug!("evaluate_stack: pushing cause = {:?}", cause);
741 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
745 return Ok(EvaluatedToAmbig);
747 if unbound_input_types
748 && stack.iter().skip(1).any(|prev| {
749 stack.obligation.param_env == prev.obligation.param_env
750 && self.match_fresh_trait_refs(
751 stack.fresh_trait_ref,
752 prev.fresh_trait_ref,
753 prev.obligation.param_env,
758 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
759 stack.fresh_trait_ref
761 return Ok(EvaluatedToUnknown);
764 match self.candidate_from_obligation(stack) {
765 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
766 Ok(None) => Ok(EvaluatedToAmbig),
767 Err(Overflow) => Err(OverflowError),
768 Err(..) => Ok(EvaluatedToErr),
772 /// For defaulted traits, we use a co-inductive strategy to solve, so
773 /// that recursion is ok. This routine returns `true` if the top of the
774 /// stack (`cycle[0]`):
776 /// - is a defaulted trait,
777 /// - it also appears in the backtrace at some position `X`,
778 /// - all the predicates at positions `X..` between `X` and the top are
779 /// also defaulted traits.
780 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
782 I: Iterator<Item = ty::Predicate<'tcx>>,
784 let mut cycle = cycle;
785 cycle.all(|predicate| self.coinductive_predicate(predicate))
788 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
789 let result = match predicate.kind() {
790 ty::PredicateKind::Trait(ref data, _) => self.tcx().trait_is_auto(data.def_id()),
793 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
797 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
798 /// obligations are met. Returns whether `candidate` remains viable after this further
800 fn evaluate_candidate<'o>(
802 stack: &TraitObligationStack<'o, 'tcx>,
803 candidate: &SelectionCandidate<'tcx>,
804 ) -> Result<EvaluationResult, OverflowError> {
806 "evaluate_candidate: depth={} candidate={:?}",
807 stack.obligation.recursion_depth, candidate
809 let result = self.evaluation_probe(|this| {
810 let candidate = (*candidate).clone();
811 match this.confirm_candidate(stack.obligation, candidate) {
812 Ok(selection) => this.evaluate_predicates_recursively(
814 selection.nested_obligations().into_iter(),
816 Err(..) => Ok(EvaluatedToErr),
820 "evaluate_candidate: depth={} result={:?}",
821 stack.obligation.recursion_depth, result
826 fn check_evaluation_cache(
828 param_env: ty::ParamEnv<'tcx>,
829 trait_ref: ty::PolyTraitRef<'tcx>,
830 ) -> Option<EvaluationResult> {
831 let tcx = self.tcx();
832 if self.can_use_global_caches(param_env) {
833 let cache = tcx.evaluation_cache.hashmap.borrow();
834 if let Some(cached) = cache.get(¶m_env.and(trait_ref)) {
835 return Some(cached.get(tcx));
842 .get(¶m_env.and(trait_ref))
846 fn insert_evaluation_cache(
848 param_env: ty::ParamEnv<'tcx>,
849 trait_ref: ty::PolyTraitRef<'tcx>,
850 dep_node: DepNodeIndex,
851 result: EvaluationResult,
853 // Avoid caching results that depend on more than just the trait-ref
854 // - the stack can create recursion.
855 if result.is_stack_dependent() {
859 if self.can_use_global_caches(param_env) {
860 if !trait_ref.needs_infer() {
862 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
865 // This may overwrite the cache with the same value
866 // FIXME: Due to #50507 this overwrites the different values
867 // This should be changed to use HashMapExt::insert_same
868 // when that is fixed
873 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
878 debug!("insert_evaluation_cache(trait_ref={:?}, candidate={:?})", trait_ref, result,);
883 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
886 /// For various reasons, it's possible for a subobligation
887 /// to have a *lower* recursion_depth than the obligation used to create it.
888 /// Projection sub-obligations may be returned from the projection cache,
889 /// which results in obligations with an 'old' `recursion_depth`.
890 /// Additionally, methods like `wf::obligations` and
891 /// `InferCtxt.subtype_predicate` produce subobligations without
892 /// taking in a 'parent' depth, causing the generated subobligations
893 /// to have a `recursion_depth` of `0`.
895 /// To ensure that obligation_depth never decreasees, we force all subobligations
896 /// to have at least the depth of the original obligation.
897 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
902 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
905 /// Checks that the recursion limit has not been exceeded.
907 /// The weird return type of this function allows it to be used with the `try` (`?`)
908 /// operator within certain functions.
909 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
911 obligation: &Obligation<'tcx, T>,
912 error_obligation: &Obligation<'tcx, V>,
913 ) -> Result<(), OverflowError> {
914 if !self.infcx.tcx.sess.recursion_limit().value_within_limit(obligation.recursion_depth) {
915 match self.query_mode {
916 TraitQueryMode::Standard => {
917 self.infcx().report_overflow_error(error_obligation, true);
919 TraitQueryMode::Canonical => {
920 return Err(OverflowError);
927 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
929 OP: FnOnce(&mut Self) -> R,
931 let (result, dep_node) =
932 self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || op(self));
933 self.tcx().dep_graph.read_index(dep_node);
937 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
938 fn filter_negative_and_reservation_impls(
940 candidate: SelectionCandidate<'tcx>,
941 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
942 if let ImplCandidate(def_id) = candidate {
943 let tcx = self.tcx();
944 match tcx.impl_polarity(def_id) {
945 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
946 return Err(Unimplemented);
948 ty::ImplPolarity::Reservation => {
949 if let Some(intercrate_ambiguity_clauses) =
950 &mut self.intercrate_ambiguity_causes
952 let attrs = tcx.get_attrs(def_id);
953 let attr = attr::find_by_name(&attrs, sym::rustc_reservation_impl);
954 let value = attr.and_then(|a| a.value_str());
955 if let Some(value) = value {
957 "filter_negative_and_reservation_impls: \
958 reservation impl ambiguity on {:?}",
961 intercrate_ambiguity_clauses.push(
962 IntercrateAmbiguityCause::ReservationImpl {
963 message: value.to_string(),
976 fn candidate_from_obligation_no_cache<'o>(
978 stack: &TraitObligationStack<'o, 'tcx>,
979 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
980 if let Some(conflict) = self.is_knowable(stack) {
981 debug!("coherence stage: not knowable");
982 if self.intercrate_ambiguity_causes.is_some() {
983 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
984 // Heuristics: show the diagnostics when there are no candidates in crate.
985 if let Ok(candidate_set) = self.assemble_candidates(stack) {
986 let mut no_candidates_apply = true;
988 for c in candidate_set.vec.iter() {
989 if self.evaluate_candidate(stack, &c)?.may_apply() {
990 no_candidates_apply = false;
995 if !candidate_set.ambiguous && no_candidates_apply {
996 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
997 let self_ty = trait_ref.self_ty();
998 let trait_desc = trait_ref.print_only_trait_path().to_string();
999 let self_desc = if self_ty.has_concrete_skeleton() {
1000 Some(self_ty.to_string())
1004 let cause = if let Conflict::Upstream = conflict {
1005 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
1007 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1009 debug!("evaluate_stack: pushing cause = {:?}", cause);
1010 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1017 let candidate_set = self.assemble_candidates(stack)?;
1019 if candidate_set.ambiguous {
1020 debug!("candidate set contains ambig");
1024 let mut candidates = candidate_set.vec;
1026 debug!("assembled {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1028 // At this point, we know that each of the entries in the
1029 // candidate set is *individually* applicable. Now we have to
1030 // figure out if they contain mutual incompatibilities. This
1031 // frequently arises if we have an unconstrained input type --
1032 // for example, we are looking for `$0: Eq` where `$0` is some
1033 // unconstrained type variable. In that case, we'll get a
1034 // candidate which assumes $0 == int, one that assumes `$0 ==
1035 // usize`, etc. This spells an ambiguity.
1037 // If there is more than one candidate, first winnow them down
1038 // by considering extra conditions (nested obligations and so
1039 // forth). We don't winnow if there is exactly one
1040 // candidate. This is a relatively minor distinction but it
1041 // can lead to better inference and error-reporting. An
1042 // example would be if there was an impl:
1044 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1046 // and we were to see some code `foo.push_clone()` where `boo`
1047 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1048 // we were to winnow, we'd wind up with zero candidates.
1049 // Instead, we select the right impl now but report "`Bar` does
1050 // not implement `Clone`".
1051 if candidates.len() == 1 {
1052 return self.filter_negative_and_reservation_impls(candidates.pop().unwrap());
1055 // Winnow, but record the exact outcome of evaluation, which
1056 // is needed for specialization. Propagate overflow if it occurs.
1057 let mut candidates = candidates
1059 .map(|c| match self.evaluate_candidate(stack, &c) {
1060 Ok(eval) if eval.may_apply() => {
1061 Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
1064 Err(OverflowError) => Err(Overflow),
1066 .flat_map(Result::transpose)
1067 .collect::<Result<Vec<_>, _>>()?;
1069 debug!("winnowed to {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1071 let needs_infer = stack.obligation.predicate.needs_infer();
1073 // If there are STILL multiple candidates, we can further
1074 // reduce the list by dropping duplicates -- including
1075 // resolving specializations.
1076 if candidates.len() > 1 {
1078 while i < candidates.len() {
1079 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1080 self.candidate_should_be_dropped_in_favor_of(
1087 debug!("Dropping candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1088 candidates.swap_remove(i);
1090 debug!("Retaining candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1093 // If there are *STILL* multiple candidates, give up
1094 // and report ambiguity.
1096 debug!("multiple matches, ambig");
1103 // If there are *NO* candidates, then there are no impls --
1104 // that we know of, anyway. Note that in the case where there
1105 // are unbound type variables within the obligation, it might
1106 // be the case that you could still satisfy the obligation
1107 // from another crate by instantiating the type variables with
1108 // a type from another crate that does have an impl. This case
1109 // is checked for in `evaluate_stack` (and hence users
1110 // who might care about this case, like coherence, should use
1112 if candidates.is_empty() {
1113 // If there's an error type, 'downgrade' our result from
1114 // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
1115 // emitting additional spurious errors, since we're guaranteed
1116 // to have emitted at least one.
1117 if stack.obligation.references_error() {
1118 debug!("no results for error type, treating as ambiguous");
1121 return Err(Unimplemented);
1124 // Just one candidate left.
1125 self.filter_negative_and_reservation_impls(candidates.pop().unwrap().candidate)
1128 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1129 debug!("is_knowable(intercrate={:?})", self.intercrate);
1131 if !self.intercrate {
1135 let obligation = &stack.obligation;
1136 let predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1138 // Okay to skip binder because of the nature of the
1139 // trait-ref-is-knowable check, which does not care about
1141 let trait_ref = predicate.skip_binder().trait_ref;
1143 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1146 /// Returns `true` if the global caches can be used.
1147 /// Do note that if the type itself is not in the
1148 /// global tcx, the local caches will be used.
1149 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1150 // If there are any inference variables in the `ParamEnv`, then we
1151 // always use a cache local to this particular scope. Otherwise, we
1152 // switch to a global cache.
1153 if param_env.needs_infer() {
1157 // Avoid using the master cache during coherence and just rely
1158 // on the local cache. This effectively disables caching
1159 // during coherence. It is really just a simplification to
1160 // avoid us having to fear that coherence results "pollute"
1161 // the master cache. Since coherence executes pretty quickly,
1162 // it's not worth going to more trouble to increase the
1163 // hit-rate, I don't think.
1164 if self.intercrate {
1168 // Otherwise, we can use the global cache.
1172 fn check_candidate_cache(
1174 param_env: ty::ParamEnv<'tcx>,
1175 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1176 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1177 let tcx = self.tcx();
1178 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1179 if self.can_use_global_caches(param_env) {
1180 let cache = tcx.selection_cache.hashmap.borrow();
1181 if let Some(cached) = cache.get(¶m_env.and(*trait_ref)) {
1182 return Some(cached.get(tcx));
1189 .get(¶m_env.and(*trait_ref))
1190 .map(|v| v.get(tcx))
1193 /// Determines whether can we safely cache the result
1194 /// of selecting an obligation. This is almost always `true`,
1195 /// except when dealing with certain `ParamCandidate`s.
1197 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1198 /// since it was usually produced directly from a `DefId`. However,
1199 /// certain cases (currently only librustdoc's blanket impl finder),
1200 /// a `ParamEnv` may be explicitly constructed with inference types.
1201 /// When this is the case, we do *not* want to cache the resulting selection
1202 /// candidate. This is due to the fact that it might not always be possible
1203 /// to equate the obligation's trait ref and the candidate's trait ref,
1204 /// if more constraints end up getting added to an inference variable.
1206 /// Because of this, we always want to re-run the full selection
1207 /// process for our obligation the next time we see it, since
1208 /// we might end up picking a different `SelectionCandidate` (or none at all).
1209 fn can_cache_candidate(
1211 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1214 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1219 fn insert_candidate_cache(
1221 param_env: ty::ParamEnv<'tcx>,
1222 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1223 dep_node: DepNodeIndex,
1224 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1226 let tcx = self.tcx();
1227 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1229 if !self.can_cache_candidate(&candidate) {
1231 "insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1232 candidate is not cacheable",
1233 trait_ref, candidate
1238 if self.can_use_global_caches(param_env) {
1239 if let Err(Overflow) = candidate {
1240 // Don't cache overflow globally; we only produce this in certain modes.
1241 } else if !trait_ref.needs_infer() {
1242 if !candidate.needs_infer() {
1244 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1245 trait_ref, candidate,
1247 // This may overwrite the cache with the same value.
1251 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1258 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1259 trait_ref, candidate,
1265 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1268 fn match_projection_obligation_against_definition_bounds(
1270 obligation: &TraitObligation<'tcx>,
1272 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1273 let (placeholder_trait_predicate, _) =
1274 self.infcx().replace_bound_vars_with_placeholders(&poly_trait_predicate);
1276 "match_projection_obligation_against_definition_bounds: \
1277 placeholder_trait_predicate={:?}",
1278 placeholder_trait_predicate,
1281 let tcx = self.infcx.tcx;
1282 let predicates = match placeholder_trait_predicate.trait_ref.self_ty().kind {
1283 ty::Projection(ref data) => {
1284 tcx.projection_predicates(data.item_def_id).subst(tcx, data.substs)
1286 ty::Opaque(def_id, substs) => tcx.projection_predicates(def_id).subst(tcx, substs),
1289 obligation.cause.span,
1290 "match_projection_obligation_against_definition_bounds() called \
1291 but self-ty is not a projection: {:?}",
1292 placeholder_trait_predicate.trait_ref.self_ty()
1297 let matching_bound = predicates.iter().find_map(|bound| {
1298 if let ty::PredicateKind::Trait(bound, _) = bound.kind() {
1299 let bound = bound.to_poly_trait_ref();
1300 if self.infcx.probe(|_| {
1301 self.match_projection(obligation, bound, placeholder_trait_predicate.trait_ref)
1310 "match_projection_obligation_against_definition_bounds: \
1311 matching_bound={:?}",
1314 match matching_bound {
1317 // Repeat the successful match, if any, this time outside of a probe.
1319 self.match_projection(obligation, bound, placeholder_trait_predicate.trait_ref);
1327 fn match_projection(
1329 obligation: &TraitObligation<'tcx>,
1330 trait_bound: ty::PolyTraitRef<'tcx>,
1331 placeholder_trait_ref: ty::TraitRef<'tcx>,
1333 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1335 .at(&obligation.cause, obligation.param_env)
1336 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1340 fn evaluate_where_clause<'o>(
1342 stack: &TraitObligationStack<'o, 'tcx>,
1343 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1344 ) -> Result<EvaluationResult, OverflowError> {
1345 self.evaluation_probe(|this| {
1346 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1347 Ok(obligations) => {
1348 this.evaluate_predicates_recursively(stack.list(), obligations.into_iter())
1350 Err(()) => Ok(EvaluatedToErr),
1355 ///////////////////////////////////////////////////////////////////////////
1358 // Winnowing is the process of attempting to resolve ambiguity by
1359 // probing further. During the winnowing process, we unify all
1360 // type variables and then we also attempt to evaluate recursive
1361 // bounds to see if they are satisfied.
1363 /// Returns `true` if `victim` should be dropped in favor of
1364 /// `other`. Generally speaking we will drop duplicate
1365 /// candidates and prefer where-clause candidates.
1367 /// See the comment for "SelectionCandidate" for more details.
1368 fn candidate_should_be_dropped_in_favor_of(
1370 victim: &EvaluatedCandidate<'tcx>,
1371 other: &EvaluatedCandidate<'tcx>,
1374 if victim.candidate == other.candidate {
1378 // Check if a bound would previously have been removed when normalizing
1379 // the param_env so that it can be given the lowest priority. See
1380 // #50825 for the motivation for this.
1382 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
1384 // (*) Prefer `BuiltinCandidate { has_nested: false }` and `DiscriminantKindCandidate`
1385 // to anything else.
1387 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1388 // lifetime of a variable.
1389 match other.candidate {
1391 BuiltinCandidate { has_nested: false } | DiscriminantKindCandidate => true,
1392 ParamCandidate(ref cand) => match victim.candidate {
1393 AutoImplCandidate(..) => {
1395 "default implementations shouldn't be recorded \
1396 when there are other valid candidates"
1400 BuiltinCandidate { has_nested: false } | DiscriminantKindCandidate => false,
1403 | GeneratorCandidate
1404 | FnPointerCandidate
1405 | BuiltinObjectCandidate
1406 | BuiltinUnsizeCandidate
1407 | BuiltinCandidate { .. }
1408 | TraitAliasCandidate(..) => {
1409 // Global bounds from the where clause should be ignored
1410 // here (see issue #50825). Otherwise, we have a where
1411 // clause so don't go around looking for impls.
1414 ObjectCandidate | ProjectionCandidate => {
1415 // Arbitrarily give param candidates priority
1416 // over projection and object candidates.
1419 ParamCandidate(..) => false,
1421 ObjectCandidate | ProjectionCandidate => match victim.candidate {
1422 AutoImplCandidate(..) => {
1424 "default implementations shouldn't be recorded \
1425 when there are other valid candidates"
1429 BuiltinCandidate { has_nested: false } | DiscriminantKindCandidate => false,
1432 | GeneratorCandidate
1433 | FnPointerCandidate
1434 | BuiltinObjectCandidate
1435 | BuiltinUnsizeCandidate
1436 | BuiltinCandidate { .. }
1437 | TraitAliasCandidate(..) => true,
1438 ObjectCandidate | ProjectionCandidate => {
1439 // Arbitrarily give param candidates priority
1440 // over projection and object candidates.
1443 ParamCandidate(ref cand) => is_global(cand),
1445 ImplCandidate(other_def) => {
1446 // See if we can toss out `victim` based on specialization.
1447 // This requires us to know *for sure* that the `other` impl applies
1448 // i.e., `EvaluatedToOk`.
1449 if other.evaluation.must_apply_modulo_regions() {
1450 match victim.candidate {
1451 ImplCandidate(victim_def) => {
1452 let tcx = self.tcx();
1453 if tcx.specializes((other_def, victim_def)) {
1456 return match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1457 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1458 // Subtle: If the predicate we are evaluating has inference
1459 // variables, do *not* allow discarding candidates due to
1460 // marker trait impls.
1462 // Without this restriction, we could end up accidentally
1463 // constrainting inference variables based on an arbitrarily
1464 // chosen trait impl.
1466 // Imagine we have the following code:
1469 // #[marker] trait MyTrait {}
1470 // impl MyTrait for u8 {}
1471 // impl MyTrait for bool {}
1474 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1476 // During selection, we will end up with one candidate for each
1477 // impl of `MyTrait`. If we were to discard one impl in favor
1478 // of the other, we would be left with one candidate, causing
1479 // us to "successfully" select the predicate, unifying
1480 // _#0t with (for example) `u8`.
1482 // However, we have no reason to believe that this unification
1483 // is correct - we've essentially just picked an arbitrary
1484 // *possibility* for _#0t, and required that this be the *only*
1487 // Eventually, we will either:
1488 // 1) Unify all inference variables in the predicate through
1489 // some other means (e.g. type-checking of a function). We will
1490 // then be in a position to drop marker trait candidates
1491 // without constraining inference variables (since there are
1492 // none left to constrin)
1493 // 2) Be left with some unconstrained inference variables. We
1494 // will then correctly report an inference error, since the
1495 // existence of multiple marker trait impls tells us nothing
1496 // about which one should actually apply.
1503 ParamCandidate(ref cand) => {
1504 // Prefer the impl to a global where clause candidate.
1505 return is_global(cand);
1514 | GeneratorCandidate
1515 | FnPointerCandidate
1516 | BuiltinObjectCandidate
1517 | BuiltinUnsizeCandidate
1518 | BuiltinCandidate { has_nested: true } => {
1519 match victim.candidate {
1520 ParamCandidate(ref cand) => {
1521 // Prefer these to a global where-clause bound
1522 // (see issue #50825).
1523 is_global(cand) && other.evaluation.must_apply_modulo_regions()
1532 fn sized_conditions(
1534 obligation: &TraitObligation<'tcx>,
1535 ) -> BuiltinImplConditions<'tcx> {
1536 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1538 // NOTE: binder moved to (*)
1539 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1541 match self_ty.kind {
1542 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1553 | ty::GeneratorWitness(..)
1558 // safe for everything
1559 Where(ty::Binder::dummy(Vec::new()))
1562 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1565 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
1568 ty::Adt(def, substs) => {
1569 let sized_crit = def.sized_constraint(self.tcx());
1570 // (*) binder moved here
1571 Where(ty::Binder::bind(
1572 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect(),
1576 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1577 ty::Infer(ty::TyVar(_)) => Ambiguous,
1581 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1582 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1587 fn copy_clone_conditions(
1589 obligation: &TraitObligation<'tcx>,
1590 ) -> BuiltinImplConditions<'tcx> {
1591 // NOTE: binder moved to (*)
1592 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1594 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1596 match self_ty.kind {
1597 ty::Infer(ty::IntVar(_))
1598 | ty::Infer(ty::FloatVar(_))
1601 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1610 | ty::Ref(_, _, hir::Mutability::Not) => {
1611 // Implementations provided in libcore
1619 | ty::GeneratorWitness(..)
1621 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1623 ty::Array(element_ty, _) => {
1624 // (*) binder moved here
1625 Where(ty::Binder::bind(vec![element_ty]))
1629 // (*) binder moved here
1630 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
1633 ty::Closure(_, substs) => {
1634 // (*) binder moved here
1635 Where(ty::Binder::bind(substs.as_closure().upvar_tys().collect()))
1638 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1639 // Fallback to whatever user-defined impls exist in this case.
1643 ty::Infer(ty::TyVar(_)) => {
1644 // Unbound type variable. Might or might not have
1645 // applicable impls and so forth, depending on what
1646 // those type variables wind up being bound to.
1652 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1653 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1658 /// For default impls, we need to break apart a type into its
1659 /// "constituent types" -- meaning, the types that it contains.
1661 /// Here are some (simple) examples:
1664 /// (i32, u32) -> [i32, u32]
1665 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1666 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1667 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1669 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
1679 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1681 | ty::Char => Vec::new(),
1687 | ty::Projection(..)
1689 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1690 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1693 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1697 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
1699 ty::Tuple(ref tys) => {
1700 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1701 tys.iter().map(|k| k.expect_ty()).collect()
1704 ty::Closure(_, ref substs) => substs.as_closure().upvar_tys().collect(),
1706 ty::Generator(_, ref substs, _) => {
1707 let witness = substs.as_generator().witness();
1708 substs.as_generator().upvar_tys().chain(iter::once(witness)).collect()
1711 ty::GeneratorWitness(types) => {
1712 // This is sound because no regions in the witness can refer to
1713 // the binder outside the witness. So we'll effectivly reuse
1714 // the implicit binder around the witness.
1715 types.skip_binder().to_vec()
1718 // For `PhantomData<T>`, we pass `T`.
1719 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
1721 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
1723 ty::Opaque(def_id, substs) => {
1724 // We can resolve the `impl Trait` to its concrete type,
1725 // which enforces a DAG between the functions requiring
1726 // the auto trait bounds in question.
1727 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
1732 fn collect_predicates_for_types(
1734 param_env: ty::ParamEnv<'tcx>,
1735 cause: ObligationCause<'tcx>,
1736 recursion_depth: usize,
1737 trait_def_id: DefId,
1738 types: ty::Binder<Vec<Ty<'tcx>>>,
1739 ) -> Vec<PredicateObligation<'tcx>> {
1740 // Because the types were potentially derived from
1741 // higher-ranked obligations they may reference late-bound
1742 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
1743 // yield a type like `for<'a> &'a i32`. In general, we
1744 // maintain the invariant that we never manipulate bound
1745 // regions, so we have to process these bound regions somehow.
1747 // The strategy is to:
1749 // 1. Instantiate those regions to placeholder regions (e.g.,
1750 // `for<'a> &'a i32` becomes `&0 i32`.
1751 // 2. Produce something like `&'0 i32 : Copy`
1752 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
1755 .skip_binder() // binder moved -\
1758 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
1760 self.infcx.commit_unconditionally(|_| {
1761 let (placeholder_ty, _) = self.infcx.replace_bound_vars_with_placeholders(&ty);
1762 let Normalized { value: normalized_ty, mut obligations } =
1763 ensure_sufficient_stack(|| {
1764 project::normalize_with_depth(
1772 let placeholder_obligation = predicate_for_trait_def(
1781 obligations.push(placeholder_obligation);
1788 ///////////////////////////////////////////////////////////////////////////
1791 // Matching is a common path used for both evaluation and
1792 // confirmation. It basically unifies types that appear in impls
1793 // and traits. This does affect the surrounding environment;
1794 // therefore, when used during evaluation, match routines must be
1795 // run inside of a `probe()` so that their side-effects are
1801 obligation: &TraitObligation<'tcx>,
1802 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
1803 match self.match_impl(impl_def_id, obligation) {
1804 Ok(substs) => substs,
1807 "Impl {:?} was matchable against {:?} but now is not",
1818 obligation: &TraitObligation<'tcx>,
1819 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
1820 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
1822 // Before we create the substitutions and everything, first
1823 // consider a "quick reject". This avoids creating more types
1824 // and so forth that we need to.
1825 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
1829 let (placeholder_obligation, _) =
1830 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
1831 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
1833 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
1835 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
1837 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
1838 ensure_sufficient_stack(|| {
1839 project::normalize_with_depth(
1841 obligation.param_env,
1842 obligation.cause.clone(),
1843 obligation.recursion_depth + 1,
1849 "match_impl(impl_def_id={:?}, obligation={:?}, \
1850 impl_trait_ref={:?}, placeholder_obligation_trait_ref={:?})",
1851 impl_def_id, obligation, impl_trait_ref, placeholder_obligation_trait_ref
1854 let InferOk { obligations, .. } = self
1856 .at(&obligation.cause, obligation.param_env)
1857 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
1858 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
1859 nested_obligations.extend(obligations);
1862 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
1864 debug!("match_impl: reservation impls only apply in intercrate mode");
1868 debug!("match_impl: success impl_substs={:?}", impl_substs);
1869 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
1872 fn fast_reject_trait_refs(
1874 obligation: &TraitObligation<'_>,
1875 impl_trait_ref: &ty::TraitRef<'_>,
1877 // We can avoid creating type variables and doing the full
1878 // substitution if we find that any of the input types, when
1879 // simplified, do not match.
1881 obligation.predicate.skip_binder().trait_ref.substs.iter().zip(impl_trait_ref.substs).any(
1882 |(obligation_arg, impl_arg)| {
1883 match (obligation_arg.unpack(), impl_arg.unpack()) {
1884 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
1885 let simplified_obligation_ty =
1886 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
1887 let simplified_impl_ty =
1888 fast_reject::simplify_type(self.tcx(), impl_ty, false);
1890 simplified_obligation_ty.is_some()
1891 && simplified_impl_ty.is_some()
1892 && simplified_obligation_ty != simplified_impl_ty
1894 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
1895 // Lifetimes can never cause a rejection.
1898 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
1899 // Conservatively ignore consts (i.e. assume they might
1900 // unify later) until we have `fast_reject` support for
1901 // them (if we'll ever need it, even).
1904 _ => unreachable!(),
1910 /// Normalize `where_clause_trait_ref` and try to match it against
1911 /// `obligation`. If successful, return any predicates that
1912 /// result from the normalization. Normalization is necessary
1913 /// because where-clauses are stored in the parameter environment
1915 fn match_where_clause_trait_ref(
1917 obligation: &TraitObligation<'tcx>,
1918 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1919 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
1920 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
1923 /// Returns `Ok` if `poly_trait_ref` being true implies that the
1924 /// obligation is satisfied.
1925 fn match_poly_trait_ref(
1927 obligation: &TraitObligation<'tcx>,
1928 poly_trait_ref: ty::PolyTraitRef<'tcx>,
1929 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
1931 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
1932 obligation, poly_trait_ref
1936 .at(&obligation.cause, obligation.param_env)
1937 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
1938 .map(|InferOk { obligations, .. }| obligations)
1942 ///////////////////////////////////////////////////////////////////////////
1945 fn match_fresh_trait_refs(
1947 previous: ty::PolyTraitRef<'tcx>,
1948 current: ty::PolyTraitRef<'tcx>,
1949 param_env: ty::ParamEnv<'tcx>,
1951 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
1952 matcher.relate(previous, current).is_ok()
1957 previous_stack: TraitObligationStackList<'o, 'tcx>,
1958 obligation: &'o TraitObligation<'tcx>,
1959 ) -> TraitObligationStack<'o, 'tcx> {
1960 let fresh_trait_ref =
1961 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
1963 let dfn = previous_stack.cache.next_dfn();
1964 let depth = previous_stack.depth() + 1;
1965 TraitObligationStack {
1968 reached_depth: Cell::new(depth),
1969 previous: previous_stack,
1975 fn closure_trait_ref_unnormalized(
1977 obligation: &TraitObligation<'tcx>,
1978 substs: SubstsRef<'tcx>,
1979 ) -> ty::PolyTraitRef<'tcx> {
1980 debug!("closure_trait_ref_unnormalized(obligation={:?}, substs={:?})", obligation, substs);
1981 let closure_sig = substs.as_closure().sig();
1983 debug!("closure_trait_ref_unnormalized: closure_sig = {:?}", closure_sig);
1985 // (1) Feels icky to skip the binder here, but OTOH we know
1986 // that the self-type is an unboxed closure type and hence is
1987 // in fact unparameterized (or at least does not reference any
1988 // regions bound in the obligation). Still probably some
1989 // refactoring could make this nicer.
1990 closure_trait_ref_and_return_type(
1992 obligation.predicate.def_id(),
1993 obligation.predicate.skip_binder().self_ty(), // (1)
1995 util::TupleArgumentsFlag::No,
1997 .map_bound(|(trait_ref, _)| trait_ref)
2000 fn generator_trait_ref_unnormalized(
2002 obligation: &TraitObligation<'tcx>,
2003 substs: SubstsRef<'tcx>,
2004 ) -> ty::PolyTraitRef<'tcx> {
2005 let gen_sig = substs.as_generator().poly_sig();
2007 // (1) Feels icky to skip the binder here, but OTOH we know
2008 // that the self-type is an generator type and hence is
2009 // in fact unparameterized (or at least does not reference any
2010 // regions bound in the obligation). Still probably some
2011 // refactoring could make this nicer.
2013 super::util::generator_trait_ref_and_outputs(
2015 obligation.predicate.def_id(),
2016 obligation.predicate.skip_binder().self_ty(), // (1)
2019 .map_bound(|(trait_ref, ..)| trait_ref)
2022 /// Returns the obligations that are implied by instantiating an
2023 /// impl or trait. The obligations are substituted and fully
2024 /// normalized. This is used when confirming an impl or default
2026 fn impl_or_trait_obligations(
2028 cause: ObligationCause<'tcx>,
2029 recursion_depth: usize,
2030 param_env: ty::ParamEnv<'tcx>,
2031 def_id: DefId, // of impl or trait
2032 substs: SubstsRef<'tcx>, // for impl or trait
2033 ) -> Vec<PredicateObligation<'tcx>> {
2034 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
2035 let tcx = self.tcx();
2037 // To allow for one-pass evaluation of the nested obligation,
2038 // each predicate must be preceded by the obligations required
2040 // for example, if we have:
2041 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2042 // the impl will have the following predicates:
2043 // <V as Iterator>::Item = U,
2044 // U: Iterator, U: Sized,
2045 // V: Iterator, V: Sized,
2046 // <U as Iterator>::Item: Copy
2047 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2048 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2049 // `$1: Copy`, so we must ensure the obligations are emitted in
2051 let predicates = tcx.predicates_of(def_id);
2052 assert_eq!(predicates.parent, None);
2053 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2054 for (predicate, _) in predicates.predicates {
2055 let predicate = normalize_with_depth_to(
2060 &predicate.subst(tcx, substs),
2063 obligations.push(Obligation {
2064 cause: cause.clone(),
2071 // We are performing deduplication here to avoid exponential blowups
2072 // (#38528) from happening, but the real cause of the duplication is
2073 // unknown. What we know is that the deduplication avoids exponential
2074 // amount of predicates being propagated when processing deeply nested
2077 // This code is hot enough that it's worth avoiding the allocation
2078 // required for the FxHashSet when possible. Special-casing lengths 0,
2079 // 1 and 2 covers roughly 75-80% of the cases.
2080 if obligations.len() <= 1 {
2081 // No possibility of duplicates.
2082 } else if obligations.len() == 2 {
2083 // Only two elements. Drop the second if they are equal.
2084 if obligations[0] == obligations[1] {
2085 obligations.truncate(1);
2088 // Three or more elements. Use a general deduplication process.
2089 let mut seen = FxHashSet::default();
2090 obligations.retain(|i| seen.insert(i.clone()));
2097 trait TraitObligationExt<'tcx> {
2100 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2101 ) -> ObligationCause<'tcx>;
2104 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2105 #[allow(unused_comparisons)]
2108 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2109 ) -> ObligationCause<'tcx> {
2111 * Creates a cause for obligations that are derived from
2112 * `obligation` by a recursive search (e.g., for a builtin
2113 * bound, or eventually a `auto trait Foo`). If `obligation`
2114 * is itself a derived obligation, this is just a clone, but
2115 * otherwise we create a "derived obligation" cause so as to
2116 * keep track of the original root obligation for error
2120 let obligation = self;
2122 // NOTE(flaper87): As of now, it keeps track of the whole error
2123 // chain. Ideally, we should have a way to configure this either
2124 // by using -Z verbose or just a CLI argument.
2125 let derived_cause = DerivedObligationCause {
2126 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2127 parent_code: Rc::new(obligation.cause.code.clone()),
2129 let derived_code = variant(derived_cause);
2130 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2134 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2135 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2136 TraitObligationStackList::with(self)
2139 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2143 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2147 /// Indicates that attempting to evaluate this stack entry
2148 /// required accessing something from the stack at depth `reached_depth`.
2149 fn update_reached_depth(&self, reached_depth: usize) {
2151 self.depth > reached_depth,
2152 "invoked `update_reached_depth` with something under this stack: \
2153 self.depth={} reached_depth={}",
2157 debug!("update_reached_depth(reached_depth={})", reached_depth);
2159 while reached_depth < p.depth {
2160 debug!("update_reached_depth: marking {:?} as cycle participant", p.fresh_trait_ref);
2161 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2162 p = p.previous.head.unwrap();
2167 /// The "provisional evaluation cache" is used to store intermediate cache results
2168 /// when solving auto traits. Auto traits are unusual in that they can support
2169 /// cycles. So, for example, a "proof tree" like this would be ok:
2171 /// - `Foo<T>: Send` :-
2172 /// - `Bar<T>: Send` :-
2173 /// - `Foo<T>: Send` -- cycle, but ok
2174 /// - `Baz<T>: Send`
2176 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2177 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2178 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2179 /// they are coinductive) it is considered ok.
2181 /// However, there is a complication: at the point where we have
2182 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2183 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2184 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2185 /// find out this assumption is wrong? Specifically, we could
2186 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2187 /// `Bar<T>: Send` didn't turn out to be true.
2189 /// In Issue #60010, we found a bug in rustc where it would cache
2190 /// these intermediate results. This was fixed in #60444 by disabling
2191 /// *all* caching for things involved in a cycle -- in our example,
2192 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2193 /// to large slowdowns.
2195 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2196 /// first requires proving `Bar<T>: Send` (which is true:
2198 /// - `Foo<T>: Send` :-
2199 /// - `Bar<T>: Send` :-
2200 /// - `Foo<T>: Send` -- cycle, but ok
2201 /// - `Baz<T>: Send`
2202 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2203 /// - `*const T: Send` -- but what if we later encounter an error?
2205 /// The *provisional evaluation cache* resolves this issue. It stores
2206 /// cache results that we've proven but which were involved in a cycle
2207 /// in some way. We track the minimal stack depth (i.e., the
2208 /// farthest from the top of the stack) that we are dependent on.
2209 /// The idea is that the cache results within are all valid -- so long as
2210 /// none of the nodes in between the current node and the node at that minimum
2211 /// depth result in an error (in which case the cached results are just thrown away).
2213 /// During evaluation, we consult this provisional cache and rely on
2214 /// it. Accessing a cached value is considered equivalent to accessing
2215 /// a result at `reached_depth`, so it marks the *current* solution as
2216 /// provisional as well. If an error is encountered, we toss out any
2217 /// provisional results added from the subtree that encountered the
2218 /// error. When we pop the node at `reached_depth` from the stack, we
2219 /// can commit all the things that remain in the provisional cache.
2220 struct ProvisionalEvaluationCache<'tcx> {
2221 /// next "depth first number" to issue -- just a counter
2224 /// Stores the "coldest" depth (bottom of stack) reached by any of
2225 /// the evaluation entries. The idea here is that all things in the provisional
2226 /// cache are always dependent on *something* that is colder in the stack:
2227 /// therefore, if we add a new entry that is dependent on something *colder still*,
2228 /// we have to modify the depth for all entries at once.
2232 /// Imagine we have a stack `A B C D E` (with `E` being the top of
2233 /// the stack). We cache something with depth 2, which means that
2234 /// it was dependent on C. Then we pop E but go on and process a
2235 /// new node F: A B C D F. Now F adds something to the cache with
2236 /// depth 1, meaning it is dependent on B. Our original cache
2237 /// entry is also dependent on B, because there is a path from E
2238 /// to C and then from C to F and from F to B.
2239 reached_depth: Cell<usize>,
2241 /// Map from cache key to the provisionally evaluated thing.
2242 /// The cache entries contain the result but also the DFN in which they
2243 /// were added. The DFN is used to clear out values on failure.
2245 /// Imagine we have a stack like:
2247 /// - `A B C` and we add a cache for the result of C (DFN 2)
2248 /// - Then we have a stack `A B D` where `D` has DFN 3
2249 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2250 /// - `E` generates various cache entries which have cyclic dependices on `B`
2251 /// - `A B D E F` and so forth
2252 /// - the DFN of `F` for example would be 5
2253 /// - then we determine that `E` is in error -- we will then clear
2254 /// all cache values whose DFN is >= 4 -- in this case, that
2255 /// means the cached value for `F`.
2256 map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
2259 /// A cache value for the provisional cache: contains the depth-first
2260 /// number (DFN) and result.
2261 #[derive(Copy, Clone, Debug)]
2262 struct ProvisionalEvaluation {
2264 result: EvaluationResult,
2267 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2268 fn default() -> Self {
2269 Self { dfn: Cell::new(0), reached_depth: Cell::new(usize::MAX), map: Default::default() }
2273 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2274 /// Get the next DFN in sequence (basically a counter).
2275 fn next_dfn(&self) -> usize {
2276 let result = self.dfn.get();
2277 self.dfn.set(result + 1);
2281 /// Check the provisional cache for any result for
2282 /// `fresh_trait_ref`. If there is a hit, then you must consider
2283 /// it an access to the stack slots at depth
2284 /// `self.current_reached_depth()` and above.
2285 fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
2287 "get_provisional(fresh_trait_ref={:?}) = {:#?} with reached-depth {}",
2289 self.map.borrow().get(&fresh_trait_ref),
2290 self.reached_depth.get(),
2292 Some(self.map.borrow().get(&fresh_trait_ref)?.result)
2295 /// Current value of the `reached_depth` counter -- all the
2296 /// provisional cache entries are dependent on the item at this
2298 fn current_reached_depth(&self) -> usize {
2299 self.reached_depth.get()
2302 /// Insert a provisional result into the cache. The result came
2303 /// from the node with the given DFN. It accessed a minimum depth
2304 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
2305 /// and resulted in `result`.
2306 fn insert_provisional(
2309 reached_depth: usize,
2310 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
2311 result: EvaluationResult,
2314 "insert_provisional(from_dfn={}, reached_depth={}, fresh_trait_ref={:?}, result={:?})",
2315 from_dfn, reached_depth, fresh_trait_ref, result,
2317 let r_d = self.reached_depth.get();
2318 self.reached_depth.set(r_d.min(reached_depth));
2320 debug!("insert_provisional: reached_depth={:?}", self.reached_depth.get());
2322 self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
2325 /// Invoked when the node with dfn `dfn` does not get a successful
2326 /// result. This will clear out any provisional cache entries
2327 /// that were added since `dfn` was created. This is because the
2328 /// provisional entries are things which must assume that the
2329 /// things on the stack at the time of their creation succeeded --
2330 /// since the failing node is presently at the top of the stack,
2331 /// these provisional entries must either depend on it or some
2333 fn on_failure(&self, dfn: usize) {
2334 debug!("on_failure(dfn={:?})", dfn,);
2335 self.map.borrow_mut().retain(|key, eval| {
2336 if !eval.from_dfn >= dfn {
2337 debug!("on_failure: removing {:?}", key);
2345 /// Invoked when the node at depth `depth` completed without
2346 /// depending on anything higher in the stack (if that completion
2347 /// was a failure, then `on_failure` should have been invoked
2348 /// already). The callback `op` will be invoked for each
2349 /// provisional entry that we can now confirm.
2353 mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
2355 debug!("on_completion(depth={}, reached_depth={})", depth, self.reached_depth.get(),);
2357 if self.reached_depth.get() < depth {
2358 debug!("on_completion: did not yet reach depth to complete");
2362 for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
2363 debug!("on_completion: fresh_trait_ref={:?} eval={:?}", fresh_trait_ref, eval,);
2365 op(fresh_trait_ref, eval.result);
2368 self.reached_depth.set(usize::MAX);
2372 #[derive(Copy, Clone)]
2373 struct TraitObligationStackList<'o, 'tcx> {
2374 cache: &'o ProvisionalEvaluationCache<'tcx>,
2375 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2378 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2379 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2380 TraitObligationStackList { cache, head: None }
2383 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2384 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2387 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2391 fn depth(&self) -> usize {
2392 if let Some(head) = self.head { head.depth } else { 0 }
2396 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2397 type Item = &'o TraitObligationStack<'o, 'tcx>;
2399 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2410 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2411 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2412 write!(f, "TraitObligationStack({:?})", self.obligation)