1 //! Candidate selection. See the [rustc dev guide] for more information on how this works.
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection
5 use self::EvaluationResult::*;
6 use self::SelectionCandidate::*;
8 use super::coherence::{self, Conflict};
9 use super::const_evaluatable;
11 use super::project::normalize_with_depth_to;
12 use super::project::ProjectionTyObligation;
14 use super::util::{closure_trait_ref_and_return_type, predicate_for_trait_def};
16 use super::DerivedObligationCause;
17 use super::Normalized;
18 use super::Obligation;
19 use super::ObligationCauseCode;
21 use super::SelectionResult;
22 use super::TraitQueryMode;
23 use super::{ObligationCause, PredicateObligation, TraitObligation};
24 use super::{Overflow, SelectionError, Unimplemented};
26 use crate::infer::{InferCtxt, InferOk, TypeFreshener};
27 use crate::traits::error_reporting::InferCtxtExt;
28 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
29 use rustc_data_structures::stack::ensure_sufficient_stack;
30 use rustc_data_structures::sync::Lrc;
31 use rustc_errors::ErrorReported;
33 use rustc_hir::def_id::DefId;
34 use rustc_infer::infer::LateBoundRegionConversionTime;
35 use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
36 use rustc_middle::mir::interpret::ErrorHandled;
37 use rustc_middle::thir::abstract_const::NotConstEvaluatable;
38 use rustc_middle::ty::fast_reject;
39 use rustc_middle::ty::print::with_no_trimmed_paths;
40 use rustc_middle::ty::relate::TypeRelation;
41 use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef};
42 use rustc_middle::ty::WithConstness;
43 use rustc_middle::ty::{self, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate};
44 use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable};
45 use rustc_span::symbol::sym;
47 use std::cell::{Cell, RefCell};
49 use std::fmt::{self, Display};
52 pub use rustc_middle::traits::select::*;
54 mod candidate_assembly;
57 #[derive(Clone, Debug)]
58 pub enum IntercrateAmbiguityCause {
59 DownstreamCrate { trait_desc: String, self_desc: Option<String> },
60 UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
61 ReservationImpl { message: String },
64 impl IntercrateAmbiguityCause {
65 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
66 /// See #23980 for details.
67 pub fn add_intercrate_ambiguity_hint(&self, err: &mut rustc_errors::DiagnosticBuilder<'_>) {
68 err.note(&self.intercrate_ambiguity_hint());
71 pub fn intercrate_ambiguity_hint(&self) -> String {
73 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } => {
74 let self_desc = if let Some(ty) = self_desc {
75 format!(" for type `{}`", ty)
79 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
81 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc } => {
82 let self_desc = if let Some(ty) = self_desc {
83 format!(" for type `{}`", ty)
88 "upstream crates may add a new impl of trait `{}`{} \
93 IntercrateAmbiguityCause::ReservationImpl { message } => message.clone(),
98 pub struct SelectionContext<'cx, 'tcx> {
99 infcx: &'cx InferCtxt<'cx, 'tcx>,
101 /// Freshener used specifically for entries on the obligation
102 /// stack. This ensures that all entries on the stack at one time
103 /// will have the same set of placeholder entries, which is
104 /// important for checking for trait bounds that recursively
105 /// require themselves.
106 freshener: TypeFreshener<'cx, 'tcx>,
108 /// If `true`, indicates that the evaluation should be conservative
109 /// and consider the possibility of types outside this crate.
110 /// This comes up primarily when resolving ambiguity. Imagine
111 /// there is some trait reference `$0: Bar` where `$0` is an
112 /// inference variable. If `intercrate` is true, then we can never
113 /// say for sure that this reference is not implemented, even if
114 /// there are *no impls at all for `Bar`*, because `$0` could be
115 /// bound to some type that in a downstream crate that implements
116 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
117 /// though, we set this to false, because we are only interested
118 /// in types that the user could actually have written --- in
119 /// other words, we consider `$0: Bar` to be unimplemented if
120 /// there is no type that the user could *actually name* that
121 /// would satisfy it. This avoids crippling inference, basically.
124 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
126 /// Controls whether or not to filter out negative impls when selecting.
127 /// This is used in librustdoc to distinguish between the lack of an impl
128 /// and a negative impl
129 allow_negative_impls: bool,
131 /// Are we in a const context that needs `~const` bounds to be const?
132 is_in_const_context: bool,
134 /// The mode that trait queries run in, which informs our error handling
135 /// policy. In essence, canonicalized queries need their errors propagated
136 /// rather than immediately reported because we do not have accurate spans.
137 query_mode: TraitQueryMode,
140 // A stack that walks back up the stack frame.
141 struct TraitObligationStack<'prev, 'tcx> {
142 obligation: &'prev TraitObligation<'tcx>,
144 /// The trait ref from `obligation` but "freshened" with the
145 /// selection-context's freshener. Used to check for recursion.
146 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
148 /// Starts out equal to `depth` -- if, during evaluation, we
149 /// encounter a cycle, then we will set this flag to the minimum
150 /// depth of that cycle for all participants in the cycle. These
151 /// participants will then forego caching their results. This is
152 /// not the most efficient solution, but it addresses #60010. The
153 /// problem we are trying to prevent:
155 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
156 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
157 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
159 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
160 /// is `EvaluatedToOk`; this is because they were only considered
161 /// ok on the premise that if `A: AutoTrait` held, but we indeed
162 /// encountered a problem (later on) with `A: AutoTrait. So we
163 /// currently set a flag on the stack node for `B: AutoTrait` (as
164 /// well as the second instance of `A: AutoTrait`) to suppress
167 /// This is a simple, targeted fix. A more-performant fix requires
168 /// deeper changes, but would permit more caching: we could
169 /// basically defer caching until we have fully evaluated the
170 /// tree, and then cache the entire tree at once. In any case, the
171 /// performance impact here shouldn't be so horrible: every time
172 /// this is hit, we do cache at least one trait, so we only
173 /// evaluate each member of a cycle up to N times, where N is the
174 /// length of the cycle. This means the performance impact is
175 /// bounded and we shouldn't have any terrible worst-cases.
176 reached_depth: Cell<usize>,
178 previous: TraitObligationStackList<'prev, 'tcx>,
180 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
183 /// The depth-first number of this node in the search graph -- a
184 /// pre-order index. Basically, a freshly incremented counter.
188 struct SelectionCandidateSet<'tcx> {
189 // A list of candidates that definitely apply to the current
190 // obligation (meaning: types unify).
191 vec: Vec<SelectionCandidate<'tcx>>,
193 // If `true`, then there were candidates that might or might
194 // not have applied, but we couldn't tell. This occurs when some
195 // of the input types are type variables, in which case there are
196 // various "builtin" rules that might or might not trigger.
200 #[derive(PartialEq, Eq, Debug, Clone)]
201 struct EvaluatedCandidate<'tcx> {
202 candidate: SelectionCandidate<'tcx>,
203 evaluation: EvaluationResult,
206 /// When does the builtin impl for `T: Trait` apply?
207 enum BuiltinImplConditions<'tcx> {
208 /// The impl is conditional on `T1, T2, ...: Trait`.
209 Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
210 /// There is no built-in impl. There may be some other
211 /// candidate (a where-clause or user-defined impl).
213 /// It is unknown whether there is an impl.
217 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
218 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
221 freshener: infcx.freshener_keep_static(),
223 intercrate_ambiguity_causes: None,
224 allow_negative_impls: false,
225 is_in_const_context: false,
226 query_mode: TraitQueryMode::Standard,
230 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
233 freshener: infcx.freshener_keep_static(),
235 intercrate_ambiguity_causes: None,
236 allow_negative_impls: false,
237 is_in_const_context: false,
238 query_mode: TraitQueryMode::Standard,
242 pub fn with_negative(
243 infcx: &'cx InferCtxt<'cx, 'tcx>,
244 allow_negative_impls: bool,
245 ) -> SelectionContext<'cx, 'tcx> {
246 debug!(?allow_negative_impls, "with_negative");
249 freshener: infcx.freshener_keep_static(),
251 intercrate_ambiguity_causes: None,
252 allow_negative_impls,
253 is_in_const_context: false,
254 query_mode: TraitQueryMode::Standard,
258 pub fn with_query_mode(
259 infcx: &'cx InferCtxt<'cx, 'tcx>,
260 query_mode: TraitQueryMode,
261 ) -> SelectionContext<'cx, 'tcx> {
262 debug!(?query_mode, "with_query_mode");
265 freshener: infcx.freshener_keep_static(),
267 intercrate_ambiguity_causes: None,
268 allow_negative_impls: false,
269 is_in_const_context: false,
274 pub fn with_constness(
275 infcx: &'cx InferCtxt<'cx, 'tcx>,
276 constness: hir::Constness,
277 ) -> SelectionContext<'cx, 'tcx> {
280 freshener: infcx.freshener_keep_static(),
282 intercrate_ambiguity_causes: None,
283 allow_negative_impls: false,
284 is_in_const_context: matches!(constness, hir::Constness::Const),
285 query_mode: TraitQueryMode::Standard,
289 /// Enables tracking of intercrate ambiguity causes. These are
290 /// used in coherence to give improved diagnostics. We don't do
291 /// this until we detect a coherence error because it can lead to
292 /// false overflow results (#47139) and because it costs
293 /// computation time.
294 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
295 assert!(self.intercrate);
296 assert!(self.intercrate_ambiguity_causes.is_none());
297 self.intercrate_ambiguity_causes = Some(vec![]);
298 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
301 /// Gets the intercrate ambiguity causes collected since tracking
302 /// was enabled and disables tracking at the same time. If
303 /// tracking is not enabled, just returns an empty vector.
304 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
305 assert!(self.intercrate);
306 self.intercrate_ambiguity_causes.take().unwrap_or_default()
309 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
313 pub fn tcx(&self) -> TyCtxt<'tcx> {
317 /// Returns `true` if the trait predicate is considerd `const` to this selection context.
318 pub fn is_trait_predicate_const(&self, pred: ty::TraitPredicate<'_>) -> bool {
319 match pred.constness {
320 ty::BoundConstness::ConstIfConst if self.is_in_const_context => true,
325 /// Returns `true` if the predicate is considered `const` to
326 /// this selection context.
327 pub fn is_predicate_const(&self, pred: ty::Predicate<'_>) -> bool {
328 match pred.kind().skip_binder() {
329 ty::PredicateKind::Trait(pred) => self.is_trait_predicate_const(pred),
334 ///////////////////////////////////////////////////////////////////////////
337 // The selection phase tries to identify *how* an obligation will
338 // be resolved. For example, it will identify which impl or
339 // parameter bound is to be used. The process can be inconclusive
340 // if the self type in the obligation is not fully inferred. Selection
341 // can result in an error in one of two ways:
343 // 1. If no applicable impl or parameter bound can be found.
344 // 2. If the output type parameters in the obligation do not match
345 // those specified by the impl/bound. For example, if the obligation
346 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
347 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
349 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
350 /// type environment by performing unification.
351 #[instrument(level = "debug", skip(self))]
354 obligation: &TraitObligation<'tcx>,
355 ) -> SelectionResult<'tcx, Selection<'tcx>> {
356 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
358 let pec = &ProvisionalEvaluationCache::default();
359 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
361 let candidate = match self.candidate_from_obligation(&stack) {
362 Err(SelectionError::Overflow) => {
363 // In standard mode, overflow must have been caught and reported
365 assert!(self.query_mode == TraitQueryMode::Canonical);
366 return Err(SelectionError::Overflow);
374 Ok(Some(candidate)) => candidate,
377 match self.confirm_candidate(obligation, candidate) {
378 Err(SelectionError::Overflow) => {
379 assert!(self.query_mode == TraitQueryMode::Canonical);
380 Err(SelectionError::Overflow)
390 ///////////////////////////////////////////////////////////////////////////
393 // Tests whether an obligation can be selected or whether an impl
394 // can be applied to particular types. It skips the "confirmation"
395 // step and hence completely ignores output type parameters.
397 // The result is "true" if the obligation *may* hold and "false" if
398 // we can be sure it does not.
400 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
401 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
402 debug!(?obligation, "predicate_may_hold_fatal");
404 // This fatal query is a stopgap that should only be used in standard mode,
405 // where we do not expect overflow to be propagated.
406 assert!(self.query_mode == TraitQueryMode::Standard);
408 self.evaluate_root_obligation(obligation)
409 .expect("Overflow should be caught earlier in standard query mode")
413 /// Evaluates whether the obligation `obligation` can be satisfied
414 /// and returns an `EvaluationResult`. This is meant for the
416 pub fn evaluate_root_obligation(
418 obligation: &PredicateObligation<'tcx>,
419 ) -> Result<EvaluationResult, OverflowError> {
420 self.evaluation_probe(|this| {
421 this.evaluate_predicate_recursively(
422 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
430 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
431 ) -> Result<EvaluationResult, OverflowError> {
432 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
433 let result = op(self)?;
435 match self.infcx.leak_check(true, snapshot) {
437 Err(_) => return Ok(EvaluatedToErr),
440 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
442 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
447 /// Evaluates the predicates in `predicates` recursively. Note that
448 /// this applies projections in the predicates, and therefore
449 /// is run within an inference probe.
450 fn evaluate_predicates_recursively<'o, I>(
452 stack: TraitObligationStackList<'o, 'tcx>,
454 ) -> Result<EvaluationResult, OverflowError>
456 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
458 let mut result = EvaluatedToOk;
459 debug!(?predicates, "evaluate_predicates_recursively");
460 for obligation in predicates {
461 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
462 if let EvaluatedToErr = eval {
463 // fast-path - EvaluatedToErr is the top of the lattice,
464 // so we don't need to look on the other predicates.
465 return Ok(EvaluatedToErr);
467 result = cmp::max(result, eval);
475 skip(self, previous_stack),
476 fields(previous_stack = ?previous_stack.head())
478 fn evaluate_predicate_recursively<'o>(
480 previous_stack: TraitObligationStackList<'o, 'tcx>,
481 obligation: PredicateObligation<'tcx>,
482 ) -> Result<EvaluationResult, OverflowError> {
483 // `previous_stack` stores a `TraitObligation`, while `obligation` is
484 // a `PredicateObligation`. These are distinct types, so we can't
485 // use any `Option` combinator method that would force them to be
487 match previous_stack.head() {
488 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
489 None => self.check_recursion_limit(&obligation, &obligation)?,
492 let result = ensure_sufficient_stack(|| {
493 let bound_predicate = obligation.predicate.kind();
494 match bound_predicate.skip_binder() {
495 ty::PredicateKind::Trait(t) => {
496 let t = bound_predicate.rebind(t);
497 debug_assert!(!t.has_escaping_bound_vars());
498 let obligation = obligation.with(t);
499 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
502 ty::PredicateKind::Subtype(p) => {
503 let p = bound_predicate.rebind(p);
504 // Does this code ever run?
505 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
506 Some(Ok(InferOk { mut obligations, .. })) => {
507 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
508 self.evaluate_predicates_recursively(
510 obligations.into_iter(),
513 Some(Err(_)) => Ok(EvaluatedToErr),
514 None => Ok(EvaluatedToAmbig),
518 ty::PredicateKind::Coerce(p) => {
519 let p = bound_predicate.rebind(p);
520 // Does this code ever run?
521 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
522 Some(Ok(InferOk { mut obligations, .. })) => {
523 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
524 self.evaluate_predicates_recursively(
526 obligations.into_iter(),
529 Some(Err(_)) => Ok(EvaluatedToErr),
530 None => Ok(EvaluatedToAmbig),
534 ty::PredicateKind::WellFormed(arg) => match wf::obligations(
536 obligation.param_env,
537 obligation.cause.body_id,
538 obligation.recursion_depth + 1,
540 obligation.cause.span,
542 Some(mut obligations) => {
543 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
544 self.evaluate_predicates_recursively(previous_stack, obligations)
546 None => Ok(EvaluatedToAmbig),
549 ty::PredicateKind::TypeOutlives(pred) => {
550 if pred.0.is_known_global() {
553 Ok(EvaluatedToOkModuloRegions)
557 ty::PredicateKind::RegionOutlives(..) => {
558 // We do not consider region relationships when evaluating trait matches.
559 Ok(EvaluatedToOkModuloRegions)
562 ty::PredicateKind::ObjectSafe(trait_def_id) => {
563 if self.tcx().is_object_safe(trait_def_id) {
570 ty::PredicateKind::Projection(data) => {
571 let data = bound_predicate.rebind(data);
572 let project_obligation = obligation.with(data);
573 match project::poly_project_and_unify_type(self, &project_obligation) {
574 Ok(Ok(Some(mut subobligations))) => {
575 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
576 self.evaluate_predicates_recursively(previous_stack, subobligations)
578 Ok(Ok(None)) => Ok(EvaluatedToAmbig),
579 Ok(Err(project::InProgress)) => Ok(EvaluatedToRecur),
580 Err(_) => Ok(EvaluatedToErr),
584 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
585 match self.infcx.closure_kind(closure_substs) {
586 Some(closure_kind) => {
587 if closure_kind.extends(kind) {
593 None => Ok(EvaluatedToAmbig),
597 ty::PredicateKind::ConstEvaluatable(uv) => {
598 match const_evaluatable::is_const_evaluatable(
601 obligation.param_env,
602 obligation.cause.span,
604 Ok(()) => Ok(EvaluatedToOk),
605 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
606 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
607 Err(_) => Ok(EvaluatedToErr),
611 ty::PredicateKind::ConstEquate(c1, c2) => {
612 debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
614 if self.tcx().features().generic_const_exprs {
615 // FIXME: we probably should only try to unify abstract constants
616 // if the constants depend on generic parameters.
618 // Let's just see where this breaks :shrug:
619 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
622 if self.infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
623 return Ok(EvaluatedToOk);
628 let evaluate = |c: &'tcx ty::Const<'tcx>| {
629 if let ty::ConstKind::Unevaluated(unevaluated) = c.val {
632 obligation.param_env,
634 Some(obligation.cause.span),
636 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty))
642 match (evaluate(c1), evaluate(c2)) {
643 (Ok(c1), Ok(c2)) => {
646 .at(&obligation.cause, obligation.param_env)
649 Ok(_) => Ok(EvaluatedToOk),
650 Err(_) => Ok(EvaluatedToErr),
653 (Err(ErrorHandled::Reported(ErrorReported)), _)
654 | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
655 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
657 obligation.cause.span(self.tcx()),
658 "ConstEquate: const_eval_resolve returned an unexpected error"
661 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
662 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
665 // Two different constants using generic parameters ~> error.
671 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
672 bug!("TypeWellFormedFromEnv is only used for chalk")
677 debug!("finished: {:?} from {:?}", result, obligation);
682 fn evaluate_trait_predicate_recursively<'o>(
684 previous_stack: TraitObligationStackList<'o, 'tcx>,
685 mut obligation: TraitObligation<'tcx>,
686 ) -> Result<EvaluationResult, OverflowError> {
687 debug!(?obligation, "evaluate_trait_predicate_recursively");
690 && obligation.is_global(self.tcx())
695 .all(|bound| bound.definitely_needs_subst(self.tcx()))
697 // If a param env has no global bounds, global obligations do not
698 // depend on its particular value in order to work, so we can clear
699 // out the param env and get better caching.
700 debug!("evaluate_trait_predicate_recursively - in global");
701 obligation.param_env = obligation.param_env.without_caller_bounds();
704 let stack = self.push_stack(previous_stack, &obligation);
705 let fresh_trait_ref = stack.fresh_trait_ref;
707 debug!(?fresh_trait_ref);
709 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
710 debug!(?result, "CACHE HIT");
714 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
715 debug!(?result, "PROVISIONAL CACHE HIT");
716 stack.update_reached_depth(result.reached_depth);
717 return Ok(result.result);
720 // Check if this is a match for something already on the
721 // stack. If so, we don't want to insert the result into the
722 // main cache (it is cycle dependent) nor the provisional
723 // cache (which is meant for things that have completed but
724 // for a "backedge" -- this result *is* the backedge).
725 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
726 return Ok(cycle_result);
729 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
730 let result = result?;
732 if !result.must_apply_modulo_regions() {
733 stack.cache().on_failure(stack.dfn);
736 let reached_depth = stack.reached_depth.get();
737 if reached_depth >= stack.depth {
738 debug!(?result, "CACHE MISS");
739 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
741 stack.cache().on_completion(stack.dfn, |fresh_trait_ref, provisional_result| {
742 self.insert_evaluation_cache(
743 obligation.param_env,
746 provisional_result.max(result),
750 debug!(?result, "PROVISIONAL");
752 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
753 is a cycle participant (at depth {}, reached depth {})",
754 fresh_trait_ref, stack.depth, reached_depth,
757 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
763 /// If there is any previous entry on the stack that precisely
764 /// matches this obligation, then we can assume that the
765 /// obligation is satisfied for now (still all other conditions
766 /// must be met of course). One obvious case this comes up is
767 /// marker traits like `Send`. Think of a linked list:
769 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
771 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
772 /// `Option<Box<List<T>>>` is `Send`, and in turn
773 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
776 /// Note that we do this comparison using the `fresh_trait_ref`
777 /// fields. Because these have all been freshened using
778 /// `self.freshener`, we can be sure that (a) this will not
779 /// affect the inferencer state and (b) that if we see two
780 /// fresh regions with the same index, they refer to the same
781 /// unbound type variable.
782 fn check_evaluation_cycle(
784 stack: &TraitObligationStack<'_, 'tcx>,
785 ) -> Option<EvaluationResult> {
786 if let Some(cycle_depth) = stack
788 .skip(1) // Skip top-most frame.
790 stack.obligation.param_env == prev.obligation.param_env
791 && stack.fresh_trait_ref == prev.fresh_trait_ref
793 .map(|stack| stack.depth)
795 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
797 // If we have a stack like `A B C D E A`, where the top of
798 // the stack is the final `A`, then this will iterate over
799 // `A, E, D, C, B` -- i.e., all the participants apart
800 // from the cycle head. We mark them as participating in a
801 // cycle. This suppresses caching for those nodes. See
802 // `in_cycle` field for more details.
803 stack.update_reached_depth(cycle_depth);
805 // Subtle: when checking for a coinductive cycle, we do
806 // not compare using the "freshened trait refs" (which
807 // have erased regions) but rather the fully explicit
808 // trait refs. This is important because it's only a cycle
809 // if the regions match exactly.
810 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
811 let tcx = self.tcx();
812 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
813 if self.coinductive_match(cycle) {
814 debug!("evaluate_stack --> recursive, coinductive");
817 debug!("evaluate_stack --> recursive, inductive");
818 Some(EvaluatedToRecur)
825 fn evaluate_stack<'o>(
827 stack: &TraitObligationStack<'o, 'tcx>,
828 ) -> Result<EvaluationResult, OverflowError> {
829 // In intercrate mode, whenever any of the generics are unbound,
830 // there can always be an impl. Even if there are no impls in
831 // this crate, perhaps the type would be unified with
832 // something from another crate that does provide an impl.
834 // In intra mode, we must still be conservative. The reason is
835 // that we want to avoid cycles. Imagine an impl like:
837 // impl<T:Eq> Eq for Vec<T>
839 // and a trait reference like `$0 : Eq` where `$0` is an
840 // unbound variable. When we evaluate this trait-reference, we
841 // will unify `$0` with `Vec<$1>` (for some fresh variable
842 // `$1`), on the condition that `$1 : Eq`. We will then wind
843 // up with many candidates (since that are other `Eq` impls
844 // that apply) and try to winnow things down. This results in
845 // a recursive evaluation that `$1 : Eq` -- as you can
846 // imagine, this is just where we started. To avoid that, we
847 // check for unbound variables and return an ambiguous (hence possible)
848 // match if we've seen this trait before.
850 // This suffices to allow chains like `FnMut` implemented in
851 // terms of `Fn` etc, but we could probably make this more
853 let unbound_input_types =
854 stack.fresh_trait_ref.value.skip_binder().substs.types().any(|ty| ty.is_fresh());
855 // This check was an imperfect workaround for a bug in the old
856 // intercrate mode; it should be removed when that goes away.
857 if unbound_input_types && self.intercrate {
858 debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
859 // Heuristics: show the diagnostics when there are no candidates in crate.
860 if self.intercrate_ambiguity_causes.is_some() {
861 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
862 if let Ok(candidate_set) = self.assemble_candidates(stack) {
863 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
864 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
865 let self_ty = trait_ref.self_ty();
867 with_no_trimmed_paths(|| IntercrateAmbiguityCause::DownstreamCrate {
868 trait_desc: trait_ref.print_only_trait_path().to_string(),
869 self_desc: if self_ty.has_concrete_skeleton() {
870 Some(self_ty.to_string())
876 debug!(?cause, "evaluate_stack: pushing cause");
877 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
881 return Ok(EvaluatedToAmbig);
883 if unbound_input_types
884 && stack.iter().skip(1).any(|prev| {
885 stack.obligation.param_env == prev.obligation.param_env
886 && self.match_fresh_trait_refs(
887 stack.fresh_trait_ref,
888 prev.fresh_trait_ref,
889 prev.obligation.param_env,
893 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
894 return Ok(EvaluatedToUnknown);
897 match self.candidate_from_obligation(stack) {
898 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
899 Ok(None) => Ok(EvaluatedToAmbig),
900 Err(Overflow) => Err(OverflowError),
901 Err(..) => Ok(EvaluatedToErr),
905 /// For defaulted traits, we use a co-inductive strategy to solve, so
906 /// that recursion is ok. This routine returns `true` if the top of the
907 /// stack (`cycle[0]`):
909 /// - is a defaulted trait,
910 /// - it also appears in the backtrace at some position `X`,
911 /// - all the predicates at positions `X..` between `X` and the top are
912 /// also defaulted traits.
913 pub fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
915 I: Iterator<Item = ty::Predicate<'tcx>>,
917 cycle.all(|predicate| self.coinductive_predicate(predicate))
920 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
921 let result = match predicate.kind().skip_binder() {
922 ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
925 debug!(?predicate, ?result, "coinductive_predicate");
929 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
930 /// obligations are met. Returns whether `candidate` remains viable after this further
935 fields(depth = stack.obligation.recursion_depth)
937 fn evaluate_candidate<'o>(
939 stack: &TraitObligationStack<'o, 'tcx>,
940 candidate: &SelectionCandidate<'tcx>,
941 ) -> Result<EvaluationResult, OverflowError> {
942 let mut result = self.evaluation_probe(|this| {
943 let candidate = (*candidate).clone();
944 match this.confirm_candidate(stack.obligation, candidate) {
947 this.evaluate_predicates_recursively(
949 selection.nested_obligations().into_iter(),
952 Err(..) => Ok(EvaluatedToErr),
956 // If we erased any lifetimes, then we want to use
957 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
958 // as your final result. The result will be cached using
959 // the freshened trait predicate as a key, so we need
960 // our result to be correct by *any* choice of original lifetimes,
961 // not just the lifetime choice for this particular (non-erased)
964 if stack.fresh_trait_ref.has_erased_regions() {
965 result = result.max(EvaluatedToOkModuloRegions);
972 fn check_evaluation_cache(
974 param_env: ty::ParamEnv<'tcx>,
975 trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
976 ) -> Option<EvaluationResult> {
977 // Neither the global nor local cache is aware of intercrate
978 // mode, so don't do any caching. In particular, we might
979 // re-use the same `InferCtxt` with both an intercrate
980 // and non-intercrate `SelectionContext`
985 let tcx = self.tcx();
986 if self.can_use_global_caches(param_env) {
987 if let Some(res) = tcx.evaluation_cache.get(¶m_env.and(trait_ref), tcx) {
991 self.infcx.evaluation_cache.get(¶m_env.and(trait_ref), tcx)
994 fn insert_evaluation_cache(
996 param_env: ty::ParamEnv<'tcx>,
997 trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
998 dep_node: DepNodeIndex,
999 result: EvaluationResult,
1001 // Avoid caching results that depend on more than just the trait-ref
1002 // - the stack can create recursion.
1003 if result.is_stack_dependent() {
1007 // Neither the global nor local cache is aware of intercrate
1008 // mode, so don't do any caching. In particular, we might
1009 // re-use the same `InferCtxt` with both an intercrate
1010 // and non-intercrate `SelectionContext`
1011 if self.intercrate {
1015 if self.can_use_global_caches(param_env) {
1016 if !trait_ref.needs_infer() {
1017 debug!(?trait_ref, ?result, "insert_evaluation_cache global");
1018 // This may overwrite the cache with the same value
1019 // FIXME: Due to #50507 this overwrites the different values
1020 // This should be changed to use HashMapExt::insert_same
1021 // when that is fixed
1022 self.tcx().evaluation_cache.insert(param_env.and(trait_ref), dep_node, result);
1027 debug!(?trait_ref, ?result, "insert_evaluation_cache");
1028 self.infcx.evaluation_cache.insert(param_env.and(trait_ref), dep_node, result);
1031 /// For various reasons, it's possible for a subobligation
1032 /// to have a *lower* recursion_depth than the obligation used to create it.
1033 /// Projection sub-obligations may be returned from the projection cache,
1034 /// which results in obligations with an 'old' `recursion_depth`.
1035 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1036 /// subobligations without taking in a 'parent' depth, causing the
1037 /// generated subobligations to have a `recursion_depth` of `0`.
1039 /// To ensure that obligation_depth never decreases, we force all subobligations
1040 /// to have at least the depth of the original obligation.
1041 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1046 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1049 fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
1052 error_obligation: &Obligation<'tcx, T>,
1053 ) -> Result<(), OverflowError> {
1054 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1055 match self.query_mode {
1056 TraitQueryMode::Standard => {
1057 self.infcx.report_overflow_error(error_obligation, true);
1059 TraitQueryMode::Canonical => {
1060 return Err(OverflowError);
1067 /// Checks that the recursion limit has not been exceeded.
1069 /// The weird return type of this function allows it to be used with the `try` (`?`)
1070 /// operator within certain functions.
1072 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1074 obligation: &Obligation<'tcx, T>,
1075 error_obligation: &Obligation<'tcx, V>,
1076 ) -> Result<(), OverflowError> {
1077 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1080 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1082 OP: FnOnce(&mut Self) -> R,
1084 let (result, dep_node) =
1085 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1086 self.tcx().dep_graph.read_index(dep_node);
1090 #[instrument(level = "debug", skip(self))]
1093 candidate: SelectionCandidate<'tcx>,
1094 obligation: &TraitObligation<'tcx>,
1095 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1096 let tcx = self.tcx();
1097 // Respect const trait obligations
1098 if self.is_trait_predicate_const(obligation.predicate.skip_binder()) {
1101 ImplCandidate(def_id) if tcx.impl_constness(def_id) == hir::Constness::Const => {}
1103 ParamCandidate(ty::ConstnessAnd {
1104 constness: ty::BoundConstness::ConstIfConst,
1108 AutoImplCandidate(..) => {}
1109 // generator, this will raise error in other places
1110 // or ignore error with const_async_blocks feature
1111 GeneratorCandidate => {}
1112 ConstDropCandidate => {}
1114 // reject all other types of candidates
1115 return Err(Unimplemented);
1119 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
1120 if let ImplCandidate(def_id) = candidate {
1121 match tcx.impl_polarity(def_id) {
1122 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
1123 return Err(Unimplemented);
1125 ty::ImplPolarity::Reservation => {
1126 if let Some(intercrate_ambiguity_clauses) =
1127 &mut self.intercrate_ambiguity_causes
1129 let attrs = tcx.get_attrs(def_id);
1130 let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
1131 let value = attr.and_then(|a| a.value_str());
1132 if let Some(value) = value {
1135 reservation impl ambiguity on {:?}",
1138 intercrate_ambiguity_clauses.push(
1139 IntercrateAmbiguityCause::ReservationImpl {
1140 message: value.to_string(),
1153 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1154 debug!("is_knowable(intercrate={:?})", self.intercrate);
1156 if !self.intercrate {
1160 let obligation = &stack.obligation;
1161 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1163 // Okay to skip binder because of the nature of the
1164 // trait-ref-is-knowable check, which does not care about
1166 let trait_ref = predicate.skip_binder().trait_ref;
1168 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1171 /// Returns `true` if the global caches can be used.
1172 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1173 // If there are any inference variables in the `ParamEnv`, then we
1174 // always use a cache local to this particular scope. Otherwise, we
1175 // switch to a global cache.
1176 if param_env.needs_infer() {
1180 // Avoid using the master cache during coherence and just rely
1181 // on the local cache. This effectively disables caching
1182 // during coherence. It is really just a simplification to
1183 // avoid us having to fear that coherence results "pollute"
1184 // the master cache. Since coherence executes pretty quickly,
1185 // it's not worth going to more trouble to increase the
1186 // hit-rate, I don't think.
1187 if self.intercrate {
1191 // Otherwise, we can use the global cache.
1195 fn check_candidate_cache(
1197 param_env: ty::ParamEnv<'tcx>,
1198 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1199 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1200 let tcx = self.tcx();
1201 let pred = &cache_fresh_trait_pred.skip_binder();
1202 let trait_ref = pred.trait_ref;
1203 if self.can_use_global_caches(param_env) {
1204 if let Some(res) = tcx
1206 .get(¶m_env.and(trait_ref).with_constness(pred.constness), tcx)
1213 .get(¶m_env.and(trait_ref).with_constness(pred.constness), tcx)
1216 /// Determines whether can we safely cache the result
1217 /// of selecting an obligation. This is almost always `true`,
1218 /// except when dealing with certain `ParamCandidate`s.
1220 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1221 /// since it was usually produced directly from a `DefId`. However,
1222 /// certain cases (currently only librustdoc's blanket impl finder),
1223 /// a `ParamEnv` may be explicitly constructed with inference types.
1224 /// When this is the case, we do *not* want to cache the resulting selection
1225 /// candidate. This is due to the fact that it might not always be possible
1226 /// to equate the obligation's trait ref and the candidate's trait ref,
1227 /// if more constraints end up getting added to an inference variable.
1229 /// Because of this, we always want to re-run the full selection
1230 /// process for our obligation the next time we see it, since
1231 /// we might end up picking a different `SelectionCandidate` (or none at all).
1232 fn can_cache_candidate(
1234 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1237 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1242 fn insert_candidate_cache(
1244 param_env: ty::ParamEnv<'tcx>,
1245 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1246 dep_node: DepNodeIndex,
1247 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1249 let tcx = self.tcx();
1250 let pred = cache_fresh_trait_pred.skip_binder();
1251 let trait_ref = pred.trait_ref;
1253 if !self.can_cache_candidate(&candidate) {
1254 debug!(?trait_ref, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1258 if self.can_use_global_caches(param_env) {
1259 if let Err(Overflow) = candidate {
1260 // Don't cache overflow globally; we only produce this in certain modes.
1261 } else if !trait_ref.needs_infer() {
1262 if !candidate.needs_infer() {
1263 debug!(?trait_ref, ?candidate, "insert_candidate_cache global");
1264 // This may overwrite the cache with the same value.
1265 tcx.selection_cache.insert(
1266 param_env.and(trait_ref).with_constness(pred.constness),
1275 debug!(?trait_ref, ?candidate, "insert_candidate_cache local");
1276 self.infcx.selection_cache.insert(
1277 param_env.and(trait_ref).with_constness(pred.constness),
1283 /// Matches a predicate against the bounds of its self type.
1285 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1286 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1287 /// `Baz` bound. We return indexes into the list returned by
1288 /// `tcx.item_bounds` for any applicable bounds.
1289 fn match_projection_obligation_against_definition_bounds(
1291 obligation: &TraitObligation<'tcx>,
1292 ) -> smallvec::SmallVec<[usize; 2]> {
1293 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1294 let placeholder_trait_predicate =
1295 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1297 ?placeholder_trait_predicate,
1298 "match_projection_obligation_against_definition_bounds"
1301 let tcx = self.infcx.tcx;
1302 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1303 ty::Projection(ref data) => (data.item_def_id, data.substs),
1304 ty::Opaque(def_id, substs) => (def_id, substs),
1307 obligation.cause.span,
1308 "match_projection_obligation_against_definition_bounds() called \
1309 but self-ty is not a projection: {:?}",
1310 placeholder_trait_predicate.trait_ref.self_ty()
1314 let bounds = tcx.item_bounds(def_id).subst(tcx, substs);
1316 // The bounds returned by `item_bounds` may contain duplicates after
1317 // normalization, so try to deduplicate when possible to avoid
1318 // unnecessary ambiguity.
1319 let mut distinct_normalized_bounds = FxHashSet::default();
1321 let matching_bounds = bounds
1324 .filter_map(|(idx, bound)| {
1325 let bound_predicate = bound.kind();
1326 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1327 let bound = bound_predicate.rebind(pred.trait_ref);
1328 if self.infcx.probe(|_| {
1329 match self.match_normalize_trait_ref(
1332 placeholder_trait_predicate.trait_ref,
1335 Ok(Some(normalized_trait))
1336 if distinct_normalized_bounds.insert(normalized_trait) =>
1350 debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds");
1354 /// Equates the trait in `obligation` with trait bound. If the two traits
1355 /// can be equated and the normalized trait bound doesn't contain inference
1356 /// variables or placeholders, the normalized bound is returned.
1357 fn match_normalize_trait_ref(
1359 obligation: &TraitObligation<'tcx>,
1360 trait_bound: ty::PolyTraitRef<'tcx>,
1361 placeholder_trait_ref: ty::TraitRef<'tcx>,
1362 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1363 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1364 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1365 // Avoid unnecessary normalization
1369 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1370 project::normalize_with_depth(
1372 obligation.param_env,
1373 obligation.cause.clone(),
1374 obligation.recursion_depth + 1,
1379 .at(&obligation.cause, obligation.param_env)
1380 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1381 .map(|InferOk { obligations: _, value: () }| {
1382 // This method is called within a probe, so we can't have
1383 // inference variables and placeholders escape.
1384 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1393 fn evaluate_where_clause<'o>(
1395 stack: &TraitObligationStack<'o, 'tcx>,
1396 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1397 ) -> Result<EvaluationResult, OverflowError> {
1398 self.evaluation_probe(|this| {
1399 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1400 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1401 Err(()) => Ok(EvaluatedToErr),
1406 pub(super) fn match_projection_projections(
1408 obligation: &ProjectionTyObligation<'tcx>,
1409 env_predicate: PolyProjectionPredicate<'tcx>,
1410 potentially_unnormalized_candidates: bool,
1412 let mut nested_obligations = Vec::new();
1413 let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars(
1414 obligation.cause.span,
1415 LateBoundRegionConversionTime::HigherRankedType,
1418 let infer_projection = if potentially_unnormalized_candidates {
1419 ensure_sufficient_stack(|| {
1420 project::normalize_with_depth_to(
1422 obligation.param_env,
1423 obligation.cause.clone(),
1424 obligation.recursion_depth + 1,
1425 infer_predicate.projection_ty,
1426 &mut nested_obligations,
1430 infer_predicate.projection_ty
1434 .at(&obligation.cause, obligation.param_env)
1435 .sup(obligation.predicate, infer_projection)
1436 .map_or(false, |InferOk { obligations, value: () }| {
1437 self.evaluate_predicates_recursively(
1438 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1439 nested_obligations.into_iter().chain(obligations),
1441 .map_or(false, |res| res.may_apply())
1445 ///////////////////////////////////////////////////////////////////////////
1448 // Winnowing is the process of attempting to resolve ambiguity by
1449 // probing further. During the winnowing process, we unify all
1450 // type variables and then we also attempt to evaluate recursive
1451 // bounds to see if they are satisfied.
1453 /// Returns `true` if `victim` should be dropped in favor of
1454 /// `other`. Generally speaking we will drop duplicate
1455 /// candidates and prefer where-clause candidates.
1457 /// See the comment for "SelectionCandidate" for more details.
1458 fn candidate_should_be_dropped_in_favor_of(
1460 victim: &EvaluatedCandidate<'tcx>,
1461 other: &EvaluatedCandidate<'tcx>,
1464 if victim.candidate == other.candidate {
1468 // Check if a bound would previously have been removed when normalizing
1469 // the param_env so that it can be given the lowest priority. See
1470 // #50825 for the motivation for this.
1472 |cand: &ty::PolyTraitRef<'_>| cand.is_known_global() && !cand.has_late_bound_regions();
1474 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1475 // and `DiscriminantKindCandidate` to anything else.
1477 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1478 // lifetime of a variable.
1479 match (&other.candidate, &victim.candidate) {
1480 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1482 "default implementations shouldn't be recorded \
1483 when there are other valid candidates"
1489 BuiltinCandidate { has_nested: false }
1490 | DiscriminantKindCandidate
1492 | ConstDropCandidate,
1497 BuiltinCandidate { has_nested: false }
1498 | DiscriminantKindCandidate
1500 | ConstDropCandidate,
1503 (ParamCandidate(other), ParamCandidate(victim)) => {
1504 let same_except_bound_vars = other.value.skip_binder()
1505 == victim.value.skip_binder()
1506 && other.constness == victim.constness
1507 && !other.value.skip_binder().has_escaping_bound_vars();
1508 if same_except_bound_vars {
1509 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1510 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1511 // or the current one if tied (they should both evaluate to the same answer). This is
1512 // probably best characterized as a "hack", since we might prefer to just do our
1513 // best to *not* create essentially duplicate candidates in the first place.
1514 other.value.bound_vars().len() <= victim.value.bound_vars().len()
1515 } else if other.value == victim.value
1516 && victim.constness == ty::BoundConstness::NotConst
1518 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1525 // Global bounds from the where clause should be ignored
1526 // here (see issue #50825). Otherwise, we have a where
1527 // clause so don't go around looking for impls.
1528 // Arbitrarily give param candidates priority
1529 // over projection and object candidates.
1531 ParamCandidate(ref cand),
1534 | GeneratorCandidate
1535 | FnPointerCandidate
1536 | BuiltinObjectCandidate
1537 | BuiltinUnsizeCandidate
1538 | TraitUpcastingUnsizeCandidate(_)
1539 | BuiltinCandidate { .. }
1540 | TraitAliasCandidate(..)
1541 | ObjectCandidate(_)
1542 | ProjectionCandidate(_),
1543 ) => !is_global(&cand.value),
1544 (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1545 // Prefer these to a global where-clause bound
1546 // (see issue #50825).
1547 is_global(&cand.value)
1552 | GeneratorCandidate
1553 | FnPointerCandidate
1554 | BuiltinObjectCandidate
1555 | BuiltinUnsizeCandidate
1556 | TraitUpcastingUnsizeCandidate(_)
1557 | BuiltinCandidate { has_nested: true }
1558 | TraitAliasCandidate(..),
1559 ParamCandidate(ref cand),
1561 // Prefer these to a global where-clause bound
1562 // (see issue #50825).
1563 is_global(&cand.value) && other.evaluation.must_apply_modulo_regions()
1566 (ProjectionCandidate(i), ProjectionCandidate(j))
1567 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1568 // Arbitrarily pick the lower numbered candidate for backwards
1569 // compatibility reasons. Don't let this affect inference.
1570 i < j && !needs_infer
1572 (ObjectCandidate(_), ProjectionCandidate(_))
1573 | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1574 bug!("Have both object and projection candidate")
1577 // Arbitrarily give projection and object candidates priority.
1579 ObjectCandidate(_) | ProjectionCandidate(_),
1582 | GeneratorCandidate
1583 | FnPointerCandidate
1584 | BuiltinObjectCandidate
1585 | BuiltinUnsizeCandidate
1586 | TraitUpcastingUnsizeCandidate(_)
1587 | BuiltinCandidate { .. }
1588 | TraitAliasCandidate(..),
1594 | GeneratorCandidate
1595 | FnPointerCandidate
1596 | BuiltinObjectCandidate
1597 | BuiltinUnsizeCandidate
1598 | TraitUpcastingUnsizeCandidate(_)
1599 | BuiltinCandidate { .. }
1600 | TraitAliasCandidate(..),
1601 ObjectCandidate(_) | ProjectionCandidate(_),
1604 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1605 // See if we can toss out `victim` based on specialization.
1606 // This requires us to know *for sure* that the `other` impl applies
1607 // i.e., `EvaluatedToOk`.
1609 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1610 // to me but is required for `std` to compile, so I didn't change it
1612 let tcx = self.tcx();
1613 if other.evaluation.must_apply_modulo_regions() {
1614 if tcx.specializes((other_def, victim_def)) {
1619 if other.evaluation.must_apply_considering_regions() {
1620 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1621 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1622 // Subtle: If the predicate we are evaluating has inference
1623 // variables, do *not* allow discarding candidates due to
1624 // marker trait impls.
1626 // Without this restriction, we could end up accidentally
1627 // constrainting inference variables based on an arbitrarily
1628 // chosen trait impl.
1630 // Imagine we have the following code:
1633 // #[marker] trait MyTrait {}
1634 // impl MyTrait for u8 {}
1635 // impl MyTrait for bool {}
1638 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1640 // During selection, we will end up with one candidate for each
1641 // impl of `MyTrait`. If we were to discard one impl in favor
1642 // of the other, we would be left with one candidate, causing
1643 // us to "successfully" select the predicate, unifying
1644 // _#0t with (for example) `u8`.
1646 // However, we have no reason to believe that this unification
1647 // is correct - we've essentially just picked an arbitrary
1648 // *possibility* for _#0t, and required that this be the *only*
1651 // Eventually, we will either:
1652 // 1) Unify all inference variables in the predicate through
1653 // some other means (e.g. type-checking of a function). We will
1654 // then be in a position to drop marker trait candidates
1655 // without constraining inference variables (since there are
1656 // none left to constrin)
1657 // 2) Be left with some unconstrained inference variables. We
1658 // will then correctly report an inference error, since the
1659 // existence of multiple marker trait impls tells us nothing
1660 // about which one should actually apply.
1671 // Everything else is ambiguous
1675 | GeneratorCandidate
1676 | FnPointerCandidate
1677 | BuiltinObjectCandidate
1678 | BuiltinUnsizeCandidate
1679 | TraitUpcastingUnsizeCandidate(_)
1680 | BuiltinCandidate { has_nested: true }
1681 | TraitAliasCandidate(..),
1684 | GeneratorCandidate
1685 | FnPointerCandidate
1686 | BuiltinObjectCandidate
1687 | BuiltinUnsizeCandidate
1688 | TraitUpcastingUnsizeCandidate(_)
1689 | BuiltinCandidate { has_nested: true }
1690 | TraitAliasCandidate(..),
1695 fn sized_conditions(
1697 obligation: &TraitObligation<'tcx>,
1698 ) -> BuiltinImplConditions<'tcx> {
1699 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1701 // NOTE: binder moved to (*)
1702 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1704 match self_ty.kind() {
1705 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1716 | ty::GeneratorWitness(..)
1721 // safe for everything
1722 Where(ty::Binder::dummy(Vec::new()))
1725 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1727 ty::Tuple(tys) => Where(
1730 .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()),
1733 ty::Adt(def, substs) => {
1734 let sized_crit = def.sized_constraint(self.tcx());
1735 // (*) binder moved here
1737 obligation.predicate.rebind({
1738 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1743 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1744 ty::Infer(ty::TyVar(_)) => Ambiguous,
1748 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1749 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1754 fn copy_clone_conditions(
1756 obligation: &TraitObligation<'tcx>,
1757 ) -> BuiltinImplConditions<'tcx> {
1758 // NOTE: binder moved to (*)
1759 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1761 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1763 match *self_ty.kind() {
1764 ty::Infer(ty::IntVar(_))
1765 | ty::Infer(ty::FloatVar(_))
1768 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1777 | ty::Ref(_, _, hir::Mutability::Not) => {
1778 // Implementations provided in libcore
1786 | ty::GeneratorWitness(..)
1788 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1790 ty::Array(element_ty, _) => {
1791 // (*) binder moved here
1792 Where(obligation.predicate.rebind(vec![element_ty]))
1796 // (*) binder moved here
1797 Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect()))
1800 ty::Closure(_, substs) => {
1801 // (*) binder moved here
1802 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1803 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1804 // Not yet resolved.
1807 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1811 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1812 // Fallback to whatever user-defined impls exist in this case.
1816 ty::Infer(ty::TyVar(_)) => {
1817 // Unbound type variable. Might or might not have
1818 // applicable impls and so forth, depending on what
1819 // those type variables wind up being bound to.
1825 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1826 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1831 /// For default impls, we need to break apart a type into its
1832 /// "constituent types" -- meaning, the types that it contains.
1834 /// Here are some (simple) examples:
1837 /// (i32, u32) -> [i32, u32]
1838 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1839 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1840 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1842 fn constituent_types_for_ty(
1844 t: ty::Binder<'tcx, Ty<'tcx>>,
1845 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1846 match *t.skip_binder().kind() {
1855 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1857 | ty::Char => ty::Binder::dummy(Vec::new()),
1863 | ty::Projection(..)
1865 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1866 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1869 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1870 t.rebind(vec![element_ty])
1873 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
1875 ty::Tuple(ref tys) => {
1876 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1877 t.rebind(tys.iter().map(|k| k.expect_ty()).collect())
1880 ty::Closure(_, ref substs) => {
1881 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1885 ty::Generator(_, ref substs, _) => {
1886 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
1887 let witness = substs.as_generator().witness();
1888 t.rebind(vec![ty].into_iter().chain(iter::once(witness)).collect())
1891 ty::GeneratorWitness(types) => {
1892 debug_assert!(!types.has_escaping_bound_vars());
1893 types.map_bound(|types| types.to_vec())
1896 // For `PhantomData<T>`, we pass `T`.
1897 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
1899 ty::Adt(def, substs) => {
1900 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
1903 ty::Opaque(def_id, substs) => {
1904 // We can resolve the `impl Trait` to its concrete type,
1905 // which enforces a DAG between the functions requiring
1906 // the auto trait bounds in question.
1907 t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
1912 fn collect_predicates_for_types(
1914 param_env: ty::ParamEnv<'tcx>,
1915 cause: ObligationCause<'tcx>,
1916 recursion_depth: usize,
1917 trait_def_id: DefId,
1918 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
1919 ) -> Vec<PredicateObligation<'tcx>> {
1920 // Because the types were potentially derived from
1921 // higher-ranked obligations they may reference late-bound
1922 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
1923 // yield a type like `for<'a> &'a i32`. In general, we
1924 // maintain the invariant that we never manipulate bound
1925 // regions, so we have to process these bound regions somehow.
1927 // The strategy is to:
1929 // 1. Instantiate those regions to placeholder regions (e.g.,
1930 // `for<'a> &'a i32` becomes `&0 i32`.
1931 // 2. Produce something like `&'0 i32 : Copy`
1932 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
1936 .skip_binder() // binder moved -\
1939 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(ty); // <----/
1941 self.infcx.commit_unconditionally(|_| {
1942 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
1943 let Normalized { value: normalized_ty, mut obligations } =
1944 ensure_sufficient_stack(|| {
1945 project::normalize_with_depth(
1953 let placeholder_obligation = predicate_for_trait_def(
1962 obligations.push(placeholder_obligation);
1969 ///////////////////////////////////////////////////////////////////////////
1972 // Matching is a common path used for both evaluation and
1973 // confirmation. It basically unifies types that appear in impls
1974 // and traits. This does affect the surrounding environment;
1975 // therefore, when used during evaluation, match routines must be
1976 // run inside of a `probe()` so that their side-effects are
1982 obligation: &TraitObligation<'tcx>,
1983 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
1984 match self.match_impl(impl_def_id, obligation) {
1985 Ok(substs) => substs,
1988 "Impl {:?} was matchable against {:?} but now is not",
1996 #[tracing::instrument(level = "debug", skip(self))]
2000 obligation: &TraitObligation<'tcx>,
2001 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2002 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2004 // Before we create the substitutions and everything, first
2005 // consider a "quick reject". This avoids creating more types
2006 // and so forth that we need to.
2007 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2011 let placeholder_obligation =
2012 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
2013 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2015 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2017 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2019 debug!(?impl_trait_ref);
2021 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2022 ensure_sufficient_stack(|| {
2023 project::normalize_with_depth(
2025 obligation.param_env,
2026 obligation.cause.clone(),
2027 obligation.recursion_depth + 1,
2032 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2034 let cause = ObligationCause::new(
2035 obligation.cause.span,
2036 obligation.cause.body_id,
2037 ObligationCauseCode::MatchImpl(Lrc::new(obligation.cause.code.clone()), impl_def_id),
2040 let InferOk { obligations, .. } = self
2042 .at(&cause, obligation.param_env)
2043 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2044 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2045 nested_obligations.extend(obligations);
2048 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2050 debug!("match_impl: reservation impls only apply in intercrate mode");
2054 debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2055 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2058 fn fast_reject_trait_refs(
2060 obligation: &TraitObligation<'_>,
2061 impl_trait_ref: &ty::TraitRef<'_>,
2063 // We can avoid creating type variables and doing the full
2064 // substitution if we find that any of the input types, when
2065 // simplified, do not match.
2067 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
2068 |(obligation_arg, impl_arg)| {
2069 match (obligation_arg.unpack(), impl_arg.unpack()) {
2070 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
2071 let simplified_obligation_ty =
2072 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2073 let simplified_impl_ty =
2074 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2076 simplified_obligation_ty.is_some()
2077 && simplified_impl_ty.is_some()
2078 && simplified_obligation_ty != simplified_impl_ty
2080 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
2081 // Lifetimes can never cause a rejection.
2084 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
2085 // Conservatively ignore consts (i.e. assume they might
2086 // unify later) until we have `fast_reject` support for
2087 // them (if we'll ever need it, even).
2090 _ => unreachable!(),
2096 /// Normalize `where_clause_trait_ref` and try to match it against
2097 /// `obligation`. If successful, return any predicates that
2098 /// result from the normalization.
2099 fn match_where_clause_trait_ref(
2101 obligation: &TraitObligation<'tcx>,
2102 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2103 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2104 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2107 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2108 /// obligation is satisfied.
2109 fn match_poly_trait_ref(
2111 obligation: &TraitObligation<'tcx>,
2112 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2113 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2114 debug!(?obligation, ?poly_trait_ref, "match_poly_trait_ref");
2117 .at(&obligation.cause, obligation.param_env)
2118 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2119 .map(|InferOk { obligations, .. }| obligations)
2123 ///////////////////////////////////////////////////////////////////////////
2126 fn match_fresh_trait_refs(
2128 previous: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2129 current: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2130 param_env: ty::ParamEnv<'tcx>,
2132 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2133 matcher.relate(previous, current).is_ok()
2138 previous_stack: TraitObligationStackList<'o, 'tcx>,
2139 obligation: &'o TraitObligation<'tcx>,
2140 ) -> TraitObligationStack<'o, 'tcx> {
2141 let fresh_trait_ref = obligation
2143 .to_poly_trait_ref()
2144 .fold_with(&mut self.freshener)
2145 .with_constness(obligation.predicate.skip_binder().constness);
2147 let dfn = previous_stack.cache.next_dfn();
2148 let depth = previous_stack.depth() + 1;
2149 TraitObligationStack {
2152 reached_depth: Cell::new(depth),
2153 previous: previous_stack,
2159 fn closure_trait_ref_unnormalized(
2161 obligation: &TraitObligation<'tcx>,
2162 substs: SubstsRef<'tcx>,
2163 ) -> ty::PolyTraitRef<'tcx> {
2164 debug!(?obligation, ?substs, "closure_trait_ref_unnormalized");
2165 let closure_sig = substs.as_closure().sig();
2167 debug!(?closure_sig);
2169 // (1) Feels icky to skip the binder here, but OTOH we know
2170 // that the self-type is an unboxed closure type and hence is
2171 // in fact unparameterized (or at least does not reference any
2172 // regions bound in the obligation). Still probably some
2173 // refactoring could make this nicer.
2174 closure_trait_ref_and_return_type(
2176 obligation.predicate.def_id(),
2177 obligation.predicate.skip_binder().self_ty(), // (1)
2179 util::TupleArgumentsFlag::No,
2181 .map_bound(|(trait_ref, _)| trait_ref)
2184 fn generator_trait_ref_unnormalized(
2186 obligation: &TraitObligation<'tcx>,
2187 substs: SubstsRef<'tcx>,
2188 ) -> ty::PolyTraitRef<'tcx> {
2189 let gen_sig = substs.as_generator().poly_sig();
2191 // (1) Feels icky to skip the binder here, but OTOH we know
2192 // that the self-type is an generator type and hence is
2193 // in fact unparameterized (or at least does not reference any
2194 // regions bound in the obligation). Still probably some
2195 // refactoring could make this nicer.
2197 super::util::generator_trait_ref_and_outputs(
2199 obligation.predicate.def_id(),
2200 obligation.predicate.skip_binder().self_ty(), // (1)
2203 .map_bound(|(trait_ref, ..)| trait_ref)
2206 /// Returns the obligations that are implied by instantiating an
2207 /// impl or trait. The obligations are substituted and fully
2208 /// normalized. This is used when confirming an impl or default
2210 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2211 fn impl_or_trait_obligations(
2213 cause: ObligationCause<'tcx>,
2214 recursion_depth: usize,
2215 param_env: ty::ParamEnv<'tcx>,
2216 def_id: DefId, // of impl or trait
2217 substs: SubstsRef<'tcx>, // for impl or trait
2218 ) -> Vec<PredicateObligation<'tcx>> {
2219 let tcx = self.tcx();
2221 // To allow for one-pass evaluation of the nested obligation,
2222 // each predicate must be preceded by the obligations required
2224 // for example, if we have:
2225 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2226 // the impl will have the following predicates:
2227 // <V as Iterator>::Item = U,
2228 // U: Iterator, U: Sized,
2229 // V: Iterator, V: Sized,
2230 // <U as Iterator>::Item: Copy
2231 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2232 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2233 // `$1: Copy`, so we must ensure the obligations are emitted in
2235 let predicates = tcx.predicates_of(def_id);
2236 debug!(?predicates);
2237 assert_eq!(predicates.parent, None);
2238 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2239 for (predicate, _) in predicates.predicates {
2241 let predicate = normalize_with_depth_to(
2246 predicate.subst(tcx, substs),
2249 obligations.push(Obligation {
2250 cause: cause.clone(),
2257 // We are performing deduplication here to avoid exponential blowups
2258 // (#38528) from happening, but the real cause of the duplication is
2259 // unknown. What we know is that the deduplication avoids exponential
2260 // amount of predicates being propagated when processing deeply nested
2263 // This code is hot enough that it's worth avoiding the allocation
2264 // required for the FxHashSet when possible. Special-casing lengths 0,
2265 // 1 and 2 covers roughly 75-80% of the cases.
2266 if obligations.len() <= 1 {
2267 // No possibility of duplicates.
2268 } else if obligations.len() == 2 {
2269 // Only two elements. Drop the second if they are equal.
2270 if obligations[0] == obligations[1] {
2271 obligations.truncate(1);
2274 // Three or more elements. Use a general deduplication process.
2275 let mut seen = FxHashSet::default();
2276 obligations.retain(|i| seen.insert(i.clone()));
2283 trait TraitObligationExt<'tcx> {
2286 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2287 ) -> ObligationCause<'tcx>;
2290 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2293 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2294 ) -> ObligationCause<'tcx> {
2296 * Creates a cause for obligations that are derived from
2297 * `obligation` by a recursive search (e.g., for a builtin
2298 * bound, or eventually a `auto trait Foo`). If `obligation`
2299 * is itself a derived obligation, this is just a clone, but
2300 * otherwise we create a "derived obligation" cause so as to
2301 * keep track of the original root obligation for error
2305 let obligation = self;
2307 // NOTE(flaper87): As of now, it keeps track of the whole error
2308 // chain. Ideally, we should have a way to configure this either
2309 // by using -Z verbose or just a CLI argument.
2310 let derived_cause = DerivedObligationCause {
2311 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2312 parent_code: Lrc::new(obligation.cause.code.clone()),
2314 let derived_code = variant(derived_cause);
2315 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2319 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2320 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2321 TraitObligationStackList::with(self)
2324 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2328 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2332 /// Indicates that attempting to evaluate this stack entry
2333 /// required accessing something from the stack at depth `reached_depth`.
2334 fn update_reached_depth(&self, reached_depth: usize) {
2336 self.depth >= reached_depth,
2337 "invoked `update_reached_depth` with something under this stack: \
2338 self.depth={} reached_depth={}",
2342 debug!(reached_depth, "update_reached_depth");
2344 while reached_depth < p.depth {
2345 debug!(?p.fresh_trait_ref, "update_reached_depth: marking as cycle participant");
2346 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2347 p = p.previous.head.unwrap();
2352 /// The "provisional evaluation cache" is used to store intermediate cache results
2353 /// when solving auto traits. Auto traits are unusual in that they can support
2354 /// cycles. So, for example, a "proof tree" like this would be ok:
2356 /// - `Foo<T>: Send` :-
2357 /// - `Bar<T>: Send` :-
2358 /// - `Foo<T>: Send` -- cycle, but ok
2359 /// - `Baz<T>: Send`
2361 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2362 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2363 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2364 /// they are coinductive) it is considered ok.
2366 /// However, there is a complication: at the point where we have
2367 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2368 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2369 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2370 /// find out this assumption is wrong? Specifically, we could
2371 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2372 /// `Bar<T>: Send` didn't turn out to be true.
2374 /// In Issue #60010, we found a bug in rustc where it would cache
2375 /// these intermediate results. This was fixed in #60444 by disabling
2376 /// *all* caching for things involved in a cycle -- in our example,
2377 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2378 /// to large slowdowns.
2380 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2381 /// first requires proving `Bar<T>: Send` (which is true:
2383 /// - `Foo<T>: Send` :-
2384 /// - `Bar<T>: Send` :-
2385 /// - `Foo<T>: Send` -- cycle, but ok
2386 /// - `Baz<T>: Send`
2387 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2388 /// - `*const T: Send` -- but what if we later encounter an error?
2390 /// The *provisional evaluation cache* resolves this issue. It stores
2391 /// cache results that we've proven but which were involved in a cycle
2392 /// in some way. We track the minimal stack depth (i.e., the
2393 /// farthest from the top of the stack) that we are dependent on.
2394 /// The idea is that the cache results within are all valid -- so long as
2395 /// none of the nodes in between the current node and the node at that minimum
2396 /// depth result in an error (in which case the cached results are just thrown away).
2398 /// During evaluation, we consult this provisional cache and rely on
2399 /// it. Accessing a cached value is considered equivalent to accessing
2400 /// a result at `reached_depth`, so it marks the *current* solution as
2401 /// provisional as well. If an error is encountered, we toss out any
2402 /// provisional results added from the subtree that encountered the
2403 /// error. When we pop the node at `reached_depth` from the stack, we
2404 /// can commit all the things that remain in the provisional cache.
2405 struct ProvisionalEvaluationCache<'tcx> {
2406 /// next "depth first number" to issue -- just a counter
2409 /// Map from cache key to the provisionally evaluated thing.
2410 /// The cache entries contain the result but also the DFN in which they
2411 /// were added. The DFN is used to clear out values on failure.
2413 /// Imagine we have a stack like:
2415 /// - `A B C` and we add a cache for the result of C (DFN 2)
2416 /// - Then we have a stack `A B D` where `D` has DFN 3
2417 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2418 /// - `E` generates various cache entries which have cyclic dependices on `B`
2419 /// - `A B D E F` and so forth
2420 /// - the DFN of `F` for example would be 5
2421 /// - then we determine that `E` is in error -- we will then clear
2422 /// all cache values whose DFN is >= 4 -- in this case, that
2423 /// means the cached value for `F`.
2424 map: RefCell<FxHashMap<ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, ProvisionalEvaluation>>,
2427 /// A cache value for the provisional cache: contains the depth-first
2428 /// number (DFN) and result.
2429 #[derive(Copy, Clone, Debug)]
2430 struct ProvisionalEvaluation {
2432 reached_depth: usize,
2433 result: EvaluationResult,
2436 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2437 fn default() -> Self {
2438 Self { dfn: Cell::new(0), map: Default::default() }
2442 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2443 /// Get the next DFN in sequence (basically a counter).
2444 fn next_dfn(&self) -> usize {
2445 let result = self.dfn.get();
2446 self.dfn.set(result + 1);
2450 /// Check the provisional cache for any result for
2451 /// `fresh_trait_ref`. If there is a hit, then you must consider
2452 /// it an access to the stack slots at depth
2453 /// `reached_depth` (from the returned value).
2456 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2457 ) -> Option<ProvisionalEvaluation> {
2460 "get_provisional = {:#?}",
2461 self.map.borrow().get(&fresh_trait_ref),
2463 Some(*self.map.borrow().get(&fresh_trait_ref)?)
2466 /// Insert a provisional result into the cache. The result came
2467 /// from the node with the given DFN. It accessed a minimum depth
2468 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
2469 /// and resulted in `result`.
2470 fn insert_provisional(
2473 reached_depth: usize,
2474 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2475 result: EvaluationResult,
2477 debug!(?from_dfn, ?fresh_trait_ref, ?result, "insert_provisional");
2479 let mut map = self.map.borrow_mut();
2481 // Subtle: when we complete working on the DFN `from_dfn`, anything
2482 // that remains in the provisional cache must be dependent on some older
2483 // stack entry than `from_dfn`. We have to update their depth with our transitive
2484 // depth in that case or else it would be referring to some popped note.
2487 // A (reached depth 0)
2489 // B // depth 1 -- reached depth = 0
2490 // C // depth 2 -- reached depth = 1 (should be 0)
2493 // D (reached depth 1)
2494 // C (cache -- reached depth = 2)
2495 for (_k, v) in &mut *map {
2496 if v.from_dfn >= from_dfn {
2497 v.reached_depth = reached_depth.min(v.reached_depth);
2501 map.insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, reached_depth, result });
2504 /// Invoked when the node with dfn `dfn` does not get a successful
2505 /// result. This will clear out any provisional cache entries
2506 /// that were added since `dfn` was created. This is because the
2507 /// provisional entries are things which must assume that the
2508 /// things on the stack at the time of their creation succeeded --
2509 /// since the failing node is presently at the top of the stack,
2510 /// these provisional entries must either depend on it or some
2512 fn on_failure(&self, dfn: usize) {
2513 debug!(?dfn, "on_failure");
2514 self.map.borrow_mut().retain(|key, eval| {
2515 if !eval.from_dfn >= dfn {
2516 debug!("on_failure: removing {:?}", key);
2524 /// Invoked when the node at depth `depth` completed without
2525 /// depending on anything higher in the stack (if that completion
2526 /// was a failure, then `on_failure` should have been invoked
2527 /// already). The callback `op` will be invoked for each
2528 /// provisional entry that we can now confirm.
2530 /// Note that we may still have provisional cache items remaining
2531 /// in the cache when this is done. For example, if there is a
2534 /// * A depends on...
2535 /// * B depends on A
2536 /// * C depends on...
2537 /// * D depends on C
2540 /// Then as we complete the C node we will have a provisional cache
2541 /// with results for A, B, C, and D. This method would clear out
2542 /// the C and D results, but leave A and B provisional.
2544 /// This is determined based on the DFN: we remove any provisional
2545 /// results created since `dfn` started (e.g., in our example, dfn
2546 /// would be 2, representing the C node, and hence we would
2547 /// remove the result for D, which has DFN 3, but not the results for
2548 /// A and B, which have DFNs 0 and 1 respectively).
2552 mut op: impl FnMut(ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, EvaluationResult),
2554 debug!(?dfn, "on_completion");
2556 for (fresh_trait_ref, eval) in
2557 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2559 debug!(?fresh_trait_ref, ?eval, "on_completion");
2561 op(fresh_trait_ref, eval.result);
2566 #[derive(Copy, Clone)]
2567 struct TraitObligationStackList<'o, 'tcx> {
2568 cache: &'o ProvisionalEvaluationCache<'tcx>,
2569 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2572 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2573 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2574 TraitObligationStackList { cache, head: None }
2577 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2578 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2581 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2585 fn depth(&self) -> usize {
2586 if let Some(head) = self.head { head.depth } else { 0 }
2590 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2591 type Item = &'o TraitObligationStack<'o, 'tcx>;
2593 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2600 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2602 write!(f, "TraitObligationStack({:?})", self.obligation)