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::{ErrorReporting, Overflow, SelectionError};
24 use super::{ObligationCause, PredicateObligation, TraitObligation};
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 pub fn is_intercrate(&self) -> bool {
321 /// Returns `true` if the trait predicate is considerd `const` to this selection context.
322 pub fn is_trait_predicate_const(&self, pred: ty::TraitPredicate<'_>) -> bool {
323 matches!(pred.constness, ty::BoundConstness::ConstIfConst) && self.is_in_const_context
326 /// Returns `true` if the predicate is considered `const` to
327 /// this selection context.
328 pub fn is_predicate_const(&self, pred: ty::Predicate<'_>) -> bool {
329 match pred.kind().skip_binder() {
330 ty::PredicateKind::Trait(pred) => self.is_trait_predicate_const(pred),
335 ///////////////////////////////////////////////////////////////////////////
338 // The selection phase tries to identify *how* an obligation will
339 // be resolved. For example, it will identify which impl or
340 // parameter bound is to be used. The process can be inconclusive
341 // if the self type in the obligation is not fully inferred. Selection
342 // can result in an error in one of two ways:
344 // 1. If no applicable impl or parameter bound can be found.
345 // 2. If the output type parameters in the obligation do not match
346 // those specified by the impl/bound. For example, if the obligation
347 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
348 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
350 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
351 /// type environment by performing unification.
352 #[instrument(level = "debug", skip(self))]
355 obligation: &TraitObligation<'tcx>,
356 ) -> SelectionResult<'tcx, Selection<'tcx>> {
357 let candidate = match self.select_from_obligation(obligation) {
358 Err(SelectionError::Overflow) => {
359 // In standard mode, overflow must have been caught and reported
361 assert!(self.query_mode == TraitQueryMode::Canonical);
362 return Err(SelectionError::Overflow);
364 Err(SelectionError::Ambiguous(_)) => {
373 Ok(Some(candidate)) => candidate,
376 match self.confirm_candidate(obligation, candidate) {
377 Err(SelectionError::Overflow) => {
378 assert!(self.query_mode == TraitQueryMode::Canonical);
379 Err(SelectionError::Overflow)
389 crate fn select_from_obligation(
391 obligation: &TraitObligation<'tcx>,
392 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
393 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
395 let pec = &ProvisionalEvaluationCache::default();
396 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
398 self.candidate_from_obligation(&stack)
401 ///////////////////////////////////////////////////////////////////////////
404 // Tests whether an obligation can be selected or whether an impl
405 // can be applied to particular types. It skips the "confirmation"
406 // step and hence completely ignores output type parameters.
408 // The result is "true" if the obligation *may* hold and "false" if
409 // we can be sure it does not.
411 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
412 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
413 debug!(?obligation, "predicate_may_hold_fatal");
415 // This fatal query is a stopgap that should only be used in standard mode,
416 // where we do not expect overflow to be propagated.
417 assert!(self.query_mode == TraitQueryMode::Standard);
419 self.evaluate_root_obligation(obligation)
420 .expect("Overflow should be caught earlier in standard query mode")
424 /// Evaluates whether the obligation `obligation` can be satisfied
425 /// and returns an `EvaluationResult`. This is meant for the
427 pub fn evaluate_root_obligation(
429 obligation: &PredicateObligation<'tcx>,
430 ) -> Result<EvaluationResult, OverflowError> {
431 self.evaluation_probe(|this| {
432 this.evaluate_predicate_recursively(
433 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
441 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
442 ) -> Result<EvaluationResult, OverflowError> {
443 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
444 let result = op(self)?;
446 match self.infcx.leak_check(true, snapshot) {
448 Err(_) => return Ok(EvaluatedToErr),
451 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
453 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
458 /// Evaluates the predicates in `predicates` recursively. Note that
459 /// this applies projections in the predicates, and therefore
460 /// is run within an inference probe.
461 #[instrument(skip(self, stack), level = "debug")]
462 fn evaluate_predicates_recursively<'o, I>(
464 stack: TraitObligationStackList<'o, 'tcx>,
466 ) -> Result<EvaluationResult, OverflowError>
468 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
470 let mut result = EvaluatedToOk;
471 for obligation in predicates {
472 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
473 if let EvaluatedToErr = eval {
474 // fast-path - EvaluatedToErr is the top of the lattice,
475 // so we don't need to look on the other predicates.
476 return Ok(EvaluatedToErr);
478 result = cmp::max(result, eval);
486 skip(self, previous_stack),
487 fields(previous_stack = ?previous_stack.head())
489 fn evaluate_predicate_recursively<'o>(
491 previous_stack: TraitObligationStackList<'o, 'tcx>,
492 obligation: PredicateObligation<'tcx>,
493 ) -> Result<EvaluationResult, OverflowError> {
494 // `previous_stack` stores a `TraitObligation`, while `obligation` is
495 // a `PredicateObligation`. These are distinct types, so we can't
496 // use any `Option` combinator method that would force them to be
498 match previous_stack.head() {
499 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
500 None => self.check_recursion_limit(&obligation, &obligation)?,
503 let result = ensure_sufficient_stack(|| {
504 let bound_predicate = obligation.predicate.kind();
505 match bound_predicate.skip_binder() {
506 ty::PredicateKind::Trait(t) => {
507 let t = bound_predicate.rebind(t);
508 debug_assert!(!t.has_escaping_bound_vars());
509 let obligation = obligation.with(t);
510 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
513 ty::PredicateKind::Subtype(p) => {
514 let p = bound_predicate.rebind(p);
515 // Does this code ever run?
516 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
517 Some(Ok(InferOk { mut obligations, .. })) => {
518 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
519 self.evaluate_predicates_recursively(
521 obligations.into_iter(),
524 Some(Err(_)) => Ok(EvaluatedToErr),
525 None => Ok(EvaluatedToAmbig),
529 ty::PredicateKind::Coerce(p) => {
530 let p = bound_predicate.rebind(p);
531 // Does this code ever run?
532 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
533 Some(Ok(InferOk { mut obligations, .. })) => {
534 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
535 self.evaluate_predicates_recursively(
537 obligations.into_iter(),
540 Some(Err(_)) => Ok(EvaluatedToErr),
541 None => Ok(EvaluatedToAmbig),
545 ty::PredicateKind::WellFormed(arg) => match wf::obligations(
547 obligation.param_env,
548 obligation.cause.body_id,
549 obligation.recursion_depth + 1,
551 obligation.cause.span,
553 Some(mut obligations) => {
554 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
555 self.evaluate_predicates_recursively(previous_stack, obligations)
557 None => Ok(EvaluatedToAmbig),
560 ty::PredicateKind::TypeOutlives(pred) => {
561 if pred.0.is_known_global() {
564 Ok(EvaluatedToOkModuloRegions)
568 ty::PredicateKind::RegionOutlives(..) => {
569 // We do not consider region relationships when evaluating trait matches.
570 Ok(EvaluatedToOkModuloRegions)
573 ty::PredicateKind::ObjectSafe(trait_def_id) => {
574 if self.tcx().is_object_safe(trait_def_id) {
581 ty::PredicateKind::Projection(data) => {
582 let data = bound_predicate.rebind(data);
583 let project_obligation = obligation.with(data);
584 match project::poly_project_and_unify_type(self, &project_obligation) {
585 Ok(Ok(Some(mut subobligations))) => {
586 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
587 self.evaluate_predicates_recursively(previous_stack, subobligations)
589 Ok(Ok(None)) => Ok(EvaluatedToAmbig),
590 Ok(Err(project::InProgress)) => Ok(EvaluatedToRecur),
591 Err(_) => Ok(EvaluatedToErr),
595 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
596 match self.infcx.closure_kind(closure_substs) {
597 Some(closure_kind) => {
598 if closure_kind.extends(kind) {
604 None => Ok(EvaluatedToAmbig),
608 ty::PredicateKind::ConstEvaluatable(uv) => {
609 match const_evaluatable::is_const_evaluatable(
612 obligation.param_env,
613 obligation.cause.span,
615 Ok(()) => Ok(EvaluatedToOk),
616 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
617 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
618 Err(_) => Ok(EvaluatedToErr),
622 ty::PredicateKind::ConstEquate(c1, c2) => {
623 debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
625 if self.tcx().features().generic_const_exprs {
626 // FIXME: we probably should only try to unify abstract constants
627 // if the constants depend on generic parameters.
629 // Let's just see where this breaks :shrug:
630 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
633 if self.infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
634 return Ok(EvaluatedToOk);
639 let evaluate = |c: &'tcx ty::Const<'tcx>| {
640 if let ty::ConstKind::Unevaluated(unevaluated) = c.val {
643 obligation.param_env,
645 Some(obligation.cause.span),
647 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty))
653 match (evaluate(c1), evaluate(c2)) {
654 (Ok(c1), Ok(c2)) => {
657 .at(&obligation.cause, obligation.param_env)
660 Ok(_) => Ok(EvaluatedToOk),
661 Err(_) => Ok(EvaluatedToErr),
664 (Err(ErrorHandled::Reported(ErrorReported)), _)
665 | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
666 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
668 obligation.cause.span(self.tcx()),
669 "ConstEquate: const_eval_resolve returned an unexpected error"
672 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
673 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
676 // Two different constants using generic parameters ~> error.
682 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
683 bug!("TypeWellFormedFromEnv is only used for chalk")
688 debug!("finished: {:?} from {:?}", result, obligation);
693 #[instrument(skip(self, previous_stack), level = "debug")]
694 fn evaluate_trait_predicate_recursively<'o>(
696 previous_stack: TraitObligationStackList<'o, 'tcx>,
697 mut obligation: TraitObligation<'tcx>,
698 ) -> Result<EvaluationResult, OverflowError> {
700 && obligation.is_global(self.tcx())
705 .all(|bound| bound.definitely_needs_subst(self.tcx()))
707 // If a param env has no global bounds, global obligations do not
708 // depend on its particular value in order to work, so we can clear
709 // out the param env and get better caching.
711 obligation.param_env = obligation.param_env.without_caller_bounds();
714 let stack = self.push_stack(previous_stack, &obligation);
715 let fresh_trait_ref = stack.fresh_trait_ref;
717 debug!(?fresh_trait_ref);
719 if let Some(result) = self.check_evaluation_cache(
720 obligation.param_env,
722 obligation.polarity(),
724 debug!(?result, "CACHE HIT");
728 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
729 debug!(?result, "PROVISIONAL CACHE HIT");
730 stack.update_reached_depth(result.reached_depth);
731 return Ok(result.result);
734 // Check if this is a match for something already on the
735 // stack. If so, we don't want to insert the result into the
736 // main cache (it is cycle dependent) nor the provisional
737 // cache (which is meant for things that have completed but
738 // for a "backedge" -- this result *is* the backedge).
739 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
740 return Ok(cycle_result);
743 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
744 let result = result?;
746 if !result.must_apply_modulo_regions() {
747 stack.cache().on_failure(stack.dfn);
750 let reached_depth = stack.reached_depth.get();
751 if reached_depth >= stack.depth {
752 debug!(?result, "CACHE MISS");
753 self.insert_evaluation_cache(
754 obligation.param_env,
756 obligation.polarity(),
761 stack.cache().on_completion(stack.dfn, |fresh_trait_ref, provisional_result| {
762 self.insert_evaluation_cache(
763 obligation.param_env,
765 obligation.polarity(),
767 provisional_result.max(result),
771 debug!(?result, "PROVISIONAL");
773 "caching provisionally because {:?} \
774 is a cycle participant (at depth {}, reached depth {})",
775 fresh_trait_ref, stack.depth, reached_depth,
778 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
784 /// If there is any previous entry on the stack that precisely
785 /// matches this obligation, then we can assume that the
786 /// obligation is satisfied for now (still all other conditions
787 /// must be met of course). One obvious case this comes up is
788 /// marker traits like `Send`. Think of a linked list:
790 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
792 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
793 /// `Option<Box<List<T>>>` is `Send`, and in turn
794 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
797 /// Note that we do this comparison using the `fresh_trait_ref`
798 /// fields. Because these have all been freshened using
799 /// `self.freshener`, we can be sure that (a) this will not
800 /// affect the inferencer state and (b) that if we see two
801 /// fresh regions with the same index, they refer to the same
802 /// unbound type variable.
803 fn check_evaluation_cycle(
805 stack: &TraitObligationStack<'_, 'tcx>,
806 ) -> Option<EvaluationResult> {
807 if let Some(cycle_depth) = stack
809 .skip(1) // Skip top-most frame.
811 stack.obligation.param_env == prev.obligation.param_env
812 && stack.fresh_trait_ref == prev.fresh_trait_ref
814 .map(|stack| stack.depth)
816 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
818 // If we have a stack like `A B C D E A`, where the top of
819 // the stack is the final `A`, then this will iterate over
820 // `A, E, D, C, B` -- i.e., all the participants apart
821 // from the cycle head. We mark them as participating in a
822 // cycle. This suppresses caching for those nodes. See
823 // `in_cycle` field for more details.
824 stack.update_reached_depth(cycle_depth);
826 // Subtle: when checking for a coinductive cycle, we do
827 // not compare using the "freshened trait refs" (which
828 // have erased regions) but rather the fully explicit
829 // trait refs. This is important because it's only a cycle
830 // if the regions match exactly.
831 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
832 let tcx = self.tcx();
833 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
834 if self.coinductive_match(cycle) {
835 debug!("evaluate_stack --> recursive, coinductive");
838 debug!("evaluate_stack --> recursive, inductive");
839 Some(EvaluatedToRecur)
846 fn evaluate_stack<'o>(
848 stack: &TraitObligationStack<'o, 'tcx>,
849 ) -> Result<EvaluationResult, OverflowError> {
850 // In intercrate mode, whenever any of the generics are unbound,
851 // there can always be an impl. Even if there are no impls in
852 // this crate, perhaps the type would be unified with
853 // something from another crate that does provide an impl.
855 // In intra mode, we must still be conservative. The reason is
856 // that we want to avoid cycles. Imagine an impl like:
858 // impl<T:Eq> Eq for Vec<T>
860 // and a trait reference like `$0 : Eq` where `$0` is an
861 // unbound variable. When we evaluate this trait-reference, we
862 // will unify `$0` with `Vec<$1>` (for some fresh variable
863 // `$1`), on the condition that `$1 : Eq`. We will then wind
864 // up with many candidates (since that are other `Eq` impls
865 // that apply) and try to winnow things down. This results in
866 // a recursive evaluation that `$1 : Eq` -- as you can
867 // imagine, this is just where we started. To avoid that, we
868 // check for unbound variables and return an ambiguous (hence possible)
869 // match if we've seen this trait before.
871 // This suffices to allow chains like `FnMut` implemented in
872 // terms of `Fn` etc, but we could probably make this more
874 let unbound_input_types =
875 stack.fresh_trait_ref.value.skip_binder().substs.types().any(|ty| ty.is_fresh());
877 if stack.obligation.polarity() != ty::ImplPolarity::Negative {
878 // This check was an imperfect workaround for a bug in the old
879 // intercrate mode; it should be removed when that goes away.
880 if unbound_input_types && self.intercrate {
881 debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
882 // Heuristics: show the diagnostics when there are no candidates in crate.
883 if self.intercrate_ambiguity_causes.is_some() {
884 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
885 if let Ok(candidate_set) = self.assemble_candidates(stack) {
886 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
887 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
888 let self_ty = trait_ref.self_ty();
889 let cause = with_no_trimmed_paths(|| {
890 IntercrateAmbiguityCause::DownstreamCrate {
891 trait_desc: trait_ref.print_only_trait_path().to_string(),
892 self_desc: if self_ty.has_concrete_skeleton() {
893 Some(self_ty.to_string())
900 debug!(?cause, "evaluate_stack: pushing cause");
901 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
905 return Ok(EvaluatedToAmbig);
909 if unbound_input_types
910 && stack.iter().skip(1).any(|prev| {
911 stack.obligation.param_env == prev.obligation.param_env
912 && self.match_fresh_trait_refs(
913 stack.fresh_trait_ref,
914 prev.fresh_trait_ref,
915 prev.obligation.param_env,
919 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
920 return Ok(EvaluatedToUnknown);
923 match self.candidate_from_obligation(stack) {
924 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
925 Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig),
926 Ok(None) => Ok(EvaluatedToAmbig),
927 Err(Overflow) => Err(OverflowError::Canonical),
928 Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
929 Err(..) => Ok(EvaluatedToErr),
933 /// For defaulted traits, we use a co-inductive strategy to solve, so
934 /// that recursion is ok. This routine returns `true` if the top of the
935 /// stack (`cycle[0]`):
937 /// - is a defaulted trait,
938 /// - it also appears in the backtrace at some position `X`,
939 /// - all the predicates at positions `X..` between `X` and the top are
940 /// also defaulted traits.
941 pub fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
943 I: Iterator<Item = ty::Predicate<'tcx>>,
945 cycle.all(|predicate| self.coinductive_predicate(predicate))
948 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
949 let result = match predicate.kind().skip_binder() {
950 ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
953 debug!(?predicate, ?result, "coinductive_predicate");
957 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
958 /// obligations are met. Returns whether `candidate` remains viable after this further
963 fields(depth = stack.obligation.recursion_depth)
965 fn evaluate_candidate<'o>(
967 stack: &TraitObligationStack<'o, 'tcx>,
968 candidate: &SelectionCandidate<'tcx>,
969 ) -> Result<EvaluationResult, OverflowError> {
970 let mut result = self.evaluation_probe(|this| {
971 let candidate = (*candidate).clone();
972 match this.confirm_candidate(stack.obligation, candidate) {
975 this.evaluate_predicates_recursively(
977 selection.nested_obligations().into_iter(),
980 Err(..) => Ok(EvaluatedToErr),
984 // If we erased any lifetimes, then we want to use
985 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
986 // as your final result. The result will be cached using
987 // the freshened trait predicate as a key, so we need
988 // our result to be correct by *any* choice of original lifetimes,
989 // not just the lifetime choice for this particular (non-erased)
992 if stack.fresh_trait_ref.has_erased_regions() {
993 result = result.max(EvaluatedToOkModuloRegions);
1000 fn check_evaluation_cache(
1002 param_env: ty::ParamEnv<'tcx>,
1003 trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
1004 polarity: ty::ImplPolarity,
1005 ) -> Option<EvaluationResult> {
1006 // Neither the global nor local cache is aware of intercrate
1007 // mode, so don't do any caching. In particular, we might
1008 // re-use the same `InferCtxt` with both an intercrate
1009 // and non-intercrate `SelectionContext`
1010 if self.intercrate {
1014 let tcx = self.tcx();
1015 if self.can_use_global_caches(param_env) {
1016 if let Some(res) = tcx.evaluation_cache.get(&(param_env.and(trait_ref), polarity), tcx)
1021 self.infcx.evaluation_cache.get(&(param_env.and(trait_ref), polarity), tcx)
1024 fn insert_evaluation_cache(
1026 param_env: ty::ParamEnv<'tcx>,
1027 trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
1028 polarity: ty::ImplPolarity,
1029 dep_node: DepNodeIndex,
1030 result: EvaluationResult,
1032 // Avoid caching results that depend on more than just the trait-ref
1033 // - the stack can create recursion.
1034 if result.is_stack_dependent() {
1038 // Neither the global nor local cache is aware of intercrate
1039 // mode, so don't do any caching. In particular, we might
1040 // re-use the same `InferCtxt` with both an intercrate
1041 // and non-intercrate `SelectionContext`
1042 if self.intercrate {
1046 if self.can_use_global_caches(param_env) {
1047 if !trait_ref.needs_infer() {
1048 debug!(?trait_ref, ?result, "insert_evaluation_cache global");
1049 // This may overwrite the cache with the same value
1050 // FIXME: Due to #50507 this overwrites the different values
1051 // This should be changed to use HashMapExt::insert_same
1052 // when that is fixed
1053 self.tcx().evaluation_cache.insert(
1054 (param_env.and(trait_ref), polarity),
1062 debug!(?trait_ref, ?result, "insert_evaluation_cache");
1063 self.infcx.evaluation_cache.insert((param_env.and(trait_ref), polarity), dep_node, result);
1066 /// For various reasons, it's possible for a subobligation
1067 /// to have a *lower* recursion_depth than the obligation used to create it.
1068 /// Projection sub-obligations may be returned from the projection cache,
1069 /// which results in obligations with an 'old' `recursion_depth`.
1070 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1071 /// subobligations without taking in a 'parent' depth, causing the
1072 /// generated subobligations to have a `recursion_depth` of `0`.
1074 /// To ensure that obligation_depth never decreases, we force all subobligations
1075 /// to have at least the depth of the original obligation.
1076 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1081 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1084 fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
1087 error_obligation: &Obligation<'tcx, T>,
1088 ) -> Result<(), OverflowError> {
1089 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1090 match self.query_mode {
1091 TraitQueryMode::Standard => {
1092 if self.infcx.is_tainted_by_errors() {
1093 return Err(OverflowError::ErrorReporting);
1095 self.infcx.report_overflow_error(error_obligation, true);
1097 TraitQueryMode::Canonical => {
1098 return Err(OverflowError::Canonical);
1105 /// Checks that the recursion limit has not been exceeded.
1107 /// The weird return type of this function allows it to be used with the `try` (`?`)
1108 /// operator within certain functions.
1110 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1112 obligation: &Obligation<'tcx, T>,
1113 error_obligation: &Obligation<'tcx, V>,
1114 ) -> Result<(), OverflowError> {
1115 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1118 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1120 OP: FnOnce(&mut Self) -> R,
1122 let (result, dep_node) =
1123 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1124 self.tcx().dep_graph.read_index(dep_node);
1128 /// filter_impls filters constant trait obligations and candidates that have a positive impl
1129 /// for a negative goal and a negative impl for a positive goal
1130 #[instrument(level = "debug", skip(self))]
1133 candidates: Vec<SelectionCandidate<'tcx>>,
1134 obligation: &TraitObligation<'tcx>,
1135 ) -> Vec<SelectionCandidate<'tcx>> {
1136 let tcx = self.tcx();
1137 let mut result = Vec::with_capacity(candidates.len());
1139 for candidate in candidates {
1140 // Respect const trait obligations
1141 if self.is_trait_predicate_const(obligation.predicate.skip_binder()) {
1144 ImplCandidate(def_id)
1145 if tcx.impl_constness(def_id) == hir::Constness::Const => {}
1148 ty::ConstnessAnd { constness: ty::BoundConstness::ConstIfConst, .. },
1152 AutoImplCandidate(..) => {}
1153 // generator, this will raise error in other places
1154 // or ignore error with const_async_blocks feature
1155 GeneratorCandidate => {}
1156 // FnDef where the function is const
1157 FnPointerCandidate { is_const: true } => {}
1158 ConstDropCandidate => {}
1160 // reject all other types of candidates
1166 if let ImplCandidate(def_id) = candidate {
1167 if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id)
1168 || obligation.polarity() == tcx.impl_polarity(def_id)
1169 || self.allow_negative_impls
1171 result.push(candidate);
1174 result.push(candidate);
1181 /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1182 #[instrument(level = "debug", skip(self))]
1183 fn filter_reservation_impls(
1185 candidate: SelectionCandidate<'tcx>,
1186 obligation: &TraitObligation<'tcx>,
1187 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1188 let tcx = self.tcx();
1189 // Treat reservation impls as ambiguity.
1190 if let ImplCandidate(def_id) = candidate {
1191 if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
1192 if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1193 let attrs = tcx.get_attrs(def_id);
1194 let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
1195 let value = attr.and_then(|a| a.value_str());
1196 if let Some(value) = value {
1198 "filter_reservation_impls: \
1199 reservation impl ambiguity on {:?}",
1202 intercrate_ambiguity_clauses.push(
1203 IntercrateAmbiguityCause::ReservationImpl {
1204 message: value.to_string(),
1215 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1216 debug!("is_knowable(intercrate={:?})", self.intercrate);
1218 if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative {
1222 let obligation = &stack.obligation;
1223 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1225 // Okay to skip binder because of the nature of the
1226 // trait-ref-is-knowable check, which does not care about
1228 let trait_ref = predicate.skip_binder().trait_ref;
1230 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1233 /// Returns `true` if the global caches can be used.
1234 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1235 // If there are any inference variables in the `ParamEnv`, then we
1236 // always use a cache local to this particular scope. Otherwise, we
1237 // switch to a global cache.
1238 if param_env.needs_infer() {
1242 // Avoid using the master cache during coherence and just rely
1243 // on the local cache. This effectively disables caching
1244 // during coherence. It is really just a simplification to
1245 // avoid us having to fear that coherence results "pollute"
1246 // the master cache. Since coherence executes pretty quickly,
1247 // it's not worth going to more trouble to increase the
1248 // hit-rate, I don't think.
1249 if self.intercrate {
1253 // Otherwise, we can use the global cache.
1257 fn check_candidate_cache(
1259 param_env: ty::ParamEnv<'tcx>,
1260 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1261 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1262 // Neither the global nor local cache is aware of intercrate
1263 // mode, so don't do any caching. In particular, we might
1264 // re-use the same `InferCtxt` with both an intercrate
1265 // and non-intercrate `SelectionContext`
1266 if self.intercrate {
1269 let tcx = self.tcx();
1270 let pred = &cache_fresh_trait_pred.skip_binder();
1271 let trait_ref = pred.trait_ref;
1272 if self.can_use_global_caches(param_env) {
1273 if let Some(res) = tcx
1275 .get(&(param_env.and(trait_ref).with_constness(pred.constness), pred.polarity), tcx)
1282 .get(&(param_env.and(trait_ref).with_constness(pred.constness), pred.polarity), tcx)
1285 /// Determines whether can we safely cache the result
1286 /// of selecting an obligation. This is almost always `true`,
1287 /// except when dealing with certain `ParamCandidate`s.
1289 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1290 /// since it was usually produced directly from a `DefId`. However,
1291 /// certain cases (currently only librustdoc's blanket impl finder),
1292 /// a `ParamEnv` may be explicitly constructed with inference types.
1293 /// When this is the case, we do *not* want to cache the resulting selection
1294 /// candidate. This is due to the fact that it might not always be possible
1295 /// to equate the obligation's trait ref and the candidate's trait ref,
1296 /// if more constraints end up getting added to an inference variable.
1298 /// Because of this, we always want to re-run the full selection
1299 /// process for our obligation the next time we see it, since
1300 /// we might end up picking a different `SelectionCandidate` (or none at all).
1301 fn can_cache_candidate(
1303 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1305 // Neither the global nor local cache is aware of intercrate
1306 // mode, so don't do any caching. In particular, we might
1307 // re-use the same `InferCtxt` with both an intercrate
1308 // and non-intercrate `SelectionContext`
1309 if self.intercrate {
1313 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1318 fn insert_candidate_cache(
1320 param_env: ty::ParamEnv<'tcx>,
1321 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1322 dep_node: DepNodeIndex,
1323 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1325 let tcx = self.tcx();
1326 let pred = cache_fresh_trait_pred.skip_binder();
1327 let trait_ref = pred.trait_ref;
1329 if !self.can_cache_candidate(&candidate) {
1330 debug!(?trait_ref, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1334 if self.can_use_global_caches(param_env) {
1335 if let Err(Overflow) = candidate {
1336 // Don't cache overflow globally; we only produce this in certain modes.
1337 } else if !trait_ref.needs_infer() {
1338 if !candidate.needs_infer() {
1339 debug!(?trait_ref, ?candidate, "insert_candidate_cache global");
1340 // This may overwrite the cache with the same value.
1341 tcx.selection_cache.insert(
1342 (param_env.and(trait_ref).with_constness(pred.constness), pred.polarity),
1351 debug!(?trait_ref, ?candidate, "insert_candidate_cache local");
1352 self.infcx.selection_cache.insert(
1353 (param_env.and(trait_ref).with_constness(pred.constness), pred.polarity),
1359 /// Matches a predicate against the bounds of its self type.
1361 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1362 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1363 /// `Baz` bound. We return indexes into the list returned by
1364 /// `tcx.item_bounds` for any applicable bounds.
1365 fn match_projection_obligation_against_definition_bounds(
1367 obligation: &TraitObligation<'tcx>,
1368 ) -> smallvec::SmallVec<[usize; 2]> {
1369 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1370 let placeholder_trait_predicate =
1371 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1373 ?placeholder_trait_predicate,
1374 "match_projection_obligation_against_definition_bounds"
1377 let tcx = self.infcx.tcx;
1378 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1379 ty::Projection(ref data) => (data.item_def_id, data.substs),
1380 ty::Opaque(def_id, substs) => (def_id, substs),
1383 obligation.cause.span,
1384 "match_projection_obligation_against_definition_bounds() called \
1385 but self-ty is not a projection: {:?}",
1386 placeholder_trait_predicate.trait_ref.self_ty()
1390 let bounds = tcx.item_bounds(def_id).subst(tcx, substs);
1392 // The bounds returned by `item_bounds` may contain duplicates after
1393 // normalization, so try to deduplicate when possible to avoid
1394 // unnecessary ambiguity.
1395 let mut distinct_normalized_bounds = FxHashSet::default();
1397 let matching_bounds = bounds
1400 .filter_map(|(idx, bound)| {
1401 let bound_predicate = bound.kind();
1402 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1403 let bound = bound_predicate.rebind(pred.trait_ref);
1404 if self.infcx.probe(|_| {
1405 match self.match_normalize_trait_ref(
1408 placeholder_trait_predicate.trait_ref,
1411 Ok(Some(normalized_trait))
1412 if distinct_normalized_bounds.insert(normalized_trait) =>
1426 debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds");
1430 /// Equates the trait in `obligation` with trait bound. If the two traits
1431 /// can be equated and the normalized trait bound doesn't contain inference
1432 /// variables or placeholders, the normalized bound is returned.
1433 fn match_normalize_trait_ref(
1435 obligation: &TraitObligation<'tcx>,
1436 trait_bound: ty::PolyTraitRef<'tcx>,
1437 placeholder_trait_ref: ty::TraitRef<'tcx>,
1438 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1439 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1440 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1441 // Avoid unnecessary normalization
1445 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1446 project::normalize_with_depth(
1448 obligation.param_env,
1449 obligation.cause.clone(),
1450 obligation.recursion_depth + 1,
1455 .at(&obligation.cause, obligation.param_env)
1456 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1457 .map(|InferOk { obligations: _, value: () }| {
1458 // This method is called within a probe, so we can't have
1459 // inference variables and placeholders escape.
1460 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1469 fn evaluate_where_clause<'o>(
1471 stack: &TraitObligationStack<'o, 'tcx>,
1472 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1473 ) -> Result<EvaluationResult, OverflowError> {
1474 self.evaluation_probe(|this| {
1475 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1476 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1477 Err(()) => Ok(EvaluatedToErr),
1482 pub(super) fn match_projection_projections(
1484 obligation: &ProjectionTyObligation<'tcx>,
1485 env_predicate: PolyProjectionPredicate<'tcx>,
1486 potentially_unnormalized_candidates: bool,
1488 let mut nested_obligations = Vec::new();
1489 let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars(
1490 obligation.cause.span,
1491 LateBoundRegionConversionTime::HigherRankedType,
1494 let infer_projection = if potentially_unnormalized_candidates {
1495 ensure_sufficient_stack(|| {
1496 project::normalize_with_depth_to(
1498 obligation.param_env,
1499 obligation.cause.clone(),
1500 obligation.recursion_depth + 1,
1501 infer_predicate.projection_ty,
1502 &mut nested_obligations,
1506 infer_predicate.projection_ty
1510 .at(&obligation.cause, obligation.param_env)
1511 .sup(obligation.predicate, infer_projection)
1512 .map_or(false, |InferOk { obligations, value: () }| {
1513 self.evaluate_predicates_recursively(
1514 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1515 nested_obligations.into_iter().chain(obligations),
1517 .map_or(false, |res| res.may_apply())
1521 ///////////////////////////////////////////////////////////////////////////
1524 // Winnowing is the process of attempting to resolve ambiguity by
1525 // probing further. During the winnowing process, we unify all
1526 // type variables and then we also attempt to evaluate recursive
1527 // bounds to see if they are satisfied.
1529 /// Returns `true` if `victim` should be dropped in favor of
1530 /// `other`. Generally speaking we will drop duplicate
1531 /// candidates and prefer where-clause candidates.
1533 /// See the comment for "SelectionCandidate" for more details.
1534 fn candidate_should_be_dropped_in_favor_of(
1536 victim: &EvaluatedCandidate<'tcx>,
1537 other: &EvaluatedCandidate<'tcx>,
1540 if victim.candidate == other.candidate {
1544 // Check if a bound would previously have been removed when normalizing
1545 // the param_env so that it can be given the lowest priority. See
1546 // #50825 for the motivation for this.
1547 let is_global = |cand: &ty::PolyTraitRef<'tcx>| {
1548 cand.is_global(self.infcx.tcx) && !cand.has_late_bound_regions()
1551 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1552 // and `DiscriminantKindCandidate` to anything else.
1554 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1555 // lifetime of a variable.
1556 match (&other.candidate, &victim.candidate) {
1557 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1559 "default implementations shouldn't be recorded \
1560 when there are other valid candidates"
1566 BuiltinCandidate { has_nested: false }
1567 | DiscriminantKindCandidate
1569 | ConstDropCandidate,
1574 BuiltinCandidate { has_nested: false }
1575 | DiscriminantKindCandidate
1577 | ConstDropCandidate,
1581 ParamCandidate((other, other_polarity)),
1582 ParamCandidate((victim, victim_polarity)),
1584 let same_except_bound_vars = other.value.skip_binder()
1585 == victim.value.skip_binder()
1586 && other.constness == victim.constness
1587 && other_polarity == victim_polarity
1588 && !other.value.skip_binder().has_escaping_bound_vars();
1589 if same_except_bound_vars {
1590 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1591 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1592 // or the current one if tied (they should both evaluate to the same answer). This is
1593 // probably best characterized as a "hack", since we might prefer to just do our
1594 // best to *not* create essentially duplicate candidates in the first place.
1595 other.value.bound_vars().len() <= victim.value.bound_vars().len()
1596 } else if other.value == victim.value
1597 && victim.constness == ty::BoundConstness::NotConst
1598 && other_polarity == victim_polarity
1600 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1607 // Drop otherwise equivalent non-const fn pointer candidates
1608 (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
1610 // Global bounds from the where clause should be ignored
1611 // here (see issue #50825). Otherwise, we have a where
1612 // clause so don't go around looking for impls.
1613 // Arbitrarily give param candidates priority
1614 // over projection and object candidates.
1616 ParamCandidate(ref cand),
1619 | GeneratorCandidate
1620 | FnPointerCandidate { .. }
1621 | BuiltinObjectCandidate
1622 | BuiltinUnsizeCandidate
1623 | TraitUpcastingUnsizeCandidate(_)
1624 | BuiltinCandidate { .. }
1625 | TraitAliasCandidate(..)
1626 | ObjectCandidate(_)
1627 | ProjectionCandidate(_),
1628 ) => !is_global(&cand.0.value),
1629 (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1630 // Prefer these to a global where-clause bound
1631 // (see issue #50825).
1632 is_global(&cand.0.value)
1637 | GeneratorCandidate
1638 | FnPointerCandidate { .. }
1639 | BuiltinObjectCandidate
1640 | BuiltinUnsizeCandidate
1641 | TraitUpcastingUnsizeCandidate(_)
1642 | BuiltinCandidate { has_nested: true }
1643 | TraitAliasCandidate(..),
1644 ParamCandidate(ref cand),
1646 // Prefer these to a global where-clause bound
1647 // (see issue #50825).
1648 is_global(&cand.0.value) && other.evaluation.must_apply_modulo_regions()
1651 (ProjectionCandidate(i), ProjectionCandidate(j))
1652 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1653 // Arbitrarily pick the lower numbered candidate for backwards
1654 // compatibility reasons. Don't let this affect inference.
1655 i < j && !needs_infer
1657 (ObjectCandidate(_), ProjectionCandidate(_))
1658 | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1659 bug!("Have both object and projection candidate")
1662 // Arbitrarily give projection and object candidates priority.
1664 ObjectCandidate(_) | ProjectionCandidate(_),
1667 | GeneratorCandidate
1668 | FnPointerCandidate { .. }
1669 | BuiltinObjectCandidate
1670 | BuiltinUnsizeCandidate
1671 | TraitUpcastingUnsizeCandidate(_)
1672 | BuiltinCandidate { .. }
1673 | TraitAliasCandidate(..),
1679 | GeneratorCandidate
1680 | FnPointerCandidate { .. }
1681 | BuiltinObjectCandidate
1682 | BuiltinUnsizeCandidate
1683 | TraitUpcastingUnsizeCandidate(_)
1684 | BuiltinCandidate { .. }
1685 | TraitAliasCandidate(..),
1686 ObjectCandidate(_) | ProjectionCandidate(_),
1689 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1690 // See if we can toss out `victim` based on specialization.
1691 // This requires us to know *for sure* that the `other` impl applies
1692 // i.e., `EvaluatedToOk`.
1694 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1695 // to me but is required for `std` to compile, so I didn't change it
1697 let tcx = self.tcx();
1698 if other.evaluation.must_apply_modulo_regions() {
1699 if tcx.specializes((other_def, victim_def)) {
1704 if other.evaluation.must_apply_considering_regions() {
1705 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1706 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1707 // Subtle: If the predicate we are evaluating has inference
1708 // variables, do *not* allow discarding candidates due to
1709 // marker trait impls.
1711 // Without this restriction, we could end up accidentally
1712 // constrainting inference variables based on an arbitrarily
1713 // chosen trait impl.
1715 // Imagine we have the following code:
1718 // #[marker] trait MyTrait {}
1719 // impl MyTrait for u8 {}
1720 // impl MyTrait for bool {}
1723 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1725 // During selection, we will end up with one candidate for each
1726 // impl of `MyTrait`. If we were to discard one impl in favor
1727 // of the other, we would be left with one candidate, causing
1728 // us to "successfully" select the predicate, unifying
1729 // _#0t with (for example) `u8`.
1731 // However, we have no reason to believe that this unification
1732 // is correct - we've essentially just picked an arbitrary
1733 // *possibility* for _#0t, and required that this be the *only*
1736 // Eventually, we will either:
1737 // 1) Unify all inference variables in the predicate through
1738 // some other means (e.g. type-checking of a function). We will
1739 // then be in a position to drop marker trait candidates
1740 // without constraining inference variables (since there are
1741 // none left to constrin)
1742 // 2) Be left with some unconstrained inference variables. We
1743 // will then correctly report an inference error, since the
1744 // existence of multiple marker trait impls tells us nothing
1745 // about which one should actually apply.
1756 // Everything else is ambiguous
1760 | GeneratorCandidate
1761 | FnPointerCandidate { .. }
1762 | BuiltinObjectCandidate
1763 | BuiltinUnsizeCandidate
1764 | TraitUpcastingUnsizeCandidate(_)
1765 | BuiltinCandidate { has_nested: true }
1766 | TraitAliasCandidate(..),
1769 | GeneratorCandidate
1770 | FnPointerCandidate { .. }
1771 | BuiltinObjectCandidate
1772 | BuiltinUnsizeCandidate
1773 | TraitUpcastingUnsizeCandidate(_)
1774 | BuiltinCandidate { has_nested: true }
1775 | TraitAliasCandidate(..),
1780 fn sized_conditions(
1782 obligation: &TraitObligation<'tcx>,
1783 ) -> BuiltinImplConditions<'tcx> {
1784 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1786 // NOTE: binder moved to (*)
1787 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1789 match self_ty.kind() {
1790 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1801 | ty::GeneratorWitness(..)
1806 // safe for everything
1807 Where(ty::Binder::dummy(Vec::new()))
1810 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1812 ty::Tuple(tys) => Where(
1815 .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()),
1818 ty::Adt(def, substs) => {
1819 let sized_crit = def.sized_constraint(self.tcx());
1820 // (*) binder moved here
1822 obligation.predicate.rebind({
1823 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1828 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1829 ty::Infer(ty::TyVar(_)) => Ambiguous,
1833 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1834 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1839 fn copy_clone_conditions(
1841 obligation: &TraitObligation<'tcx>,
1842 ) -> BuiltinImplConditions<'tcx> {
1843 // NOTE: binder moved to (*)
1844 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1846 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1848 match *self_ty.kind() {
1849 ty::Infer(ty::IntVar(_))
1850 | ty::Infer(ty::FloatVar(_))
1853 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1862 | ty::Ref(_, _, hir::Mutability::Not) => {
1863 // Implementations provided in libcore
1871 | ty::GeneratorWitness(..)
1873 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1875 ty::Array(element_ty, _) => {
1876 // (*) binder moved here
1877 Where(obligation.predicate.rebind(vec![element_ty]))
1881 // (*) binder moved here
1882 Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect()))
1885 ty::Closure(_, substs) => {
1886 // (*) binder moved here
1887 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1888 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1889 // Not yet resolved.
1892 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1896 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1897 // Fallback to whatever user-defined impls exist in this case.
1901 ty::Infer(ty::TyVar(_)) => {
1902 // Unbound type variable. Might or might not have
1903 // applicable impls and so forth, depending on what
1904 // those type variables wind up being bound to.
1910 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1911 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1916 /// For default impls, we need to break apart a type into its
1917 /// "constituent types" -- meaning, the types that it contains.
1919 /// Here are some (simple) examples:
1922 /// (i32, u32) -> [i32, u32]
1923 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1924 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1925 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1927 fn constituent_types_for_ty(
1929 t: ty::Binder<'tcx, Ty<'tcx>>,
1930 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1931 match *t.skip_binder().kind() {
1940 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1942 | ty::Char => ty::Binder::dummy(Vec::new()),
1948 | ty::Projection(..)
1950 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1951 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1954 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1955 t.rebind(vec![element_ty])
1958 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
1960 ty::Tuple(ref tys) => {
1961 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1962 t.rebind(tys.iter().map(|k| k.expect_ty()).collect())
1965 ty::Closure(_, ref substs) => {
1966 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1970 ty::Generator(_, ref substs, _) => {
1971 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
1972 let witness = substs.as_generator().witness();
1973 t.rebind(vec![ty].into_iter().chain(iter::once(witness)).collect())
1976 ty::GeneratorWitness(types) => {
1977 debug_assert!(!types.has_escaping_bound_vars());
1978 types.map_bound(|types| types.to_vec())
1981 // For `PhantomData<T>`, we pass `T`.
1982 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
1984 ty::Adt(def, substs) => {
1985 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
1988 ty::Opaque(def_id, substs) => {
1989 // We can resolve the `impl Trait` to its concrete type,
1990 // which enforces a DAG between the functions requiring
1991 // the auto trait bounds in question.
1992 t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
1997 fn collect_predicates_for_types(
1999 param_env: ty::ParamEnv<'tcx>,
2000 cause: ObligationCause<'tcx>,
2001 recursion_depth: usize,
2002 trait_def_id: DefId,
2003 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
2004 ) -> Vec<PredicateObligation<'tcx>> {
2005 // Because the types were potentially derived from
2006 // higher-ranked obligations they may reference late-bound
2007 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2008 // yield a type like `for<'a> &'a i32`. In general, we
2009 // maintain the invariant that we never manipulate bound
2010 // regions, so we have to process these bound regions somehow.
2012 // The strategy is to:
2014 // 1. Instantiate those regions to placeholder regions (e.g.,
2015 // `for<'a> &'a i32` becomes `&0 i32`.
2016 // 2. Produce something like `&'0 i32 : Copy`
2017 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2021 .skip_binder() // binder moved -\
2024 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(ty); // <----/
2026 self.infcx.commit_unconditionally(|_| {
2027 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
2028 let Normalized { value: normalized_ty, mut obligations } =
2029 ensure_sufficient_stack(|| {
2030 project::normalize_with_depth(
2038 let placeholder_obligation = predicate_for_trait_def(
2047 obligations.push(placeholder_obligation);
2054 ///////////////////////////////////////////////////////////////////////////
2057 // Matching is a common path used for both evaluation and
2058 // confirmation. It basically unifies types that appear in impls
2059 // and traits. This does affect the surrounding environment;
2060 // therefore, when used during evaluation, match routines must be
2061 // run inside of a `probe()` so that their side-effects are
2067 obligation: &TraitObligation<'tcx>,
2068 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
2069 match self.match_impl(impl_def_id, obligation) {
2070 Ok(substs) => substs,
2073 "Impl {:?} was matchable against {:?} but now is not",
2081 #[tracing::instrument(level = "debug", skip(self))]
2085 obligation: &TraitObligation<'tcx>,
2086 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2087 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2089 // Before we create the substitutions and everything, first
2090 // consider a "quick reject". This avoids creating more types
2091 // and so forth that we need to.
2092 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2096 let placeholder_obligation =
2097 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
2098 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2100 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2102 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2104 debug!(?impl_trait_ref);
2106 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2107 ensure_sufficient_stack(|| {
2108 project::normalize_with_depth(
2110 obligation.param_env,
2111 obligation.cause.clone(),
2112 obligation.recursion_depth + 1,
2117 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2119 let cause = ObligationCause::new(
2120 obligation.cause.span,
2121 obligation.cause.body_id,
2122 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2125 let InferOk { obligations, .. } = self
2127 .at(&cause, obligation.param_env)
2128 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2129 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2130 nested_obligations.extend(obligations);
2133 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2135 debug!("match_impl: reservation impls only apply in intercrate mode");
2139 debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2140 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2143 fn fast_reject_trait_refs(
2145 obligation: &TraitObligation<'_>,
2146 impl_trait_ref: &ty::TraitRef<'_>,
2148 // We can avoid creating type variables and doing the full
2149 // substitution if we find that any of the input types, when
2150 // simplified, do not match.
2152 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
2153 |(obligation_arg, impl_arg)| {
2154 match (obligation_arg.unpack(), impl_arg.unpack()) {
2155 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
2156 let simplified_obligation_ty =
2157 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2158 let simplified_impl_ty =
2159 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2161 simplified_obligation_ty.is_some()
2162 && simplified_impl_ty.is_some()
2163 && simplified_obligation_ty != simplified_impl_ty
2165 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
2166 // Lifetimes can never cause a rejection.
2169 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
2170 // Conservatively ignore consts (i.e. assume they might
2171 // unify later) until we have `fast_reject` support for
2172 // them (if we'll ever need it, even).
2175 _ => unreachable!(),
2181 /// Normalize `where_clause_trait_ref` and try to match it against
2182 /// `obligation`. If successful, return any predicates that
2183 /// result from the normalization.
2184 fn match_where_clause_trait_ref(
2186 obligation: &TraitObligation<'tcx>,
2187 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2188 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2189 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2192 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2193 /// obligation is satisfied.
2194 #[instrument(skip(self), level = "debug")]
2195 fn match_poly_trait_ref(
2197 obligation: &TraitObligation<'tcx>,
2198 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2199 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2201 .at(&obligation.cause, obligation.param_env)
2202 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2203 .map(|InferOk { obligations, .. }| obligations)
2207 ///////////////////////////////////////////////////////////////////////////
2210 fn match_fresh_trait_refs(
2212 previous: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2213 current: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2214 param_env: ty::ParamEnv<'tcx>,
2216 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2217 matcher.relate(previous, current).is_ok()
2222 previous_stack: TraitObligationStackList<'o, 'tcx>,
2223 obligation: &'o TraitObligation<'tcx>,
2224 ) -> TraitObligationStack<'o, 'tcx> {
2225 let fresh_trait_ref = obligation
2227 .to_poly_trait_ref()
2228 .fold_with(&mut self.freshener)
2229 .with_constness(obligation.predicate.skip_binder().constness);
2231 let dfn = previous_stack.cache.next_dfn();
2232 let depth = previous_stack.depth() + 1;
2233 TraitObligationStack {
2236 reached_depth: Cell::new(depth),
2237 previous: previous_stack,
2243 #[instrument(skip(self), level = "debug")]
2244 fn closure_trait_ref_unnormalized(
2246 obligation: &TraitObligation<'tcx>,
2247 substs: SubstsRef<'tcx>,
2248 ) -> ty::PolyTraitRef<'tcx> {
2249 let closure_sig = substs.as_closure().sig();
2251 debug!(?closure_sig);
2253 // (1) Feels icky to skip the binder here, but OTOH we know
2254 // that the self-type is an unboxed closure type and hence is
2255 // in fact unparameterized (or at least does not reference any
2256 // regions bound in the obligation). Still probably some
2257 // refactoring could make this nicer.
2258 closure_trait_ref_and_return_type(
2260 obligation.predicate.def_id(),
2261 obligation.predicate.skip_binder().self_ty(), // (1)
2263 util::TupleArgumentsFlag::No,
2265 .map_bound(|(trait_ref, _)| trait_ref)
2268 fn generator_trait_ref_unnormalized(
2270 obligation: &TraitObligation<'tcx>,
2271 substs: SubstsRef<'tcx>,
2272 ) -> ty::PolyTraitRef<'tcx> {
2273 let gen_sig = substs.as_generator().poly_sig();
2275 // (1) Feels icky to skip the binder here, but OTOH we know
2276 // that the self-type is an generator type and hence is
2277 // in fact unparameterized (or at least does not reference any
2278 // regions bound in the obligation). Still probably some
2279 // refactoring could make this nicer.
2281 super::util::generator_trait_ref_and_outputs(
2283 obligation.predicate.def_id(),
2284 obligation.predicate.skip_binder().self_ty(), // (1)
2287 .map_bound(|(trait_ref, ..)| trait_ref)
2290 /// Returns the obligations that are implied by instantiating an
2291 /// impl or trait. The obligations are substituted and fully
2292 /// normalized. This is used when confirming an impl or default
2294 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2295 fn impl_or_trait_obligations(
2297 cause: ObligationCause<'tcx>,
2298 recursion_depth: usize,
2299 param_env: ty::ParamEnv<'tcx>,
2300 def_id: DefId, // of impl or trait
2301 substs: SubstsRef<'tcx>, // for impl or trait
2302 ) -> Vec<PredicateObligation<'tcx>> {
2303 let tcx = self.tcx();
2305 // To allow for one-pass evaluation of the nested obligation,
2306 // each predicate must be preceded by the obligations required
2308 // for example, if we have:
2309 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2310 // the impl will have the following predicates:
2311 // <V as Iterator>::Item = U,
2312 // U: Iterator, U: Sized,
2313 // V: Iterator, V: Sized,
2314 // <U as Iterator>::Item: Copy
2315 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2316 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2317 // `$1: Copy`, so we must ensure the obligations are emitted in
2319 let predicates = tcx.predicates_of(def_id);
2320 debug!(?predicates);
2321 assert_eq!(predicates.parent, None);
2322 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2323 for (predicate, _) in predicates.predicates {
2325 let predicate = normalize_with_depth_to(
2330 predicate.subst(tcx, substs),
2333 obligations.push(Obligation {
2334 cause: cause.clone(),
2341 // We are performing deduplication here to avoid exponential blowups
2342 // (#38528) from happening, but the real cause of the duplication is
2343 // unknown. What we know is that the deduplication avoids exponential
2344 // amount of predicates being propagated when processing deeply nested
2347 // This code is hot enough that it's worth avoiding the allocation
2348 // required for the FxHashSet when possible. Special-casing lengths 0,
2349 // 1 and 2 covers roughly 75-80% of the cases.
2350 if obligations.len() <= 1 {
2351 // No possibility of duplicates.
2352 } else if obligations.len() == 2 {
2353 // Only two elements. Drop the second if they are equal.
2354 if obligations[0] == obligations[1] {
2355 obligations.truncate(1);
2358 // Three or more elements. Use a general deduplication process.
2359 let mut seen = FxHashSet::default();
2360 obligations.retain(|i| seen.insert(i.clone()));
2367 trait TraitObligationExt<'tcx> {
2370 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2371 ) -> ObligationCause<'tcx>;
2374 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2377 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2378 ) -> ObligationCause<'tcx> {
2380 * Creates a cause for obligations that are derived from
2381 * `obligation` by a recursive search (e.g., for a builtin
2382 * bound, or eventually a `auto trait Foo`). If `obligation`
2383 * is itself a derived obligation, this is just a clone, but
2384 * otherwise we create a "derived obligation" cause so as to
2385 * keep track of the original root obligation for error
2389 let obligation = self;
2391 // NOTE(flaper87): As of now, it keeps track of the whole error
2392 // chain. Ideally, we should have a way to configure this either
2393 // by using -Z verbose or just a CLI argument.
2394 let derived_cause = DerivedObligationCause {
2395 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2396 parent_code: Lrc::new(obligation.cause.code.clone()),
2398 let derived_code = variant(derived_cause);
2399 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2403 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2404 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2405 TraitObligationStackList::with(self)
2408 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2412 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2416 /// Indicates that attempting to evaluate this stack entry
2417 /// required accessing something from the stack at depth `reached_depth`.
2418 fn update_reached_depth(&self, reached_depth: usize) {
2420 self.depth >= reached_depth,
2421 "invoked `update_reached_depth` with something under this stack: \
2422 self.depth={} reached_depth={}",
2426 debug!(reached_depth, "update_reached_depth");
2428 while reached_depth < p.depth {
2429 debug!(?p.fresh_trait_ref, "update_reached_depth: marking as cycle participant");
2430 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2431 p = p.previous.head.unwrap();
2436 /// The "provisional evaluation cache" is used to store intermediate cache results
2437 /// when solving auto traits. Auto traits are unusual in that they can support
2438 /// cycles. So, for example, a "proof tree" like this would be ok:
2440 /// - `Foo<T>: Send` :-
2441 /// - `Bar<T>: Send` :-
2442 /// - `Foo<T>: Send` -- cycle, but ok
2443 /// - `Baz<T>: Send`
2445 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2446 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2447 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2448 /// they are coinductive) it is considered ok.
2450 /// However, there is a complication: at the point where we have
2451 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2452 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2453 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2454 /// find out this assumption is wrong? Specifically, we could
2455 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2456 /// `Bar<T>: Send` didn't turn out to be true.
2458 /// In Issue #60010, we found a bug in rustc where it would cache
2459 /// these intermediate results. This was fixed in #60444 by disabling
2460 /// *all* caching for things involved in a cycle -- in our example,
2461 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2462 /// to large slowdowns.
2464 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2465 /// first requires proving `Bar<T>: Send` (which is true:
2467 /// - `Foo<T>: Send` :-
2468 /// - `Bar<T>: Send` :-
2469 /// - `Foo<T>: Send` -- cycle, but ok
2470 /// - `Baz<T>: Send`
2471 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2472 /// - `*const T: Send` -- but what if we later encounter an error?
2474 /// The *provisional evaluation cache* resolves this issue. It stores
2475 /// cache results that we've proven but which were involved in a cycle
2476 /// in some way. We track the minimal stack depth (i.e., the
2477 /// farthest from the top of the stack) that we are dependent on.
2478 /// The idea is that the cache results within are all valid -- so long as
2479 /// none of the nodes in between the current node and the node at that minimum
2480 /// depth result in an error (in which case the cached results are just thrown away).
2482 /// During evaluation, we consult this provisional cache and rely on
2483 /// it. Accessing a cached value is considered equivalent to accessing
2484 /// a result at `reached_depth`, so it marks the *current* solution as
2485 /// provisional as well. If an error is encountered, we toss out any
2486 /// provisional results added from the subtree that encountered the
2487 /// error. When we pop the node at `reached_depth` from the stack, we
2488 /// can commit all the things that remain in the provisional cache.
2489 struct ProvisionalEvaluationCache<'tcx> {
2490 /// next "depth first number" to issue -- just a counter
2493 /// Map from cache key to the provisionally evaluated thing.
2494 /// The cache entries contain the result but also the DFN in which they
2495 /// were added. The DFN is used to clear out values on failure.
2497 /// Imagine we have a stack like:
2499 /// - `A B C` and we add a cache for the result of C (DFN 2)
2500 /// - Then we have a stack `A B D` where `D` has DFN 3
2501 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2502 /// - `E` generates various cache entries which have cyclic dependices on `B`
2503 /// - `A B D E F` and so forth
2504 /// - the DFN of `F` for example would be 5
2505 /// - then we determine that `E` is in error -- we will then clear
2506 /// all cache values whose DFN is >= 4 -- in this case, that
2507 /// means the cached value for `F`.
2508 map: RefCell<FxHashMap<ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, ProvisionalEvaluation>>,
2511 /// A cache value for the provisional cache: contains the depth-first
2512 /// number (DFN) and result.
2513 #[derive(Copy, Clone, Debug)]
2514 struct ProvisionalEvaluation {
2516 reached_depth: usize,
2517 result: EvaluationResult,
2520 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2521 fn default() -> Self {
2522 Self { dfn: Cell::new(0), map: Default::default() }
2526 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2527 /// Get the next DFN in sequence (basically a counter).
2528 fn next_dfn(&self) -> usize {
2529 let result = self.dfn.get();
2530 self.dfn.set(result + 1);
2534 /// Check the provisional cache for any result for
2535 /// `fresh_trait_ref`. If there is a hit, then you must consider
2536 /// it an access to the stack slots at depth
2537 /// `reached_depth` (from the returned value).
2540 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2541 ) -> Option<ProvisionalEvaluation> {
2544 "get_provisional = {:#?}",
2545 self.map.borrow().get(&fresh_trait_ref),
2547 Some(*self.map.borrow().get(&fresh_trait_ref)?)
2550 /// Insert a provisional result into the cache. The result came
2551 /// from the node with the given DFN. It accessed a minimum depth
2552 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
2553 /// and resulted in `result`.
2554 fn insert_provisional(
2557 reached_depth: usize,
2558 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2559 result: EvaluationResult,
2561 debug!(?from_dfn, ?fresh_trait_ref, ?result, "insert_provisional");
2563 let mut map = self.map.borrow_mut();
2565 // Subtle: when we complete working on the DFN `from_dfn`, anything
2566 // that remains in the provisional cache must be dependent on some older
2567 // stack entry than `from_dfn`. We have to update their depth with our transitive
2568 // depth in that case or else it would be referring to some popped note.
2571 // A (reached depth 0)
2573 // B // depth 1 -- reached depth = 0
2574 // C // depth 2 -- reached depth = 1 (should be 0)
2577 // D (reached depth 1)
2578 // C (cache -- reached depth = 2)
2579 for (_k, v) in &mut *map {
2580 if v.from_dfn >= from_dfn {
2581 v.reached_depth = reached_depth.min(v.reached_depth);
2585 map.insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, reached_depth, result });
2588 /// Invoked when the node with dfn `dfn` does not get a successful
2589 /// result. This will clear out any provisional cache entries
2590 /// that were added since `dfn` was created. This is because the
2591 /// provisional entries are things which must assume that the
2592 /// things on the stack at the time of their creation succeeded --
2593 /// since the failing node is presently at the top of the stack,
2594 /// these provisional entries must either depend on it or some
2596 fn on_failure(&self, dfn: usize) {
2597 debug!(?dfn, "on_failure");
2598 self.map.borrow_mut().retain(|key, eval| {
2599 if !eval.from_dfn >= dfn {
2600 debug!("on_failure: removing {:?}", key);
2608 /// Invoked when the node at depth `depth` completed without
2609 /// depending on anything higher in the stack (if that completion
2610 /// was a failure, then `on_failure` should have been invoked
2611 /// already). The callback `op` will be invoked for each
2612 /// provisional entry that we can now confirm.
2614 /// Note that we may still have provisional cache items remaining
2615 /// in the cache when this is done. For example, if there is a
2618 /// * A depends on...
2619 /// * B depends on A
2620 /// * C depends on...
2621 /// * D depends on C
2624 /// Then as we complete the C node we will have a provisional cache
2625 /// with results for A, B, C, and D. This method would clear out
2626 /// the C and D results, but leave A and B provisional.
2628 /// This is determined based on the DFN: we remove any provisional
2629 /// results created since `dfn` started (e.g., in our example, dfn
2630 /// would be 2, representing the C node, and hence we would
2631 /// remove the result for D, which has DFN 3, but not the results for
2632 /// A and B, which have DFNs 0 and 1 respectively).
2636 mut op: impl FnMut(ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, EvaluationResult),
2638 debug!(?dfn, "on_completion");
2640 for (fresh_trait_ref, eval) in
2641 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2643 debug!(?fresh_trait_ref, ?eval, "on_completion");
2645 op(fresh_trait_ref, eval.result);
2650 #[derive(Copy, Clone)]
2651 struct TraitObligationStackList<'o, 'tcx> {
2652 cache: &'o ProvisionalEvaluationCache<'tcx>,
2653 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2656 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2657 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2658 TraitObligationStackList { cache, head: None }
2661 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2662 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2665 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2669 fn depth(&self) -> usize {
2670 if let Some(head) = self.head { head.depth } else { 0 }
2674 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2675 type Item = &'o TraitObligationStack<'o, 'tcx>;
2677 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2684 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2686 write!(f, "TraitObligationStack({:?})", self.obligation)