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 let tcx = self.tcx();
978 if self.can_use_global_caches(param_env) {
979 if let Some(res) = tcx.evaluation_cache.get(¶m_env.and(trait_ref), tcx) {
983 self.infcx.evaluation_cache.get(¶m_env.and(trait_ref), tcx)
986 fn insert_evaluation_cache(
988 param_env: ty::ParamEnv<'tcx>,
989 trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
990 dep_node: DepNodeIndex,
991 result: EvaluationResult,
993 // Avoid caching results that depend on more than just the trait-ref
994 // - the stack can create recursion.
995 if result.is_stack_dependent() {
999 if self.can_use_global_caches(param_env) {
1000 if !trait_ref.needs_infer() {
1001 debug!(?trait_ref, ?result, "insert_evaluation_cache global");
1002 // This may overwrite the cache with the same value
1003 // FIXME: Due to #50507 this overwrites the different values
1004 // This should be changed to use HashMapExt::insert_same
1005 // when that is fixed
1006 self.tcx().evaluation_cache.insert(param_env.and(trait_ref), dep_node, result);
1011 debug!(?trait_ref, ?result, "insert_evaluation_cache");
1012 self.infcx.evaluation_cache.insert(param_env.and(trait_ref), dep_node, result);
1015 /// For various reasons, it's possible for a subobligation
1016 /// to have a *lower* recursion_depth than the obligation used to create it.
1017 /// Projection sub-obligations may be returned from the projection cache,
1018 /// which results in obligations with an 'old' `recursion_depth`.
1019 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1020 /// subobligations without taking in a 'parent' depth, causing the
1021 /// generated subobligations to have a `recursion_depth` of `0`.
1023 /// To ensure that obligation_depth never decreases, we force all subobligations
1024 /// to have at least the depth of the original obligation.
1025 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1030 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1033 fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
1036 error_obligation: &Obligation<'tcx, T>,
1037 ) -> Result<(), OverflowError> {
1038 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1039 match self.query_mode {
1040 TraitQueryMode::Standard => {
1041 self.infcx.report_overflow_error(error_obligation, true);
1043 TraitQueryMode::Canonical => {
1044 return Err(OverflowError);
1051 /// Checks that the recursion limit has not been exceeded.
1053 /// The weird return type of this function allows it to be used with the `try` (`?`)
1054 /// operator within certain functions.
1056 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1058 obligation: &Obligation<'tcx, T>,
1059 error_obligation: &Obligation<'tcx, V>,
1060 ) -> Result<(), OverflowError> {
1061 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1064 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1066 OP: FnOnce(&mut Self) -> R,
1068 let (result, dep_node) =
1069 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1070 self.tcx().dep_graph.read_index(dep_node);
1074 #[instrument(level = "debug", skip(self))]
1077 candidate: SelectionCandidate<'tcx>,
1078 obligation: &TraitObligation<'tcx>,
1079 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1080 let tcx = self.tcx();
1081 // Respect const trait obligations
1082 if self.is_trait_predicate_const(obligation.predicate.skip_binder()) {
1085 ImplCandidate(def_id) if tcx.impl_constness(def_id) == hir::Constness::Const => {}
1087 ParamCandidate(ty::ConstnessAnd {
1088 constness: ty::BoundConstness::ConstIfConst,
1092 AutoImplCandidate(..) => {}
1093 // generator, this will raise error in other places
1094 // or ignore error with const_async_blocks feature
1095 GeneratorCandidate => {}
1096 ConstDropCandidate => {}
1098 // reject all other types of candidates
1099 return Err(Unimplemented);
1103 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
1104 if let ImplCandidate(def_id) = candidate {
1105 match tcx.impl_polarity(def_id) {
1106 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
1107 return Err(Unimplemented);
1109 ty::ImplPolarity::Reservation => {
1110 if let Some(intercrate_ambiguity_clauses) =
1111 &mut self.intercrate_ambiguity_causes
1113 let attrs = tcx.get_attrs(def_id);
1114 let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
1115 let value = attr.and_then(|a| a.value_str());
1116 if let Some(value) = value {
1119 reservation impl ambiguity on {:?}",
1122 intercrate_ambiguity_clauses.push(
1123 IntercrateAmbiguityCause::ReservationImpl {
1124 message: value.to_string(),
1137 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1138 debug!("is_knowable(intercrate={:?})", self.intercrate);
1140 if !self.intercrate {
1144 let obligation = &stack.obligation;
1145 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1147 // Okay to skip binder because of the nature of the
1148 // trait-ref-is-knowable check, which does not care about
1150 let trait_ref = predicate.skip_binder().trait_ref;
1152 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1155 /// Returns `true` if the global caches can 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 pred = &cache_fresh_trait_pred.skip_binder();
1186 let trait_ref = pred.trait_ref;
1187 if self.can_use_global_caches(param_env) {
1188 if let Some(res) = tcx
1190 .get(¶m_env.and(trait_ref).with_constness(pred.constness), tcx)
1197 .get(¶m_env.and(trait_ref).with_constness(pred.constness), 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 pred = cache_fresh_trait_pred.skip_binder();
1235 let trait_ref = pred.trait_ref;
1237 if !self.can_cache_candidate(&candidate) {
1238 debug!(?trait_ref, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1242 if self.can_use_global_caches(param_env) {
1243 if let Err(Overflow) = candidate {
1244 // Don't cache overflow globally; we only produce this in certain modes.
1245 } else if !trait_ref.needs_infer() {
1246 if !candidate.needs_infer() {
1247 debug!(?trait_ref, ?candidate, "insert_candidate_cache global");
1248 // This may overwrite the cache with the same value.
1249 tcx.selection_cache.insert(
1250 param_env.and(trait_ref).with_constness(pred.constness),
1259 debug!(?trait_ref, ?candidate, "insert_candidate_cache local");
1260 self.infcx.selection_cache.insert(
1261 param_env.and(trait_ref).with_constness(pred.constness),
1267 /// Matches a predicate against the bounds of its self type.
1269 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1270 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1271 /// `Baz` bound. We return indexes into the list returned by
1272 /// `tcx.item_bounds` for any applicable bounds.
1273 fn match_projection_obligation_against_definition_bounds(
1275 obligation: &TraitObligation<'tcx>,
1276 ) -> smallvec::SmallVec<[usize; 2]> {
1277 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1278 let placeholder_trait_predicate =
1279 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1281 ?placeholder_trait_predicate,
1282 "match_projection_obligation_against_definition_bounds"
1285 let tcx = self.infcx.tcx;
1286 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1287 ty::Projection(ref data) => (data.item_def_id, data.substs),
1288 ty::Opaque(def_id, substs) => (def_id, substs),
1291 obligation.cause.span,
1292 "match_projection_obligation_against_definition_bounds() called \
1293 but self-ty is not a projection: {:?}",
1294 placeholder_trait_predicate.trait_ref.self_ty()
1298 let bounds = tcx.item_bounds(def_id).subst(tcx, substs);
1300 // The bounds returned by `item_bounds` may contain duplicates after
1301 // normalization, so try to deduplicate when possible to avoid
1302 // unnecessary ambiguity.
1303 let mut distinct_normalized_bounds = FxHashSet::default();
1305 let matching_bounds = bounds
1308 .filter_map(|(idx, bound)| {
1309 let bound_predicate = bound.kind();
1310 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1311 let bound = bound_predicate.rebind(pred.trait_ref);
1312 if self.infcx.probe(|_| {
1313 match self.match_normalize_trait_ref(
1316 placeholder_trait_predicate.trait_ref,
1319 Ok(Some(normalized_trait))
1320 if distinct_normalized_bounds.insert(normalized_trait) =>
1334 debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds");
1338 /// Equates the trait in `obligation` with trait bound. If the two traits
1339 /// can be equated and the normalized trait bound doesn't contain inference
1340 /// variables or placeholders, the normalized bound is returned.
1341 fn match_normalize_trait_ref(
1343 obligation: &TraitObligation<'tcx>,
1344 trait_bound: ty::PolyTraitRef<'tcx>,
1345 placeholder_trait_ref: ty::TraitRef<'tcx>,
1346 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1347 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1348 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1349 // Avoid unnecessary normalization
1353 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1354 project::normalize_with_depth(
1356 obligation.param_env,
1357 obligation.cause.clone(),
1358 obligation.recursion_depth + 1,
1363 .at(&obligation.cause, obligation.param_env)
1364 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1365 .map(|InferOk { obligations: _, value: () }| {
1366 // This method is called within a probe, so we can't have
1367 // inference variables and placeholders escape.
1368 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1377 fn evaluate_where_clause<'o>(
1379 stack: &TraitObligationStack<'o, 'tcx>,
1380 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1381 ) -> Result<EvaluationResult, OverflowError> {
1382 self.evaluation_probe(|this| {
1383 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1384 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1385 Err(()) => Ok(EvaluatedToErr),
1390 pub(super) fn match_projection_projections(
1392 obligation: &ProjectionTyObligation<'tcx>,
1393 env_predicate: PolyProjectionPredicate<'tcx>,
1394 potentially_unnormalized_candidates: bool,
1396 let mut nested_obligations = Vec::new();
1397 let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars(
1398 obligation.cause.span,
1399 LateBoundRegionConversionTime::HigherRankedType,
1402 let infer_projection = if potentially_unnormalized_candidates {
1403 ensure_sufficient_stack(|| {
1404 project::normalize_with_depth_to(
1406 obligation.param_env,
1407 obligation.cause.clone(),
1408 obligation.recursion_depth + 1,
1409 infer_predicate.projection_ty,
1410 &mut nested_obligations,
1414 infer_predicate.projection_ty
1418 .at(&obligation.cause, obligation.param_env)
1419 .sup(obligation.predicate, infer_projection)
1420 .map_or(false, |InferOk { obligations, value: () }| {
1421 self.evaluate_predicates_recursively(
1422 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1423 nested_obligations.into_iter().chain(obligations),
1425 .map_or(false, |res| res.may_apply())
1429 ///////////////////////////////////////////////////////////////////////////
1432 // Winnowing is the process of attempting to resolve ambiguity by
1433 // probing further. During the winnowing process, we unify all
1434 // type variables and then we also attempt to evaluate recursive
1435 // bounds to see if they are satisfied.
1437 /// Returns `true` if `victim` should be dropped in favor of
1438 /// `other`. Generally speaking we will drop duplicate
1439 /// candidates and prefer where-clause candidates.
1441 /// See the comment for "SelectionCandidate" for more details.
1442 fn candidate_should_be_dropped_in_favor_of(
1444 victim: &EvaluatedCandidate<'tcx>,
1445 other: &EvaluatedCandidate<'tcx>,
1448 if victim.candidate == other.candidate {
1452 // Check if a bound would previously have been removed when normalizing
1453 // the param_env so that it can be given the lowest priority. See
1454 // #50825 for the motivation for this.
1456 |cand: &ty::PolyTraitRef<'_>| cand.is_known_global() && !cand.has_late_bound_regions();
1458 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1459 // and `DiscriminantKindCandidate` to anything else.
1461 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1462 // lifetime of a variable.
1463 match (&other.candidate, &victim.candidate) {
1464 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1466 "default implementations shouldn't be recorded \
1467 when there are other valid candidates"
1473 BuiltinCandidate { has_nested: false }
1474 | DiscriminantKindCandidate
1476 | ConstDropCandidate,
1481 BuiltinCandidate { has_nested: false }
1482 | DiscriminantKindCandidate
1484 | ConstDropCandidate,
1487 (ParamCandidate(other), ParamCandidate(victim)) => {
1488 let same_except_bound_vars = other.value.skip_binder()
1489 == victim.value.skip_binder()
1490 && other.constness == victim.constness
1491 && !other.value.skip_binder().has_escaping_bound_vars();
1492 if same_except_bound_vars {
1493 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1494 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1495 // or the current one if tied (they should both evaluate to the same answer). This is
1496 // probably best characterized as a "hack", since we might prefer to just do our
1497 // best to *not* create essentially duplicate candidates in the first place.
1498 other.value.bound_vars().len() <= victim.value.bound_vars().len()
1499 } else if other.value == victim.value
1500 && victim.constness == ty::BoundConstness::NotConst
1502 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1509 // Global bounds from the where clause should be ignored
1510 // here (see issue #50825). Otherwise, we have a where
1511 // clause so don't go around looking for impls.
1512 // Arbitrarily give param candidates priority
1513 // over projection and object candidates.
1515 ParamCandidate(ref cand),
1518 | GeneratorCandidate
1519 | FnPointerCandidate
1520 | BuiltinObjectCandidate
1521 | BuiltinUnsizeCandidate
1522 | TraitUpcastingUnsizeCandidate(_)
1523 | BuiltinCandidate { .. }
1524 | TraitAliasCandidate(..)
1525 | ObjectCandidate(_)
1526 | ProjectionCandidate(_),
1527 ) => !is_global(&cand.value),
1528 (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1529 // Prefer these to a global where-clause bound
1530 // (see issue #50825).
1531 is_global(&cand.value)
1536 | GeneratorCandidate
1537 | FnPointerCandidate
1538 | BuiltinObjectCandidate
1539 | BuiltinUnsizeCandidate
1540 | TraitUpcastingUnsizeCandidate(_)
1541 | BuiltinCandidate { has_nested: true }
1542 | TraitAliasCandidate(..),
1543 ParamCandidate(ref cand),
1545 // Prefer these to a global where-clause bound
1546 // (see issue #50825).
1547 is_global(&cand.value) && other.evaluation.must_apply_modulo_regions()
1550 (ProjectionCandidate(i), ProjectionCandidate(j))
1551 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1552 // Arbitrarily pick the lower numbered candidate for backwards
1553 // compatibility reasons. Don't let this affect inference.
1554 i < j && !needs_infer
1556 (ObjectCandidate(_), ProjectionCandidate(_))
1557 | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1558 bug!("Have both object and projection candidate")
1561 // Arbitrarily give projection and object candidates priority.
1563 ObjectCandidate(_) | ProjectionCandidate(_),
1566 | GeneratorCandidate
1567 | FnPointerCandidate
1568 | BuiltinObjectCandidate
1569 | BuiltinUnsizeCandidate
1570 | TraitUpcastingUnsizeCandidate(_)
1571 | BuiltinCandidate { .. }
1572 | TraitAliasCandidate(..),
1578 | GeneratorCandidate
1579 | FnPointerCandidate
1580 | BuiltinObjectCandidate
1581 | BuiltinUnsizeCandidate
1582 | TraitUpcastingUnsizeCandidate(_)
1583 | BuiltinCandidate { .. }
1584 | TraitAliasCandidate(..),
1585 ObjectCandidate(_) | ProjectionCandidate(_),
1588 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1589 // See if we can toss out `victim` based on specialization.
1590 // This requires us to know *for sure* that the `other` impl applies
1591 // i.e., `EvaluatedToOk`.
1593 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1594 // to me but is required for `std` to compile, so I didn't change it
1596 let tcx = self.tcx();
1597 if other.evaluation.must_apply_modulo_regions() {
1598 if tcx.specializes((other_def, victim_def)) {
1603 if other.evaluation.must_apply_considering_regions() {
1604 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1605 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1606 // Subtle: If the predicate we are evaluating has inference
1607 // variables, do *not* allow discarding candidates due to
1608 // marker trait impls.
1610 // Without this restriction, we could end up accidentally
1611 // constrainting inference variables based on an arbitrarily
1612 // chosen trait impl.
1614 // Imagine we have the following code:
1617 // #[marker] trait MyTrait {}
1618 // impl MyTrait for u8 {}
1619 // impl MyTrait for bool {}
1622 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1624 // During selection, we will end up with one candidate for each
1625 // impl of `MyTrait`. If we were to discard one impl in favor
1626 // of the other, we would be left with one candidate, causing
1627 // us to "successfully" select the predicate, unifying
1628 // _#0t with (for example) `u8`.
1630 // However, we have no reason to believe that this unification
1631 // is correct - we've essentially just picked an arbitrary
1632 // *possibility* for _#0t, and required that this be the *only*
1635 // Eventually, we will either:
1636 // 1) Unify all inference variables in the predicate through
1637 // some other means (e.g. type-checking of a function). We will
1638 // then be in a position to drop marker trait candidates
1639 // without constraining inference variables (since there are
1640 // none left to constrin)
1641 // 2) Be left with some unconstrained inference variables. We
1642 // will then correctly report an inference error, since the
1643 // existence of multiple marker trait impls tells us nothing
1644 // about which one should actually apply.
1655 // Everything else is ambiguous
1659 | GeneratorCandidate
1660 | FnPointerCandidate
1661 | BuiltinObjectCandidate
1662 | BuiltinUnsizeCandidate
1663 | TraitUpcastingUnsizeCandidate(_)
1664 | BuiltinCandidate { has_nested: true }
1665 | TraitAliasCandidate(..),
1668 | GeneratorCandidate
1669 | FnPointerCandidate
1670 | BuiltinObjectCandidate
1671 | BuiltinUnsizeCandidate
1672 | TraitUpcastingUnsizeCandidate(_)
1673 | BuiltinCandidate { has_nested: true }
1674 | TraitAliasCandidate(..),
1679 fn sized_conditions(
1681 obligation: &TraitObligation<'tcx>,
1682 ) -> BuiltinImplConditions<'tcx> {
1683 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1685 // NOTE: binder moved to (*)
1686 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1688 match self_ty.kind() {
1689 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1700 | ty::GeneratorWitness(..)
1705 // safe for everything
1706 Where(ty::Binder::dummy(Vec::new()))
1709 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1711 ty::Tuple(tys) => Where(
1714 .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()),
1717 ty::Adt(def, substs) => {
1718 let sized_crit = def.sized_constraint(self.tcx());
1719 // (*) binder moved here
1721 obligation.predicate.rebind({
1722 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1727 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1728 ty::Infer(ty::TyVar(_)) => Ambiguous,
1732 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1733 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1738 fn copy_clone_conditions(
1740 obligation: &TraitObligation<'tcx>,
1741 ) -> BuiltinImplConditions<'tcx> {
1742 // NOTE: binder moved to (*)
1743 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1745 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1747 match *self_ty.kind() {
1748 ty::Infer(ty::IntVar(_))
1749 | ty::Infer(ty::FloatVar(_))
1752 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1761 | ty::Ref(_, _, hir::Mutability::Not) => {
1762 // Implementations provided in libcore
1770 | ty::GeneratorWitness(..)
1772 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1774 ty::Array(element_ty, _) => {
1775 // (*) binder moved here
1776 Where(obligation.predicate.rebind(vec![element_ty]))
1780 // (*) binder moved here
1781 Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect()))
1784 ty::Closure(_, substs) => {
1785 // (*) binder moved here
1786 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1787 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1788 // Not yet resolved.
1791 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1795 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1796 // Fallback to whatever user-defined impls exist in this case.
1800 ty::Infer(ty::TyVar(_)) => {
1801 // Unbound type variable. Might or might not have
1802 // applicable impls and so forth, depending on what
1803 // those type variables wind up being bound to.
1809 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1810 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1815 /// For default impls, we need to break apart a type into its
1816 /// "constituent types" -- meaning, the types that it contains.
1818 /// Here are some (simple) examples:
1821 /// (i32, u32) -> [i32, u32]
1822 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1823 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1824 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1826 fn constituent_types_for_ty(
1828 t: ty::Binder<'tcx, Ty<'tcx>>,
1829 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1830 match *t.skip_binder().kind() {
1839 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1841 | ty::Char => ty::Binder::dummy(Vec::new()),
1847 | ty::Projection(..)
1849 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1850 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1853 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1854 t.rebind(vec![element_ty])
1857 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
1859 ty::Tuple(ref tys) => {
1860 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1861 t.rebind(tys.iter().map(|k| k.expect_ty()).collect())
1864 ty::Closure(_, ref substs) => {
1865 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1869 ty::Generator(_, ref substs, _) => {
1870 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
1871 let witness = substs.as_generator().witness();
1872 t.rebind(vec![ty].into_iter().chain(iter::once(witness)).collect())
1875 ty::GeneratorWitness(types) => {
1876 debug_assert!(!types.has_escaping_bound_vars());
1877 types.map_bound(|types| types.to_vec())
1880 // For `PhantomData<T>`, we pass `T`.
1881 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
1883 ty::Adt(def, substs) => {
1884 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
1887 ty::Opaque(def_id, substs) => {
1888 // We can resolve the `impl Trait` to its concrete type,
1889 // which enforces a DAG between the functions requiring
1890 // the auto trait bounds in question.
1891 t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
1896 fn collect_predicates_for_types(
1898 param_env: ty::ParamEnv<'tcx>,
1899 cause: ObligationCause<'tcx>,
1900 recursion_depth: usize,
1901 trait_def_id: DefId,
1902 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
1903 ) -> Vec<PredicateObligation<'tcx>> {
1904 // Because the types were potentially derived from
1905 // higher-ranked obligations they may reference late-bound
1906 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
1907 // yield a type like `for<'a> &'a i32`. In general, we
1908 // maintain the invariant that we never manipulate bound
1909 // regions, so we have to process these bound regions somehow.
1911 // The strategy is to:
1913 // 1. Instantiate those regions to placeholder regions (e.g.,
1914 // `for<'a> &'a i32` becomes `&0 i32`.
1915 // 2. Produce something like `&'0 i32 : Copy`
1916 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
1920 .skip_binder() // binder moved -\
1923 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(ty); // <----/
1925 self.infcx.commit_unconditionally(|_| {
1926 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
1927 let Normalized { value: normalized_ty, mut obligations } =
1928 ensure_sufficient_stack(|| {
1929 project::normalize_with_depth(
1937 let placeholder_obligation = predicate_for_trait_def(
1946 obligations.push(placeholder_obligation);
1953 ///////////////////////////////////////////////////////////////////////////
1956 // Matching is a common path used for both evaluation and
1957 // confirmation. It basically unifies types that appear in impls
1958 // and traits. This does affect the surrounding environment;
1959 // therefore, when used during evaluation, match routines must be
1960 // run inside of a `probe()` so that their side-effects are
1966 obligation: &TraitObligation<'tcx>,
1967 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
1968 match self.match_impl(impl_def_id, obligation) {
1969 Ok(substs) => substs,
1972 "Impl {:?} was matchable against {:?} but now is not",
1980 #[tracing::instrument(level = "debug", skip(self))]
1984 obligation: &TraitObligation<'tcx>,
1985 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
1986 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
1988 // Before we create the substitutions and everything, first
1989 // consider a "quick reject". This avoids creating more types
1990 // and so forth that we need to.
1991 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
1995 let placeholder_obligation =
1996 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
1997 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
1999 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2001 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2003 debug!(?impl_trait_ref);
2005 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2006 ensure_sufficient_stack(|| {
2007 project::normalize_with_depth(
2009 obligation.param_env,
2010 obligation.cause.clone(),
2011 obligation.recursion_depth + 1,
2016 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2018 let cause = ObligationCause::new(
2019 obligation.cause.span,
2020 obligation.cause.body_id,
2021 ObligationCauseCode::MatchImpl(Lrc::new(obligation.cause.code.clone()), impl_def_id),
2024 let InferOk { obligations, .. } = self
2026 .at(&cause, obligation.param_env)
2027 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2028 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2029 nested_obligations.extend(obligations);
2032 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2034 debug!("match_impl: reservation impls only apply in intercrate mode");
2038 debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2039 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2042 fn fast_reject_trait_refs(
2044 obligation: &TraitObligation<'_>,
2045 impl_trait_ref: &ty::TraitRef<'_>,
2047 // We can avoid creating type variables and doing the full
2048 // substitution if we find that any of the input types, when
2049 // simplified, do not match.
2051 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
2052 |(obligation_arg, impl_arg)| {
2053 match (obligation_arg.unpack(), impl_arg.unpack()) {
2054 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
2055 let simplified_obligation_ty =
2056 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2057 let simplified_impl_ty =
2058 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2060 simplified_obligation_ty.is_some()
2061 && simplified_impl_ty.is_some()
2062 && simplified_obligation_ty != simplified_impl_ty
2064 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
2065 // Lifetimes can never cause a rejection.
2068 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
2069 // Conservatively ignore consts (i.e. assume they might
2070 // unify later) until we have `fast_reject` support for
2071 // them (if we'll ever need it, even).
2074 _ => unreachable!(),
2080 /// Normalize `where_clause_trait_ref` and try to match it against
2081 /// `obligation`. If successful, return any predicates that
2082 /// result from the normalization.
2083 fn match_where_clause_trait_ref(
2085 obligation: &TraitObligation<'tcx>,
2086 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2087 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2088 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2091 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2092 /// obligation is satisfied.
2093 fn match_poly_trait_ref(
2095 obligation: &TraitObligation<'tcx>,
2096 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2097 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2098 debug!(?obligation, ?poly_trait_ref, "match_poly_trait_ref");
2101 .at(&obligation.cause, obligation.param_env)
2102 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2103 .map(|InferOk { obligations, .. }| obligations)
2107 ///////////////////////////////////////////////////////////////////////////
2110 fn match_fresh_trait_refs(
2112 previous: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2113 current: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2114 param_env: ty::ParamEnv<'tcx>,
2116 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2117 matcher.relate(previous, current).is_ok()
2122 previous_stack: TraitObligationStackList<'o, 'tcx>,
2123 obligation: &'o TraitObligation<'tcx>,
2124 ) -> TraitObligationStack<'o, 'tcx> {
2125 let fresh_trait_ref = obligation
2127 .to_poly_trait_ref()
2128 .fold_with(&mut self.freshener)
2129 .with_constness(obligation.predicate.skip_binder().constness);
2131 let dfn = previous_stack.cache.next_dfn();
2132 let depth = previous_stack.depth() + 1;
2133 TraitObligationStack {
2136 reached_depth: Cell::new(depth),
2137 previous: previous_stack,
2143 fn closure_trait_ref_unnormalized(
2145 obligation: &TraitObligation<'tcx>,
2146 substs: SubstsRef<'tcx>,
2147 ) -> ty::PolyTraitRef<'tcx> {
2148 debug!(?obligation, ?substs, "closure_trait_ref_unnormalized");
2149 let closure_sig = substs.as_closure().sig();
2151 debug!(?closure_sig);
2153 // (1) Feels icky to skip the binder here, but OTOH we know
2154 // that the self-type is an unboxed closure type and hence is
2155 // in fact unparameterized (or at least does not reference any
2156 // regions bound in the obligation). Still probably some
2157 // refactoring could make this nicer.
2158 closure_trait_ref_and_return_type(
2160 obligation.predicate.def_id(),
2161 obligation.predicate.skip_binder().self_ty(), // (1)
2163 util::TupleArgumentsFlag::No,
2165 .map_bound(|(trait_ref, _)| trait_ref)
2168 fn generator_trait_ref_unnormalized(
2170 obligation: &TraitObligation<'tcx>,
2171 substs: SubstsRef<'tcx>,
2172 ) -> ty::PolyTraitRef<'tcx> {
2173 let gen_sig = substs.as_generator().poly_sig();
2175 // (1) Feels icky to skip the binder here, but OTOH we know
2176 // that the self-type is an generator type and hence is
2177 // in fact unparameterized (or at least does not reference any
2178 // regions bound in the obligation). Still probably some
2179 // refactoring could make this nicer.
2181 super::util::generator_trait_ref_and_outputs(
2183 obligation.predicate.def_id(),
2184 obligation.predicate.skip_binder().self_ty(), // (1)
2187 .map_bound(|(trait_ref, ..)| trait_ref)
2190 /// Returns the obligations that are implied by instantiating an
2191 /// impl or trait. The obligations are substituted and fully
2192 /// normalized. This is used when confirming an impl or default
2194 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2195 fn impl_or_trait_obligations(
2197 cause: ObligationCause<'tcx>,
2198 recursion_depth: usize,
2199 param_env: ty::ParamEnv<'tcx>,
2200 def_id: DefId, // of impl or trait
2201 substs: SubstsRef<'tcx>, // for impl or trait
2202 ) -> Vec<PredicateObligation<'tcx>> {
2203 let tcx = self.tcx();
2205 // To allow for one-pass evaluation of the nested obligation,
2206 // each predicate must be preceded by the obligations required
2208 // for example, if we have:
2209 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2210 // the impl will have the following predicates:
2211 // <V as Iterator>::Item = U,
2212 // U: Iterator, U: Sized,
2213 // V: Iterator, V: Sized,
2214 // <U as Iterator>::Item: Copy
2215 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2216 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2217 // `$1: Copy`, so we must ensure the obligations are emitted in
2219 let predicates = tcx.predicates_of(def_id);
2220 debug!(?predicates);
2221 assert_eq!(predicates.parent, None);
2222 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2223 for (predicate, _) in predicates.predicates {
2225 let predicate = normalize_with_depth_to(
2230 predicate.subst(tcx, substs),
2233 obligations.push(Obligation {
2234 cause: cause.clone(),
2241 // We are performing deduplication here to avoid exponential blowups
2242 // (#38528) from happening, but the real cause of the duplication is
2243 // unknown. What we know is that the deduplication avoids exponential
2244 // amount of predicates being propagated when processing deeply nested
2247 // This code is hot enough that it's worth avoiding the allocation
2248 // required for the FxHashSet when possible. Special-casing lengths 0,
2249 // 1 and 2 covers roughly 75-80% of the cases.
2250 if obligations.len() <= 1 {
2251 // No possibility of duplicates.
2252 } else if obligations.len() == 2 {
2253 // Only two elements. Drop the second if they are equal.
2254 if obligations[0] == obligations[1] {
2255 obligations.truncate(1);
2258 // Three or more elements. Use a general deduplication process.
2259 let mut seen = FxHashSet::default();
2260 obligations.retain(|i| seen.insert(i.clone()));
2267 trait TraitObligationExt<'tcx> {
2270 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2271 ) -> ObligationCause<'tcx>;
2274 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2277 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2278 ) -> ObligationCause<'tcx> {
2280 * Creates a cause for obligations that are derived from
2281 * `obligation` by a recursive search (e.g., for a builtin
2282 * bound, or eventually a `auto trait Foo`). If `obligation`
2283 * is itself a derived obligation, this is just a clone, but
2284 * otherwise we create a "derived obligation" cause so as to
2285 * keep track of the original root obligation for error
2289 let obligation = self;
2291 // NOTE(flaper87): As of now, it keeps track of the whole error
2292 // chain. Ideally, we should have a way to configure this either
2293 // by using -Z verbose or just a CLI argument.
2294 let derived_cause = DerivedObligationCause {
2295 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2296 parent_code: Lrc::new(obligation.cause.code.clone()),
2298 let derived_code = variant(derived_cause);
2299 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2303 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2304 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2305 TraitObligationStackList::with(self)
2308 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2312 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2316 /// Indicates that attempting to evaluate this stack entry
2317 /// required accessing something from the stack at depth `reached_depth`.
2318 fn update_reached_depth(&self, reached_depth: usize) {
2320 self.depth >= reached_depth,
2321 "invoked `update_reached_depth` with something under this stack: \
2322 self.depth={} reached_depth={}",
2326 debug!(reached_depth, "update_reached_depth");
2328 while reached_depth < p.depth {
2329 debug!(?p.fresh_trait_ref, "update_reached_depth: marking as cycle participant");
2330 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2331 p = p.previous.head.unwrap();
2336 /// The "provisional evaluation cache" is used to store intermediate cache results
2337 /// when solving auto traits. Auto traits are unusual in that they can support
2338 /// cycles. So, for example, a "proof tree" like this would be ok:
2340 /// - `Foo<T>: Send` :-
2341 /// - `Bar<T>: Send` :-
2342 /// - `Foo<T>: Send` -- cycle, but ok
2343 /// - `Baz<T>: Send`
2345 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2346 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2347 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2348 /// they are coinductive) it is considered ok.
2350 /// However, there is a complication: at the point where we have
2351 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2352 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2353 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2354 /// find out this assumption is wrong? Specifically, we could
2355 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2356 /// `Bar<T>: Send` didn't turn out to be true.
2358 /// In Issue #60010, we found a bug in rustc where it would cache
2359 /// these intermediate results. This was fixed in #60444 by disabling
2360 /// *all* caching for things involved in a cycle -- in our example,
2361 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2362 /// to large slowdowns.
2364 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2365 /// first requires proving `Bar<T>: Send` (which is true:
2367 /// - `Foo<T>: Send` :-
2368 /// - `Bar<T>: Send` :-
2369 /// - `Foo<T>: Send` -- cycle, but ok
2370 /// - `Baz<T>: Send`
2371 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2372 /// - `*const T: Send` -- but what if we later encounter an error?
2374 /// The *provisional evaluation cache* resolves this issue. It stores
2375 /// cache results that we've proven but which were involved in a cycle
2376 /// in some way. We track the minimal stack depth (i.e., the
2377 /// farthest from the top of the stack) that we are dependent on.
2378 /// The idea is that the cache results within are all valid -- so long as
2379 /// none of the nodes in between the current node and the node at that minimum
2380 /// depth result in an error (in which case the cached results are just thrown away).
2382 /// During evaluation, we consult this provisional cache and rely on
2383 /// it. Accessing a cached value is considered equivalent to accessing
2384 /// a result at `reached_depth`, so it marks the *current* solution as
2385 /// provisional as well. If an error is encountered, we toss out any
2386 /// provisional results added from the subtree that encountered the
2387 /// error. When we pop the node at `reached_depth` from the stack, we
2388 /// can commit all the things that remain in the provisional cache.
2389 struct ProvisionalEvaluationCache<'tcx> {
2390 /// next "depth first number" to issue -- just a counter
2393 /// Map from cache key to the provisionally evaluated thing.
2394 /// The cache entries contain the result but also the DFN in which they
2395 /// were added. The DFN is used to clear out values on failure.
2397 /// Imagine we have a stack like:
2399 /// - `A B C` and we add a cache for the result of C (DFN 2)
2400 /// - Then we have a stack `A B D` where `D` has DFN 3
2401 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2402 /// - `E` generates various cache entries which have cyclic dependices on `B`
2403 /// - `A B D E F` and so forth
2404 /// - the DFN of `F` for example would be 5
2405 /// - then we determine that `E` is in error -- we will then clear
2406 /// all cache values whose DFN is >= 4 -- in this case, that
2407 /// means the cached value for `F`.
2408 map: RefCell<FxHashMap<ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, ProvisionalEvaluation>>,
2411 /// A cache value for the provisional cache: contains the depth-first
2412 /// number (DFN) and result.
2413 #[derive(Copy, Clone, Debug)]
2414 struct ProvisionalEvaluation {
2416 reached_depth: usize,
2417 result: EvaluationResult,
2420 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2421 fn default() -> Self {
2422 Self { dfn: Cell::new(0), map: Default::default() }
2426 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2427 /// Get the next DFN in sequence (basically a counter).
2428 fn next_dfn(&self) -> usize {
2429 let result = self.dfn.get();
2430 self.dfn.set(result + 1);
2434 /// Check the provisional cache for any result for
2435 /// `fresh_trait_ref`. If there is a hit, then you must consider
2436 /// it an access to the stack slots at depth
2437 /// `reached_depth` (from the returned value).
2440 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2441 ) -> Option<ProvisionalEvaluation> {
2444 "get_provisional = {:#?}",
2445 self.map.borrow().get(&fresh_trait_ref),
2447 Some(*self.map.borrow().get(&fresh_trait_ref)?)
2450 /// Insert a provisional result into the cache. The result came
2451 /// from the node with the given DFN. It accessed a minimum depth
2452 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
2453 /// and resulted in `result`.
2454 fn insert_provisional(
2457 reached_depth: usize,
2458 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2459 result: EvaluationResult,
2461 debug!(?from_dfn, ?fresh_trait_ref, ?result, "insert_provisional");
2463 let mut map = self.map.borrow_mut();
2465 // Subtle: when we complete working on the DFN `from_dfn`, anything
2466 // that remains in the provisional cache must be dependent on some older
2467 // stack entry than `from_dfn`. We have to update their depth with our transitive
2468 // depth in that case or else it would be referring to some popped note.
2471 // A (reached depth 0)
2473 // B // depth 1 -- reached depth = 0
2474 // C // depth 2 -- reached depth = 1 (should be 0)
2477 // D (reached depth 1)
2478 // C (cache -- reached depth = 2)
2479 for (_k, v) in &mut *map {
2480 if v.from_dfn >= from_dfn {
2481 v.reached_depth = reached_depth.min(v.reached_depth);
2485 map.insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, reached_depth, result });
2488 /// Invoked when the node with dfn `dfn` does not get a successful
2489 /// result. This will clear out any provisional cache entries
2490 /// that were added since `dfn` was created. This is because the
2491 /// provisional entries are things which must assume that the
2492 /// things on the stack at the time of their creation succeeded --
2493 /// since the failing node is presently at the top of the stack,
2494 /// these provisional entries must either depend on it or some
2496 fn on_failure(&self, dfn: usize) {
2497 debug!(?dfn, "on_failure");
2498 self.map.borrow_mut().retain(|key, eval| {
2499 if !eval.from_dfn >= dfn {
2500 debug!("on_failure: removing {:?}", key);
2508 /// Invoked when the node at depth `depth` completed without
2509 /// depending on anything higher in the stack (if that completion
2510 /// was a failure, then `on_failure` should have been invoked
2511 /// already). The callback `op` will be invoked for each
2512 /// provisional entry that we can now confirm.
2514 /// Note that we may still have provisional cache items remaining
2515 /// in the cache when this is done. For example, if there is a
2518 /// * A depends on...
2519 /// * B depends on A
2520 /// * C depends on...
2521 /// * D depends on C
2524 /// Then as we complete the C node we will have a provisional cache
2525 /// with results for A, B, C, and D. This method would clear out
2526 /// the C and D results, but leave A and B provisional.
2528 /// This is determined based on the DFN: we remove any provisional
2529 /// results created since `dfn` started (e.g., in our example, dfn
2530 /// would be 2, representing the C node, and hence we would
2531 /// remove the result for D, which has DFN 3, but not the results for
2532 /// A and B, which have DFNs 0 and 1 respectively).
2536 mut op: impl FnMut(ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, EvaluationResult),
2538 debug!(?dfn, "on_completion");
2540 for (fresh_trait_ref, eval) in
2541 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2543 debug!(?fresh_trait_ref, ?eval, "on_completion");
2545 op(fresh_trait_ref, eval.result);
2550 #[derive(Copy, Clone)]
2551 struct TraitObligationStackList<'o, 'tcx> {
2552 cache: &'o ProvisionalEvaluationCache<'tcx>,
2553 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2556 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2557 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2558 TraitObligationStackList { cache, head: None }
2561 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2562 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2565 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2569 fn depth(&self) -> usize {
2570 if let Some(head) = self.head { head.depth } else { 0 }
2574 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2575 type Item = &'o TraitObligationStack<'o, 'tcx>;
2577 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2584 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2585 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2586 write!(f, "TraitObligationStack({:?})", self.obligation)