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::{
39 self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
41 use rustc_span::symbol::sym;
43 use std::cell::{Cell, RefCell};
45 use std::fmt::{self, Display};
49 pub use rustc_middle::traits::select::*;
51 mod candidate_assembly;
54 pub struct SelectionContext<'cx, 'tcx> {
55 infcx: &'cx InferCtxt<'cx, 'tcx>,
57 /// Freshener used specifically for entries on the obligation
58 /// stack. This ensures that all entries on the stack at one time
59 /// will have the same set of placeholder entries, which is
60 /// important for checking for trait bounds that recursively
61 /// require themselves.
62 freshener: TypeFreshener<'cx, 'tcx>,
64 /// If `true`, indicates that the evaluation should be conservative
65 /// and consider the possibility of types outside this crate.
66 /// This comes up primarily when resolving ambiguity. Imagine
67 /// there is some trait reference `$0: Bar` where `$0` is an
68 /// inference variable. If `intercrate` is true, then we can never
69 /// say for sure that this reference is not implemented, even if
70 /// there are *no impls at all for `Bar`*, because `$0` could be
71 /// bound to some type that in a downstream crate that implements
72 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
73 /// though, we set this to false, because we are only interested
74 /// in types that the user could actually have written --- in
75 /// other words, we consider `$0: Bar` to be unimplemented if
76 /// there is no type that the user could *actually name* that
77 /// would satisfy it. This avoids crippling inference, basically.
80 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
82 /// Controls whether or not to filter out negative impls when selecting.
83 /// This is used in librustdoc to distinguish between the lack of an impl
84 /// and a negative impl
85 allow_negative_impls: bool,
87 /// The mode that trait queries run in, which informs our error handling
88 /// policy. In essence, canonicalized queries need their errors propagated
89 /// rather than immediately reported because we do not have accurate spans.
90 query_mode: TraitQueryMode,
93 // A stack that walks back up the stack frame.
94 struct TraitObligationStack<'prev, 'tcx> {
95 obligation: &'prev TraitObligation<'tcx>,
97 /// The trait ref from `obligation` but "freshened" with the
98 /// selection-context's freshener. Used to check for recursion.
99 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
101 /// Starts out equal to `depth` -- if, during evaluation, we
102 /// encounter a cycle, then we will set this flag to the minimum
103 /// depth of that cycle for all participants in the cycle. These
104 /// participants will then forego caching their results. This is
105 /// not the most efficient solution, but it addresses #60010. The
106 /// problem we are trying to prevent:
108 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
109 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
110 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
112 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
113 /// is `EvaluatedToOk`; this is because they were only considered
114 /// ok on the premise that if `A: AutoTrait` held, but we indeed
115 /// encountered a problem (later on) with `A: AutoTrait. So we
116 /// currently set a flag on the stack node for `B: AutoTrait` (as
117 /// well as the second instance of `A: AutoTrait`) to suppress
120 /// This is a simple, targeted fix. A more-performant fix requires
121 /// deeper changes, but would permit more caching: we could
122 /// basically defer caching until we have fully evaluated the
123 /// tree, and then cache the entire tree at once. In any case, the
124 /// performance impact here shouldn't be so horrible: every time
125 /// this is hit, we do cache at least one trait, so we only
126 /// evaluate each member of a cycle up to N times, where N is the
127 /// length of the cycle. This means the performance impact is
128 /// bounded and we shouldn't have any terrible worst-cases.
129 reached_depth: Cell<usize>,
131 previous: TraitObligationStackList<'prev, 'tcx>,
133 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
136 /// The depth-first number of this node in the search graph -- a
137 /// pre-order index. Basically, a freshly incremented counter.
141 struct SelectionCandidateSet<'tcx> {
142 // A list of candidates that definitely apply to the current
143 // obligation (meaning: types unify).
144 vec: Vec<SelectionCandidate<'tcx>>,
146 // If `true`, then there were candidates that might or might
147 // not have applied, but we couldn't tell. This occurs when some
148 // of the input types are type variables, in which case there are
149 // various "builtin" rules that might or might not trigger.
153 #[derive(PartialEq, Eq, Debug, Clone)]
154 struct EvaluatedCandidate<'tcx> {
155 candidate: SelectionCandidate<'tcx>,
156 evaluation: EvaluationResult,
159 /// When does the builtin impl for `T: Trait` apply?
160 enum BuiltinImplConditions<'tcx> {
161 /// The impl is conditional on `T1, T2, ...: Trait`.
162 Where(ty::Binder<Vec<Ty<'tcx>>>),
163 /// There is no built-in impl. There may be some other
164 /// candidate (a where-clause or user-defined impl).
166 /// It is unknown whether there is an impl.
170 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
171 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
174 freshener: infcx.freshener(),
176 intercrate_ambiguity_causes: None,
177 allow_negative_impls: false,
178 query_mode: TraitQueryMode::Standard,
182 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
185 freshener: infcx.freshener(),
187 intercrate_ambiguity_causes: None,
188 allow_negative_impls: false,
189 query_mode: TraitQueryMode::Standard,
193 pub fn with_negative(
194 infcx: &'cx InferCtxt<'cx, 'tcx>,
195 allow_negative_impls: bool,
196 ) -> SelectionContext<'cx, 'tcx> {
197 debug!("with_negative({:?})", allow_negative_impls);
200 freshener: infcx.freshener(),
202 intercrate_ambiguity_causes: None,
203 allow_negative_impls,
204 query_mode: TraitQueryMode::Standard,
208 pub fn with_query_mode(
209 infcx: &'cx InferCtxt<'cx, 'tcx>,
210 query_mode: TraitQueryMode,
211 ) -> SelectionContext<'cx, 'tcx> {
212 debug!("with_query_mode({:?})", query_mode);
215 freshener: infcx.freshener(),
217 intercrate_ambiguity_causes: None,
218 allow_negative_impls: false,
223 /// Enables tracking of intercrate ambiguity causes. These are
224 /// used in coherence to give improved diagnostics. We don't do
225 /// this until we detect a coherence error because it can lead to
226 /// false overflow results (#47139) and because it costs
227 /// computation time.
228 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
229 assert!(self.intercrate);
230 assert!(self.intercrate_ambiguity_causes.is_none());
231 self.intercrate_ambiguity_causes = Some(vec![]);
232 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
235 /// Gets the intercrate ambiguity causes collected since tracking
236 /// was enabled and disables tracking at the same time. If
237 /// tracking is not enabled, just returns an empty vector.
238 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
239 assert!(self.intercrate);
240 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
243 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
247 pub fn tcx(&self) -> TyCtxt<'tcx> {
251 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
255 ///////////////////////////////////////////////////////////////////////////
258 // The selection phase tries to identify *how* an obligation will
259 // be resolved. For example, it will identify which impl or
260 // parameter bound is to be used. The process can be inconclusive
261 // if the self type in the obligation is not fully inferred. Selection
262 // can result in an error in one of two ways:
264 // 1. If no applicable impl or parameter bound can be found.
265 // 2. If the output type parameters in the obligation do not match
266 // those specified by the impl/bound. For example, if the obligation
267 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
268 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
270 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
271 /// type environment by performing unification.
274 obligation: &TraitObligation<'tcx>,
275 ) -> SelectionResult<'tcx, Selection<'tcx>> {
276 debug!("select({:?})", obligation);
277 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
279 let pec = &ProvisionalEvaluationCache::default();
280 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
282 let candidate = match self.candidate_from_obligation(&stack) {
283 Err(SelectionError::Overflow) => {
284 // In standard mode, overflow must have been caught and reported
286 assert!(self.query_mode == TraitQueryMode::Canonical);
287 return Err(SelectionError::Overflow);
295 Ok(Some(candidate)) => candidate,
298 match self.confirm_candidate(obligation, candidate) {
299 Err(SelectionError::Overflow) => {
300 assert!(self.query_mode == TraitQueryMode::Canonical);
301 Err(SelectionError::Overflow)
304 Ok(candidate) => Ok(Some(candidate)),
308 ///////////////////////////////////////////////////////////////////////////
311 // Tests whether an obligation can be selected or whether an impl
312 // can be applied to particular types. It skips the "confirmation"
313 // step and hence completely ignores output type parameters.
315 // The result is "true" if the obligation *may* hold and "false" if
316 // we can be sure it does not.
318 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
319 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
320 debug!("predicate_may_hold_fatal({:?})", obligation);
322 // This fatal query is a stopgap that should only be used in standard mode,
323 // where we do not expect overflow to be propagated.
324 assert!(self.query_mode == TraitQueryMode::Standard);
326 self.evaluate_root_obligation(obligation)
327 .expect("Overflow should be caught earlier in standard query mode")
331 /// Evaluates whether the obligation `obligation` can be satisfied
332 /// and returns an `EvaluationResult`. This is meant for the
334 pub fn evaluate_root_obligation(
336 obligation: &PredicateObligation<'tcx>,
337 ) -> Result<EvaluationResult, OverflowError> {
338 self.evaluation_probe(|this| {
339 this.evaluate_predicate_recursively(
340 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
348 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
349 ) -> Result<EvaluationResult, OverflowError> {
350 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
351 let result = op(self)?;
353 match self.infcx.leak_check(true, snapshot) {
355 Err(_) => return Ok(EvaluatedToErr),
358 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
360 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
365 /// Evaluates the predicates in `predicates` recursively. Note that
366 /// this applies projections in the predicates, and therefore
367 /// is run within an inference probe.
368 fn evaluate_predicates_recursively<'o, I>(
370 stack: TraitObligationStackList<'o, 'tcx>,
372 ) -> Result<EvaluationResult, OverflowError>
374 I: IntoIterator<Item = PredicateObligation<'tcx>>,
376 let mut result = EvaluatedToOk;
377 for obligation in predicates {
378 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
379 debug!("evaluate_predicate_recursively({:?}) = {:?}", obligation, eval);
380 if let EvaluatedToErr = eval {
381 // fast-path - EvaluatedToErr is the top of the lattice,
382 // so we don't need to look on the other predicates.
383 return Ok(EvaluatedToErr);
385 result = cmp::max(result, eval);
391 fn evaluate_predicate_recursively<'o>(
393 previous_stack: TraitObligationStackList<'o, 'tcx>,
394 obligation: PredicateObligation<'tcx>,
395 ) -> Result<EvaluationResult, OverflowError> {
397 "evaluate_predicate_recursively(previous_stack={:?}, obligation={:?})",
398 previous_stack.head(),
402 // `previous_stack` stores a `TraitObligatiom`, while `obligation` is
403 // a `PredicateObligation`. These are distinct types, so we can't
404 // use any `Option` combinator method that would force them to be
406 match previous_stack.head() {
407 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
408 None => self.check_recursion_limit(&obligation, &obligation)?,
412 match obligation.predicate.ignore_qualifiers(self.tcx()).skip_binder().kind() {
413 ty::PredicateKind::ForAll(_) => {
414 bug!("unexpected predicate: {:?}", obligation.predicate)
416 &ty::PredicateKind::Trait(t, _) => {
417 let t = ty::Binder::bind(t);
418 debug_assert!(!t.has_escaping_bound_vars());
419 let obligation = obligation.with(t);
420 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
423 &ty::PredicateKind::Subtype(p) => {
424 let p = ty::Binder::bind(p);
425 // Does this code ever run?
426 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
427 Some(Ok(InferOk { mut obligations, .. })) => {
428 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
429 self.evaluate_predicates_recursively(
431 obligations.into_iter(),
434 Some(Err(_)) => Ok(EvaluatedToErr),
435 None => Ok(EvaluatedToAmbig),
439 &ty::PredicateKind::WellFormed(arg) => match wf::obligations(
441 obligation.param_env,
442 obligation.cause.body_id,
444 obligation.cause.span,
446 Some(mut obligations) => {
447 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
448 self.evaluate_predicates_recursively(previous_stack, obligations.into_iter())
450 None => Ok(EvaluatedToAmbig),
453 ty::PredicateKind::TypeOutlives(..) | ty::PredicateKind::RegionOutlives(..) => {
454 // We do not consider region relationships when evaluating trait matches.
455 Ok(EvaluatedToOkModuloRegions)
458 &ty::PredicateKind::ObjectSafe(trait_def_id) => {
459 if self.tcx().is_object_safe(trait_def_id) {
466 &ty::PredicateKind::Projection(data) => {
467 let data = ty::Binder::bind(data);
468 let project_obligation = obligation.with(data);
469 match project::poly_project_and_unify_type(self, &project_obligation) {
470 Ok(Some(mut subobligations)) => {
471 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
472 let result = self.evaluate_predicates_recursively(
474 subobligations.into_iter(),
477 ProjectionCacheKey::from_poly_projection_predicate(self, data)
479 self.infcx.inner.borrow_mut().projection_cache().complete(key);
483 Ok(None) => Ok(EvaluatedToAmbig),
484 Err(_) => Ok(EvaluatedToErr),
488 &ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
489 match self.infcx.closure_kind(closure_substs) {
490 Some(closure_kind) => {
491 if closure_kind.extends(kind) {
497 None => Ok(EvaluatedToAmbig),
501 &ty::PredicateKind::ConstEvaluatable(def_id, substs) => {
502 match self.tcx().const_eval_resolve(
503 obligation.param_env,
509 Ok(_) => Ok(EvaluatedToOk),
510 Err(ErrorHandled::TooGeneric) => Ok(EvaluatedToAmbig),
511 Err(_) => Ok(EvaluatedToErr),
515 ty::PredicateKind::ConstEquate(c1, c2) => {
516 debug!("evaluate_predicate_recursively: equating consts c1={:?} c2={:?}", c1, c2);
518 let evaluate = |c: &'tcx ty::Const<'tcx>| {
519 if let ty::ConstKind::Unevaluated(def, substs, promoted) = c.val {
522 obligation.param_env,
526 Some(obligation.cause.span),
528 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty))
534 match (evaluate(c1), evaluate(c2)) {
535 (Ok(c1), Ok(c2)) => {
536 match self.infcx().at(&obligation.cause, obligation.param_env).eq(c1, c2) {
537 Ok(_) => Ok(EvaluatedToOk),
538 Err(_) => Ok(EvaluatedToErr),
541 (Err(ErrorHandled::Reported(ErrorReported)), _)
542 | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
543 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => span_bug!(
544 obligation.cause.span(self.tcx()),
545 "ConstEquate: const_eval_resolve returned an unexpected error"
547 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
555 fn evaluate_trait_predicate_recursively<'o>(
557 previous_stack: TraitObligationStackList<'o, 'tcx>,
558 mut obligation: TraitObligation<'tcx>,
559 ) -> Result<EvaluationResult, OverflowError> {
560 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
563 && obligation.is_global()
564 && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst())
566 // If a param env has no global bounds, global obligations do not
567 // depend on its particular value in order to work, so we can clear
568 // out the param env and get better caching.
569 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
570 obligation.param_env = obligation.param_env.without_caller_bounds();
573 let stack = self.push_stack(previous_stack, &obligation);
574 let fresh_trait_ref = stack.fresh_trait_ref;
575 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
576 debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
580 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
581 debug!("PROVISIONAL CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
582 stack.update_reached_depth(stack.cache().current_reached_depth());
586 // Check if this is a match for something already on the
587 // stack. If so, we don't want to insert the result into the
588 // main cache (it is cycle dependent) nor the provisional
589 // cache (which is meant for things that have completed but
590 // for a "backedge" -- this result *is* the backedge).
591 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
592 return Ok(cycle_result);
595 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
596 let result = result?;
598 if !result.must_apply_modulo_regions() {
599 stack.cache().on_failure(stack.dfn);
602 let reached_depth = stack.reached_depth.get();
603 if reached_depth >= stack.depth {
604 debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
605 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
607 stack.cache().on_completion(stack.depth, |fresh_trait_ref, provisional_result| {
608 self.insert_evaluation_cache(
609 obligation.param_env,
612 provisional_result.max(result),
616 debug!("PROVISIONAL: {:?}={:?}", fresh_trait_ref, result);
618 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
619 is a cycle participant (at depth {}, reached depth {})",
620 fresh_trait_ref, stack.depth, reached_depth,
623 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
629 /// If there is any previous entry on the stack that precisely
630 /// matches this obligation, then we can assume that the
631 /// obligation is satisfied for now (still all other conditions
632 /// must be met of course). One obvious case this comes up is
633 /// marker traits like `Send`. Think of a linked list:
635 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
637 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
638 /// `Option<Box<List<T>>>` is `Send`, and in turn
639 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
642 /// Note that we do this comparison using the `fresh_trait_ref`
643 /// fields. Because these have all been freshened using
644 /// `self.freshener`, we can be sure that (a) this will not
645 /// affect the inferencer state and (b) that if we see two
646 /// fresh regions with the same index, they refer to the same
647 /// unbound type variable.
648 fn check_evaluation_cycle(
650 stack: &TraitObligationStack<'_, 'tcx>,
651 ) -> Option<EvaluationResult> {
652 if let Some(cycle_depth) = stack
654 .skip(1) // Skip top-most frame.
656 stack.obligation.param_env == prev.obligation.param_env
657 && stack.fresh_trait_ref == prev.fresh_trait_ref
659 .map(|stack| stack.depth)
662 "evaluate_stack({:?}) --> recursive at depth {}",
663 stack.fresh_trait_ref, cycle_depth,
666 // If we have a stack like `A B C D E A`, where the top of
667 // the stack is the final `A`, then this will iterate over
668 // `A, E, D, C, B` -- i.e., all the participants apart
669 // from the cycle head. We mark them as participating in a
670 // cycle. This suppresses caching for those nodes. See
671 // `in_cycle` field for more details.
672 stack.update_reached_depth(cycle_depth);
674 // Subtle: when checking for a coinductive cycle, we do
675 // not compare using the "freshened trait refs" (which
676 // have erased regions) but rather the fully explicit
677 // trait refs. This is important because it's only a cycle
678 // if the regions match exactly.
679 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
680 let tcx = self.tcx();
682 cycle.map(|stack| stack.obligation.predicate.without_const().to_predicate(tcx));
683 if self.coinductive_match(cycle) {
684 debug!("evaluate_stack({:?}) --> recursive, coinductive", stack.fresh_trait_ref);
687 debug!("evaluate_stack({:?}) --> recursive, inductive", stack.fresh_trait_ref);
688 Some(EvaluatedToRecur)
695 fn evaluate_stack<'o>(
697 stack: &TraitObligationStack<'o, 'tcx>,
698 ) -> Result<EvaluationResult, OverflowError> {
699 // In intercrate mode, whenever any of the generics are unbound,
700 // there can always be an impl. Even if there are no impls in
701 // this crate, perhaps the type would be unified with
702 // something from another crate that does provide an impl.
704 // In intra mode, we must still be conservative. The reason is
705 // that we want to avoid cycles. Imagine an impl like:
707 // impl<T:Eq> Eq for Vec<T>
709 // and a trait reference like `$0 : Eq` where `$0` is an
710 // unbound variable. When we evaluate this trait-reference, we
711 // will unify `$0` with `Vec<$1>` (for some fresh variable
712 // `$1`), on the condition that `$1 : Eq`. We will then wind
713 // up with many candidates (since that are other `Eq` impls
714 // that apply) and try to winnow things down. This results in
715 // a recursive evaluation that `$1 : Eq` -- as you can
716 // imagine, this is just where we started. To avoid that, we
717 // check for unbound variables and return an ambiguous (hence possible)
718 // match if we've seen this trait before.
720 // This suffices to allow chains like `FnMut` implemented in
721 // terms of `Fn` etc, but we could probably make this more
723 let unbound_input_types =
724 stack.fresh_trait_ref.skip_binder().substs.types().any(|ty| ty.is_fresh());
725 // This check was an imperfect workaround for a bug in the old
726 // intercrate mode; it should be removed when that goes away.
727 if unbound_input_types && self.intercrate {
729 "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
730 stack.fresh_trait_ref
732 // Heuristics: show the diagnostics when there are no candidates in crate.
733 if self.intercrate_ambiguity_causes.is_some() {
734 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
735 if let Ok(candidate_set) = self.assemble_candidates(stack) {
736 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
737 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
738 let self_ty = trait_ref.self_ty();
739 let cause = IntercrateAmbiguityCause::DownstreamCrate {
740 trait_desc: trait_ref.print_only_trait_path().to_string(),
741 self_desc: if self_ty.has_concrete_skeleton() {
742 Some(self_ty.to_string())
747 debug!("evaluate_stack: pushing cause = {:?}", cause);
748 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
752 return Ok(EvaluatedToAmbig);
754 if unbound_input_types
755 && stack.iter().skip(1).any(|prev| {
756 stack.obligation.param_env == prev.obligation.param_env
757 && self.match_fresh_trait_refs(
758 stack.fresh_trait_ref,
759 prev.fresh_trait_ref,
760 prev.obligation.param_env,
765 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
766 stack.fresh_trait_ref
768 return Ok(EvaluatedToUnknown);
771 match self.candidate_from_obligation(stack) {
772 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
773 Ok(None) => Ok(EvaluatedToAmbig),
774 Err(Overflow) => Err(OverflowError),
775 Err(..) => Ok(EvaluatedToErr),
779 /// For defaulted traits, we use a co-inductive strategy to solve, so
780 /// that recursion is ok. This routine returns `true` if the top of the
781 /// stack (`cycle[0]`):
783 /// - is a defaulted trait,
784 /// - it also appears in the backtrace at some position `X`,
785 /// - all the predicates at positions `X..` between `X` and the top are
786 /// also defaulted traits.
787 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
789 I: Iterator<Item = ty::Predicate<'tcx>>,
791 let mut cycle = cycle;
792 cycle.all(|predicate| self.coinductive_predicate(predicate))
795 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
796 let result = match predicate.ignore_qualifiers(self.tcx()).skip_binder().kind() {
797 ty::PredicateKind::Trait(ref data, _) => self.tcx().trait_is_auto(data.def_id()),
800 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
804 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
805 /// obligations are met. Returns whether `candidate` remains viable after this further
807 fn evaluate_candidate<'o>(
809 stack: &TraitObligationStack<'o, 'tcx>,
810 candidate: &SelectionCandidate<'tcx>,
811 ) -> Result<EvaluationResult, OverflowError> {
813 "evaluate_candidate: depth={} candidate={:?}",
814 stack.obligation.recursion_depth, candidate
816 let result = self.evaluation_probe(|this| {
817 let candidate = (*candidate).clone();
818 match this.confirm_candidate(stack.obligation, candidate) {
819 Ok(selection) => this.evaluate_predicates_recursively(
821 selection.nested_obligations().into_iter(),
823 Err(..) => Ok(EvaluatedToErr),
827 "evaluate_candidate: depth={} result={:?}",
828 stack.obligation.recursion_depth, result
833 fn check_evaluation_cache(
835 param_env: ty::ParamEnv<'tcx>,
836 trait_ref: ty::PolyTraitRef<'tcx>,
837 ) -> Option<EvaluationResult> {
838 let tcx = self.tcx();
839 if self.can_use_global_caches(param_env) {
840 let cache = tcx.evaluation_cache.hashmap.borrow();
841 if let Some(cached) = cache.get(¶m_env.and(trait_ref)) {
842 return Some(cached.get(tcx));
849 .get(¶m_env.and(trait_ref))
853 fn insert_evaluation_cache(
855 param_env: ty::ParamEnv<'tcx>,
856 trait_ref: ty::PolyTraitRef<'tcx>,
857 dep_node: DepNodeIndex,
858 result: EvaluationResult,
860 // Avoid caching results that depend on more than just the trait-ref
861 // - the stack can create recursion.
862 if result.is_stack_dependent() {
866 if self.can_use_global_caches(param_env) {
867 if !trait_ref.needs_infer() {
869 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
872 // This may overwrite the cache with the same value
873 // FIXME: Due to #50507 this overwrites the different values
874 // This should be changed to use HashMapExt::insert_same
875 // when that is fixed
880 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
885 debug!("insert_evaluation_cache(trait_ref={:?}, candidate={:?})", trait_ref, result,);
890 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
893 /// For various reasons, it's possible for a subobligation
894 /// to have a *lower* recursion_depth than the obligation used to create it.
895 /// Projection sub-obligations may be returned from the projection cache,
896 /// which results in obligations with an 'old' `recursion_depth`.
897 /// Additionally, methods like `wf::obligations` and
898 /// `InferCtxt.subtype_predicate` produce subobligations without
899 /// taking in a 'parent' depth, causing the generated subobligations
900 /// to have a `recursion_depth` of `0`.
902 /// To ensure that obligation_depth never decreasees, we force all subobligations
903 /// to have at least the depth of the original obligation.
904 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
909 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
912 /// Checks that the recursion limit has not been exceeded.
914 /// The weird return type of this function allows it to be used with the `try` (`?`)
915 /// operator within certain functions.
916 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
918 obligation: &Obligation<'tcx, T>,
919 error_obligation: &Obligation<'tcx, V>,
920 ) -> Result<(), OverflowError> {
921 if !self.infcx.tcx.sess.recursion_limit().value_within_limit(obligation.recursion_depth) {
922 match self.query_mode {
923 TraitQueryMode::Standard => {
924 self.infcx().report_overflow_error(error_obligation, true);
926 TraitQueryMode::Canonical => {
927 return Err(OverflowError);
934 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
936 OP: FnOnce(&mut Self) -> R,
938 let (result, dep_node) =
939 self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || op(self));
940 self.tcx().dep_graph.read_index(dep_node);
944 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
945 fn filter_negative_and_reservation_impls(
947 candidate: SelectionCandidate<'tcx>,
948 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
949 if let ImplCandidate(def_id) = candidate {
950 let tcx = self.tcx();
951 match tcx.impl_polarity(def_id) {
952 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
953 return Err(Unimplemented);
955 ty::ImplPolarity::Reservation => {
956 if let Some(intercrate_ambiguity_clauses) =
957 &mut self.intercrate_ambiguity_causes
959 let attrs = tcx.get_attrs(def_id);
960 let attr = attr::find_by_name(&attrs, sym::rustc_reservation_impl);
961 let value = attr.and_then(|a| a.value_str());
962 if let Some(value) = value {
964 "filter_negative_and_reservation_impls: \
965 reservation impl ambiguity on {:?}",
968 intercrate_ambiguity_clauses.push(
969 IntercrateAmbiguityCause::ReservationImpl {
970 message: value.to_string(),
983 fn candidate_from_obligation_no_cache<'o>(
985 stack: &TraitObligationStack<'o, 'tcx>,
986 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
987 if let Some(conflict) = self.is_knowable(stack) {
988 debug!("coherence stage: not knowable");
989 if self.intercrate_ambiguity_causes.is_some() {
990 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
991 // Heuristics: show the diagnostics when there are no candidates in crate.
992 if let Ok(candidate_set) = self.assemble_candidates(stack) {
993 let mut no_candidates_apply = true;
995 for c in candidate_set.vec.iter() {
996 if self.evaluate_candidate(stack, &c)?.may_apply() {
997 no_candidates_apply = false;
1002 if !candidate_set.ambiguous && no_candidates_apply {
1003 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1004 let self_ty = trait_ref.self_ty();
1005 let trait_desc = trait_ref.print_only_trait_path().to_string();
1006 let self_desc = if self_ty.has_concrete_skeleton() {
1007 Some(self_ty.to_string())
1011 let cause = if let Conflict::Upstream = conflict {
1012 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
1014 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1016 debug!("evaluate_stack: pushing cause = {:?}", cause);
1017 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1024 let candidate_set = self.assemble_candidates(stack)?;
1026 if candidate_set.ambiguous {
1027 debug!("candidate set contains ambig");
1031 let mut candidates = candidate_set.vec;
1033 debug!("assembled {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1035 // At this point, we know that each of the entries in the
1036 // candidate set is *individually* applicable. Now we have to
1037 // figure out if they contain mutual incompatibilities. This
1038 // frequently arises if we have an unconstrained input type --
1039 // for example, we are looking for `$0: Eq` where `$0` is some
1040 // unconstrained type variable. In that case, we'll get a
1041 // candidate which assumes $0 == int, one that assumes `$0 ==
1042 // usize`, etc. This spells an ambiguity.
1044 // If there is more than one candidate, first winnow them down
1045 // by considering extra conditions (nested obligations and so
1046 // forth). We don't winnow if there is exactly one
1047 // candidate. This is a relatively minor distinction but it
1048 // can lead to better inference and error-reporting. An
1049 // example would be if there was an impl:
1051 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1053 // and we were to see some code `foo.push_clone()` where `boo`
1054 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1055 // we were to winnow, we'd wind up with zero candidates.
1056 // Instead, we select the right impl now but report "`Bar` does
1057 // not implement `Clone`".
1058 if candidates.len() == 1 {
1059 return self.filter_negative_and_reservation_impls(candidates.pop().unwrap());
1062 // Winnow, but record the exact outcome of evaluation, which
1063 // is needed for specialization. Propagate overflow if it occurs.
1064 let mut candidates = candidates
1066 .map(|c| match self.evaluate_candidate(stack, &c) {
1067 Ok(eval) if eval.may_apply() => {
1068 Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
1071 Err(OverflowError) => Err(Overflow),
1073 .flat_map(Result::transpose)
1074 .collect::<Result<Vec<_>, _>>()?;
1076 debug!("winnowed to {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1078 let needs_infer = stack.obligation.predicate.needs_infer();
1080 // If there are STILL multiple candidates, we can further
1081 // reduce the list by dropping duplicates -- including
1082 // resolving specializations.
1083 if candidates.len() > 1 {
1085 while i < candidates.len() {
1086 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1087 self.candidate_should_be_dropped_in_favor_of(
1094 debug!("Dropping candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1095 candidates.swap_remove(i);
1097 debug!("Retaining candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1100 // If there are *STILL* multiple candidates, give up
1101 // and report ambiguity.
1103 debug!("multiple matches, ambig");
1110 // If there are *NO* candidates, then there are no impls --
1111 // that we know of, anyway. Note that in the case where there
1112 // are unbound type variables within the obligation, it might
1113 // be the case that you could still satisfy the obligation
1114 // from another crate by instantiating the type variables with
1115 // a type from another crate that does have an impl. This case
1116 // is checked for in `evaluate_stack` (and hence users
1117 // who might care about this case, like coherence, should use
1119 if candidates.is_empty() {
1120 // If there's an error type, 'downgrade' our result from
1121 // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
1122 // emitting additional spurious errors, since we're guaranteed
1123 // to have emitted at least one.
1124 if stack.obligation.references_error() {
1125 debug!("no results for error type, treating as ambiguous");
1128 return Err(Unimplemented);
1131 // Just one candidate left.
1132 self.filter_negative_and_reservation_impls(candidates.pop().unwrap().candidate)
1135 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1136 debug!("is_knowable(intercrate={:?})", self.intercrate);
1138 if !self.intercrate {
1142 let obligation = &stack.obligation;
1143 let predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1145 // Okay to skip binder because of the nature of the
1146 // trait-ref-is-knowable check, which does not care about
1148 let trait_ref = predicate.skip_binder().trait_ref;
1150 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1153 /// Returns `true` if the global caches can be used.
1154 /// Do note that if the type itself is not in the
1155 /// global tcx, the local caches will be used.
1156 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1157 // If there are any inference variables in the `ParamEnv`, then we
1158 // always use a cache local to this particular scope. Otherwise, we
1159 // switch to a global cache.
1160 if param_env.needs_infer() {
1164 // Avoid using the master cache during coherence and just rely
1165 // on the local cache. This effectively disables caching
1166 // during coherence. It is really just a simplification to
1167 // avoid us having to fear that coherence results "pollute"
1168 // the master cache. Since coherence executes pretty quickly,
1169 // it's not worth going to more trouble to increase the
1170 // hit-rate, I don't think.
1171 if self.intercrate {
1175 // Otherwise, we can use the global cache.
1179 fn check_candidate_cache(
1181 param_env: ty::ParamEnv<'tcx>,
1182 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1183 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1184 let tcx = self.tcx();
1185 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1186 if self.can_use_global_caches(param_env) {
1187 let cache = tcx.selection_cache.hashmap.borrow();
1188 if let Some(cached) = cache.get(¶m_env.and(*trait_ref)) {
1189 return Some(cached.get(tcx));
1196 .get(¶m_env.and(*trait_ref))
1197 .map(|v| v.get(tcx))
1200 /// Determines whether can we safely cache the result
1201 /// of selecting an obligation. This is almost always `true`,
1202 /// except when dealing with certain `ParamCandidate`s.
1204 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1205 /// since it was usually produced directly from a `DefId`. However,
1206 /// certain cases (currently only librustdoc's blanket impl finder),
1207 /// a `ParamEnv` may be explicitly constructed with inference types.
1208 /// When this is the case, we do *not* want to cache the resulting selection
1209 /// candidate. This is due to the fact that it might not always be possible
1210 /// to equate the obligation's trait ref and the candidate's trait ref,
1211 /// if more constraints end up getting added to an inference variable.
1213 /// Because of this, we always want to re-run the full selection
1214 /// process for our obligation the next time we see it, since
1215 /// we might end up picking a different `SelectionCandidate` (or none at all).
1216 fn can_cache_candidate(
1218 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1221 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1226 fn insert_candidate_cache(
1228 param_env: ty::ParamEnv<'tcx>,
1229 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1230 dep_node: DepNodeIndex,
1231 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1233 let tcx = self.tcx();
1234 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1236 if !self.can_cache_candidate(&candidate) {
1238 "insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1239 candidate is not cacheable",
1240 trait_ref, candidate
1245 if self.can_use_global_caches(param_env) {
1246 if let Err(Overflow) = candidate {
1247 // Don't cache overflow globally; we only produce this in certain modes.
1248 } else if !trait_ref.needs_infer() {
1249 if !candidate.needs_infer() {
1251 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1252 trait_ref, candidate,
1254 // This may overwrite the cache with the same value.
1258 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1265 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1266 trait_ref, candidate,
1272 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1275 fn match_projection_obligation_against_definition_bounds(
1277 obligation: &TraitObligation<'tcx>,
1279 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1280 let (placeholder_trait_predicate, _) =
1281 self.infcx().replace_bound_vars_with_placeholders(&poly_trait_predicate);
1283 "match_projection_obligation_against_definition_bounds: \
1284 placeholder_trait_predicate={:?}",
1285 placeholder_trait_predicate,
1288 let tcx = self.infcx.tcx;
1289 let predicates = match placeholder_trait_predicate.trait_ref.self_ty().kind {
1290 ty::Projection(ref data) => {
1291 tcx.projection_predicates(data.item_def_id).subst(tcx, data.substs)
1293 ty::Opaque(def_id, substs) => tcx.projection_predicates(def_id).subst(tcx, substs),
1296 obligation.cause.span,
1297 "match_projection_obligation_against_definition_bounds() called \
1298 but self-ty is not a projection: {:?}",
1299 placeholder_trait_predicate.trait_ref.self_ty()
1304 let matching_bound = predicates.iter().find_map(|bound| {
1305 if let ty::PredicateKind::Trait(bound, _) = bound.kind() {
1306 let bound = bound.to_poly_trait_ref();
1307 if self.infcx.probe(|_| {
1308 self.match_projection(obligation, bound, placeholder_trait_predicate.trait_ref)
1317 "match_projection_obligation_against_definition_bounds: \
1318 matching_bound={:?}",
1321 match matching_bound {
1324 // Repeat the successful match, if any, this time outside of a probe.
1326 self.match_projection(obligation, bound, placeholder_trait_predicate.trait_ref);
1334 fn match_projection(
1336 obligation: &TraitObligation<'tcx>,
1337 trait_bound: ty::PolyTraitRef<'tcx>,
1338 placeholder_trait_ref: ty::TraitRef<'tcx>,
1340 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1342 .at(&obligation.cause, obligation.param_env)
1343 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1347 fn evaluate_where_clause<'o>(
1349 stack: &TraitObligationStack<'o, 'tcx>,
1350 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1351 ) -> Result<EvaluationResult, OverflowError> {
1352 self.evaluation_probe(|this| {
1353 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1354 Ok(obligations) => {
1355 this.evaluate_predicates_recursively(stack.list(), obligations.into_iter())
1357 Err(()) => Ok(EvaluatedToErr),
1362 ///////////////////////////////////////////////////////////////////////////
1365 // Winnowing is the process of attempting to resolve ambiguity by
1366 // probing further. During the winnowing process, we unify all
1367 // type variables and then we also attempt to evaluate recursive
1368 // bounds to see if they are satisfied.
1370 /// Returns `true` if `victim` should be dropped in favor of
1371 /// `other`. Generally speaking we will drop duplicate
1372 /// candidates and prefer where-clause candidates.
1374 /// See the comment for "SelectionCandidate" for more details.
1375 fn candidate_should_be_dropped_in_favor_of(
1377 victim: &EvaluatedCandidate<'tcx>,
1378 other: &EvaluatedCandidate<'tcx>,
1381 if victim.candidate == other.candidate {
1385 // Check if a bound would previously have been removed when normalizing
1386 // the param_env so that it can be given the lowest priority. See
1387 // #50825 for the motivation for this.
1389 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
1391 // (*) Prefer `BuiltinCandidate { has_nested: false }` and `DiscriminantKindCandidate`
1392 // to anything else.
1394 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1395 // lifetime of a variable.
1396 match other.candidate {
1398 BuiltinCandidate { has_nested: false } | DiscriminantKindCandidate => true,
1399 ParamCandidate(ref cand) => match victim.candidate {
1400 AutoImplCandidate(..) => {
1402 "default implementations shouldn't be recorded \
1403 when there are other valid candidates"
1407 BuiltinCandidate { has_nested: false } | DiscriminantKindCandidate => false,
1410 | GeneratorCandidate
1411 | FnPointerCandidate
1412 | BuiltinObjectCandidate
1413 | BuiltinUnsizeCandidate
1414 | BuiltinCandidate { .. }
1415 | TraitAliasCandidate(..) => {
1416 // Global bounds from the where clause should be ignored
1417 // here (see issue #50825). Otherwise, we have a where
1418 // clause so don't go around looking for impls.
1421 ObjectCandidate | ProjectionCandidate => {
1422 // Arbitrarily give param candidates priority
1423 // over projection and object candidates.
1426 ParamCandidate(..) => false,
1428 ObjectCandidate | ProjectionCandidate => match victim.candidate {
1429 AutoImplCandidate(..) => {
1431 "default implementations shouldn't be recorded \
1432 when there are other valid candidates"
1436 BuiltinCandidate { has_nested: false } | DiscriminantKindCandidate => false,
1439 | GeneratorCandidate
1440 | FnPointerCandidate
1441 | BuiltinObjectCandidate
1442 | BuiltinUnsizeCandidate
1443 | BuiltinCandidate { .. }
1444 | TraitAliasCandidate(..) => true,
1445 ObjectCandidate | ProjectionCandidate => {
1446 // Arbitrarily give param candidates priority
1447 // over projection and object candidates.
1450 ParamCandidate(ref cand) => is_global(cand),
1452 ImplCandidate(other_def) => {
1453 // See if we can toss out `victim` based on specialization.
1454 // This requires us to know *for sure* that the `other` impl applies
1455 // i.e., `EvaluatedToOk`.
1456 if other.evaluation.must_apply_modulo_regions() {
1457 match victim.candidate {
1458 ImplCandidate(victim_def) => {
1459 let tcx = self.tcx();
1460 if tcx.specializes((other_def, victim_def)) {
1463 return match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1464 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1465 // Subtle: If the predicate we are evaluating has inference
1466 // variables, do *not* allow discarding candidates due to
1467 // marker trait impls.
1469 // Without this restriction, we could end up accidentally
1470 // constrainting inference variables based on an arbitrarily
1471 // chosen trait impl.
1473 // Imagine we have the following code:
1476 // #[marker] trait MyTrait {}
1477 // impl MyTrait for u8 {}
1478 // impl MyTrait for bool {}
1481 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1483 // During selection, we will end up with one candidate for each
1484 // impl of `MyTrait`. If we were to discard one impl in favor
1485 // of the other, we would be left with one candidate, causing
1486 // us to "successfully" select the predicate, unifying
1487 // _#0t with (for example) `u8`.
1489 // However, we have no reason to believe that this unification
1490 // is correct - we've essentially just picked an arbitrary
1491 // *possibility* for _#0t, and required that this be the *only*
1494 // Eventually, we will either:
1495 // 1) Unify all inference variables in the predicate through
1496 // some other means (e.g. type-checking of a function). We will
1497 // then be in a position to drop marker trait candidates
1498 // without constraining inference variables (since there are
1499 // none left to constrin)
1500 // 2) Be left with some unconstrained inference variables. We
1501 // will then correctly report an inference error, since the
1502 // existence of multiple marker trait impls tells us nothing
1503 // about which one should actually apply.
1510 ParamCandidate(ref cand) => {
1511 // Prefer the impl to a global where clause candidate.
1512 return is_global(cand);
1521 | GeneratorCandidate
1522 | FnPointerCandidate
1523 | BuiltinObjectCandidate
1524 | BuiltinUnsizeCandidate
1525 | BuiltinCandidate { has_nested: true } => {
1526 match victim.candidate {
1527 ParamCandidate(ref cand) => {
1528 // Prefer these to a global where-clause bound
1529 // (see issue #50825).
1530 is_global(cand) && other.evaluation.must_apply_modulo_regions()
1539 fn sized_conditions(
1541 obligation: &TraitObligation<'tcx>,
1542 ) -> BuiltinImplConditions<'tcx> {
1543 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1545 // NOTE: binder moved to (*)
1546 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1548 match self_ty.kind {
1549 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1560 | ty::GeneratorWitness(..)
1565 // safe for everything
1566 Where(ty::Binder::dummy(Vec::new()))
1569 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1572 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
1575 ty::Adt(def, substs) => {
1576 let sized_crit = def.sized_constraint(self.tcx());
1577 // (*) binder moved here
1578 Where(ty::Binder::bind(
1579 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect(),
1583 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1584 ty::Infer(ty::TyVar(_)) => Ambiguous,
1588 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1589 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1594 fn copy_clone_conditions(
1596 obligation: &TraitObligation<'tcx>,
1597 ) -> BuiltinImplConditions<'tcx> {
1598 // NOTE: binder moved to (*)
1599 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1601 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1603 match self_ty.kind {
1604 ty::Infer(ty::IntVar(_))
1605 | ty::Infer(ty::FloatVar(_))
1608 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1617 | ty::Ref(_, _, hir::Mutability::Not) => {
1618 // Implementations provided in libcore
1626 | ty::GeneratorWitness(..)
1628 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1630 ty::Array(element_ty, _) => {
1631 // (*) binder moved here
1632 Where(ty::Binder::bind(vec![element_ty]))
1636 // (*) binder moved here
1637 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
1640 ty::Closure(_, substs) => {
1641 // (*) binder moved here
1642 Where(ty::Binder::bind(substs.as_closure().upvar_tys().collect()))
1645 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1646 // Fallback to whatever user-defined impls exist in this case.
1650 ty::Infer(ty::TyVar(_)) => {
1651 // Unbound type variable. Might or might not have
1652 // applicable impls and so forth, depending on what
1653 // those type variables wind up being bound to.
1659 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1660 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1665 /// For default impls, we need to break apart a type into its
1666 /// "constituent types" -- meaning, the types that it contains.
1668 /// Here are some (simple) examples:
1671 /// (i32, u32) -> [i32, u32]
1672 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1673 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1674 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1676 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
1686 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1688 | ty::Char => Vec::new(),
1694 | ty::Projection(..)
1696 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1697 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1700 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1704 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
1706 ty::Tuple(ref tys) => {
1707 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1708 tys.iter().map(|k| k.expect_ty()).collect()
1711 ty::Closure(_, ref substs) => substs.as_closure().upvar_tys().collect(),
1713 ty::Generator(_, ref substs, _) => {
1714 let witness = substs.as_generator().witness();
1715 substs.as_generator().upvar_tys().chain(iter::once(witness)).collect()
1718 ty::GeneratorWitness(types) => {
1719 // This is sound because no regions in the witness can refer to
1720 // the binder outside the witness. So we'll effectivly reuse
1721 // the implicit binder around the witness.
1722 types.skip_binder().to_vec()
1725 // For `PhantomData<T>`, we pass `T`.
1726 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
1728 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
1730 ty::Opaque(def_id, substs) => {
1731 // We can resolve the `impl Trait` to its concrete type,
1732 // which enforces a DAG between the functions requiring
1733 // the auto trait bounds in question.
1734 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
1739 fn collect_predicates_for_types(
1741 param_env: ty::ParamEnv<'tcx>,
1742 cause: ObligationCause<'tcx>,
1743 recursion_depth: usize,
1744 trait_def_id: DefId,
1745 types: ty::Binder<Vec<Ty<'tcx>>>,
1746 ) -> Vec<PredicateObligation<'tcx>> {
1747 // Because the types were potentially derived from
1748 // higher-ranked obligations they may reference late-bound
1749 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
1750 // yield a type like `for<'a> &'a i32`. In general, we
1751 // maintain the invariant that we never manipulate bound
1752 // regions, so we have to process these bound regions somehow.
1754 // The strategy is to:
1756 // 1. Instantiate those regions to placeholder regions (e.g.,
1757 // `for<'a> &'a i32` becomes `&0 i32`.
1758 // 2. Produce something like `&'0 i32 : Copy`
1759 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
1762 .skip_binder() // binder moved -\
1765 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
1767 self.infcx.commit_unconditionally(|_| {
1768 let (placeholder_ty, _) = self.infcx.replace_bound_vars_with_placeholders(&ty);
1769 let Normalized { value: normalized_ty, mut obligations } =
1770 ensure_sufficient_stack(|| {
1771 project::normalize_with_depth(
1779 let placeholder_obligation = predicate_for_trait_def(
1788 obligations.push(placeholder_obligation);
1795 ///////////////////////////////////////////////////////////////////////////
1798 // Matching is a common path used for both evaluation and
1799 // confirmation. It basically unifies types that appear in impls
1800 // and traits. This does affect the surrounding environment;
1801 // therefore, when used during evaluation, match routines must be
1802 // run inside of a `probe()` so that their side-effects are
1808 obligation: &TraitObligation<'tcx>,
1809 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
1810 match self.match_impl(impl_def_id, obligation) {
1811 Ok(substs) => substs,
1814 "Impl {:?} was matchable against {:?} but now is not",
1825 obligation: &TraitObligation<'tcx>,
1826 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
1827 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
1829 // Before we create the substitutions and everything, first
1830 // consider a "quick reject". This avoids creating more types
1831 // and so forth that we need to.
1832 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
1836 let (placeholder_obligation, _) =
1837 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
1838 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
1840 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
1842 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
1844 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
1845 ensure_sufficient_stack(|| {
1846 project::normalize_with_depth(
1848 obligation.param_env,
1849 obligation.cause.clone(),
1850 obligation.recursion_depth + 1,
1856 "match_impl(impl_def_id={:?}, obligation={:?}, \
1857 impl_trait_ref={:?}, placeholder_obligation_trait_ref={:?})",
1858 impl_def_id, obligation, impl_trait_ref, placeholder_obligation_trait_ref
1861 let InferOk { obligations, .. } = self
1863 .at(&obligation.cause, obligation.param_env)
1864 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
1865 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
1866 nested_obligations.extend(obligations);
1869 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
1871 debug!("match_impl: reservation impls only apply in intercrate mode");
1875 debug!("match_impl: success impl_substs={:?}", impl_substs);
1876 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
1879 fn fast_reject_trait_refs(
1881 obligation: &TraitObligation<'_>,
1882 impl_trait_ref: &ty::TraitRef<'_>,
1884 // We can avoid creating type variables and doing the full
1885 // substitution if we find that any of the input types, when
1886 // simplified, do not match.
1888 obligation.predicate.skip_binder().trait_ref.substs.iter().zip(impl_trait_ref.substs).any(
1889 |(obligation_arg, impl_arg)| {
1890 match (obligation_arg.unpack(), impl_arg.unpack()) {
1891 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
1892 let simplified_obligation_ty =
1893 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
1894 let simplified_impl_ty =
1895 fast_reject::simplify_type(self.tcx(), impl_ty, false);
1897 simplified_obligation_ty.is_some()
1898 && simplified_impl_ty.is_some()
1899 && simplified_obligation_ty != simplified_impl_ty
1901 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
1902 // Lifetimes can never cause a rejection.
1905 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
1906 // Conservatively ignore consts (i.e. assume they might
1907 // unify later) until we have `fast_reject` support for
1908 // them (if we'll ever need it, even).
1911 _ => unreachable!(),
1917 /// Normalize `where_clause_trait_ref` and try to match it against
1918 /// `obligation`. If successful, return any predicates that
1919 /// result from the normalization. Normalization is necessary
1920 /// because where-clauses are stored in the parameter environment
1922 fn match_where_clause_trait_ref(
1924 obligation: &TraitObligation<'tcx>,
1925 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1926 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
1927 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
1930 /// Returns `Ok` if `poly_trait_ref` being true implies that the
1931 /// obligation is satisfied.
1932 fn match_poly_trait_ref(
1934 obligation: &TraitObligation<'tcx>,
1935 poly_trait_ref: ty::PolyTraitRef<'tcx>,
1936 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
1938 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
1939 obligation, poly_trait_ref
1943 .at(&obligation.cause, obligation.param_env)
1944 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
1945 .map(|InferOk { obligations, .. }| obligations)
1949 ///////////////////////////////////////////////////////////////////////////
1952 fn match_fresh_trait_refs(
1954 previous: ty::PolyTraitRef<'tcx>,
1955 current: ty::PolyTraitRef<'tcx>,
1956 param_env: ty::ParamEnv<'tcx>,
1958 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
1959 matcher.relate(previous, current).is_ok()
1964 previous_stack: TraitObligationStackList<'o, 'tcx>,
1965 obligation: &'o TraitObligation<'tcx>,
1966 ) -> TraitObligationStack<'o, 'tcx> {
1967 let fresh_trait_ref =
1968 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
1970 let dfn = previous_stack.cache.next_dfn();
1971 let depth = previous_stack.depth() + 1;
1972 TraitObligationStack {
1975 reached_depth: Cell::new(depth),
1976 previous: previous_stack,
1982 fn closure_trait_ref_unnormalized(
1984 obligation: &TraitObligation<'tcx>,
1985 substs: SubstsRef<'tcx>,
1986 ) -> ty::PolyTraitRef<'tcx> {
1987 debug!("closure_trait_ref_unnormalized(obligation={:?}, substs={:?})", obligation, substs);
1988 let closure_sig = substs.as_closure().sig();
1990 debug!("closure_trait_ref_unnormalized: closure_sig = {:?}", closure_sig);
1992 // (1) Feels icky to skip the binder here, but OTOH we know
1993 // that the self-type is an unboxed closure type and hence is
1994 // in fact unparameterized (or at least does not reference any
1995 // regions bound in the obligation). Still probably some
1996 // refactoring could make this nicer.
1997 closure_trait_ref_and_return_type(
1999 obligation.predicate.def_id(),
2000 obligation.predicate.skip_binder().self_ty(), // (1)
2002 util::TupleArgumentsFlag::No,
2004 .map_bound(|(trait_ref, _)| trait_ref)
2007 fn generator_trait_ref_unnormalized(
2009 obligation: &TraitObligation<'tcx>,
2010 substs: SubstsRef<'tcx>,
2011 ) -> ty::PolyTraitRef<'tcx> {
2012 let gen_sig = substs.as_generator().poly_sig();
2014 // (1) Feels icky to skip the binder here, but OTOH we know
2015 // that the self-type is an generator type and hence is
2016 // in fact unparameterized (or at least does not reference any
2017 // regions bound in the obligation). Still probably some
2018 // refactoring could make this nicer.
2020 super::util::generator_trait_ref_and_outputs(
2022 obligation.predicate.def_id(),
2023 obligation.predicate.skip_binder().self_ty(), // (1)
2026 .map_bound(|(trait_ref, ..)| trait_ref)
2029 /// Returns the obligations that are implied by instantiating an
2030 /// impl or trait. The obligations are substituted and fully
2031 /// normalized. This is used when confirming an impl or default
2033 fn impl_or_trait_obligations(
2035 cause: ObligationCause<'tcx>,
2036 recursion_depth: usize,
2037 param_env: ty::ParamEnv<'tcx>,
2038 def_id: DefId, // of impl or trait
2039 substs: SubstsRef<'tcx>, // for impl or trait
2040 ) -> Vec<PredicateObligation<'tcx>> {
2041 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
2042 let tcx = self.tcx();
2044 // To allow for one-pass evaluation of the nested obligation,
2045 // each predicate must be preceded by the obligations required
2047 // for example, if we have:
2048 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2049 // the impl will have the following predicates:
2050 // <V as Iterator>::Item = U,
2051 // U: Iterator, U: Sized,
2052 // V: Iterator, V: Sized,
2053 // <U as Iterator>::Item: Copy
2054 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2055 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2056 // `$1: Copy`, so we must ensure the obligations are emitted in
2058 let predicates = tcx.predicates_of(def_id);
2059 assert_eq!(predicates.parent, None);
2060 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2061 for (predicate, _) in predicates.predicates {
2062 let predicate = normalize_with_depth_to(
2067 &predicate.subst(tcx, substs),
2070 obligations.push(Obligation {
2071 cause: cause.clone(),
2078 // We are performing deduplication here to avoid exponential blowups
2079 // (#38528) from happening, but the real cause of the duplication is
2080 // unknown. What we know is that the deduplication avoids exponential
2081 // amount of predicates being propagated when processing deeply nested
2084 // This code is hot enough that it's worth avoiding the allocation
2085 // required for the FxHashSet when possible. Special-casing lengths 0,
2086 // 1 and 2 covers roughly 75-80% of the cases.
2087 if obligations.len() <= 1 {
2088 // No possibility of duplicates.
2089 } else if obligations.len() == 2 {
2090 // Only two elements. Drop the second if they are equal.
2091 if obligations[0] == obligations[1] {
2092 obligations.truncate(1);
2095 // Three or more elements. Use a general deduplication process.
2096 let mut seen = FxHashSet::default();
2097 obligations.retain(|i| seen.insert(i.clone()));
2104 trait TraitObligationExt<'tcx> {
2107 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2108 ) -> ObligationCause<'tcx>;
2111 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2112 #[allow(unused_comparisons)]
2115 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2116 ) -> ObligationCause<'tcx> {
2118 * Creates a cause for obligations that are derived from
2119 * `obligation` by a recursive search (e.g., for a builtin
2120 * bound, or eventually a `auto trait Foo`). If `obligation`
2121 * is itself a derived obligation, this is just a clone, but
2122 * otherwise we create a "derived obligation" cause so as to
2123 * keep track of the original root obligation for error
2127 let obligation = self;
2129 // NOTE(flaper87): As of now, it keeps track of the whole error
2130 // chain. Ideally, we should have a way to configure this either
2131 // by using -Z verbose or just a CLI argument.
2132 let derived_cause = DerivedObligationCause {
2133 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2134 parent_code: Rc::new(obligation.cause.code.clone()),
2136 let derived_code = variant(derived_cause);
2137 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2141 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2142 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2143 TraitObligationStackList::with(self)
2146 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2150 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2154 /// Indicates that attempting to evaluate this stack entry
2155 /// required accessing something from the stack at depth `reached_depth`.
2156 fn update_reached_depth(&self, reached_depth: usize) {
2158 self.depth > reached_depth,
2159 "invoked `update_reached_depth` with something under this stack: \
2160 self.depth={} reached_depth={}",
2164 debug!("update_reached_depth(reached_depth={})", reached_depth);
2166 while reached_depth < p.depth {
2167 debug!("update_reached_depth: marking {:?} as cycle participant", p.fresh_trait_ref);
2168 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2169 p = p.previous.head.unwrap();
2174 /// The "provisional evaluation cache" is used to store intermediate cache results
2175 /// when solving auto traits. Auto traits are unusual in that they can support
2176 /// cycles. So, for example, a "proof tree" like this would be ok:
2178 /// - `Foo<T>: Send` :-
2179 /// - `Bar<T>: Send` :-
2180 /// - `Foo<T>: Send` -- cycle, but ok
2181 /// - `Baz<T>: Send`
2183 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2184 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2185 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2186 /// they are coinductive) it is considered ok.
2188 /// However, there is a complication: at the point where we have
2189 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2190 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2191 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2192 /// find out this assumption is wrong? Specifically, we could
2193 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2194 /// `Bar<T>: Send` didn't turn out to be true.
2196 /// In Issue #60010, we found a bug in rustc where it would cache
2197 /// these intermediate results. This was fixed in #60444 by disabling
2198 /// *all* caching for things involved in a cycle -- in our example,
2199 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2200 /// to large slowdowns.
2202 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2203 /// first requires proving `Bar<T>: Send` (which is true:
2205 /// - `Foo<T>: Send` :-
2206 /// - `Bar<T>: Send` :-
2207 /// - `Foo<T>: Send` -- cycle, but ok
2208 /// - `Baz<T>: Send`
2209 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2210 /// - `*const T: Send` -- but what if we later encounter an error?
2212 /// The *provisional evaluation cache* resolves this issue. It stores
2213 /// cache results that we've proven but which were involved in a cycle
2214 /// in some way. We track the minimal stack depth (i.e., the
2215 /// farthest from the top of the stack) that we are dependent on.
2216 /// The idea is that the cache results within are all valid -- so long as
2217 /// none of the nodes in between the current node and the node at that minimum
2218 /// depth result in an error (in which case the cached results are just thrown away).
2220 /// During evaluation, we consult this provisional cache and rely on
2221 /// it. Accessing a cached value is considered equivalent to accessing
2222 /// a result at `reached_depth`, so it marks the *current* solution as
2223 /// provisional as well. If an error is encountered, we toss out any
2224 /// provisional results added from the subtree that encountered the
2225 /// error. When we pop the node at `reached_depth` from the stack, we
2226 /// can commit all the things that remain in the provisional cache.
2227 struct ProvisionalEvaluationCache<'tcx> {
2228 /// next "depth first number" to issue -- just a counter
2231 /// Stores the "coldest" depth (bottom of stack) reached by any of
2232 /// the evaluation entries. The idea here is that all things in the provisional
2233 /// cache are always dependent on *something* that is colder in the stack:
2234 /// therefore, if we add a new entry that is dependent on something *colder still*,
2235 /// we have to modify the depth for all entries at once.
2239 /// Imagine we have a stack `A B C D E` (with `E` being the top of
2240 /// the stack). We cache something with depth 2, which means that
2241 /// it was dependent on C. Then we pop E but go on and process a
2242 /// new node F: A B C D F. Now F adds something to the cache with
2243 /// depth 1, meaning it is dependent on B. Our original cache
2244 /// entry is also dependent on B, because there is a path from E
2245 /// to C and then from C to F and from F to B.
2246 reached_depth: Cell<usize>,
2248 /// Map from cache key to the provisionally evaluated thing.
2249 /// The cache entries contain the result but also the DFN in which they
2250 /// were added. The DFN is used to clear out values on failure.
2252 /// Imagine we have a stack like:
2254 /// - `A B C` and we add a cache for the result of C (DFN 2)
2255 /// - Then we have a stack `A B D` where `D` has DFN 3
2256 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2257 /// - `E` generates various cache entries which have cyclic dependices on `B`
2258 /// - `A B D E F` and so forth
2259 /// - the DFN of `F` for example would be 5
2260 /// - then we determine that `E` is in error -- we will then clear
2261 /// all cache values whose DFN is >= 4 -- in this case, that
2262 /// means the cached value for `F`.
2263 map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
2266 /// A cache value for the provisional cache: contains the depth-first
2267 /// number (DFN) and result.
2268 #[derive(Copy, Clone, Debug)]
2269 struct ProvisionalEvaluation {
2271 result: EvaluationResult,
2274 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2275 fn default() -> Self {
2276 Self { dfn: Cell::new(0), reached_depth: Cell::new(usize::MAX), map: Default::default() }
2280 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2281 /// Get the next DFN in sequence (basically a counter).
2282 fn next_dfn(&self) -> usize {
2283 let result = self.dfn.get();
2284 self.dfn.set(result + 1);
2288 /// Check the provisional cache for any result for
2289 /// `fresh_trait_ref`. If there is a hit, then you must consider
2290 /// it an access to the stack slots at depth
2291 /// `self.current_reached_depth()` and above.
2292 fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
2294 "get_provisional(fresh_trait_ref={:?}) = {:#?} with reached-depth {}",
2296 self.map.borrow().get(&fresh_trait_ref),
2297 self.reached_depth.get(),
2299 Some(self.map.borrow().get(&fresh_trait_ref)?.result)
2302 /// Current value of the `reached_depth` counter -- all the
2303 /// provisional cache entries are dependent on the item at this
2305 fn current_reached_depth(&self) -> usize {
2306 self.reached_depth.get()
2309 /// Insert a provisional result into the cache. The result came
2310 /// from the node with the given DFN. It accessed a minimum depth
2311 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
2312 /// and resulted in `result`.
2313 fn insert_provisional(
2316 reached_depth: usize,
2317 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
2318 result: EvaluationResult,
2321 "insert_provisional(from_dfn={}, reached_depth={}, fresh_trait_ref={:?}, result={:?})",
2322 from_dfn, reached_depth, fresh_trait_ref, result,
2324 let r_d = self.reached_depth.get();
2325 self.reached_depth.set(r_d.min(reached_depth));
2327 debug!("insert_provisional: reached_depth={:?}", self.reached_depth.get());
2329 self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
2332 /// Invoked when the node with dfn `dfn` does not get a successful
2333 /// result. This will clear out any provisional cache entries
2334 /// that were added since `dfn` was created. This is because the
2335 /// provisional entries are things which must assume that the
2336 /// things on the stack at the time of their creation succeeded --
2337 /// since the failing node is presently at the top of the stack,
2338 /// these provisional entries must either depend on it or some
2340 fn on_failure(&self, dfn: usize) {
2341 debug!("on_failure(dfn={:?})", dfn,);
2342 self.map.borrow_mut().retain(|key, eval| {
2343 if !eval.from_dfn >= dfn {
2344 debug!("on_failure: removing {:?}", key);
2352 /// Invoked when the node at depth `depth` completed without
2353 /// depending on anything higher in the stack (if that completion
2354 /// was a failure, then `on_failure` should have been invoked
2355 /// already). The callback `op` will be invoked for each
2356 /// provisional entry that we can now confirm.
2360 mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
2362 debug!("on_completion(depth={}, reached_depth={})", depth, self.reached_depth.get(),);
2364 if self.reached_depth.get() < depth {
2365 debug!("on_completion: did not yet reach depth to complete");
2369 for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
2370 debug!("on_completion: fresh_trait_ref={:?} eval={:?}", fresh_trait_ref, eval,);
2372 op(fresh_trait_ref, eval.result);
2375 self.reached_depth.set(usize::MAX);
2379 #[derive(Copy, Clone)]
2380 struct TraitObligationStackList<'o, 'tcx> {
2381 cache: &'o ProvisionalEvaluationCache<'tcx>,
2382 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2385 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2386 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2387 TraitObligationStackList { cache, head: None }
2390 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2391 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2394 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2398 fn depth(&self) -> usize {
2399 if let Some(head) = self.head { head.depth } else { 0 }
2403 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2404 type Item = &'o TraitObligationStack<'o, 'tcx>;
2406 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2417 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2418 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2419 write!(f, "TraitObligationStack({:?})", self.obligation)