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 crate::traits::project::ProjectionCacheKeyExt;
29 use crate::traits::ProjectionCacheKey;
30 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
31 use rustc_data_structures::stack::ensure_sufficient_stack;
32 use rustc_errors::ErrorReported;
34 use rustc_hir::def_id::DefId;
35 use rustc_infer::infer::LateBoundRegionConversionTime;
36 use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
37 use rustc_middle::mir::interpret::ErrorHandled;
38 use rustc_middle::thir::abstract_const::NotConstEvaluatable;
39 use rustc_middle::ty::fast_reject::{self, SimplifyParams, StripReferences};
40 use rustc_middle::ty::print::with_no_trimmed_paths;
41 use rustc_middle::ty::relate::TypeRelation;
42 use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef};
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 /// The mode that trait queries run in, which informs our error handling
132 /// policy. In essence, canonicalized queries need their errors propagated
133 /// rather than immediately reported because we do not have accurate spans.
134 query_mode: TraitQueryMode,
137 // A stack that walks back up the stack frame.
138 struct TraitObligationStack<'prev, 'tcx> {
139 obligation: &'prev TraitObligation<'tcx>,
141 /// The trait predicate from `obligation` but "freshened" with the
142 /// selection-context's freshener. Used to check for recursion.
143 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
145 /// Starts out equal to `depth` -- if, during evaluation, we
146 /// encounter a cycle, then we will set this flag to the minimum
147 /// depth of that cycle for all participants in the cycle. These
148 /// participants will then forego caching their results. This is
149 /// not the most efficient solution, but it addresses #60010. The
150 /// problem we are trying to prevent:
152 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
153 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
154 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
156 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
157 /// is `EvaluatedToOk`; this is because they were only considered
158 /// ok on the premise that if `A: AutoTrait` held, but we indeed
159 /// encountered a problem (later on) with `A: AutoTrait. So we
160 /// currently set a flag on the stack node for `B: AutoTrait` (as
161 /// well as the second instance of `A: AutoTrait`) to suppress
164 /// This is a simple, targeted fix. A more-performant fix requires
165 /// deeper changes, but would permit more caching: we could
166 /// basically defer caching until we have fully evaluated the
167 /// tree, and then cache the entire tree at once. In any case, the
168 /// performance impact here shouldn't be so horrible: every time
169 /// this is hit, we do cache at least one trait, so we only
170 /// evaluate each member of a cycle up to N times, where N is the
171 /// length of the cycle. This means the performance impact is
172 /// bounded and we shouldn't have any terrible worst-cases.
173 reached_depth: Cell<usize>,
175 previous: TraitObligationStackList<'prev, 'tcx>,
177 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
180 /// The depth-first number of this node in the search graph -- a
181 /// pre-order index. Basically, a freshly incremented counter.
185 struct SelectionCandidateSet<'tcx> {
186 // A list of candidates that definitely apply to the current
187 // obligation (meaning: types unify).
188 vec: Vec<SelectionCandidate<'tcx>>,
190 // If `true`, then there were candidates that might or might
191 // not have applied, but we couldn't tell. This occurs when some
192 // of the input types are type variables, in which case there are
193 // various "builtin" rules that might or might not trigger.
197 #[derive(PartialEq, Eq, Debug, Clone)]
198 struct EvaluatedCandidate<'tcx> {
199 candidate: SelectionCandidate<'tcx>,
200 evaluation: EvaluationResult,
203 /// When does the builtin impl for `T: Trait` apply?
205 enum BuiltinImplConditions<'tcx> {
206 /// The impl is conditional on `T1, T2, ...: Trait`.
207 Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
208 /// There is no built-in impl. There may be some other
209 /// candidate (a where-clause or user-defined impl).
211 /// It is unknown whether there is an impl.
215 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
216 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
219 freshener: infcx.freshener_keep_static(),
221 intercrate_ambiguity_causes: None,
222 allow_negative_impls: false,
223 query_mode: TraitQueryMode::Standard,
227 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
230 freshener: infcx.freshener_keep_static(),
232 intercrate_ambiguity_causes: None,
233 allow_negative_impls: false,
234 query_mode: TraitQueryMode::Standard,
238 pub fn with_negative(
239 infcx: &'cx InferCtxt<'cx, 'tcx>,
240 allow_negative_impls: bool,
241 ) -> SelectionContext<'cx, 'tcx> {
242 debug!(?allow_negative_impls, "with_negative");
245 freshener: infcx.freshener_keep_static(),
247 intercrate_ambiguity_causes: None,
248 allow_negative_impls,
249 query_mode: TraitQueryMode::Standard,
253 pub fn with_query_mode(
254 infcx: &'cx InferCtxt<'cx, 'tcx>,
255 query_mode: TraitQueryMode,
256 ) -> SelectionContext<'cx, 'tcx> {
257 debug!(?query_mode, "with_query_mode");
260 freshener: infcx.freshener_keep_static(),
262 intercrate_ambiguity_causes: None,
263 allow_negative_impls: false,
268 /// Enables tracking of intercrate ambiguity causes. These are
269 /// used in coherence to give improved diagnostics. We don't do
270 /// this until we detect a coherence error because it can lead to
271 /// false overflow results (#47139) and because it costs
272 /// computation time.
273 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
274 assert!(self.intercrate);
275 assert!(self.intercrate_ambiguity_causes.is_none());
276 self.intercrate_ambiguity_causes = Some(vec![]);
277 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
280 /// Gets the intercrate ambiguity causes collected since tracking
281 /// was enabled and disables tracking at the same time. If
282 /// tracking is not enabled, just returns an empty vector.
283 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
284 assert!(self.intercrate);
285 self.intercrate_ambiguity_causes.take().unwrap_or_default()
288 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
292 pub fn tcx(&self) -> TyCtxt<'tcx> {
296 pub fn is_intercrate(&self) -> bool {
300 ///////////////////////////////////////////////////////////////////////////
303 // The selection phase tries to identify *how* an obligation will
304 // be resolved. For example, it will identify which impl or
305 // parameter bound is to be used. The process can be inconclusive
306 // if the self type in the obligation is not fully inferred. Selection
307 // can result in an error in one of two ways:
309 // 1. If no applicable impl or parameter bound can be found.
310 // 2. If the output type parameters in the obligation do not match
311 // those specified by the impl/bound. For example, if the obligation
312 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
313 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
315 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
316 /// type environment by performing unification.
317 #[instrument(level = "debug", skip(self))]
320 obligation: &TraitObligation<'tcx>,
321 ) -> SelectionResult<'tcx, Selection<'tcx>> {
322 let candidate = match self.select_from_obligation(obligation) {
323 Err(SelectionError::Overflow) => {
324 // In standard mode, overflow must have been caught and reported
326 assert!(self.query_mode == TraitQueryMode::Canonical);
327 return Err(SelectionError::Overflow);
329 Err(SelectionError::Ambiguous(_)) => {
338 Ok(Some(candidate)) => candidate,
341 match self.confirm_candidate(obligation, candidate) {
342 Err(SelectionError::Overflow) => {
343 assert!(self.query_mode == TraitQueryMode::Canonical);
344 Err(SelectionError::Overflow)
348 debug!(?candidate, "confirmed");
354 crate fn select_from_obligation(
356 obligation: &TraitObligation<'tcx>,
357 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
358 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
360 let pec = &ProvisionalEvaluationCache::default();
361 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
363 self.candidate_from_obligation(&stack)
366 ///////////////////////////////////////////////////////////////////////////
369 // Tests whether an obligation can be selected or whether an impl
370 // can be applied to particular types. It skips the "confirmation"
371 // step and hence completely ignores output type parameters.
373 // The result is "true" if the obligation *may* hold and "false" if
374 // we can be sure it does not.
376 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
377 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
378 debug!(?obligation, "predicate_may_hold_fatal");
380 // This fatal query is a stopgap that should only be used in standard mode,
381 // where we do not expect overflow to be propagated.
382 assert!(self.query_mode == TraitQueryMode::Standard);
384 self.evaluate_root_obligation(obligation)
385 .expect("Overflow should be caught earlier in standard query mode")
389 /// Evaluates whether the obligation `obligation` can be satisfied
390 /// and returns an `EvaluationResult`. This is meant for the
392 pub fn evaluate_root_obligation(
394 obligation: &PredicateObligation<'tcx>,
395 ) -> Result<EvaluationResult, OverflowError> {
396 self.evaluation_probe(|this| {
397 this.evaluate_predicate_recursively(
398 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
406 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
407 ) -> Result<EvaluationResult, OverflowError> {
408 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
409 let result = op(self)?;
411 match self.infcx.leak_check(true, snapshot) {
413 Err(_) => return Ok(EvaluatedToErr),
416 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
418 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
423 /// Evaluates the predicates in `predicates` recursively. Note that
424 /// this applies projections in the predicates, and therefore
425 /// is run within an inference probe.
426 #[instrument(skip(self, stack), level = "debug")]
427 fn evaluate_predicates_recursively<'o, I>(
429 stack: TraitObligationStackList<'o, 'tcx>,
431 ) -> Result<EvaluationResult, OverflowError>
433 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
435 let mut result = EvaluatedToOk;
436 for obligation in predicates {
437 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
438 if let EvaluatedToErr = eval {
439 // fast-path - EvaluatedToErr is the top of the lattice,
440 // so we don't need to look on the other predicates.
441 return Ok(EvaluatedToErr);
443 result = cmp::max(result, eval);
451 skip(self, previous_stack),
452 fields(previous_stack = ?previous_stack.head())
454 fn evaluate_predicate_recursively<'o>(
456 previous_stack: TraitObligationStackList<'o, 'tcx>,
457 obligation: PredicateObligation<'tcx>,
458 ) -> Result<EvaluationResult, OverflowError> {
459 // `previous_stack` stores a `TraitObligation`, while `obligation` is
460 // a `PredicateObligation`. These are distinct types, so we can't
461 // use any `Option` combinator method that would force them to be
463 match previous_stack.head() {
464 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
465 None => self.check_recursion_limit(&obligation, &obligation)?,
468 let result = ensure_sufficient_stack(|| {
469 let bound_predicate = obligation.predicate.kind();
470 match bound_predicate.skip_binder() {
471 ty::PredicateKind::Trait(t) => {
472 let t = bound_predicate.rebind(t);
473 debug_assert!(!t.has_escaping_bound_vars());
474 let obligation = obligation.with(t);
475 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
478 ty::PredicateKind::Subtype(p) => {
479 let p = bound_predicate.rebind(p);
480 // Does this code ever run?
481 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
482 Some(Ok(InferOk { mut obligations, .. })) => {
483 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
484 self.evaluate_predicates_recursively(
486 obligations.into_iter(),
489 Some(Err(_)) => Ok(EvaluatedToErr),
490 None => Ok(EvaluatedToAmbig),
494 ty::PredicateKind::Coerce(p) => {
495 let p = bound_predicate.rebind(p);
496 // Does this code ever run?
497 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
498 Some(Ok(InferOk { mut obligations, .. })) => {
499 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
500 self.evaluate_predicates_recursively(
502 obligations.into_iter(),
505 Some(Err(_)) => Ok(EvaluatedToErr),
506 None => Ok(EvaluatedToAmbig),
510 ty::PredicateKind::WellFormed(arg) => match wf::obligations(
512 obligation.param_env,
513 obligation.cause.body_id,
514 obligation.recursion_depth + 1,
516 obligation.cause.span,
518 Some(mut obligations) => {
519 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
520 self.evaluate_predicates_recursively(previous_stack, obligations)
522 None => Ok(EvaluatedToAmbig),
525 ty::PredicateKind::TypeOutlives(pred) => {
526 // A global type with no late-bound regions can only
527 // contain the "'static" lifetime (any other lifetime
528 // would either be late-bound or local), so it is guaranteed
529 // to outlive any other lifetime
530 if pred.0.is_global() && !pred.0.has_late_bound_regions() {
533 Ok(EvaluatedToOkModuloRegions)
537 ty::PredicateKind::RegionOutlives(..) => {
538 // We do not consider region relationships when evaluating trait matches.
539 Ok(EvaluatedToOkModuloRegions)
542 ty::PredicateKind::ObjectSafe(trait_def_id) => {
543 if self.tcx().is_object_safe(trait_def_id) {
550 ty::PredicateKind::Projection(data) => {
551 let data = bound_predicate.rebind(data);
552 let project_obligation = obligation.with(data);
553 match project::poly_project_and_unify_type(self, &project_obligation) {
554 Ok(Ok(Some(mut subobligations))) => {
556 // If we've previously marked this projection as 'complete', thne
557 // use the final cached result (either `EvaluatedToOk` or
558 // `EvaluatedToOkModuloRegions`), and skip re-evaluating the
561 ProjectionCacheKey::from_poly_projection_predicate(self, data)
563 if let Some(cached_res) = self
570 break 'compute_res Ok(cached_res);
575 subobligations.iter_mut(),
576 obligation.recursion_depth,
578 let res = self.evaluate_predicates_recursively(
582 if let Ok(res) = res {
583 if res == EvaluatedToOk || res == EvaluatedToOkModuloRegions {
585 ProjectionCacheKey::from_poly_projection_predicate(
589 // If the result is something that we can cache, then mark this
590 // entry as 'complete'. This will allow us to skip evaluating the
591 // suboligations at all the next time we evaluate the projection
604 Ok(Ok(None)) => Ok(EvaluatedToAmbig),
605 Ok(Err(project::InProgress)) => Ok(EvaluatedToRecur),
606 Err(_) => Ok(EvaluatedToErr),
610 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
611 match self.infcx.closure_kind(closure_substs) {
612 Some(closure_kind) => {
613 if closure_kind.extends(kind) {
619 None => Ok(EvaluatedToAmbig),
623 ty::PredicateKind::ConstEvaluatable(uv) => {
624 match const_evaluatable::is_const_evaluatable(
627 obligation.param_env,
628 obligation.cause.span,
630 Ok(()) => Ok(EvaluatedToOk),
631 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
632 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
633 Err(_) => Ok(EvaluatedToErr),
637 ty::PredicateKind::ConstEquate(c1, c2) => {
638 debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
640 if self.tcx().features().generic_const_exprs {
641 // FIXME: we probably should only try to unify abstract constants
642 // if the constants depend on generic parameters.
644 // Let's just see where this breaks :shrug:
645 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
648 if self.infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
649 return Ok(EvaluatedToOk);
654 let evaluate = |c: &'tcx ty::Const<'tcx>| {
655 if let ty::ConstKind::Unevaluated(unevaluated) = c.val {
658 obligation.param_env,
660 Some(obligation.cause.span),
662 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty))
668 match (evaluate(c1), evaluate(c2)) {
669 (Ok(c1), Ok(c2)) => {
672 .at(&obligation.cause, obligation.param_env)
675 Ok(_) => Ok(EvaluatedToOk),
676 Err(_) => Ok(EvaluatedToErr),
679 (Err(ErrorHandled::Reported(ErrorReported)), _)
680 | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
681 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
683 obligation.cause.span(self.tcx()),
684 "ConstEquate: const_eval_resolve returned an unexpected error"
687 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
688 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
691 // Two different constants using generic parameters ~> error.
697 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
698 bug!("TypeWellFormedFromEnv is only used for chalk")
703 debug!("finished: {:?} from {:?}", result, obligation);
708 #[instrument(skip(self, previous_stack), level = "debug")]
709 fn evaluate_trait_predicate_recursively<'o>(
711 previous_stack: TraitObligationStackList<'o, 'tcx>,
712 mut obligation: TraitObligation<'tcx>,
713 ) -> Result<EvaluationResult, OverflowError> {
715 && obligation.is_global()
716 && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst())
718 // If a param env has no global bounds, global obligations do not
719 // depend on its particular value in order to work, so we can clear
720 // out the param env and get better caching.
722 obligation.param_env = obligation.param_env.without_caller_bounds();
725 let stack = self.push_stack(previous_stack, &obligation);
726 let mut fresh_trait_pred = stack.fresh_trait_pred;
727 let mut param_env = obligation.param_env;
729 fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| {
730 pred.remap_constness(self.tcx(), &mut param_env);
734 debug!(?fresh_trait_pred);
736 if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
737 debug!(?result, "CACHE HIT");
741 if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
742 debug!(?result, "PROVISIONAL CACHE HIT");
743 stack.update_reached_depth(result.reached_depth);
744 return Ok(result.result);
747 // Check if this is a match for something already on the
748 // stack. If so, we don't want to insert the result into the
749 // main cache (it is cycle dependent) nor the provisional
750 // cache (which is meant for things that have completed but
751 // for a "backedge" -- this result *is* the backedge).
752 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
753 return Ok(cycle_result);
756 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
757 let result = result?;
759 if !result.must_apply_modulo_regions() {
760 stack.cache().on_failure(stack.dfn);
763 let reached_depth = stack.reached_depth.get();
764 if reached_depth >= stack.depth {
765 debug!(?result, "CACHE MISS");
766 self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
768 stack.cache().on_completion(
770 |fresh_trait_pred, provisional_result, provisional_dep_node| {
771 // Create a new `DepNode` that has dependencies on:
772 // * The `DepNode` for the original evaluation that resulted in a provisional cache
773 // entry being crated
774 // * The `DepNode` for the *current* evaluation, which resulted in us completing
775 // provisional caches entries and inserting them into the evaluation cache
777 // This ensures that when a query reads this entry from the evaluation cache,
778 // it will end up (transitively) dependening on all of the incr-comp dependencies
779 // created during the evaluation of this trait. For example, evaluating a trait
780 // will usually require us to invoke `type_of(field_def_id)` to determine the
781 // constituent types, and we want any queries reading from this evaluation
782 // cache entry to end up with a transitive `type_of(field_def_id`)` dependency.
784 // By using `in_task`, we're also creating an edge from the *current* query
785 // to the newly-created `combined_dep_node`. This is probably redundant,
786 // but it's better to add too many dep graph edges than to add too few
788 let ((), combined_dep_node) = self.in_task(|this| {
789 this.tcx().dep_graph.read_index(provisional_dep_node);
790 this.tcx().dep_graph.read_index(dep_node);
792 self.insert_evaluation_cache(
796 provisional_result.max(result),
801 debug!(?result, "PROVISIONAL");
803 "caching provisionally because {:?} \
804 is a cycle participant (at depth {}, reached depth {})",
805 fresh_trait_pred, stack.depth, reached_depth,
808 stack.cache().insert_provisional(
820 /// If there is any previous entry on the stack that precisely
821 /// matches this obligation, then we can assume that the
822 /// obligation is satisfied for now (still all other conditions
823 /// must be met of course). One obvious case this comes up is
824 /// marker traits like `Send`. Think of a linked list:
826 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
828 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
829 /// `Option<Box<List<T>>>` is `Send`, and in turn
830 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
833 /// Note that we do this comparison using the `fresh_trait_ref`
834 /// fields. Because these have all been freshened using
835 /// `self.freshener`, we can be sure that (a) this will not
836 /// affect the inferencer state and (b) that if we see two
837 /// fresh regions with the same index, they refer to the same
838 /// unbound type variable.
839 fn check_evaluation_cycle(
841 stack: &TraitObligationStack<'_, 'tcx>,
842 ) -> Option<EvaluationResult> {
843 if let Some(cycle_depth) = stack
845 .skip(1) // Skip top-most frame.
847 stack.obligation.param_env == prev.obligation.param_env
848 && stack.fresh_trait_pred == prev.fresh_trait_pred
850 .map(|stack| stack.depth)
852 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
854 // If we have a stack like `A B C D E A`, where the top of
855 // the stack is the final `A`, then this will iterate over
856 // `A, E, D, C, B` -- i.e., all the participants apart
857 // from the cycle head. We mark them as participating in a
858 // cycle. This suppresses caching for those nodes. See
859 // `in_cycle` field for more details.
860 stack.update_reached_depth(cycle_depth);
862 // Subtle: when checking for a coinductive cycle, we do
863 // not compare using the "freshened trait refs" (which
864 // have erased regions) but rather the fully explicit
865 // trait refs. This is important because it's only a cycle
866 // if the regions match exactly.
867 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
868 let tcx = self.tcx();
869 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
870 if self.coinductive_match(cycle) {
871 debug!("evaluate_stack --> recursive, coinductive");
874 debug!("evaluate_stack --> recursive, inductive");
875 Some(EvaluatedToRecur)
882 fn evaluate_stack<'o>(
884 stack: &TraitObligationStack<'o, 'tcx>,
885 ) -> Result<EvaluationResult, OverflowError> {
886 // In intercrate mode, whenever any of the generics are unbound,
887 // there can always be an impl. Even if there are no impls in
888 // this crate, perhaps the type would be unified with
889 // something from another crate that does provide an impl.
891 // In intra mode, we must still be conservative. The reason is
892 // that we want to avoid cycles. Imagine an impl like:
894 // impl<T:Eq> Eq for Vec<T>
896 // and a trait reference like `$0 : Eq` where `$0` is an
897 // unbound variable. When we evaluate this trait-reference, we
898 // will unify `$0` with `Vec<$1>` (for some fresh variable
899 // `$1`), on the condition that `$1 : Eq`. We will then wind
900 // up with many candidates (since that are other `Eq` impls
901 // that apply) and try to winnow things down. This results in
902 // a recursive evaluation that `$1 : Eq` -- as you can
903 // imagine, this is just where we started. To avoid that, we
904 // check for unbound variables and return an ambiguous (hence possible)
905 // match if we've seen this trait before.
907 // This suffices to allow chains like `FnMut` implemented in
908 // terms of `Fn` etc, but we could probably make this more
910 let unbound_input_types =
911 stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh());
913 if stack.obligation.polarity() != ty::ImplPolarity::Negative {
914 // This check was an imperfect workaround for a bug in the old
915 // intercrate mode; it should be removed when that goes away.
916 if unbound_input_types && self.intercrate {
917 debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
918 // Heuristics: show the diagnostics when there are no candidates in crate.
919 if self.intercrate_ambiguity_causes.is_some() {
920 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
921 if let Ok(candidate_set) = self.assemble_candidates(stack) {
922 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
923 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
924 let self_ty = trait_ref.self_ty();
925 let cause = with_no_trimmed_paths(|| {
926 IntercrateAmbiguityCause::DownstreamCrate {
927 trait_desc: trait_ref.print_only_trait_path().to_string(),
928 self_desc: if self_ty.has_concrete_skeleton() {
929 Some(self_ty.to_string())
936 debug!(?cause, "evaluate_stack: pushing cause");
937 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
941 return Ok(EvaluatedToAmbig);
945 if unbound_input_types
946 && stack.iter().skip(1).any(|prev| {
947 stack.obligation.param_env == prev.obligation.param_env
948 && self.match_fresh_trait_refs(
949 stack.fresh_trait_pred,
950 prev.fresh_trait_pred,
951 prev.obligation.param_env,
955 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
956 return Ok(EvaluatedToUnknown);
959 match self.candidate_from_obligation(stack) {
960 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
961 Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig),
962 Ok(None) => Ok(EvaluatedToAmbig),
963 Err(Overflow) => Err(OverflowError::Canonical),
964 Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
965 Err(..) => Ok(EvaluatedToErr),
969 /// For defaulted traits, we use a co-inductive strategy to solve, so
970 /// that recursion is ok. This routine returns `true` if the top of the
971 /// stack (`cycle[0]`):
973 /// - is a defaulted trait,
974 /// - it also appears in the backtrace at some position `X`,
975 /// - all the predicates at positions `X..` between `X` and the top are
976 /// also defaulted traits.
977 pub fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
979 I: Iterator<Item = ty::Predicate<'tcx>>,
981 cycle.all(|predicate| self.coinductive_predicate(predicate))
984 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
985 let result = match predicate.kind().skip_binder() {
986 ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
989 debug!(?predicate, ?result, "coinductive_predicate");
993 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
994 /// obligations are met. Returns whether `candidate` remains viable after this further
999 fields(depth = stack.obligation.recursion_depth)
1001 fn evaluate_candidate<'o>(
1003 stack: &TraitObligationStack<'o, 'tcx>,
1004 candidate: &SelectionCandidate<'tcx>,
1005 ) -> Result<EvaluationResult, OverflowError> {
1006 let mut result = self.evaluation_probe(|this| {
1007 let candidate = (*candidate).clone();
1008 match this.confirm_candidate(stack.obligation, candidate) {
1011 this.evaluate_predicates_recursively(
1013 selection.nested_obligations().into_iter(),
1016 Err(..) => Ok(EvaluatedToErr),
1020 // If we erased any lifetimes, then we want to use
1021 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
1022 // as your final result. The result will be cached using
1023 // the freshened trait predicate as a key, so we need
1024 // our result to be correct by *any* choice of original lifetimes,
1025 // not just the lifetime choice for this particular (non-erased)
1028 if stack.fresh_trait_pred.has_erased_regions() {
1029 result = result.max(EvaluatedToOkModuloRegions);
1036 fn check_evaluation_cache(
1038 param_env: ty::ParamEnv<'tcx>,
1039 trait_pred: ty::PolyTraitPredicate<'tcx>,
1040 ) -> Option<EvaluationResult> {
1041 // Neither the global nor local cache is aware of intercrate
1042 // mode, so don't do any caching. In particular, we might
1043 // re-use the same `InferCtxt` with both an intercrate
1044 // and non-intercrate `SelectionContext`
1045 if self.intercrate {
1049 let tcx = self.tcx();
1050 if self.can_use_global_caches(param_env) {
1051 if let Some(res) = tcx.evaluation_cache.get(¶m_env.and(trait_pred), tcx) {
1055 self.infcx.evaluation_cache.get(¶m_env.and(trait_pred), tcx)
1058 fn insert_evaluation_cache(
1060 param_env: ty::ParamEnv<'tcx>,
1061 trait_pred: ty::PolyTraitPredicate<'tcx>,
1062 dep_node: DepNodeIndex,
1063 result: EvaluationResult,
1065 // Avoid caching results that depend on more than just the trait-ref
1066 // - the stack can create recursion.
1067 if result.is_stack_dependent() {
1071 // Neither the global nor local cache is aware of intercrate
1072 // mode, so don't do any caching. In particular, we might
1073 // re-use the same `InferCtxt` with both an intercrate
1074 // and non-intercrate `SelectionContext`
1075 if self.intercrate {
1079 if self.can_use_global_caches(param_env) {
1080 if !trait_pred.needs_infer() {
1081 debug!(?trait_pred, ?result, "insert_evaluation_cache global");
1082 // This may overwrite the cache with the same value
1083 // FIXME: Due to #50507 this overwrites the different values
1084 // This should be changed to use HashMapExt::insert_same
1085 // when that is fixed
1086 self.tcx().evaluation_cache.insert(param_env.and(trait_pred), dep_node, result);
1091 debug!(?trait_pred, ?result, "insert_evaluation_cache");
1092 self.infcx.evaluation_cache.insert(param_env.and(trait_pred), dep_node, result);
1095 /// For various reasons, it's possible for a subobligation
1096 /// to have a *lower* recursion_depth than the obligation used to create it.
1097 /// Projection sub-obligations may be returned from the projection cache,
1098 /// which results in obligations with an 'old' `recursion_depth`.
1099 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1100 /// subobligations without taking in a 'parent' depth, causing the
1101 /// generated subobligations to have a `recursion_depth` of `0`.
1103 /// To ensure that obligation_depth never decreases, we force all subobligations
1104 /// to have at least the depth of the original obligation.
1105 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1110 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1113 fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
1116 error_obligation: &Obligation<'tcx, T>,
1117 ) -> Result<(), OverflowError> {
1118 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1119 match self.query_mode {
1120 TraitQueryMode::Standard => {
1121 if self.infcx.is_tainted_by_errors() {
1122 return Err(OverflowError::ErrorReporting);
1124 self.infcx.report_overflow_error(error_obligation, true);
1126 TraitQueryMode::Canonical => {
1127 return Err(OverflowError::Canonical);
1134 /// Checks that the recursion limit has not been exceeded.
1136 /// The weird return type of this function allows it to be used with the `try` (`?`)
1137 /// operator within certain functions.
1139 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1141 obligation: &Obligation<'tcx, T>,
1142 error_obligation: &Obligation<'tcx, V>,
1143 ) -> Result<(), OverflowError> {
1144 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1147 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1149 OP: FnOnce(&mut Self) -> R,
1151 let (result, dep_node) =
1152 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1153 self.tcx().dep_graph.read_index(dep_node);
1157 /// filter_impls filters constant trait obligations and candidates that have a positive impl
1158 /// for a negative goal and a negative impl for a positive goal
1159 #[instrument(level = "debug", skip(self))]
1162 candidates: Vec<SelectionCandidate<'tcx>>,
1163 obligation: &TraitObligation<'tcx>,
1164 ) -> Vec<SelectionCandidate<'tcx>> {
1165 let tcx = self.tcx();
1166 let mut result = Vec::with_capacity(candidates.len());
1168 for candidate in candidates {
1169 // Respect const trait obligations
1170 if obligation.is_const() {
1173 ImplCandidate(def_id)
1174 if tcx.impl_constness(def_id) == hir::Constness::Const => {}
1176 ParamCandidate(trait_pred)
1177 if trait_pred.skip_binder().constness
1178 == ty::BoundConstness::ConstIfConst => {}
1180 AutoImplCandidate(..) => {}
1181 // generator, this will raise error in other places
1182 // or ignore error with const_async_blocks feature
1183 GeneratorCandidate => {}
1184 // FnDef where the function is const
1185 FnPointerCandidate { is_const: true } => {}
1186 ConstDropCandidate(_) => {}
1188 // reject all other types of candidates
1194 if let ImplCandidate(def_id) = candidate {
1195 if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id)
1196 || obligation.polarity() == tcx.impl_polarity(def_id)
1197 || self.allow_negative_impls
1199 result.push(candidate);
1202 result.push(candidate);
1209 /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1210 #[instrument(level = "debug", skip(self))]
1211 fn filter_reservation_impls(
1213 candidate: SelectionCandidate<'tcx>,
1214 obligation: &TraitObligation<'tcx>,
1215 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1216 let tcx = self.tcx();
1217 // Treat reservation impls as ambiguity.
1218 if let ImplCandidate(def_id) = candidate {
1219 if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
1220 if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1221 let attrs = tcx.get_attrs(def_id);
1222 let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
1223 let value = attr.and_then(|a| a.value_str());
1224 if let Some(value) = value {
1226 "filter_reservation_impls: \
1227 reservation impl ambiguity on {:?}",
1230 intercrate_ambiguity_clauses.push(
1231 IntercrateAmbiguityCause::ReservationImpl {
1232 message: value.to_string(),
1243 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1244 debug!("is_knowable(intercrate={:?})", self.intercrate);
1246 if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative {
1250 let obligation = &stack.obligation;
1251 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1253 // Okay to skip binder because of the nature of the
1254 // trait-ref-is-knowable check, which does not care about
1256 let trait_ref = predicate.skip_binder().trait_ref;
1258 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1261 /// Returns `true` if the global caches can be used.
1262 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1263 // If there are any inference variables in the `ParamEnv`, then we
1264 // always use a cache local to this particular scope. Otherwise, we
1265 // switch to a global cache.
1266 if param_env.needs_infer() {
1270 // Avoid using the master cache during coherence and just rely
1271 // on the local cache. This effectively disables caching
1272 // during coherence. It is really just a simplification to
1273 // avoid us having to fear that coherence results "pollute"
1274 // the master cache. Since coherence executes pretty quickly,
1275 // it's not worth going to more trouble to increase the
1276 // hit-rate, I don't think.
1277 if self.intercrate {
1281 // Otherwise, we can use the global cache.
1285 fn check_candidate_cache(
1287 mut param_env: ty::ParamEnv<'tcx>,
1288 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1289 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1290 // Neither the global nor local cache is aware of intercrate
1291 // mode, so don't do any caching. In particular, we might
1292 // re-use the same `InferCtxt` with both an intercrate
1293 // and non-intercrate `SelectionContext`
1294 if self.intercrate {
1297 let tcx = self.tcx();
1298 let mut pred = cache_fresh_trait_pred.skip_binder();
1299 pred.remap_constness(tcx, &mut param_env);
1301 if self.can_use_global_caches(param_env) {
1302 if let Some(res) = tcx.selection_cache.get(¶m_env.and(pred), tcx) {
1306 self.infcx.selection_cache.get(¶m_env.and(pred), tcx)
1309 /// Determines whether can we safely cache the result
1310 /// of selecting an obligation. This is almost always `true`,
1311 /// except when dealing with certain `ParamCandidate`s.
1313 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1314 /// since it was usually produced directly from a `DefId`. However,
1315 /// certain cases (currently only librustdoc's blanket impl finder),
1316 /// a `ParamEnv` may be explicitly constructed with inference types.
1317 /// When this is the case, we do *not* want to cache the resulting selection
1318 /// candidate. This is due to the fact that it might not always be possible
1319 /// to equate the obligation's trait ref and the candidate's trait ref,
1320 /// if more constraints end up getting added to an inference variable.
1322 /// Because of this, we always want to re-run the full selection
1323 /// process for our obligation the next time we see it, since
1324 /// we might end up picking a different `SelectionCandidate` (or none at all).
1325 fn can_cache_candidate(
1327 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1329 // Neither the global nor local cache is aware of intercrate
1330 // mode, so don't do any caching. In particular, we might
1331 // re-use the same `InferCtxt` with both an intercrate
1332 // and non-intercrate `SelectionContext`
1333 if self.intercrate {
1337 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1342 fn insert_candidate_cache(
1344 mut param_env: ty::ParamEnv<'tcx>,
1345 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1346 dep_node: DepNodeIndex,
1347 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1349 let tcx = self.tcx();
1350 let mut pred = cache_fresh_trait_pred.skip_binder();
1352 pred.remap_constness(tcx, &mut param_env);
1354 if !self.can_cache_candidate(&candidate) {
1355 debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1359 if self.can_use_global_caches(param_env) {
1360 if let Err(Overflow) = candidate {
1361 // Don't cache overflow globally; we only produce this in certain modes.
1362 } else if !pred.needs_infer() {
1363 if !candidate.needs_infer() {
1364 debug!(?pred, ?candidate, "insert_candidate_cache global");
1365 // This may overwrite the cache with the same value.
1366 tcx.selection_cache.insert(param_env.and(pred), dep_node, candidate);
1372 debug!(?pred, ?candidate, "insert_candidate_cache local");
1373 self.infcx.selection_cache.insert(param_env.and(pred), dep_node, candidate);
1376 /// Matches a predicate against the bounds of its self type.
1378 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1379 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1380 /// `Baz` bound. We return indexes into the list returned by
1381 /// `tcx.item_bounds` for any applicable bounds.
1382 fn match_projection_obligation_against_definition_bounds(
1384 obligation: &TraitObligation<'tcx>,
1385 ) -> smallvec::SmallVec<[usize; 2]> {
1386 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1387 let placeholder_trait_predicate =
1388 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1390 ?placeholder_trait_predicate,
1391 "match_projection_obligation_against_definition_bounds"
1394 let tcx = self.infcx.tcx;
1395 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1396 ty::Projection(ref data) => (data.item_def_id, data.substs),
1397 ty::Opaque(def_id, substs) => (def_id, substs),
1400 obligation.cause.span,
1401 "match_projection_obligation_against_definition_bounds() called \
1402 but self-ty is not a projection: {:?}",
1403 placeholder_trait_predicate.trait_ref.self_ty()
1407 let bounds = tcx.item_bounds(def_id).subst(tcx, substs);
1409 // The bounds returned by `item_bounds` may contain duplicates after
1410 // normalization, so try to deduplicate when possible to avoid
1411 // unnecessary ambiguity.
1412 let mut distinct_normalized_bounds = FxHashSet::default();
1414 let matching_bounds = bounds
1417 .filter_map(|(idx, bound)| {
1418 let bound_predicate = bound.kind();
1419 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1420 let bound = bound_predicate.rebind(pred.trait_ref);
1421 if self.infcx.probe(|_| {
1422 match self.match_normalize_trait_ref(
1425 placeholder_trait_predicate.trait_ref,
1428 Ok(Some(normalized_trait))
1429 if distinct_normalized_bounds.insert(normalized_trait) =>
1443 debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds");
1447 /// Equates the trait in `obligation` with trait bound. If the two traits
1448 /// can be equated and the normalized trait bound doesn't contain inference
1449 /// variables or placeholders, the normalized bound is returned.
1450 fn match_normalize_trait_ref(
1452 obligation: &TraitObligation<'tcx>,
1453 trait_bound: ty::PolyTraitRef<'tcx>,
1454 placeholder_trait_ref: ty::TraitRef<'tcx>,
1455 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1456 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1457 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1458 // Avoid unnecessary normalization
1462 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1463 project::normalize_with_depth(
1465 obligation.param_env,
1466 obligation.cause.clone(),
1467 obligation.recursion_depth + 1,
1472 .at(&obligation.cause, obligation.param_env)
1473 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1474 .map(|InferOk { obligations: _, value: () }| {
1475 // This method is called within a probe, so we can't have
1476 // inference variables and placeholders escape.
1477 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1486 fn evaluate_where_clause<'o>(
1488 stack: &TraitObligationStack<'o, 'tcx>,
1489 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1490 ) -> Result<EvaluationResult, OverflowError> {
1491 self.evaluation_probe(|this| {
1492 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1493 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1494 Err(()) => Ok(EvaluatedToErr),
1499 pub(super) fn match_projection_projections(
1501 obligation: &ProjectionTyObligation<'tcx>,
1502 env_predicate: PolyProjectionPredicate<'tcx>,
1503 potentially_unnormalized_candidates: bool,
1505 let mut nested_obligations = Vec::new();
1506 let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars(
1507 obligation.cause.span,
1508 LateBoundRegionConversionTime::HigherRankedType,
1511 let infer_projection = if potentially_unnormalized_candidates {
1512 ensure_sufficient_stack(|| {
1513 project::normalize_with_depth_to(
1515 obligation.param_env,
1516 obligation.cause.clone(),
1517 obligation.recursion_depth + 1,
1518 infer_predicate.projection_ty,
1519 &mut nested_obligations,
1523 infer_predicate.projection_ty
1527 .at(&obligation.cause, obligation.param_env)
1528 .sup(obligation.predicate, infer_projection)
1529 .map_or(false, |InferOk { obligations, value: () }| {
1530 self.evaluate_predicates_recursively(
1531 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1532 nested_obligations.into_iter().chain(obligations),
1534 .map_or(false, |res| res.may_apply())
1538 ///////////////////////////////////////////////////////////////////////////
1541 // Winnowing is the process of attempting to resolve ambiguity by
1542 // probing further. During the winnowing process, we unify all
1543 // type variables and then we also attempt to evaluate recursive
1544 // bounds to see if they are satisfied.
1546 /// Returns `true` if `victim` should be dropped in favor of
1547 /// `other`. Generally speaking we will drop duplicate
1548 /// candidates and prefer where-clause candidates.
1550 /// See the comment for "SelectionCandidate" for more details.
1551 fn candidate_should_be_dropped_in_favor_of(
1553 sized_predicate: bool,
1554 victim: &EvaluatedCandidate<'tcx>,
1555 other: &EvaluatedCandidate<'tcx>,
1558 if victim.candidate == other.candidate {
1562 // Check if a bound would previously have been removed when normalizing
1563 // the param_env so that it can be given the lowest priority. See
1564 // #50825 for the motivation for this.
1565 let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| {
1566 cand.is_global() && !cand.has_late_bound_regions()
1569 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1570 // `DiscriminantKindCandidate`, and `ConstDropCandidate` to anything else.
1572 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1573 // lifetime of a variable.
1574 match (&other.candidate, &victim.candidate) {
1575 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1577 "default implementations shouldn't be recorded \
1578 when there are other valid candidates"
1584 BuiltinCandidate { has_nested: false }
1585 | DiscriminantKindCandidate
1587 | ConstDropCandidate(_),
1592 BuiltinCandidate { has_nested: false }
1593 | DiscriminantKindCandidate
1595 | ConstDropCandidate(_),
1598 (ParamCandidate(other), ParamCandidate(victim)) => {
1599 let same_except_bound_vars = other.skip_binder().trait_ref
1600 == victim.skip_binder().trait_ref
1601 && other.skip_binder().constness == victim.skip_binder().constness
1602 && other.skip_binder().polarity == victim.skip_binder().polarity
1603 && !other.skip_binder().trait_ref.has_escaping_bound_vars();
1604 if same_except_bound_vars {
1605 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1606 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1607 // or the current one if tied (they should both evaluate to the same answer). This is
1608 // probably best characterized as a "hack", since we might prefer to just do our
1609 // best to *not* create essentially duplicate candidates in the first place.
1610 other.bound_vars().len() <= victim.bound_vars().len()
1611 } else if other.skip_binder().trait_ref == victim.skip_binder().trait_ref
1612 && victim.skip_binder().constness == ty::BoundConstness::NotConst
1613 && other.skip_binder().polarity == victim.skip_binder().polarity
1615 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1622 // Drop otherwise equivalent non-const fn pointer candidates
1623 (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
1625 // If obligation is a sized predicate or the where-clause bound is
1626 // global, prefer the projection or object candidate. See issue
1627 // #50825 and #89352.
1628 (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1629 sized_predicate || is_global(cand)
1631 (ParamCandidate(ref cand), ObjectCandidate(_) | ProjectionCandidate(_)) => {
1632 !(sized_predicate || is_global(cand))
1635 // Global bounds from the where clause should be ignored
1636 // here (see issue #50825). Otherwise, we have a where
1637 // clause so don't go around looking for impls.
1638 // Arbitrarily give param candidates priority
1639 // over projection and object candidates.
1641 ParamCandidate(ref cand),
1644 | GeneratorCandidate
1645 | FnPointerCandidate { .. }
1646 | BuiltinObjectCandidate
1647 | BuiltinUnsizeCandidate
1648 | TraitUpcastingUnsizeCandidate(_)
1649 | BuiltinCandidate { .. }
1650 | TraitAliasCandidate(..),
1651 ) => !is_global(cand),
1655 | GeneratorCandidate
1656 | FnPointerCandidate { .. }
1657 | BuiltinObjectCandidate
1658 | BuiltinUnsizeCandidate
1659 | TraitUpcastingUnsizeCandidate(_)
1660 | BuiltinCandidate { has_nested: true }
1661 | TraitAliasCandidate(..),
1662 ParamCandidate(ref cand),
1664 // Prefer these to a global where-clause bound
1665 // (see issue #50825).
1666 is_global(cand) && other.evaluation.must_apply_modulo_regions()
1669 (ProjectionCandidate(i), ProjectionCandidate(j))
1670 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1671 // Arbitrarily pick the lower numbered candidate for backwards
1672 // compatibility reasons. Don't let this affect inference.
1673 i < j && !needs_infer
1675 (ObjectCandidate(_), ProjectionCandidate(_))
1676 | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1677 bug!("Have both object and projection candidate")
1680 // Arbitrarily give projection and object candidates priority.
1682 ObjectCandidate(_) | ProjectionCandidate(_),
1685 | GeneratorCandidate
1686 | FnPointerCandidate { .. }
1687 | BuiltinObjectCandidate
1688 | BuiltinUnsizeCandidate
1689 | TraitUpcastingUnsizeCandidate(_)
1690 | BuiltinCandidate { .. }
1691 | TraitAliasCandidate(..),
1697 | GeneratorCandidate
1698 | FnPointerCandidate { .. }
1699 | BuiltinObjectCandidate
1700 | BuiltinUnsizeCandidate
1701 | TraitUpcastingUnsizeCandidate(_)
1702 | BuiltinCandidate { .. }
1703 | TraitAliasCandidate(..),
1704 ObjectCandidate(_) | ProjectionCandidate(_),
1707 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1708 // See if we can toss out `victim` based on specialization.
1709 // This requires us to know *for sure* that the `other` impl applies
1710 // i.e., `EvaluatedToOk`.
1712 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1713 // to me but is required for `std` to compile, so I didn't change it
1715 let tcx = self.tcx();
1716 if other.evaluation.must_apply_modulo_regions() {
1717 if tcx.specializes((other_def, victim_def)) {
1722 if other.evaluation.must_apply_considering_regions() {
1723 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1724 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1725 // Subtle: If the predicate we are evaluating has inference
1726 // variables, do *not* allow discarding candidates due to
1727 // marker trait impls.
1729 // Without this restriction, we could end up accidentally
1730 // constrainting inference variables based on an arbitrarily
1731 // chosen trait impl.
1733 // Imagine we have the following code:
1736 // #[marker] trait MyTrait {}
1737 // impl MyTrait for u8 {}
1738 // impl MyTrait for bool {}
1741 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1743 // During selection, we will end up with one candidate for each
1744 // impl of `MyTrait`. If we were to discard one impl in favor
1745 // of the other, we would be left with one candidate, causing
1746 // us to "successfully" select the predicate, unifying
1747 // _#0t with (for example) `u8`.
1749 // However, we have no reason to believe that this unification
1750 // is correct - we've essentially just picked an arbitrary
1751 // *possibility* for _#0t, and required that this be the *only*
1754 // Eventually, we will either:
1755 // 1) Unify all inference variables in the predicate through
1756 // some other means (e.g. type-checking of a function). We will
1757 // then be in a position to drop marker trait candidates
1758 // without constraining inference variables (since there are
1759 // none left to constrin)
1760 // 2) Be left with some unconstrained inference variables. We
1761 // will then correctly report an inference error, since the
1762 // existence of multiple marker trait impls tells us nothing
1763 // about which one should actually apply.
1774 // Everything else is ambiguous
1778 | GeneratorCandidate
1779 | FnPointerCandidate { .. }
1780 | BuiltinObjectCandidate
1781 | BuiltinUnsizeCandidate
1782 | TraitUpcastingUnsizeCandidate(_)
1783 | BuiltinCandidate { has_nested: true }
1784 | TraitAliasCandidate(..),
1787 | GeneratorCandidate
1788 | FnPointerCandidate { .. }
1789 | BuiltinObjectCandidate
1790 | BuiltinUnsizeCandidate
1791 | TraitUpcastingUnsizeCandidate(_)
1792 | BuiltinCandidate { has_nested: true }
1793 | TraitAliasCandidate(..),
1798 fn sized_conditions(
1800 obligation: &TraitObligation<'tcx>,
1801 ) -> BuiltinImplConditions<'tcx> {
1802 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1804 // NOTE: binder moved to (*)
1805 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1807 match self_ty.kind() {
1808 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1819 | ty::GeneratorWitness(..)
1824 // safe for everything
1825 Where(ty::Binder::dummy(Vec::new()))
1828 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1830 ty::Tuple(tys) => Where(
1833 .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()),
1836 ty::Adt(def, substs) => {
1837 let sized_crit = def.sized_constraint(self.tcx());
1838 // (*) binder moved here
1840 obligation.predicate.rebind({
1841 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1846 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1847 ty::Infer(ty::TyVar(_)) => Ambiguous,
1851 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1852 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1857 fn copy_clone_conditions(
1859 obligation: &TraitObligation<'tcx>,
1860 ) -> BuiltinImplConditions<'tcx> {
1861 // NOTE: binder moved to (*)
1862 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1864 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1866 match *self_ty.kind() {
1867 ty::Infer(ty::IntVar(_))
1868 | ty::Infer(ty::FloatVar(_))
1871 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1880 | ty::Ref(_, _, hir::Mutability::Not)
1881 | ty::Array(..) => {
1882 // Implementations provided in libcore
1890 | ty::GeneratorWitness(..)
1892 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1895 // (*) binder moved here
1896 Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect()))
1899 ty::Closure(_, substs) => {
1900 // (*) binder moved here
1901 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1902 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1903 // Not yet resolved.
1906 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1910 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1911 // Fallback to whatever user-defined impls exist in this case.
1915 ty::Infer(ty::TyVar(_)) => {
1916 // Unbound type variable. Might or might not have
1917 // applicable impls and so forth, depending on what
1918 // those type variables wind up being bound to.
1924 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1925 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1930 /// For default impls, we need to break apart a type into its
1931 /// "constituent types" -- meaning, the types that it contains.
1933 /// Here are some (simple) examples:
1936 /// (i32, u32) -> [i32, u32]
1937 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1938 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1939 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1941 fn constituent_types_for_ty(
1943 t: ty::Binder<'tcx, Ty<'tcx>>,
1944 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1945 match *t.skip_binder().kind() {
1954 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1956 | ty::Char => ty::Binder::dummy(Vec::new()),
1962 | ty::Projection(..)
1964 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1965 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1968 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1969 t.rebind(vec![element_ty])
1972 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
1974 ty::Tuple(ref tys) => {
1975 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1976 t.rebind(tys.iter().map(|k| k.expect_ty()).collect())
1979 ty::Closure(_, ref substs) => {
1980 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1984 ty::Generator(_, ref substs, _) => {
1985 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
1986 let witness = substs.as_generator().witness();
1987 t.rebind([ty].into_iter().chain(iter::once(witness)).collect())
1990 ty::GeneratorWitness(types) => {
1991 debug_assert!(!types.has_escaping_bound_vars());
1992 types.map_bound(|types| types.to_vec())
1995 // For `PhantomData<T>`, we pass `T`.
1996 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
1998 ty::Adt(def, substs) => {
1999 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
2002 ty::Opaque(def_id, substs) => {
2003 // We can resolve the `impl Trait` to its concrete type,
2004 // which enforces a DAG between the functions requiring
2005 // the auto trait bounds in question.
2006 t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
2011 fn collect_predicates_for_types(
2013 param_env: ty::ParamEnv<'tcx>,
2014 cause: ObligationCause<'tcx>,
2015 recursion_depth: usize,
2016 trait_def_id: DefId,
2017 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
2018 ) -> Vec<PredicateObligation<'tcx>> {
2019 // Because the types were potentially derived from
2020 // higher-ranked obligations they may reference late-bound
2021 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2022 // yield a type like `for<'a> &'a i32`. In general, we
2023 // maintain the invariant that we never manipulate bound
2024 // regions, so we have to process these bound regions somehow.
2026 // The strategy is to:
2028 // 1. Instantiate those regions to placeholder regions (e.g.,
2029 // `for<'a> &'a i32` becomes `&0 i32`.
2030 // 2. Produce something like `&'0 i32 : Copy`
2031 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2035 .skip_binder() // binder moved -\
2038 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(ty); // <----/
2040 self.infcx.commit_unconditionally(|_| {
2041 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
2042 let Normalized { value: normalized_ty, mut obligations } =
2043 ensure_sufficient_stack(|| {
2044 project::normalize_with_depth(
2052 let placeholder_obligation = predicate_for_trait_def(
2061 obligations.push(placeholder_obligation);
2068 ///////////////////////////////////////////////////////////////////////////
2071 // Matching is a common path used for both evaluation and
2072 // confirmation. It basically unifies types that appear in impls
2073 // and traits. This does affect the surrounding environment;
2074 // therefore, when used during evaluation, match routines must be
2075 // run inside of a `probe()` so that their side-effects are
2081 obligation: &TraitObligation<'tcx>,
2082 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
2083 match self.match_impl(impl_def_id, obligation) {
2084 Ok(substs) => substs,
2087 "Impl {:?} was matchable against {:?} but now is not",
2095 #[tracing::instrument(level = "debug", skip(self))]
2099 obligation: &TraitObligation<'tcx>,
2100 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2101 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2103 // Before we create the substitutions and everything, first
2104 // consider a "quick reject". This avoids creating more types
2105 // and so forth that we need to.
2106 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2110 let placeholder_obligation =
2111 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
2112 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2114 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2116 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2118 debug!(?impl_trait_ref);
2120 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2121 ensure_sufficient_stack(|| {
2122 project::normalize_with_depth(
2124 obligation.param_env,
2125 obligation.cause.clone(),
2126 obligation.recursion_depth + 1,
2131 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2133 let cause = ObligationCause::new(
2134 obligation.cause.span,
2135 obligation.cause.body_id,
2136 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2139 let InferOk { obligations, .. } = self
2141 .at(&cause, obligation.param_env)
2142 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2143 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2144 nested_obligations.extend(obligations);
2147 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2149 debug!("match_impl: reservation impls only apply in intercrate mode");
2153 debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2154 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2157 fn fast_reject_trait_refs(
2159 obligation: &TraitObligation<'_>,
2160 impl_trait_ref: &ty::TraitRef<'_>,
2162 // We can avoid creating type variables and doing the full
2163 // substitution if we find that any of the input types, when
2164 // simplified, do not match.
2166 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
2167 |(obligation_arg, impl_arg)| {
2168 match (obligation_arg.unpack(), impl_arg.unpack()) {
2169 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
2170 // Note, we simplify parameters for the obligation but not the
2171 // impl so that we do not reject a blanket impl but do reject
2172 // more concrete impls if we're searching for `T: Trait`.
2173 let simplified_obligation_ty = fast_reject::simplify_type(
2176 SimplifyParams::Yes,
2177 StripReferences::No,
2179 let simplified_impl_ty = fast_reject::simplify_type(
2183 StripReferences::No,
2186 simplified_obligation_ty.is_some()
2187 && simplified_impl_ty.is_some()
2188 && simplified_obligation_ty != simplified_impl_ty
2190 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
2191 // Lifetimes can never cause a rejection.
2194 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
2195 // Conservatively ignore consts (i.e. assume they might
2196 // unify later) until we have `fast_reject` support for
2197 // them (if we'll ever need it, even).
2200 _ => unreachable!(),
2206 /// Normalize `where_clause_trait_ref` and try to match it against
2207 /// `obligation`. If successful, return any predicates that
2208 /// result from the normalization.
2209 fn match_where_clause_trait_ref(
2211 obligation: &TraitObligation<'tcx>,
2212 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2213 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2214 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2217 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2218 /// obligation is satisfied.
2219 #[instrument(skip(self), level = "debug")]
2220 fn match_poly_trait_ref(
2222 obligation: &TraitObligation<'tcx>,
2223 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2224 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2226 .at(&obligation.cause, obligation.param_env)
2227 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2228 .map(|InferOk { obligations, .. }| obligations)
2232 ///////////////////////////////////////////////////////////////////////////
2235 fn match_fresh_trait_refs(
2237 previous: ty::PolyTraitPredicate<'tcx>,
2238 current: ty::PolyTraitPredicate<'tcx>,
2239 param_env: ty::ParamEnv<'tcx>,
2241 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2242 matcher.relate(previous, current).is_ok()
2247 previous_stack: TraitObligationStackList<'o, 'tcx>,
2248 obligation: &'o TraitObligation<'tcx>,
2249 ) -> TraitObligationStack<'o, 'tcx> {
2250 let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
2252 let dfn = previous_stack.cache.next_dfn();
2253 let depth = previous_stack.depth() + 1;
2254 TraitObligationStack {
2257 reached_depth: Cell::new(depth),
2258 previous: previous_stack,
2264 #[instrument(skip(self), level = "debug")]
2265 fn closure_trait_ref_unnormalized(
2267 obligation: &TraitObligation<'tcx>,
2268 substs: SubstsRef<'tcx>,
2269 ) -> ty::PolyTraitRef<'tcx> {
2270 let closure_sig = substs.as_closure().sig();
2272 debug!(?closure_sig);
2274 // (1) Feels icky to skip the binder here, but OTOH we know
2275 // that the self-type is an unboxed closure type and hence is
2276 // in fact unparameterized (or at least does not reference any
2277 // regions bound in the obligation). Still probably some
2278 // refactoring could make this nicer.
2279 closure_trait_ref_and_return_type(
2281 obligation.predicate.def_id(),
2282 obligation.predicate.skip_binder().self_ty(), // (1)
2284 util::TupleArgumentsFlag::No,
2286 .map_bound(|(trait_ref, _)| trait_ref)
2289 fn generator_trait_ref_unnormalized(
2291 obligation: &TraitObligation<'tcx>,
2292 substs: SubstsRef<'tcx>,
2293 ) -> ty::PolyTraitRef<'tcx> {
2294 let gen_sig = substs.as_generator().poly_sig();
2296 // (1) Feels icky to skip the binder here, but OTOH we know
2297 // that the self-type is an generator type and hence is
2298 // in fact unparameterized (or at least does not reference any
2299 // regions bound in the obligation). Still probably some
2300 // refactoring could make this nicer.
2302 super::util::generator_trait_ref_and_outputs(
2304 obligation.predicate.def_id(),
2305 obligation.predicate.skip_binder().self_ty(), // (1)
2308 .map_bound(|(trait_ref, ..)| trait_ref)
2311 /// Returns the obligations that are implied by instantiating an
2312 /// impl or trait. The obligations are substituted and fully
2313 /// normalized. This is used when confirming an impl or default
2315 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2316 fn impl_or_trait_obligations(
2318 cause: ObligationCause<'tcx>,
2319 recursion_depth: usize,
2320 param_env: ty::ParamEnv<'tcx>,
2321 def_id: DefId, // of impl or trait
2322 substs: SubstsRef<'tcx>, // for impl or trait
2323 ) -> Vec<PredicateObligation<'tcx>> {
2324 let tcx = self.tcx();
2326 // To allow for one-pass evaluation of the nested obligation,
2327 // each predicate must be preceded by the obligations required
2329 // for example, if we have:
2330 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2331 // the impl will have the following predicates:
2332 // <V as Iterator>::Item = U,
2333 // U: Iterator, U: Sized,
2334 // V: Iterator, V: Sized,
2335 // <U as Iterator>::Item: Copy
2336 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2337 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2338 // `$1: Copy`, so we must ensure the obligations are emitted in
2340 let predicates = tcx.predicates_of(def_id);
2341 debug!(?predicates);
2342 assert_eq!(predicates.parent, None);
2343 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2344 for (predicate, _) in predicates.predicates {
2346 let predicate = normalize_with_depth_to(
2351 predicate.subst(tcx, substs),
2354 obligations.push(Obligation {
2355 cause: cause.clone(),
2362 // We are performing deduplication here to avoid exponential blowups
2363 // (#38528) from happening, but the real cause of the duplication is
2364 // unknown. What we know is that the deduplication avoids exponential
2365 // amount of predicates being propagated when processing deeply nested
2368 // This code is hot enough that it's worth avoiding the allocation
2369 // required for the FxHashSet when possible. Special-casing lengths 0,
2370 // 1 and 2 covers roughly 75-80% of the cases.
2371 if obligations.len() <= 1 {
2372 // No possibility of duplicates.
2373 } else if obligations.len() == 2 {
2374 // Only two elements. Drop the second if they are equal.
2375 if obligations[0] == obligations[1] {
2376 obligations.truncate(1);
2379 // Three or more elements. Use a general deduplication process.
2380 let mut seen = FxHashSet::default();
2381 obligations.retain(|i| seen.insert(i.clone()));
2388 trait TraitObligationExt<'tcx> {
2391 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2392 ) -> ObligationCause<'tcx>;
2395 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2398 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2399 ) -> ObligationCause<'tcx> {
2401 * Creates a cause for obligations that are derived from
2402 * `obligation` by a recursive search (e.g., for a builtin
2403 * bound, or eventually a `auto trait Foo`). If `obligation`
2404 * is itself a derived obligation, this is just a clone, but
2405 * otherwise we create a "derived obligation" cause so as to
2406 * keep track of the original root obligation for error
2410 let obligation = self;
2412 // NOTE(flaper87): As of now, it keeps track of the whole error
2413 // chain. Ideally, we should have a way to configure this either
2414 // by using -Z verbose or just a CLI argument.
2415 let derived_cause = DerivedObligationCause {
2416 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2417 parent_code: obligation.cause.clone_code(),
2419 let derived_code = variant(derived_cause);
2420 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2424 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2425 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2426 TraitObligationStackList::with(self)
2429 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2433 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2437 /// Indicates that attempting to evaluate this stack entry
2438 /// required accessing something from the stack at depth `reached_depth`.
2439 fn update_reached_depth(&self, reached_depth: usize) {
2441 self.depth >= reached_depth,
2442 "invoked `update_reached_depth` with something under this stack: \
2443 self.depth={} reached_depth={}",
2447 debug!(reached_depth, "update_reached_depth");
2449 while reached_depth < p.depth {
2450 debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
2451 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2452 p = p.previous.head.unwrap();
2457 /// The "provisional evaluation cache" is used to store intermediate cache results
2458 /// when solving auto traits. Auto traits are unusual in that they can support
2459 /// cycles. So, for example, a "proof tree" like this would be ok:
2461 /// - `Foo<T>: Send` :-
2462 /// - `Bar<T>: Send` :-
2463 /// - `Foo<T>: Send` -- cycle, but ok
2464 /// - `Baz<T>: Send`
2466 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2467 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2468 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2469 /// they are coinductive) it is considered ok.
2471 /// However, there is a complication: at the point where we have
2472 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2473 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2474 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2475 /// find out this assumption is wrong? Specifically, we could
2476 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2477 /// `Bar<T>: Send` didn't turn out to be true.
2479 /// In Issue #60010, we found a bug in rustc where it would cache
2480 /// these intermediate results. This was fixed in #60444 by disabling
2481 /// *all* caching for things involved in a cycle -- in our example,
2482 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2483 /// to large slowdowns.
2485 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2486 /// first requires proving `Bar<T>: Send` (which is true:
2488 /// - `Foo<T>: Send` :-
2489 /// - `Bar<T>: Send` :-
2490 /// - `Foo<T>: Send` -- cycle, but ok
2491 /// - `Baz<T>: Send`
2492 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2493 /// - `*const T: Send` -- but what if we later encounter an error?
2495 /// The *provisional evaluation cache* resolves this issue. It stores
2496 /// cache results that we've proven but which were involved in a cycle
2497 /// in some way. We track the minimal stack depth (i.e., the
2498 /// farthest from the top of the stack) that we are dependent on.
2499 /// The idea is that the cache results within are all valid -- so long as
2500 /// none of the nodes in between the current node and the node at that minimum
2501 /// depth result in an error (in which case the cached results are just thrown away).
2503 /// During evaluation, we consult this provisional cache and rely on
2504 /// it. Accessing a cached value is considered equivalent to accessing
2505 /// a result at `reached_depth`, so it marks the *current* solution as
2506 /// provisional as well. If an error is encountered, we toss out any
2507 /// provisional results added from the subtree that encountered the
2508 /// error. When we pop the node at `reached_depth` from the stack, we
2509 /// can commit all the things that remain in the provisional cache.
2510 struct ProvisionalEvaluationCache<'tcx> {
2511 /// next "depth first number" to issue -- just a counter
2514 /// Map from cache key to the provisionally evaluated thing.
2515 /// The cache entries contain the result but also the DFN in which they
2516 /// were added. The DFN is used to clear out values on failure.
2518 /// Imagine we have a stack like:
2520 /// - `A B C` and we add a cache for the result of C (DFN 2)
2521 /// - Then we have a stack `A B D` where `D` has DFN 3
2522 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2523 /// - `E` generates various cache entries which have cyclic dependices on `B`
2524 /// - `A B D E F` and so forth
2525 /// - the DFN of `F` for example would be 5
2526 /// - then we determine that `E` is in error -- we will then clear
2527 /// all cache values whose DFN is >= 4 -- in this case, that
2528 /// means the cached value for `F`.
2529 map: RefCell<FxHashMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
2532 /// A cache value for the provisional cache: contains the depth-first
2533 /// number (DFN) and result.
2534 #[derive(Copy, Clone, Debug)]
2535 struct ProvisionalEvaluation {
2537 reached_depth: usize,
2538 result: EvaluationResult,
2539 /// The `DepNodeIndex` created for the `evaluate_stack` call for this provisional
2540 /// evaluation. When we create an entry in the evaluation cache using this provisional
2541 /// cache entry (see `on_completion`), we use this `dep_node` to ensure that future reads from
2542 /// the cache will have all of the necessary incr comp dependencies tracked.
2543 dep_node: DepNodeIndex,
2546 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2547 fn default() -> Self {
2548 Self { dfn: Cell::new(0), map: Default::default() }
2552 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2553 /// Get the next DFN in sequence (basically a counter).
2554 fn next_dfn(&self) -> usize {
2555 let result = self.dfn.get();
2556 self.dfn.set(result + 1);
2560 /// Check the provisional cache for any result for
2561 /// `fresh_trait_ref`. If there is a hit, then you must consider
2562 /// it an access to the stack slots at depth
2563 /// `reached_depth` (from the returned value).
2566 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2567 ) -> Option<ProvisionalEvaluation> {
2570 "get_provisional = {:#?}",
2571 self.map.borrow().get(&fresh_trait_pred),
2573 Some(*self.map.borrow().get(&fresh_trait_pred)?)
2576 /// Insert a provisional result into the cache. The result came
2577 /// from the node with the given DFN. It accessed a minimum depth
2578 /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
2579 /// and resulted in `result`.
2580 fn insert_provisional(
2583 reached_depth: usize,
2584 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2585 result: EvaluationResult,
2586 dep_node: DepNodeIndex,
2588 debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
2590 let mut map = self.map.borrow_mut();
2592 // Subtle: when we complete working on the DFN `from_dfn`, anything
2593 // that remains in the provisional cache must be dependent on some older
2594 // stack entry than `from_dfn`. We have to update their depth with our transitive
2595 // depth in that case or else it would be referring to some popped note.
2598 // A (reached depth 0)
2600 // B // depth 1 -- reached depth = 0
2601 // C // depth 2 -- reached depth = 1 (should be 0)
2604 // D (reached depth 1)
2605 // C (cache -- reached depth = 2)
2606 for (_k, v) in &mut *map {
2607 if v.from_dfn >= from_dfn {
2608 v.reached_depth = reached_depth.min(v.reached_depth);
2614 ProvisionalEvaluation { from_dfn, reached_depth, result, dep_node },
2618 /// Invoked when the node with dfn `dfn` does not get a successful
2619 /// result. This will clear out any provisional cache entries
2620 /// that were added since `dfn` was created. This is because the
2621 /// provisional entries are things which must assume that the
2622 /// things on the stack at the time of their creation succeeded --
2623 /// since the failing node is presently at the top of the stack,
2624 /// these provisional entries must either depend on it or some
2626 fn on_failure(&self, dfn: usize) {
2627 debug!(?dfn, "on_failure");
2628 self.map.borrow_mut().retain(|key, eval| {
2629 if !eval.from_dfn >= dfn {
2630 debug!("on_failure: removing {:?}", key);
2638 /// Invoked when the node at depth `depth` completed without
2639 /// depending on anything higher in the stack (if that completion
2640 /// was a failure, then `on_failure` should have been invoked
2641 /// already). The callback `op` will be invoked for each
2642 /// provisional entry that we can now confirm.
2644 /// Note that we may still have provisional cache items remaining
2645 /// in the cache when this is done. For example, if there is a
2648 /// * A depends on...
2649 /// * B depends on A
2650 /// * C depends on...
2651 /// * D depends on C
2654 /// Then as we complete the C node we will have a provisional cache
2655 /// with results for A, B, C, and D. This method would clear out
2656 /// the C and D results, but leave A and B provisional.
2658 /// This is determined based on the DFN: we remove any provisional
2659 /// results created since `dfn` started (e.g., in our example, dfn
2660 /// would be 2, representing the C node, and hence we would
2661 /// remove the result for D, which has DFN 3, but not the results for
2662 /// A and B, which have DFNs 0 and 1 respectively).
2666 mut op: impl FnMut(ty::PolyTraitPredicate<'tcx>, EvaluationResult, DepNodeIndex),
2668 debug!(?dfn, "on_completion");
2670 for (fresh_trait_pred, eval) in
2671 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2673 debug!(?fresh_trait_pred, ?eval, "on_completion");
2675 op(fresh_trait_pred, eval.result, eval.dep_node);
2680 #[derive(Copy, Clone)]
2681 struct TraitObligationStackList<'o, 'tcx> {
2682 cache: &'o ProvisionalEvaluationCache<'tcx>,
2683 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2686 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2687 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2688 TraitObligationStackList { cache, head: None }
2691 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2692 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2695 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2699 fn depth(&self) -> usize {
2700 if let Some(head) = self.head { head.depth } else { 0 }
2704 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2705 type Item = &'o TraitObligationStack<'o, 'tcx>;
2707 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2714 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2715 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2716 write!(f, "TraitObligationStack({:?})", self.obligation)