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};
17 DerivedObligationCause, ErrorReporting, ImplDerivedObligation, ImplDerivedObligationCause,
18 Normalized, Obligation, ObligationCause, ObligationCauseCode, Overflow, PredicateObligation,
19 Selection, SelectionError, SelectionResult, TraitObligation, TraitQueryMode,
22 use crate::infer::{InferCtxt, InferOk, TypeFreshener};
23 use crate::traits::error_reporting::InferCtxtExt;
24 use crate::traits::project::ProjectAndUnifyResult;
25 use crate::traits::project::ProjectionCacheKeyExt;
26 use crate::traits::ProjectionCacheKey;
27 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
28 use rustc_data_structures::stack::ensure_sufficient_stack;
29 use rustc_errors::{Diagnostic, ErrorGuaranteed};
31 use rustc_hir::def_id::DefId;
32 use rustc_infer::infer::LateBoundRegionConversionTime;
33 use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
34 use rustc_middle::mir::interpret::ErrorHandled;
35 use rustc_middle::thir::abstract_const::NotConstEvaluatable;
36 use rustc_middle::ty::fast_reject::{self, TreatParams};
37 use rustc_middle::ty::fold::BottomUpFolder;
38 use rustc_middle::ty::print::with_no_trimmed_paths;
39 use rustc_middle::ty::relate::TypeRelation;
40 use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef};
41 use rustc_middle::ty::{self, EarlyBinder, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate};
42 use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable};
43 use rustc_span::symbol::sym;
45 use std::cell::{Cell, RefCell};
47 use std::fmt::{self, Display};
50 pub use rustc_middle::traits::select::*;
52 mod candidate_assembly;
55 #[derive(Clone, Debug)]
56 pub enum IntercrateAmbiguityCause {
57 DownstreamCrate { trait_desc: String, self_desc: Option<String> },
58 UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
59 ReservationImpl { message: String },
62 impl IntercrateAmbiguityCause {
63 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
64 /// See #23980 for details.
65 pub fn add_intercrate_ambiguity_hint(&self, err: &mut Diagnostic) {
66 err.note(&self.intercrate_ambiguity_hint());
69 pub fn intercrate_ambiguity_hint(&self) -> String {
71 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } => {
72 let self_desc = if let Some(ty) = self_desc {
73 format!(" for type `{}`", ty)
77 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
79 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc } => {
80 let self_desc = if let Some(ty) = self_desc {
81 format!(" for type `{}`", ty)
86 "upstream crates may add a new impl of trait `{}`{} \
91 IntercrateAmbiguityCause::ReservationImpl { message } => message.clone(),
96 pub struct SelectionContext<'cx, 'tcx> {
97 infcx: &'cx InferCtxt<'cx, 'tcx>,
99 /// Freshener used specifically for entries on the obligation
100 /// stack. This ensures that all entries on the stack at one time
101 /// will have the same set of placeholder entries, which is
102 /// important for checking for trait bounds that recursively
103 /// require themselves.
104 freshener: TypeFreshener<'cx, 'tcx>,
106 /// If `true`, indicates that the evaluation should be conservative
107 /// and consider the possibility of types outside this crate.
108 /// This comes up primarily when resolving ambiguity. Imagine
109 /// there is some trait reference `$0: Bar` where `$0` is an
110 /// inference variable. If `intercrate` is true, then we can never
111 /// say for sure that this reference is not implemented, even if
112 /// there are *no impls at all for `Bar`*, because `$0` could be
113 /// bound to some type that in a downstream crate that implements
114 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
115 /// though, we set this to false, because we are only interested
116 /// in types that the user could actually have written --- in
117 /// other words, we consider `$0: Bar` to be unimplemented if
118 /// there is no type that the user could *actually name* that
119 /// would satisfy it. This avoids crippling inference, basically.
122 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
124 /// The mode that trait queries run in, which informs our error handling
125 /// policy. In essence, canonicalized queries need their errors propagated
126 /// rather than immediately reported because we do not have accurate spans.
127 query_mode: TraitQueryMode,
130 // A stack that walks back up the stack frame.
131 struct TraitObligationStack<'prev, 'tcx> {
132 obligation: &'prev TraitObligation<'tcx>,
134 /// The trait predicate from `obligation` but "freshened" with the
135 /// selection-context's freshener. Used to check for recursion.
136 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
138 /// Starts out equal to `depth` -- if, during evaluation, we
139 /// encounter a cycle, then we will set this flag to the minimum
140 /// depth of that cycle for all participants in the cycle. These
141 /// participants will then forego caching their results. This is
142 /// not the most efficient solution, but it addresses #60010. The
143 /// problem we are trying to prevent:
145 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
146 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
147 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
149 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
150 /// is `EvaluatedToOk`; this is because they were only considered
151 /// ok on the premise that if `A: AutoTrait` held, but we indeed
152 /// encountered a problem (later on) with `A: AutoTrait. So we
153 /// currently set a flag on the stack node for `B: AutoTrait` (as
154 /// well as the second instance of `A: AutoTrait`) to suppress
157 /// This is a simple, targeted fix. A more-performant fix requires
158 /// deeper changes, but would permit more caching: we could
159 /// basically defer caching until we have fully evaluated the
160 /// tree, and then cache the entire tree at once. In any case, the
161 /// performance impact here shouldn't be so horrible: every time
162 /// this is hit, we do cache at least one trait, so we only
163 /// evaluate each member of a cycle up to N times, where N is the
164 /// length of the cycle. This means the performance impact is
165 /// bounded and we shouldn't have any terrible worst-cases.
166 reached_depth: Cell<usize>,
168 previous: TraitObligationStackList<'prev, 'tcx>,
170 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
173 /// The depth-first number of this node in the search graph -- a
174 /// pre-order index. Basically, a freshly incremented counter.
178 struct SelectionCandidateSet<'tcx> {
179 // A list of candidates that definitely apply to the current
180 // obligation (meaning: types unify).
181 vec: Vec<SelectionCandidate<'tcx>>,
183 // If `true`, then there were candidates that might or might
184 // not have applied, but we couldn't tell. This occurs when some
185 // of the input types are type variables, in which case there are
186 // various "builtin" rules that might or might not trigger.
190 #[derive(PartialEq, Eq, Debug, Clone)]
191 struct EvaluatedCandidate<'tcx> {
192 candidate: SelectionCandidate<'tcx>,
193 evaluation: EvaluationResult,
196 /// When does the builtin impl for `T: Trait` apply?
198 enum BuiltinImplConditions<'tcx> {
199 /// The impl is conditional on `T1, T2, ...: Trait`.
200 Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
201 /// There is no built-in impl. There may be some other
202 /// candidate (a where-clause or user-defined impl).
204 /// It is unknown whether there is an impl.
208 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
209 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
212 freshener: infcx.freshener_keep_static(),
214 intercrate_ambiguity_causes: None,
215 query_mode: TraitQueryMode::Standard,
219 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
222 freshener: infcx.freshener_keep_static(),
224 intercrate_ambiguity_causes: None,
225 query_mode: TraitQueryMode::Standard,
229 pub fn with_query_mode(
230 infcx: &'cx InferCtxt<'cx, 'tcx>,
231 query_mode: TraitQueryMode,
232 ) -> SelectionContext<'cx, 'tcx> {
233 debug!(?query_mode, "with_query_mode");
236 freshener: infcx.freshener_keep_static(),
238 intercrate_ambiguity_causes: None,
243 /// Enables tracking of intercrate ambiguity causes. These are
244 /// used in coherence to give improved diagnostics. We don't do
245 /// this until we detect a coherence error because it can lead to
246 /// false overflow results (#47139) and because it costs
247 /// computation time.
248 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
249 assert!(self.intercrate);
250 assert!(self.intercrate_ambiguity_causes.is_none());
251 self.intercrate_ambiguity_causes = Some(vec![]);
252 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
255 /// Gets the intercrate ambiguity causes collected since tracking
256 /// was enabled and disables tracking at the same time. If
257 /// tracking is not enabled, just returns an empty vector.
258 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
259 assert!(self.intercrate);
260 self.intercrate_ambiguity_causes.take().unwrap_or_default()
263 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
267 pub fn tcx(&self) -> TyCtxt<'tcx> {
271 pub fn is_intercrate(&self) -> bool {
275 ///////////////////////////////////////////////////////////////////////////
278 // The selection phase tries to identify *how* an obligation will
279 // be resolved. For example, it will identify which impl or
280 // parameter bound is to be used. The process can be inconclusive
281 // if the self type in the obligation is not fully inferred. Selection
282 // can result in an error in one of two ways:
284 // 1. If no applicable impl or parameter bound can be found.
285 // 2. If the output type parameters in the obligation do not match
286 // those specified by the impl/bound. For example, if the obligation
287 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
288 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
290 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
291 /// type environment by performing unification.
292 #[instrument(level = "debug", skip(self))]
295 obligation: &TraitObligation<'tcx>,
296 ) -> SelectionResult<'tcx, Selection<'tcx>> {
297 let candidate = match self.select_from_obligation(obligation) {
298 Err(SelectionError::Overflow(OverflowError::Canonical)) => {
299 // In standard mode, overflow must have been caught and reported
301 assert!(self.query_mode == TraitQueryMode::Canonical);
302 return Err(SelectionError::Overflow(OverflowError::Canonical));
304 Err(SelectionError::Ambiguous(_)) => {
313 Ok(Some(candidate)) => candidate,
316 match self.confirm_candidate(obligation, candidate) {
317 Err(SelectionError::Overflow(OverflowError::Canonical)) => {
318 assert!(self.query_mode == TraitQueryMode::Canonical);
319 Err(SelectionError::Overflow(OverflowError::Canonical))
323 debug!(?candidate, "confirmed");
329 crate fn select_from_obligation(
331 obligation: &TraitObligation<'tcx>,
332 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
333 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
335 let pec = &ProvisionalEvaluationCache::default();
336 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
338 self.candidate_from_obligation(&stack)
341 ///////////////////////////////////////////////////////////////////////////
344 // Tests whether an obligation can be selected or whether an impl
345 // can be applied to particular types. It skips the "confirmation"
346 // step and hence completely ignores output type parameters.
348 // The result is "true" if the obligation *may* hold and "false" if
349 // we can be sure it does not.
351 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
352 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
353 debug!(?obligation, "predicate_may_hold_fatal");
355 // This fatal query is a stopgap that should only be used in standard mode,
356 // where we do not expect overflow to be propagated.
357 assert!(self.query_mode == TraitQueryMode::Standard);
359 self.evaluate_root_obligation(obligation)
360 .expect("Overflow should be caught earlier in standard query mode")
364 /// Evaluates whether the obligation `obligation` can be satisfied
365 /// and returns an `EvaluationResult`. This is meant for the
367 pub fn evaluate_root_obligation(
369 obligation: &PredicateObligation<'tcx>,
370 ) -> Result<EvaluationResult, OverflowError> {
371 self.evaluation_probe(|this| {
372 this.evaluate_predicate_recursively(
373 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
381 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
382 ) -> Result<EvaluationResult, OverflowError> {
383 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
384 let result = op(self)?;
386 match self.infcx.leak_check(true, snapshot) {
388 Err(_) => return Ok(EvaluatedToErr),
391 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
393 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
398 /// Evaluates the predicates in `predicates` recursively. Note that
399 /// this applies projections in the predicates, and therefore
400 /// is run within an inference probe.
401 #[instrument(skip(self, stack), level = "debug")]
402 fn evaluate_predicates_recursively<'o, I>(
404 stack: TraitObligationStackList<'o, 'tcx>,
406 ) -> Result<EvaluationResult, OverflowError>
408 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
410 let mut result = EvaluatedToOk;
411 for obligation in predicates {
412 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
413 if let EvaluatedToErr = eval {
414 // fast-path - EvaluatedToErr is the top of the lattice,
415 // so we don't need to look on the other predicates.
416 return Ok(EvaluatedToErr);
418 result = cmp::max(result, eval);
426 skip(self, previous_stack),
427 fields(previous_stack = ?previous_stack.head())
429 fn evaluate_predicate_recursively<'o>(
431 previous_stack: TraitObligationStackList<'o, 'tcx>,
432 obligation: PredicateObligation<'tcx>,
433 ) -> Result<EvaluationResult, OverflowError> {
434 // `previous_stack` stores a `TraitObligation`, while `obligation` is
435 // a `PredicateObligation`. These are distinct types, so we can't
436 // use any `Option` combinator method that would force them to be
438 match previous_stack.head() {
439 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
440 None => self.check_recursion_limit(&obligation, &obligation)?,
443 let result = ensure_sufficient_stack(|| {
444 let bound_predicate = obligation.predicate.kind();
445 match bound_predicate.skip_binder() {
446 ty::PredicateKind::Trait(t) => {
447 let t = bound_predicate.rebind(t);
448 debug_assert!(!t.has_escaping_bound_vars());
449 let obligation = obligation.with(t);
450 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
453 ty::PredicateKind::Subtype(p) => {
454 let p = bound_predicate.rebind(p);
455 // Does this code ever run?
456 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
457 Some(Ok(InferOk { mut obligations, .. })) => {
458 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
459 self.evaluate_predicates_recursively(
461 obligations.into_iter(),
464 Some(Err(_)) => Ok(EvaluatedToErr),
465 None => Ok(EvaluatedToAmbig),
469 ty::PredicateKind::Coerce(p) => {
470 let p = bound_predicate.rebind(p);
471 // Does this code ever run?
472 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
473 Some(Ok(InferOk { mut obligations, .. })) => {
474 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
475 self.evaluate_predicates_recursively(
477 obligations.into_iter(),
480 Some(Err(_)) => Ok(EvaluatedToErr),
481 None => Ok(EvaluatedToAmbig),
485 ty::PredicateKind::WellFormed(arg) => match wf::obligations(
487 obligation.param_env,
488 obligation.cause.body_id,
489 obligation.recursion_depth + 1,
491 obligation.cause.span,
493 Some(mut obligations) => {
494 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
495 self.evaluate_predicates_recursively(previous_stack, obligations)
497 None => Ok(EvaluatedToAmbig),
500 ty::PredicateKind::TypeOutlives(pred) => {
501 // A global type with no late-bound regions can only
502 // contain the "'static" lifetime (any other lifetime
503 // would either be late-bound or local), so it is guaranteed
504 // to outlive any other lifetime
505 if pred.0.is_global() && !pred.0.has_late_bound_regions() {
508 Ok(EvaluatedToOkModuloRegions)
512 ty::PredicateKind::RegionOutlives(..) => {
513 // We do not consider region relationships when evaluating trait matches.
514 Ok(EvaluatedToOkModuloRegions)
517 ty::PredicateKind::ObjectSafe(trait_def_id) => {
518 if self.tcx().is_object_safe(trait_def_id) {
525 ty::PredicateKind::Projection(data) => {
526 let data = bound_predicate.rebind(data);
527 let project_obligation = obligation.with(data);
528 match project::poly_project_and_unify_type(self, &project_obligation) {
529 ProjectAndUnifyResult::Holds(mut subobligations) => {
531 // If we've previously marked this projection as 'complete', then
532 // use the final cached result (either `EvaluatedToOk` or
533 // `EvaluatedToOkModuloRegions`), and skip re-evaluating the
536 ProjectionCacheKey::from_poly_projection_predicate(self, data)
538 if let Some(cached_res) = self
545 break 'compute_res Ok(cached_res);
550 subobligations.iter_mut(),
551 obligation.recursion_depth,
553 let res = self.evaluate_predicates_recursively(
557 if let Ok(eval_rslt) = res
558 && (eval_rslt == EvaluatedToOk || eval_rslt == EvaluatedToOkModuloRegions)
560 ProjectionCacheKey::from_poly_projection_predicate(
564 // If the result is something that we can cache, then mark this
565 // entry as 'complete'. This will allow us to skip evaluating the
566 // subobligations at all the next time we evaluate the projection
572 .complete(key, eval_rslt);
577 ProjectAndUnifyResult::FailedNormalization => Ok(EvaluatedToAmbig),
578 ProjectAndUnifyResult::Recursive => Ok(EvaluatedToRecur),
579 ProjectAndUnifyResult::MismatchedProjectionTypes(_) => Ok(EvaluatedToErr),
583 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
584 match self.infcx.closure_kind(closure_substs) {
585 Some(closure_kind) => {
586 if closure_kind.extends(kind) {
592 None => Ok(EvaluatedToAmbig),
596 ty::PredicateKind::ConstEvaluatable(uv) => {
597 match const_evaluatable::is_const_evaluatable(
600 obligation.param_env,
601 obligation.cause.span,
603 Ok(()) => Ok(EvaluatedToOk),
604 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
605 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
606 Err(_) => Ok(EvaluatedToErr),
610 ty::PredicateKind::ConstEquate(c1, c2) => {
611 debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
613 if self.tcx().features().generic_const_exprs {
614 // FIXME: we probably should only try to unify abstract constants
615 // if the constants depend on generic parameters.
617 // Let's just see where this breaks :shrug:
618 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
621 if self.infcx.try_unify_abstract_consts(
624 obligation.param_env,
626 return Ok(EvaluatedToOk);
631 let evaluate = |c: ty::Const<'tcx>| {
632 if let ty::ConstKind::Unevaluated(unevaluated) = c.val() {
635 obligation.param_env,
637 Some(obligation.cause.span),
639 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty()))
645 match (evaluate(c1), evaluate(c2)) {
646 (Ok(c1), Ok(c2)) => {
649 .at(&obligation.cause, obligation.param_env)
652 Ok(_) => Ok(EvaluatedToOk),
653 Err(_) => Ok(EvaluatedToErr),
656 (Err(ErrorHandled::Reported(_)), _)
657 | (_, Err(ErrorHandled::Reported(_))) => Ok(EvaluatedToErr),
658 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
660 obligation.cause.span(self.tcx()),
661 "ConstEquate: const_eval_resolve returned an unexpected error"
664 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
665 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
668 // Two different constants using generic parameters ~> error.
674 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
675 bug!("TypeWellFormedFromEnv is only used for chalk")
680 debug!("finished: {:?} from {:?}", result, obligation);
685 #[instrument(skip(self, previous_stack), level = "debug")]
686 fn evaluate_trait_predicate_recursively<'o>(
688 previous_stack: TraitObligationStackList<'o, 'tcx>,
689 mut obligation: TraitObligation<'tcx>,
690 ) -> Result<EvaluationResult, OverflowError> {
692 && obligation.is_global()
693 && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst())
695 // If a param env has no global bounds, global obligations do not
696 // depend on its particular value in order to work, so we can clear
697 // out the param env and get better caching.
699 obligation.param_env = obligation.param_env.without_caller_bounds();
702 let stack = self.push_stack(previous_stack, &obligation);
703 let mut fresh_trait_pred = stack.fresh_trait_pred;
704 let mut param_env = obligation.param_env;
706 fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| {
707 pred.remap_constness(self.tcx(), &mut param_env);
711 debug!(?fresh_trait_pred);
713 if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
714 debug!(?result, "CACHE HIT");
718 if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
719 debug!(?result, "PROVISIONAL CACHE HIT");
720 stack.update_reached_depth(result.reached_depth);
721 return Ok(result.result);
724 // Check if this is a match for something already on the
725 // stack. If so, we don't want to insert the result into the
726 // main cache (it is cycle dependent) nor the provisional
727 // cache (which is meant for things that have completed but
728 // for a "backedge" -- this result *is* the backedge).
729 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
730 return Ok(cycle_result);
733 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
734 let result = result?;
736 if !result.must_apply_modulo_regions() {
737 stack.cache().on_failure(stack.dfn);
740 let reached_depth = stack.reached_depth.get();
741 if reached_depth >= stack.depth {
742 debug!(?result, "CACHE MISS");
743 self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
744 stack.cache().on_completion(stack.dfn);
746 debug!(?result, "PROVISIONAL");
748 "caching provisionally because {:?} \
749 is a cycle participant (at depth {}, reached depth {})",
750 fresh_trait_pred, stack.depth, reached_depth,
753 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_pred, result);
759 /// If there is any previous entry on the stack that precisely
760 /// matches this obligation, then we can assume that the
761 /// obligation is satisfied for now (still all other conditions
762 /// must be met of course). One obvious case this comes up is
763 /// marker traits like `Send`. Think of a linked list:
765 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
767 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
768 /// `Option<Box<List<T>>>` is `Send`, and in turn
769 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
772 /// Note that we do this comparison using the `fresh_trait_ref`
773 /// fields. Because these have all been freshened using
774 /// `self.freshener`, we can be sure that (a) this will not
775 /// affect the inferencer state and (b) that if we see two
776 /// fresh regions with the same index, they refer to the same
777 /// unbound type variable.
778 fn check_evaluation_cycle(
780 stack: &TraitObligationStack<'_, 'tcx>,
781 ) -> Option<EvaluationResult> {
782 if let Some(cycle_depth) = stack
784 .skip(1) // Skip top-most frame.
786 stack.obligation.param_env == prev.obligation.param_env
787 && stack.fresh_trait_pred == prev.fresh_trait_pred
789 .map(|stack| stack.depth)
791 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
793 // If we have a stack like `A B C D E A`, where the top of
794 // the stack is the final `A`, then this will iterate over
795 // `A, E, D, C, B` -- i.e., all the participants apart
796 // from the cycle head. We mark them as participating in a
797 // cycle. This suppresses caching for those nodes. See
798 // `in_cycle` field for more details.
799 stack.update_reached_depth(cycle_depth);
801 // Subtle: when checking for a coinductive cycle, we do
802 // not compare using the "freshened trait refs" (which
803 // have erased regions) but rather the fully explicit
804 // trait refs. This is important because it's only a cycle
805 // if the regions match exactly.
806 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
807 let tcx = self.tcx();
808 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
809 if self.coinductive_match(cycle) {
810 debug!("evaluate_stack --> recursive, coinductive");
813 debug!("evaluate_stack --> recursive, inductive");
814 Some(EvaluatedToRecur)
821 fn evaluate_stack<'o>(
823 stack: &TraitObligationStack<'o, 'tcx>,
824 ) -> Result<EvaluationResult, OverflowError> {
825 // In intercrate mode, whenever any of the generics are unbound,
826 // there can always be an impl. Even if there are no impls in
827 // this crate, perhaps the type would be unified with
828 // something from another crate that does provide an impl.
830 // In intra mode, we must still be conservative. The reason is
831 // that we want to avoid cycles. Imagine an impl like:
833 // impl<T:Eq> Eq for Vec<T>
835 // and a trait reference like `$0 : Eq` where `$0` is an
836 // unbound variable. When we evaluate this trait-reference, we
837 // will unify `$0` with `Vec<$1>` (for some fresh variable
838 // `$1`), on the condition that `$1 : Eq`. We will then wind
839 // up with many candidates (since that are other `Eq` impls
840 // that apply) and try to winnow things down. This results in
841 // a recursive evaluation that `$1 : Eq` -- as you can
842 // imagine, this is just where we started. To avoid that, we
843 // check for unbound variables and return an ambiguous (hence possible)
844 // match if we've seen this trait before.
846 // This suffices to allow chains like `FnMut` implemented in
847 // terms of `Fn` etc, but we could probably make this more
849 let unbound_input_types =
850 stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh());
852 if stack.obligation.polarity() != ty::ImplPolarity::Negative {
853 // This check was an imperfect workaround for a bug in the old
854 // intercrate mode; it should be removed when that goes away.
855 if unbound_input_types && self.intercrate {
856 debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
857 // Heuristics: show the diagnostics when there are no candidates in crate.
858 if self.intercrate_ambiguity_causes.is_some() {
859 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
860 if let Ok(candidate_set) = self.assemble_candidates(stack) {
861 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
862 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
863 let self_ty = trait_ref.self_ty();
864 let cause = with_no_trimmed_paths!({
865 IntercrateAmbiguityCause::DownstreamCrate {
866 trait_desc: trait_ref.print_only_trait_path().to_string(),
867 self_desc: if self_ty.has_concrete_skeleton() {
868 Some(self_ty.to_string())
875 debug!(?cause, "evaluate_stack: pushing cause");
876 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
880 return Ok(EvaluatedToAmbig);
884 if unbound_input_types
885 && stack.iter().skip(1).any(|prev| {
886 stack.obligation.param_env == prev.obligation.param_env
887 && self.match_fresh_trait_refs(
888 stack.fresh_trait_pred,
889 prev.fresh_trait_pred,
890 prev.obligation.param_env,
894 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
895 return Ok(EvaluatedToUnknown);
898 match self.candidate_from_obligation(stack) {
899 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
900 Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig),
901 Ok(None) => Ok(EvaluatedToAmbig),
902 Err(Overflow(OverflowError::Canonical)) => Err(OverflowError::Canonical),
903 Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
904 Err(..) => Ok(EvaluatedToErr),
908 /// For defaulted traits, we use a co-inductive strategy to solve, so
909 /// that recursion is ok. This routine returns `true` if the top of the
910 /// stack (`cycle[0]`):
912 /// - is a defaulted trait,
913 /// - it also appears in the backtrace at some position `X`,
914 /// - all the predicates at positions `X..` between `X` and the top are
915 /// also defaulted traits.
916 pub fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
918 I: Iterator<Item = ty::Predicate<'tcx>>,
920 cycle.all(|predicate| self.coinductive_predicate(predicate))
923 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
924 let result = match predicate.kind().skip_binder() {
925 ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
928 debug!(?predicate, ?result, "coinductive_predicate");
932 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
933 /// obligations are met. Returns whether `candidate` remains viable after this further
938 fields(depth = stack.obligation.recursion_depth)
940 fn evaluate_candidate<'o>(
942 stack: &TraitObligationStack<'o, 'tcx>,
943 candidate: &SelectionCandidate<'tcx>,
944 ) -> Result<EvaluationResult, OverflowError> {
945 let mut result = self.evaluation_probe(|this| {
946 let candidate = (*candidate).clone();
947 match this.confirm_candidate(stack.obligation, candidate) {
950 this.evaluate_predicates_recursively(
952 selection.nested_obligations().into_iter(),
955 Err(..) => Ok(EvaluatedToErr),
959 // If we erased any lifetimes, then we want to use
960 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
961 // as your final result. The result will be cached using
962 // the freshened trait predicate as a key, so we need
963 // our result to be correct by *any* choice of original lifetimes,
964 // not just the lifetime choice for this particular (non-erased)
967 if stack.fresh_trait_pred.has_erased_regions() {
968 result = result.max(EvaluatedToOkModuloRegions);
975 fn check_evaluation_cache(
977 param_env: ty::ParamEnv<'tcx>,
978 trait_pred: ty::PolyTraitPredicate<'tcx>,
979 ) -> Option<EvaluationResult> {
980 // Neither the global nor local cache is aware of intercrate
981 // mode, so don't do any caching. In particular, we might
982 // re-use the same `InferCtxt` with both an intercrate
983 // and non-intercrate `SelectionContext`
988 let tcx = self.tcx();
989 if self.can_use_global_caches(param_env) {
990 if let Some(res) = tcx.evaluation_cache.get(&(param_env, trait_pred), tcx) {
994 self.infcx.evaluation_cache.get(&(param_env, trait_pred), tcx)
997 fn insert_evaluation_cache(
999 param_env: ty::ParamEnv<'tcx>,
1000 trait_pred: ty::PolyTraitPredicate<'tcx>,
1001 dep_node: DepNodeIndex,
1002 result: EvaluationResult,
1004 // Avoid caching results that depend on more than just the trait-ref
1005 // - the stack can create recursion.
1006 if result.is_stack_dependent() {
1010 // Neither the global nor local cache is aware of intercrate
1011 // mode, so don't do any caching. In particular, we might
1012 // re-use the same `InferCtxt` with both an intercrate
1013 // and non-intercrate `SelectionContext`
1014 if self.intercrate {
1018 if self.can_use_global_caches(param_env) {
1019 if !trait_pred.needs_infer() {
1020 debug!(?trait_pred, ?result, "insert_evaluation_cache global");
1021 // This may overwrite the cache with the same value
1022 // FIXME: Due to #50507 this overwrites the different values
1023 // This should be changed to use HashMapExt::insert_same
1024 // when that is fixed
1025 self.tcx().evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1030 debug!(?trait_pred, ?result, "insert_evaluation_cache");
1031 self.infcx.evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1034 /// For various reasons, it's possible for a subobligation
1035 /// to have a *lower* recursion_depth than the obligation used to create it.
1036 /// Projection sub-obligations may be returned from the projection cache,
1037 /// which results in obligations with an 'old' `recursion_depth`.
1038 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1039 /// subobligations without taking in a 'parent' depth, causing the
1040 /// generated subobligations to have a `recursion_depth` of `0`.
1042 /// To ensure that obligation_depth never decreases, we force all subobligations
1043 /// to have at least the depth of the original obligation.
1044 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1049 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1052 fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
1055 error_obligation: &Obligation<'tcx, T>,
1056 ) -> Result<(), OverflowError> {
1057 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1058 match self.query_mode {
1059 TraitQueryMode::Standard => {
1060 if self.infcx.is_tainted_by_errors() {
1061 return Err(OverflowError::Error(
1062 ErrorGuaranteed::unchecked_claim_error_was_emitted(),
1065 self.infcx.report_overflow_error(error_obligation, true);
1067 TraitQueryMode::Canonical => {
1068 return Err(OverflowError::Canonical);
1075 /// Checks that the recursion limit has not been exceeded.
1077 /// The weird return type of this function allows it to be used with the `try` (`?`)
1078 /// operator within certain functions.
1080 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1082 obligation: &Obligation<'tcx, T>,
1083 error_obligation: &Obligation<'tcx, V>,
1084 ) -> Result<(), OverflowError> {
1085 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1088 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1090 OP: FnOnce(&mut Self) -> R,
1092 let (result, dep_node) =
1093 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1094 self.tcx().dep_graph.read_index(dep_node);
1098 /// filter_impls filters constant trait obligations and candidates that have a positive impl
1099 /// for a negative goal and a negative impl for a positive goal
1100 #[instrument(level = "debug", skip(self))]
1103 candidates: Vec<SelectionCandidate<'tcx>>,
1104 obligation: &TraitObligation<'tcx>,
1105 ) -> Vec<SelectionCandidate<'tcx>> {
1106 let tcx = self.tcx();
1107 let mut result = Vec::with_capacity(candidates.len());
1109 for candidate in candidates {
1110 // Respect const trait obligations
1111 if obligation.is_const() {
1114 ImplCandidate(def_id)
1115 if tcx.impl_constness(def_id) == hir::Constness::Const => {}
1117 ParamCandidate(trait_pred) if trait_pred.is_const_if_const() => {}
1119 AutoImplCandidate(..) => {}
1120 // generator, this will raise error in other places
1121 // or ignore error with const_async_blocks feature
1122 GeneratorCandidate => {}
1123 // FnDef where the function is const
1124 FnPointerCandidate { is_const: true } => {}
1125 ConstDestructCandidate(_) => {}
1127 // reject all other types of candidates
1133 if let ImplCandidate(def_id) = candidate {
1134 if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id)
1135 || obligation.polarity() == tcx.impl_polarity(def_id)
1137 result.push(candidate);
1140 result.push(candidate);
1147 /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1148 #[instrument(level = "debug", skip(self))]
1149 fn filter_reservation_impls(
1151 candidate: SelectionCandidate<'tcx>,
1152 obligation: &TraitObligation<'tcx>,
1153 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1154 let tcx = self.tcx();
1155 // Treat reservation impls as ambiguity.
1156 if let ImplCandidate(def_id) = candidate {
1157 if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
1158 if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1159 let attrs = tcx.get_attrs(def_id);
1160 let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
1161 let value = attr.and_then(|a| a.value_str());
1162 if let Some(value) = value {
1164 "filter_reservation_impls: \
1165 reservation impl ambiguity on {:?}",
1168 intercrate_ambiguity_clauses.push(
1169 IntercrateAmbiguityCause::ReservationImpl {
1170 message: value.to_string(),
1181 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1182 debug!("is_knowable(intercrate={:?})", self.intercrate);
1184 if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative {
1188 let obligation = &stack.obligation;
1189 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1191 // Okay to skip binder because of the nature of the
1192 // trait-ref-is-knowable check, which does not care about
1194 let trait_ref = predicate.skip_binder().trait_ref;
1196 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1199 /// Returns `true` if the global caches can be used.
1200 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1201 // If there are any inference variables in the `ParamEnv`, then we
1202 // always use a cache local to this particular scope. Otherwise, we
1203 // switch to a global cache.
1204 if param_env.needs_infer() {
1208 // Avoid using the master cache during coherence and just rely
1209 // on the local cache. This effectively disables caching
1210 // during coherence. It is really just a simplification to
1211 // avoid us having to fear that coherence results "pollute"
1212 // the master cache. Since coherence executes pretty quickly,
1213 // it's not worth going to more trouble to increase the
1214 // hit-rate, I don't think.
1215 if self.intercrate {
1219 // Otherwise, we can use the global cache.
1223 fn check_candidate_cache(
1225 mut param_env: ty::ParamEnv<'tcx>,
1226 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1227 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1228 // Neither the global nor local cache is aware of intercrate
1229 // mode, so don't do any caching. In particular, we might
1230 // re-use the same `InferCtxt` with both an intercrate
1231 // and non-intercrate `SelectionContext`
1232 if self.intercrate {
1235 let tcx = self.tcx();
1236 let mut pred = cache_fresh_trait_pred.skip_binder();
1237 pred.remap_constness(tcx, &mut param_env);
1239 if self.can_use_global_caches(param_env) {
1240 if let Some(res) = tcx.selection_cache.get(&(param_env, pred), tcx) {
1244 self.infcx.selection_cache.get(&(param_env, pred), tcx)
1247 /// Determines whether can we safely cache the result
1248 /// of selecting an obligation. This is almost always `true`,
1249 /// except when dealing with certain `ParamCandidate`s.
1251 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1252 /// since it was usually produced directly from a `DefId`. However,
1253 /// certain cases (currently only librustdoc's blanket impl finder),
1254 /// a `ParamEnv` may be explicitly constructed with inference types.
1255 /// When this is the case, we do *not* want to cache the resulting selection
1256 /// candidate. This is due to the fact that it might not always be possible
1257 /// to equate the obligation's trait ref and the candidate's trait ref,
1258 /// if more constraints end up getting added to an inference variable.
1260 /// Because of this, we always want to re-run the full selection
1261 /// process for our obligation the next time we see it, since
1262 /// we might end up picking a different `SelectionCandidate` (or none at all).
1263 fn can_cache_candidate(
1265 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1267 // Neither the global nor local cache is aware of intercrate
1268 // mode, so don't do any caching. In particular, we might
1269 // re-use the same `InferCtxt` with both an intercrate
1270 // and non-intercrate `SelectionContext`
1271 if self.intercrate {
1275 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1280 #[instrument(skip(self, param_env, cache_fresh_trait_pred, dep_node), level = "debug")]
1281 fn insert_candidate_cache(
1283 mut param_env: ty::ParamEnv<'tcx>,
1284 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1285 dep_node: DepNodeIndex,
1286 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1288 let tcx = self.tcx();
1289 let mut pred = cache_fresh_trait_pred.skip_binder();
1291 pred.remap_constness(tcx, &mut param_env);
1293 if !self.can_cache_candidate(&candidate) {
1294 debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1298 if self.can_use_global_caches(param_env) {
1299 if let Err(Overflow(OverflowError::Canonical)) = candidate {
1300 // Don't cache overflow globally; we only produce this in certain modes.
1301 } else if !pred.needs_infer() {
1302 if !candidate.needs_infer() {
1303 debug!(?pred, ?candidate, "insert_candidate_cache global");
1304 // This may overwrite the cache with the same value.
1305 tcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1311 debug!(?pred, ?candidate, "insert_candidate_cache local");
1312 self.infcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1315 /// Matches a predicate against the bounds of its self type.
1317 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1318 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1319 /// `Baz` bound. We return indexes into the list returned by
1320 /// `tcx.item_bounds` for any applicable bounds.
1321 #[instrument(level = "debug", skip(self))]
1322 fn match_projection_obligation_against_definition_bounds(
1324 obligation: &TraitObligation<'tcx>,
1325 ) -> smallvec::SmallVec<[usize; 2]> {
1326 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1327 let placeholder_trait_predicate =
1328 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1329 debug!(?placeholder_trait_predicate);
1331 let tcx = self.infcx.tcx;
1332 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1333 ty::Projection(ref data) => (data.item_def_id, data.substs),
1334 ty::Opaque(def_id, substs) => (def_id, substs),
1337 obligation.cause.span,
1338 "match_projection_obligation_against_definition_bounds() called \
1339 but self-ty is not a projection: {:?}",
1340 placeholder_trait_predicate.trait_ref.self_ty()
1344 let bounds = tcx.bound_item_bounds(def_id).subst(tcx, substs);
1346 // The bounds returned by `item_bounds` may contain duplicates after
1347 // normalization, so try to deduplicate when possible to avoid
1348 // unnecessary ambiguity.
1349 let mut distinct_normalized_bounds = FxHashSet::default();
1351 let matching_bounds = bounds
1354 .filter_map(|(idx, bound)| {
1355 let bound_predicate = bound.kind();
1356 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1357 let bound = bound_predicate.rebind(pred.trait_ref);
1358 if self.infcx.probe(|_| {
1359 match self.match_normalize_trait_ref(
1362 placeholder_trait_predicate.trait_ref,
1365 Ok(Some(normalized_trait))
1366 if distinct_normalized_bounds.insert(normalized_trait) =>
1380 debug!(?matching_bounds);
1384 /// Equates the trait in `obligation` with trait bound. If the two traits
1385 /// can be equated and the normalized trait bound doesn't contain inference
1386 /// variables or placeholders, the normalized bound is returned.
1387 fn match_normalize_trait_ref(
1389 obligation: &TraitObligation<'tcx>,
1390 trait_bound: ty::PolyTraitRef<'tcx>,
1391 placeholder_trait_ref: ty::TraitRef<'tcx>,
1392 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1393 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1394 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1395 // Avoid unnecessary normalization
1399 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1400 project::normalize_with_depth(
1402 obligation.param_env,
1403 obligation.cause.clone(),
1404 obligation.recursion_depth + 1,
1409 .at(&obligation.cause, obligation.param_env)
1410 .define_opaque_types(false)
1411 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1412 .map(|InferOk { obligations: _, value: () }| {
1413 // This method is called within a probe, so we can't have
1414 // inference variables and placeholders escape.
1415 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1424 fn where_clause_may_apply<'o>(
1426 stack: &TraitObligationStack<'o, 'tcx>,
1427 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1428 ) -> Result<EvaluationResult, OverflowError> {
1429 self.evaluation_probe(|this| {
1430 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1431 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1432 Err(()) => Ok(EvaluatedToErr),
1437 /// Return `Yes` if the obligation's predicate type applies to the env_predicate, and
1438 /// `No` if it does not. Return `Ambiguous` in the case that the projection type is a GAT,
1439 /// and applying this env_predicate constrains any of the obligation's GAT substitutions.
1441 /// This behavior is a somewhat of a hack to prevent over-constraining inference variables
1442 /// in cases like #91762.
1443 pub(super) fn match_projection_projections(
1445 obligation: &ProjectionTyObligation<'tcx>,
1446 env_predicate: PolyProjectionPredicate<'tcx>,
1447 potentially_unnormalized_candidates: bool,
1448 ) -> ProjectionMatchesProjection {
1449 let mut nested_obligations = Vec::new();
1450 let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars(
1451 obligation.cause.span,
1452 LateBoundRegionConversionTime::HigherRankedType,
1455 let infer_projection = if potentially_unnormalized_candidates {
1456 ensure_sufficient_stack(|| {
1457 project::normalize_with_depth_to(
1459 obligation.param_env,
1460 obligation.cause.clone(),
1461 obligation.recursion_depth + 1,
1462 infer_predicate.projection_ty,
1463 &mut nested_obligations,
1467 infer_predicate.projection_ty
1472 .at(&obligation.cause, obligation.param_env)
1473 .define_opaque_types(false)
1474 .sup(obligation.predicate, infer_projection)
1475 .map_or(false, |InferOk { obligations, value: () }| {
1476 self.evaluate_predicates_recursively(
1477 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1478 nested_obligations.into_iter().chain(obligations),
1480 .map_or(false, |res| res.may_apply())
1484 let generics = self.tcx().generics_of(obligation.predicate.item_def_id);
1485 // FIXME(generic-associated-types): Addresses aggressive inference in #92917.
1486 // If this type is a GAT, and of the GAT substs resolve to something new,
1487 // that means that we must have newly inferred something about the GAT.
1488 // We should give up in that case.
1489 if !generics.params.is_empty()
1490 && obligation.predicate.substs[generics.parent_count..]
1492 .any(|&p| p.has_infer_types_or_consts() && self.infcx.shallow_resolve(p) != p)
1494 ProjectionMatchesProjection::Ambiguous
1496 ProjectionMatchesProjection::Yes
1499 ProjectionMatchesProjection::No
1503 ///////////////////////////////////////////////////////////////////////////
1506 // Winnowing is the process of attempting to resolve ambiguity by
1507 // probing further. During the winnowing process, we unify all
1508 // type variables and then we also attempt to evaluate recursive
1509 // bounds to see if they are satisfied.
1511 /// Returns `true` if `victim` should be dropped in favor of
1512 /// `other`. Generally speaking we will drop duplicate
1513 /// candidates and prefer where-clause candidates.
1515 /// See the comment for "SelectionCandidate" for more details.
1516 fn candidate_should_be_dropped_in_favor_of(
1518 victim: &EvaluatedCandidate<'tcx>,
1519 other: &EvaluatedCandidate<'tcx>,
1522 if victim.candidate == other.candidate {
1526 // Check if a bound would previously have been removed when normalizing
1527 // the param_env so that it can be given the lowest priority. See
1528 // #50825 for the motivation for this.
1529 let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| {
1530 cand.is_global() && !cand.has_late_bound_regions()
1533 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1534 // `DiscriminantKindCandidate`, and `ConstDestructCandidate` to anything else.
1536 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1537 // lifetime of a variable.
1538 match (&other.candidate, &victim.candidate) {
1539 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1541 "default implementations shouldn't be recorded \
1542 when there are other valid candidates"
1548 BuiltinCandidate { has_nested: false }
1549 | DiscriminantKindCandidate
1551 | ConstDestructCandidate(_),
1556 BuiltinCandidate { has_nested: false }
1557 | DiscriminantKindCandidate
1559 | ConstDestructCandidate(_),
1562 (ParamCandidate(other), ParamCandidate(victim)) => {
1563 let same_except_bound_vars = other.skip_binder().trait_ref
1564 == victim.skip_binder().trait_ref
1565 && other.skip_binder().constness == victim.skip_binder().constness
1566 && other.skip_binder().polarity == victim.skip_binder().polarity
1567 && !other.skip_binder().trait_ref.has_escaping_bound_vars();
1568 if same_except_bound_vars {
1569 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1570 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1571 // or the current one if tied (they should both evaluate to the same answer). This is
1572 // probably best characterized as a "hack", since we might prefer to just do our
1573 // best to *not* create essentially duplicate candidates in the first place.
1574 other.bound_vars().len() <= victim.bound_vars().len()
1575 } else if other.skip_binder().trait_ref == victim.skip_binder().trait_ref
1576 && victim.skip_binder().constness == ty::BoundConstness::NotConst
1577 && other.skip_binder().polarity == victim.skip_binder().polarity
1579 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1586 // Drop otherwise equivalent non-const fn pointer candidates
1587 (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
1589 // Global bounds from the where clause should be ignored
1590 // here (see issue #50825). Otherwise, we have a where
1591 // clause so don't go around looking for impls.
1592 // Arbitrarily give param candidates priority
1593 // over projection and object candidates.
1595 ParamCandidate(ref cand),
1598 | GeneratorCandidate
1599 | FnPointerCandidate { .. }
1600 | BuiltinObjectCandidate
1601 | BuiltinUnsizeCandidate
1602 | TraitUpcastingUnsizeCandidate(_)
1603 | BuiltinCandidate { .. }
1604 | TraitAliasCandidate(..)
1605 | ObjectCandidate(_)
1606 | ProjectionCandidate(_),
1607 ) => !is_global(cand),
1608 (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1609 // Prefer these to a global where-clause bound
1610 // (see issue #50825).
1616 | GeneratorCandidate
1617 | FnPointerCandidate { .. }
1618 | BuiltinObjectCandidate
1619 | BuiltinUnsizeCandidate
1620 | TraitUpcastingUnsizeCandidate(_)
1621 | BuiltinCandidate { has_nested: true }
1622 | TraitAliasCandidate(..),
1623 ParamCandidate(ref cand),
1625 // Prefer these to a global where-clause bound
1626 // (see issue #50825).
1627 is_global(cand) && other.evaluation.must_apply_modulo_regions()
1630 (ProjectionCandidate(i), ProjectionCandidate(j))
1631 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1632 // Arbitrarily pick the lower numbered candidate for backwards
1633 // compatibility reasons. Don't let this affect inference.
1634 i < j && !needs_infer
1636 (ObjectCandidate(_), ProjectionCandidate(_))
1637 | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1638 bug!("Have both object and projection candidate")
1641 // Arbitrarily give projection and object candidates priority.
1643 ObjectCandidate(_) | ProjectionCandidate(_),
1646 | GeneratorCandidate
1647 | FnPointerCandidate { .. }
1648 | BuiltinObjectCandidate
1649 | BuiltinUnsizeCandidate
1650 | TraitUpcastingUnsizeCandidate(_)
1651 | BuiltinCandidate { .. }
1652 | TraitAliasCandidate(..),
1658 | GeneratorCandidate
1659 | FnPointerCandidate { .. }
1660 | BuiltinObjectCandidate
1661 | BuiltinUnsizeCandidate
1662 | TraitUpcastingUnsizeCandidate(_)
1663 | BuiltinCandidate { .. }
1664 | TraitAliasCandidate(..),
1665 ObjectCandidate(_) | ProjectionCandidate(_),
1668 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1669 // See if we can toss out `victim` based on specialization.
1670 // This requires us to know *for sure* that the `other` impl applies
1671 // i.e., `EvaluatedToOk`.
1673 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1674 // to me but is required for `std` to compile, so I didn't change it
1676 let tcx = self.tcx();
1677 if other.evaluation.must_apply_modulo_regions() {
1678 if tcx.specializes((other_def, victim_def)) {
1683 if other.evaluation.must_apply_considering_regions() {
1684 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1685 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1686 // Subtle: If the predicate we are evaluating has inference
1687 // variables, do *not* allow discarding candidates due to
1688 // marker trait impls.
1690 // Without this restriction, we could end up accidentally
1691 // constraining inference variables based on an arbitrarily
1692 // chosen trait impl.
1694 // Imagine we have the following code:
1697 // #[marker] trait MyTrait {}
1698 // impl MyTrait for u8 {}
1699 // impl MyTrait for bool {}
1702 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1704 // During selection, we will end up with one candidate for each
1705 // impl of `MyTrait`. If we were to discard one impl in favor
1706 // of the other, we would be left with one candidate, causing
1707 // us to "successfully" select the predicate, unifying
1708 // _#0t with (for example) `u8`.
1710 // However, we have no reason to believe that this unification
1711 // is correct - we've essentially just picked an arbitrary
1712 // *possibility* for _#0t, and required that this be the *only*
1715 // Eventually, we will either:
1716 // 1) Unify all inference variables in the predicate through
1717 // some other means (e.g. type-checking of a function). We will
1718 // then be in a position to drop marker trait candidates
1719 // without constraining inference variables (since there are
1720 // none left to constrain)
1721 // 2) Be left with some unconstrained inference variables. We
1722 // will then correctly report an inference error, since the
1723 // existence of multiple marker trait impls tells us nothing
1724 // about which one should actually apply.
1735 // Everything else is ambiguous
1739 | GeneratorCandidate
1740 | FnPointerCandidate { .. }
1741 | BuiltinObjectCandidate
1742 | BuiltinUnsizeCandidate
1743 | TraitUpcastingUnsizeCandidate(_)
1744 | BuiltinCandidate { has_nested: true }
1745 | TraitAliasCandidate(..),
1748 | GeneratorCandidate
1749 | FnPointerCandidate { .. }
1750 | BuiltinObjectCandidate
1751 | BuiltinUnsizeCandidate
1752 | TraitUpcastingUnsizeCandidate(_)
1753 | BuiltinCandidate { has_nested: true }
1754 | TraitAliasCandidate(..),
1759 fn sized_conditions(
1761 obligation: &TraitObligation<'tcx>,
1762 ) -> BuiltinImplConditions<'tcx> {
1763 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1765 // NOTE: binder moved to (*)
1766 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1768 match self_ty.kind() {
1769 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1780 | ty::GeneratorWitness(..)
1785 // safe for everything
1786 Where(ty::Binder::dummy(Vec::new()))
1789 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1791 ty::Tuple(tys) => Where(
1792 obligation.predicate.rebind(tys.last().map_or_else(Vec::new, |&last| vec![last])),
1795 ty::Adt(def, substs) => {
1796 let sized_crit = def.sized_constraint(self.tcx());
1797 // (*) binder moved here
1798 Where(obligation.predicate.rebind({
1799 sized_crit.iter().map(|ty| EarlyBinder(*ty).subst(self.tcx(), substs)).collect()
1803 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1804 ty::Infer(ty::TyVar(_)) => Ambiguous,
1808 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1809 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1814 fn copy_clone_conditions(
1816 obligation: &TraitObligation<'tcx>,
1817 ) -> BuiltinImplConditions<'tcx> {
1818 // NOTE: binder moved to (*)
1819 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1821 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1823 match *self_ty.kind() {
1824 ty::Infer(ty::IntVar(_))
1825 | ty::Infer(ty::FloatVar(_))
1828 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1837 | ty::Ref(_, _, hir::Mutability::Not)
1838 | ty::Array(..) => {
1839 // Implementations provided in libcore
1847 | ty::GeneratorWitness(..)
1849 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1852 // (*) binder moved here
1853 Where(obligation.predicate.rebind(tys.iter().collect()))
1856 ty::Closure(_, substs) => {
1857 // (*) binder moved here
1858 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1859 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1860 // Not yet resolved.
1863 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1867 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1868 // Fallback to whatever user-defined impls exist in this case.
1872 ty::Infer(ty::TyVar(_)) => {
1873 // Unbound type variable. Might or might not have
1874 // applicable impls and so forth, depending on what
1875 // those type variables wind up being bound to.
1881 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1882 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1887 /// For default impls, we need to break apart a type into its
1888 /// "constituent types" -- meaning, the types that it contains.
1890 /// Here are some (simple) examples:
1892 /// ```ignore (illustrative)
1893 /// (i32, u32) -> [i32, u32]
1894 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1895 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1896 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1898 fn constituent_types_for_ty(
1900 t: ty::Binder<'tcx, Ty<'tcx>>,
1901 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1902 match *t.skip_binder().kind() {
1911 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1913 | ty::Char => ty::Binder::dummy(Vec::new()),
1919 | ty::Projection(..)
1921 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1922 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1925 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1926 t.rebind(vec![element_ty])
1929 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
1931 ty::Tuple(ref tys) => {
1932 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1933 t.rebind(tys.iter().collect())
1936 ty::Closure(_, ref substs) => {
1937 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1941 ty::Generator(_, ref substs, _) => {
1942 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
1943 let witness = substs.as_generator().witness();
1944 t.rebind([ty].into_iter().chain(iter::once(witness)).collect())
1947 ty::GeneratorWitness(types) => {
1948 debug_assert!(!types.has_escaping_bound_vars());
1949 types.map_bound(|types| types.to_vec())
1952 // For `PhantomData<T>`, we pass `T`.
1953 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
1955 ty::Adt(def, substs) => {
1956 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
1959 ty::Opaque(def_id, substs) => {
1960 // We can resolve the `impl Trait` to its concrete type,
1961 // which enforces a DAG between the functions requiring
1962 // the auto trait bounds in question.
1963 t.rebind(vec![self.tcx().bound_type_of(def_id).subst(self.tcx(), substs)])
1968 fn collect_predicates_for_types(
1970 param_env: ty::ParamEnv<'tcx>,
1971 cause: ObligationCause<'tcx>,
1972 recursion_depth: usize,
1973 trait_def_id: DefId,
1974 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
1975 ) -> Vec<PredicateObligation<'tcx>> {
1976 // Because the types were potentially derived from
1977 // higher-ranked obligations they may reference late-bound
1978 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
1979 // yield a type like `for<'a> &'a i32`. In general, we
1980 // maintain the invariant that we never manipulate bound
1981 // regions, so we have to process these bound regions somehow.
1983 // The strategy is to:
1985 // 1. Instantiate those regions to placeholder regions (e.g.,
1986 // `for<'a> &'a i32` becomes `&0 i32`.
1987 // 2. Produce something like `&'0 i32 : Copy`
1988 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
1992 .skip_binder() // binder moved -\
1995 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(*ty); // <----/
1997 self.infcx.commit_unconditionally(|_| {
1998 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
1999 let Normalized { value: normalized_ty, mut obligations } =
2000 ensure_sufficient_stack(|| {
2001 project::normalize_with_depth(
2009 let placeholder_obligation = predicate_for_trait_def(
2018 obligations.push(placeholder_obligation);
2025 ///////////////////////////////////////////////////////////////////////////
2028 // Matching is a common path used for both evaluation and
2029 // confirmation. It basically unifies types that appear in impls
2030 // and traits. This does affect the surrounding environment;
2031 // therefore, when used during evaluation, match routines must be
2032 // run inside of a `probe()` so that their side-effects are
2038 obligation: &TraitObligation<'tcx>,
2039 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
2040 match self.match_impl(impl_def_id, obligation) {
2041 Ok(substs) => substs,
2043 self.infcx.tcx.sess.delay_span_bug(
2044 obligation.cause.span,
2046 "Impl {:?} was matchable against {:?} but now is not",
2047 impl_def_id, obligation
2050 let value = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2051 let err = self.tcx().ty_error();
2052 let value = value.fold_with(&mut BottomUpFolder {
2058 Normalized { value, obligations: vec![] }
2063 #[tracing::instrument(level = "debug", skip(self))]
2067 obligation: &TraitObligation<'tcx>,
2068 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2069 let impl_trait_ref = self.tcx().bound_impl_trait_ref(impl_def_id).unwrap();
2071 // Before we create the substitutions and everything, first
2072 // consider a "quick reject". This avoids creating more types
2073 // and so forth that we need to.
2074 if self.fast_reject_trait_refs(obligation, &impl_trait_ref.0) {
2078 let placeholder_obligation =
2079 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
2080 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2082 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2084 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2086 debug!(?impl_trait_ref);
2088 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2089 ensure_sufficient_stack(|| {
2090 project::normalize_with_depth(
2092 obligation.param_env,
2093 obligation.cause.clone(),
2094 obligation.recursion_depth + 1,
2099 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2101 let cause = ObligationCause::new(
2102 obligation.cause.span,
2103 obligation.cause.body_id,
2104 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2107 let InferOk { obligations, .. } = self
2109 .at(&cause, obligation.param_env)
2110 .define_opaque_types(false)
2111 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2112 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2113 nested_obligations.extend(obligations);
2116 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2118 debug!("match_impl: reservation impls only apply in intercrate mode");
2122 debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2123 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2126 fn fast_reject_trait_refs(
2128 obligation: &TraitObligation<'tcx>,
2129 impl_trait_ref: &ty::TraitRef<'tcx>,
2131 // We can avoid creating type variables and doing the full
2132 // substitution if we find that any of the input types, when
2133 // simplified, do not match.
2135 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
2136 |(obligation_arg, impl_arg)| {
2137 match (obligation_arg.unpack(), impl_arg.unpack()) {
2138 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
2139 // Note, we simplify parameters for the obligation but not the
2140 // impl so that we do not reject a blanket impl but do reject
2141 // more concrete impls if we're searching for `T: Trait`.
2142 let simplified_obligation_ty = fast_reject::simplify_type(
2145 TreatParams::AsBoundTypes,
2147 let simplified_impl_ty = fast_reject::simplify_type(
2150 TreatParams::AsPlaceholders,
2153 simplified_obligation_ty.is_some()
2154 && simplified_impl_ty.is_some()
2155 && simplified_obligation_ty != simplified_impl_ty
2157 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
2158 // Lifetimes can never cause a rejection.
2161 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
2162 // Conservatively ignore consts (i.e. assume they might
2163 // unify later) until we have `fast_reject` support for
2164 // them (if we'll ever need it, even).
2167 _ => unreachable!(),
2173 /// Normalize `where_clause_trait_ref` and try to match it against
2174 /// `obligation`. If successful, return any predicates that
2175 /// result from the normalization.
2176 fn match_where_clause_trait_ref(
2178 obligation: &TraitObligation<'tcx>,
2179 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2180 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2181 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2184 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2185 /// obligation is satisfied.
2186 #[instrument(skip(self), level = "debug")]
2187 fn match_poly_trait_ref(
2189 obligation: &TraitObligation<'tcx>,
2190 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2191 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2193 .at(&obligation.cause, obligation.param_env)
2194 // We don't want predicates for opaque types to just match all other types,
2195 // if there is an obligation on the opaque type, then that obligation must be met
2196 // opaquely. Otherwise we'd match any obligation to the opaque type and then error
2198 .define_opaque_types(false)
2199 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2200 .map(|InferOk { obligations, .. }| obligations)
2204 ///////////////////////////////////////////////////////////////////////////
2207 fn match_fresh_trait_refs(
2209 previous: ty::PolyTraitPredicate<'tcx>,
2210 current: ty::PolyTraitPredicate<'tcx>,
2211 param_env: ty::ParamEnv<'tcx>,
2213 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2214 matcher.relate(previous, current).is_ok()
2219 previous_stack: TraitObligationStackList<'o, 'tcx>,
2220 obligation: &'o TraitObligation<'tcx>,
2221 ) -> TraitObligationStack<'o, 'tcx> {
2222 let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
2224 let dfn = previous_stack.cache.next_dfn();
2225 let depth = previous_stack.depth() + 1;
2226 TraitObligationStack {
2229 reached_depth: Cell::new(depth),
2230 previous: previous_stack,
2236 #[instrument(skip(self), level = "debug")]
2237 fn closure_trait_ref_unnormalized(
2239 obligation: &TraitObligation<'tcx>,
2240 substs: SubstsRef<'tcx>,
2241 ) -> ty::PolyTraitRef<'tcx> {
2242 let closure_sig = substs.as_closure().sig();
2244 debug!(?closure_sig);
2246 // (1) Feels icky to skip the binder here, but OTOH we know
2247 // that the self-type is an unboxed closure type and hence is
2248 // in fact unparameterized (or at least does not reference any
2249 // regions bound in the obligation). Still probably some
2250 // refactoring could make this nicer.
2251 closure_trait_ref_and_return_type(
2253 obligation.predicate.def_id(),
2254 obligation.predicate.skip_binder().self_ty(), // (1)
2256 util::TupleArgumentsFlag::No,
2258 .map_bound(|(trait_ref, _)| trait_ref)
2261 fn generator_trait_ref_unnormalized(
2263 obligation: &TraitObligation<'tcx>,
2264 substs: SubstsRef<'tcx>,
2265 ) -> ty::PolyTraitRef<'tcx> {
2266 let gen_sig = substs.as_generator().poly_sig();
2268 // (1) Feels icky to skip the binder here, but OTOH we know
2269 // that the self-type is an generator type and hence is
2270 // in fact unparameterized (or at least does not reference any
2271 // regions bound in the obligation). Still probably some
2272 // refactoring could make this nicer.
2274 super::util::generator_trait_ref_and_outputs(
2276 obligation.predicate.def_id(),
2277 obligation.predicate.skip_binder().self_ty(), // (1)
2280 .map_bound(|(trait_ref, ..)| trait_ref)
2283 /// Returns the obligations that are implied by instantiating an
2284 /// impl or trait. The obligations are substituted and fully
2285 /// normalized. This is used when confirming an impl or default
2287 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2288 fn impl_or_trait_obligations(
2290 cause: &ObligationCause<'tcx>,
2291 recursion_depth: usize,
2292 param_env: ty::ParamEnv<'tcx>,
2293 def_id: DefId, // of impl or trait
2294 substs: SubstsRef<'tcx>, // for impl or trait
2295 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2296 ) -> Vec<PredicateObligation<'tcx>> {
2297 let tcx = self.tcx();
2299 // To allow for one-pass evaluation of the nested obligation,
2300 // each predicate must be preceded by the obligations required
2302 // for example, if we have:
2303 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2304 // the impl will have the following predicates:
2305 // <V as Iterator>::Item = U,
2306 // U: Iterator, U: Sized,
2307 // V: Iterator, V: Sized,
2308 // <U as Iterator>::Item: Copy
2309 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2310 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2311 // `$1: Copy`, so we must ensure the obligations are emitted in
2313 let predicates = tcx.predicates_of(def_id);
2314 debug!(?predicates);
2315 assert_eq!(predicates.parent, None);
2316 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2317 let parent_code = cause.clone_code();
2318 for (predicate, span) in predicates.predicates {
2321 DerivedObligationCause { parent_trait_pred, parent_code: parent_code.clone() };
2322 let code = ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
2324 impl_def_id: def_id,
2327 let cause = ObligationCause::new(cause.span, cause.body_id, code);
2328 let predicate = normalize_with_depth_to(
2333 EarlyBinder(*predicate).subst(tcx, substs),
2336 obligations.push(Obligation { cause, recursion_depth, param_env, predicate });
2343 trait TraitObligationExt<'tcx> {
2346 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2347 ) -> ObligationCause<'tcx>;
2350 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2353 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2354 ) -> ObligationCause<'tcx> {
2356 * Creates a cause for obligations that are derived from
2357 * `obligation` by a recursive search (e.g., for a builtin
2358 * bound, or eventually a `auto trait Foo`). If `obligation`
2359 * is itself a derived obligation, this is just a clone, but
2360 * otherwise we create a "derived obligation" cause so as to
2361 * keep track of the original root obligation for error
2365 let obligation = self;
2367 // NOTE(flaper87): As of now, it keeps track of the whole error
2368 // chain. Ideally, we should have a way to configure this either
2369 // by using -Z verbose or just a CLI argument.
2370 let derived_cause = DerivedObligationCause {
2371 parent_trait_pred: obligation.predicate,
2372 parent_code: obligation.cause.clone_code(),
2374 let derived_code = variant(derived_cause);
2375 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2379 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2380 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2381 TraitObligationStackList::with(self)
2384 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2388 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2392 /// Indicates that attempting to evaluate this stack entry
2393 /// required accessing something from the stack at depth `reached_depth`.
2394 fn update_reached_depth(&self, reached_depth: usize) {
2396 self.depth >= reached_depth,
2397 "invoked `update_reached_depth` with something under this stack: \
2398 self.depth={} reached_depth={}",
2402 debug!(reached_depth, "update_reached_depth");
2404 while reached_depth < p.depth {
2405 debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
2406 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2407 p = p.previous.head.unwrap();
2412 /// The "provisional evaluation cache" is used to store intermediate cache results
2413 /// when solving auto traits. Auto traits are unusual in that they can support
2414 /// cycles. So, for example, a "proof tree" like this would be ok:
2416 /// - `Foo<T>: Send` :-
2417 /// - `Bar<T>: Send` :-
2418 /// - `Foo<T>: Send` -- cycle, but ok
2419 /// - `Baz<T>: Send`
2421 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2422 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2423 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2424 /// they are coinductive) it is considered ok.
2426 /// However, there is a complication: at the point where we have
2427 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2428 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2429 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2430 /// find out this assumption is wrong? Specifically, we could
2431 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2432 /// `Bar<T>: Send` didn't turn out to be true.
2434 /// In Issue #60010, we found a bug in rustc where it would cache
2435 /// these intermediate results. This was fixed in #60444 by disabling
2436 /// *all* caching for things involved in a cycle -- in our example,
2437 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2438 /// to large slowdowns.
2440 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2441 /// first requires proving `Bar<T>: Send` (which is true:
2443 /// - `Foo<T>: Send` :-
2444 /// - `Bar<T>: Send` :-
2445 /// - `Foo<T>: Send` -- cycle, but ok
2446 /// - `Baz<T>: Send`
2447 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2448 /// - `*const T: Send` -- but what if we later encounter an error?
2450 /// The *provisional evaluation cache* resolves this issue. It stores
2451 /// cache results that we've proven but which were involved in a cycle
2452 /// in some way. We track the minimal stack depth (i.e., the
2453 /// farthest from the top of the stack) that we are dependent on.
2454 /// The idea is that the cache results within are all valid -- so long as
2455 /// none of the nodes in between the current node and the node at that minimum
2456 /// depth result in an error (in which case the cached results are just thrown away).
2458 /// During evaluation, we consult this provisional cache and rely on
2459 /// it. Accessing a cached value is considered equivalent to accessing
2460 /// a result at `reached_depth`, so it marks the *current* solution as
2461 /// provisional as well. If an error is encountered, we toss out any
2462 /// provisional results added from the subtree that encountered the
2463 /// error. When we pop the node at `reached_depth` from the stack, we
2464 /// can commit all the things that remain in the provisional cache.
2465 struct ProvisionalEvaluationCache<'tcx> {
2466 /// next "depth first number" to issue -- just a counter
2469 /// Map from cache key to the provisionally evaluated thing.
2470 /// The cache entries contain the result but also the DFN in which they
2471 /// were added. The DFN is used to clear out values on failure.
2473 /// Imagine we have a stack like:
2475 /// - `A B C` and we add a cache for the result of C (DFN 2)
2476 /// - Then we have a stack `A B D` where `D` has DFN 3
2477 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2478 /// - `E` generates various cache entries which have cyclic dependencies on `B`
2479 /// - `A B D E F` and so forth
2480 /// - the DFN of `F` for example would be 5
2481 /// - then we determine that `E` is in error -- we will then clear
2482 /// all cache values whose DFN is >= 4 -- in this case, that
2483 /// means the cached value for `F`.
2484 map: RefCell<FxHashMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
2487 /// A cache value for the provisional cache: contains the depth-first
2488 /// number (DFN) and result.
2489 #[derive(Copy, Clone, Debug)]
2490 struct ProvisionalEvaluation {
2492 reached_depth: usize,
2493 result: EvaluationResult,
2496 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2497 fn default() -> Self {
2498 Self { dfn: Cell::new(0), map: Default::default() }
2502 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2503 /// Get the next DFN in sequence (basically a counter).
2504 fn next_dfn(&self) -> usize {
2505 let result = self.dfn.get();
2506 self.dfn.set(result + 1);
2510 /// Check the provisional cache for any result for
2511 /// `fresh_trait_ref`. If there is a hit, then you must consider
2512 /// it an access to the stack slots at depth
2513 /// `reached_depth` (from the returned value).
2516 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2517 ) -> Option<ProvisionalEvaluation> {
2520 "get_provisional = {:#?}",
2521 self.map.borrow().get(&fresh_trait_pred),
2523 Some(*self.map.borrow().get(&fresh_trait_pred)?)
2526 /// Insert a provisional result into the cache. The result came
2527 /// from the node with the given DFN. It accessed a minimum depth
2528 /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
2529 /// and resulted in `result`.
2530 fn insert_provisional(
2533 reached_depth: usize,
2534 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2535 result: EvaluationResult,
2537 debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
2539 let mut map = self.map.borrow_mut();
2541 // Subtle: when we complete working on the DFN `from_dfn`, anything
2542 // that remains in the provisional cache must be dependent on some older
2543 // stack entry than `from_dfn`. We have to update their depth with our transitive
2544 // depth in that case or else it would be referring to some popped note.
2547 // A (reached depth 0)
2549 // B // depth 1 -- reached depth = 0
2550 // C // depth 2 -- reached depth = 1 (should be 0)
2553 // D (reached depth 1)
2554 // C (cache -- reached depth = 2)
2555 for (_k, v) in &mut *map {
2556 if v.from_dfn >= from_dfn {
2557 v.reached_depth = reached_depth.min(v.reached_depth);
2561 map.insert(fresh_trait_pred, ProvisionalEvaluation { from_dfn, reached_depth, result });
2564 /// Invoked when the node with dfn `dfn` does not get a successful
2565 /// result. This will clear out any provisional cache entries
2566 /// that were added since `dfn` was created. This is because the
2567 /// provisional entries are things which must assume that the
2568 /// things on the stack at the time of their creation succeeded --
2569 /// since the failing node is presently at the top of the stack,
2570 /// these provisional entries must either depend on it or some
2572 fn on_failure(&self, dfn: usize) {
2573 debug!(?dfn, "on_failure");
2574 self.map.borrow_mut().retain(|key, eval| {
2575 if !eval.from_dfn >= dfn {
2576 debug!("on_failure: removing {:?}", key);
2584 /// Invoked when the node at depth `depth` completed without
2585 /// depending on anything higher in the stack (if that completion
2586 /// was a failure, then `on_failure` should have been invoked
2589 /// Note that we may still have provisional cache items remaining
2590 /// in the cache when this is done. For example, if there is a
2593 /// * A depends on...
2594 /// * B depends on A
2595 /// * C depends on...
2596 /// * D depends on C
2599 /// Then as we complete the C node we will have a provisional cache
2600 /// with results for A, B, C, and D. This method would clear out
2601 /// the C and D results, but leave A and B provisional.
2603 /// This is determined based on the DFN: we remove any provisional
2604 /// results created since `dfn` started (e.g., in our example, dfn
2605 /// would be 2, representing the C node, and hence we would
2606 /// remove the result for D, which has DFN 3, but not the results for
2607 /// A and B, which have DFNs 0 and 1 respectively).
2609 /// Note that we *do not* attempt to cache these cycle participants
2610 /// in the evaluation cache. Doing so would require carefully computing
2611 /// the correct `DepNode` to store in the cache entry:
2612 /// cycle participants may implicitly depend on query results
2613 /// related to other participants in the cycle, due to our logic
2614 /// which examines the evaluation stack.
2616 /// We used to try to perform this caching,
2617 /// but it lead to multiple incremental compilation ICEs
2618 /// (see #92987 and #96319), and was very hard to understand.
2619 /// Fortunately, removing the caching didn't seem to
2620 /// have a performance impact in practice.
2621 fn on_completion(&self, dfn: usize) {
2622 debug!(?dfn, "on_completion");
2624 for (fresh_trait_pred, eval) in
2625 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2627 debug!(?fresh_trait_pred, ?eval, "on_completion");
2632 #[derive(Copy, Clone)]
2633 struct TraitObligationStackList<'o, 'tcx> {
2634 cache: &'o ProvisionalEvaluationCache<'tcx>,
2635 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2638 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2639 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2640 TraitObligationStackList { cache, head: None }
2643 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2644 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2647 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2651 fn depth(&self) -> usize {
2652 if let Some(head) = self.head { head.depth } else { 0 }
2656 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2657 type Item = &'o TraitObligationStack<'o, 'tcx>;
2659 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2666 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2667 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2668 write!(f, "TraitObligationStack({:?})", self.obligation)
2672 pub enum ProjectionMatchesProjection {