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, 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);
745 stack.cache().on_completion(
747 |fresh_trait_pred, provisional_result, provisional_dep_node| {
748 // Create a new `DepNode` that has dependencies on:
749 // * The `DepNode` for the original evaluation that resulted in a provisional cache
750 // entry being crated
751 // * The `DepNode` for the *current* evaluation, which resulted in us completing
752 // provisional caches entries and inserting them into the evaluation cache
754 // This ensures that when a query reads this entry from the evaluation cache,
755 // it will end up (transitively) depending on all of the incr-comp dependencies
756 // created during the evaluation of this trait. For example, evaluating a trait
757 // will usually require us to invoke `type_of(field_def_id)` to determine the
758 // constituent types, and we want any queries reading from this evaluation
759 // cache entry to end up with a transitive `type_of(field_def_id`)` dependency.
761 // By using `in_task`, we're also creating an edge from the *current* query
762 // to the newly-created `combined_dep_node`. This is probably redundant,
763 // but it's better to add too many dep graph edges than to add too few
765 let ((), combined_dep_node) = self.in_task(|this| {
766 this.tcx().dep_graph.read_index(provisional_dep_node);
767 this.tcx().dep_graph.read_index(dep_node);
769 self.insert_evaluation_cache(
773 provisional_result.max(result),
778 debug!(?result, "PROVISIONAL");
780 "caching provisionally because {:?} \
781 is a cycle participant (at depth {}, reached depth {})",
782 fresh_trait_pred, stack.depth, reached_depth,
785 stack.cache().insert_provisional(
797 /// If there is any previous entry on the stack that precisely
798 /// matches this obligation, then we can assume that the
799 /// obligation is satisfied for now (still all other conditions
800 /// must be met of course). One obvious case this comes up is
801 /// marker traits like `Send`. Think of a linked list:
803 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
805 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
806 /// `Option<Box<List<T>>>` is `Send`, and in turn
807 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
810 /// Note that we do this comparison using the `fresh_trait_ref`
811 /// fields. Because these have all been freshened using
812 /// `self.freshener`, we can be sure that (a) this will not
813 /// affect the inferencer state and (b) that if we see two
814 /// fresh regions with the same index, they refer to the same
815 /// unbound type variable.
816 fn check_evaluation_cycle(
818 stack: &TraitObligationStack<'_, 'tcx>,
819 ) -> Option<EvaluationResult> {
820 if let Some(cycle_depth) = stack
822 .skip(1) // Skip top-most frame.
824 stack.obligation.param_env == prev.obligation.param_env
825 && stack.fresh_trait_pred == prev.fresh_trait_pred
827 .map(|stack| stack.depth)
829 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
831 // If we have a stack like `A B C D E A`, where the top of
832 // the stack is the final `A`, then this will iterate over
833 // `A, E, D, C, B` -- i.e., all the participants apart
834 // from the cycle head. We mark them as participating in a
835 // cycle. This suppresses caching for those nodes. See
836 // `in_cycle` field for more details.
837 stack.update_reached_depth(cycle_depth);
839 // Subtle: when checking for a coinductive cycle, we do
840 // not compare using the "freshened trait refs" (which
841 // have erased regions) but rather the fully explicit
842 // trait refs. This is important because it's only a cycle
843 // if the regions match exactly.
844 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
845 let tcx = self.tcx();
846 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
847 if self.coinductive_match(cycle) {
848 debug!("evaluate_stack --> recursive, coinductive");
851 debug!("evaluate_stack --> recursive, inductive");
852 Some(EvaluatedToRecur)
859 fn evaluate_stack<'o>(
861 stack: &TraitObligationStack<'o, 'tcx>,
862 ) -> Result<EvaluationResult, OverflowError> {
863 // In intercrate mode, whenever any of the generics are unbound,
864 // there can always be an impl. Even if there are no impls in
865 // this crate, perhaps the type would be unified with
866 // something from another crate that does provide an impl.
868 // In intra mode, we must still be conservative. The reason is
869 // that we want to avoid cycles. Imagine an impl like:
871 // impl<T:Eq> Eq for Vec<T>
873 // and a trait reference like `$0 : Eq` where `$0` is an
874 // unbound variable. When we evaluate this trait-reference, we
875 // will unify `$0` with `Vec<$1>` (for some fresh variable
876 // `$1`), on the condition that `$1 : Eq`. We will then wind
877 // up with many candidates (since that are other `Eq` impls
878 // that apply) and try to winnow things down. This results in
879 // a recursive evaluation that `$1 : Eq` -- as you can
880 // imagine, this is just where we started. To avoid that, we
881 // check for unbound variables and return an ambiguous (hence possible)
882 // match if we've seen this trait before.
884 // This suffices to allow chains like `FnMut` implemented in
885 // terms of `Fn` etc, but we could probably make this more
887 let unbound_input_types =
888 stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh());
890 if stack.obligation.polarity() != ty::ImplPolarity::Negative {
891 // This check was an imperfect workaround for a bug in the old
892 // intercrate mode; it should be removed when that goes away.
893 if unbound_input_types && self.intercrate {
894 debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
895 // Heuristics: show the diagnostics when there are no candidates in crate.
896 if self.intercrate_ambiguity_causes.is_some() {
897 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
898 if let Ok(candidate_set) = self.assemble_candidates(stack) {
899 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
900 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
901 let self_ty = trait_ref.self_ty();
902 let cause = with_no_trimmed_paths!({
903 IntercrateAmbiguityCause::DownstreamCrate {
904 trait_desc: trait_ref.print_only_trait_path().to_string(),
905 self_desc: if self_ty.has_concrete_skeleton() {
906 Some(self_ty.to_string())
913 debug!(?cause, "evaluate_stack: pushing cause");
914 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
918 return Ok(EvaluatedToAmbig);
922 if unbound_input_types
923 && stack.iter().skip(1).any(|prev| {
924 stack.obligation.param_env == prev.obligation.param_env
925 && self.match_fresh_trait_refs(
926 stack.fresh_trait_pred,
927 prev.fresh_trait_pred,
928 prev.obligation.param_env,
932 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
933 return Ok(EvaluatedToUnknown);
936 match self.candidate_from_obligation(stack) {
937 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
938 Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig),
939 Ok(None) => Ok(EvaluatedToAmbig),
940 Err(Overflow(OverflowError::Canonical)) => Err(OverflowError::Canonical),
941 Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
942 Err(..) => Ok(EvaluatedToErr),
946 /// For defaulted traits, we use a co-inductive strategy to solve, so
947 /// that recursion is ok. This routine returns `true` if the top of the
948 /// stack (`cycle[0]`):
950 /// - is a defaulted trait,
951 /// - it also appears in the backtrace at some position `X`,
952 /// - all the predicates at positions `X..` between `X` and the top are
953 /// also defaulted traits.
954 pub fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
956 I: Iterator<Item = ty::Predicate<'tcx>>,
958 cycle.all(|predicate| self.coinductive_predicate(predicate))
961 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
962 let result = match predicate.kind().skip_binder() {
963 ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
966 debug!(?predicate, ?result, "coinductive_predicate");
970 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
971 /// obligations are met. Returns whether `candidate` remains viable after this further
976 fields(depth = stack.obligation.recursion_depth)
978 fn evaluate_candidate<'o>(
980 stack: &TraitObligationStack<'o, 'tcx>,
981 candidate: &SelectionCandidate<'tcx>,
982 ) -> Result<EvaluationResult, OverflowError> {
983 let mut result = self.evaluation_probe(|this| {
984 let candidate = (*candidate).clone();
985 match this.confirm_candidate(stack.obligation, candidate) {
988 this.evaluate_predicates_recursively(
990 selection.nested_obligations().into_iter(),
993 Err(..) => Ok(EvaluatedToErr),
997 // If we erased any lifetimes, then we want to use
998 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
999 // as your final result. The result will be cached using
1000 // the freshened trait predicate as a key, so we need
1001 // our result to be correct by *any* choice of original lifetimes,
1002 // not just the lifetime choice for this particular (non-erased)
1005 if stack.fresh_trait_pred.has_erased_regions() {
1006 result = result.max(EvaluatedToOkModuloRegions);
1013 fn check_evaluation_cache(
1015 param_env: ty::ParamEnv<'tcx>,
1016 trait_pred: ty::PolyTraitPredicate<'tcx>,
1017 ) -> Option<EvaluationResult> {
1018 // Neither the global nor local cache is aware of intercrate
1019 // mode, so don't do any caching. In particular, we might
1020 // re-use the same `InferCtxt` with both an intercrate
1021 // and non-intercrate `SelectionContext`
1022 if self.intercrate {
1026 let tcx = self.tcx();
1027 if self.can_use_global_caches(param_env) {
1028 if let Some(res) = tcx.evaluation_cache.get(&(param_env, trait_pred), tcx) {
1032 self.infcx.evaluation_cache.get(&(param_env, trait_pred), tcx)
1035 fn insert_evaluation_cache(
1037 param_env: ty::ParamEnv<'tcx>,
1038 trait_pred: ty::PolyTraitPredicate<'tcx>,
1039 dep_node: DepNodeIndex,
1040 result: EvaluationResult,
1042 // Avoid caching results that depend on more than just the trait-ref
1043 // - the stack can create recursion.
1044 if result.is_stack_dependent() {
1048 // Neither the global nor local cache is aware of intercrate
1049 // mode, so don't do any caching. In particular, we might
1050 // re-use the same `InferCtxt` with both an intercrate
1051 // and non-intercrate `SelectionContext`
1052 if self.intercrate {
1056 if self.can_use_global_caches(param_env) {
1057 if !trait_pred.needs_infer() {
1058 debug!(?trait_pred, ?result, "insert_evaluation_cache global");
1059 // This may overwrite the cache with the same value
1060 // FIXME: Due to #50507 this overwrites the different values
1061 // This should be changed to use HashMapExt::insert_same
1062 // when that is fixed
1063 self.tcx().evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1068 debug!(?trait_pred, ?result, "insert_evaluation_cache");
1069 self.infcx.evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1072 /// For various reasons, it's possible for a subobligation
1073 /// to have a *lower* recursion_depth than the obligation used to create it.
1074 /// Projection sub-obligations may be returned from the projection cache,
1075 /// which results in obligations with an 'old' `recursion_depth`.
1076 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1077 /// subobligations without taking in a 'parent' depth, causing the
1078 /// generated subobligations to have a `recursion_depth` of `0`.
1080 /// To ensure that obligation_depth never decreases, we force all subobligations
1081 /// to have at least the depth of the original obligation.
1082 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1087 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1090 fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
1093 error_obligation: &Obligation<'tcx, T>,
1094 ) -> Result<(), OverflowError> {
1095 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1096 match self.query_mode {
1097 TraitQueryMode::Standard => {
1098 if self.infcx.is_tainted_by_errors() {
1099 return Err(OverflowError::Error(
1100 ErrorGuaranteed::unchecked_claim_error_was_emitted(),
1103 self.infcx.report_overflow_error(error_obligation, true);
1105 TraitQueryMode::Canonical => {
1106 return Err(OverflowError::Canonical);
1113 /// Checks that the recursion limit has not been exceeded.
1115 /// The weird return type of this function allows it to be used with the `try` (`?`)
1116 /// operator within certain functions.
1118 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1120 obligation: &Obligation<'tcx, T>,
1121 error_obligation: &Obligation<'tcx, V>,
1122 ) -> Result<(), OverflowError> {
1123 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1126 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1128 OP: FnOnce(&mut Self) -> R,
1130 let (result, dep_node) =
1131 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1132 self.tcx().dep_graph.read_index(dep_node);
1136 /// filter_impls filters constant trait obligations and candidates that have a positive impl
1137 /// for a negative goal and a negative impl for a positive goal
1138 #[instrument(level = "debug", skip(self))]
1141 candidates: Vec<SelectionCandidate<'tcx>>,
1142 obligation: &TraitObligation<'tcx>,
1143 ) -> Vec<SelectionCandidate<'tcx>> {
1144 let tcx = self.tcx();
1145 let mut result = Vec::with_capacity(candidates.len());
1147 for candidate in candidates {
1148 // Respect const trait obligations
1149 if obligation.is_const() {
1152 ImplCandidate(def_id)
1153 if tcx.impl_constness(def_id) == hir::Constness::Const => {}
1155 ParamCandidate(trait_pred) if trait_pred.is_const_if_const() => {}
1157 AutoImplCandidate(..) => {}
1158 // generator, this will raise error in other places
1159 // or ignore error with const_async_blocks feature
1160 GeneratorCandidate => {}
1161 // FnDef where the function is const
1162 FnPointerCandidate { is_const: true } => {}
1163 ConstDestructCandidate(_) => {}
1165 // reject all other types of candidates
1171 if let ImplCandidate(def_id) = candidate {
1172 if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id)
1173 || obligation.polarity() == tcx.impl_polarity(def_id)
1175 result.push(candidate);
1178 result.push(candidate);
1185 /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1186 #[instrument(level = "debug", skip(self))]
1187 fn filter_reservation_impls(
1189 candidate: SelectionCandidate<'tcx>,
1190 obligation: &TraitObligation<'tcx>,
1191 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1192 let tcx = self.tcx();
1193 // Treat reservation impls as ambiguity.
1194 if let ImplCandidate(def_id) = candidate {
1195 if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
1196 if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1197 let attrs = tcx.get_attrs(def_id);
1198 let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
1199 let value = attr.and_then(|a| a.value_str());
1200 if let Some(value) = value {
1202 "filter_reservation_impls: \
1203 reservation impl ambiguity on {:?}",
1206 intercrate_ambiguity_clauses.push(
1207 IntercrateAmbiguityCause::ReservationImpl {
1208 message: value.to_string(),
1219 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1220 debug!("is_knowable(intercrate={:?})", self.intercrate);
1222 if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative {
1226 let obligation = &stack.obligation;
1227 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1229 // Okay to skip binder because of the nature of the
1230 // trait-ref-is-knowable check, which does not care about
1232 let trait_ref = predicate.skip_binder().trait_ref;
1234 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1237 /// Returns `true` if the global caches can be used.
1238 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1239 // If there are any inference variables in the `ParamEnv`, then we
1240 // always use a cache local to this particular scope. Otherwise, we
1241 // switch to a global cache.
1242 if param_env.needs_infer() {
1246 // Avoid using the master cache during coherence and just rely
1247 // on the local cache. This effectively disables caching
1248 // during coherence. It is really just a simplification to
1249 // avoid us having to fear that coherence results "pollute"
1250 // the master cache. Since coherence executes pretty quickly,
1251 // it's not worth going to more trouble to increase the
1252 // hit-rate, I don't think.
1253 if self.intercrate {
1257 // Otherwise, we can use the global cache.
1261 fn check_candidate_cache(
1263 mut param_env: ty::ParamEnv<'tcx>,
1264 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1265 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1266 // Neither the global nor local cache is aware of intercrate
1267 // mode, so don't do any caching. In particular, we might
1268 // re-use the same `InferCtxt` with both an intercrate
1269 // and non-intercrate `SelectionContext`
1270 if self.intercrate {
1273 let tcx = self.tcx();
1274 let mut pred = cache_fresh_trait_pred.skip_binder();
1275 pred.remap_constness(tcx, &mut param_env);
1277 if self.can_use_global_caches(param_env) {
1278 if let Some(res) = tcx.selection_cache.get(&(param_env, pred), tcx) {
1282 self.infcx.selection_cache.get(&(param_env, pred), tcx)
1285 /// Determines whether can we safely cache the result
1286 /// of selecting an obligation. This is almost always `true`,
1287 /// except when dealing with certain `ParamCandidate`s.
1289 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1290 /// since it was usually produced directly from a `DefId`. However,
1291 /// certain cases (currently only librustdoc's blanket impl finder),
1292 /// a `ParamEnv` may be explicitly constructed with inference types.
1293 /// When this is the case, we do *not* want to cache the resulting selection
1294 /// candidate. This is due to the fact that it might not always be possible
1295 /// to equate the obligation's trait ref and the candidate's trait ref,
1296 /// if more constraints end up getting added to an inference variable.
1298 /// Because of this, we always want to re-run the full selection
1299 /// process for our obligation the next time we see it, since
1300 /// we might end up picking a different `SelectionCandidate` (or none at all).
1301 fn can_cache_candidate(
1303 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1305 // Neither the global nor local cache is aware of intercrate
1306 // mode, so don't do any caching. In particular, we might
1307 // re-use the same `InferCtxt` with both an intercrate
1308 // and non-intercrate `SelectionContext`
1309 if self.intercrate {
1313 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1318 #[instrument(skip(self, param_env, cache_fresh_trait_pred, dep_node), level = "debug")]
1319 fn insert_candidate_cache(
1321 mut param_env: ty::ParamEnv<'tcx>,
1322 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1323 dep_node: DepNodeIndex,
1324 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1326 let tcx = self.tcx();
1327 let mut pred = cache_fresh_trait_pred.skip_binder();
1329 pred.remap_constness(tcx, &mut param_env);
1331 if !self.can_cache_candidate(&candidate) {
1332 debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1336 if self.can_use_global_caches(param_env) {
1337 if let Err(Overflow(OverflowError::Canonical)) = candidate {
1338 // Don't cache overflow globally; we only produce this in certain modes.
1339 } else if !pred.needs_infer() {
1340 if !candidate.needs_infer() {
1341 debug!(?pred, ?candidate, "insert_candidate_cache global");
1342 // This may overwrite the cache with the same value.
1343 tcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1349 debug!(?pred, ?candidate, "insert_candidate_cache local");
1350 self.infcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1353 /// Matches a predicate against the bounds of its self type.
1355 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1356 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1357 /// `Baz` bound. We return indexes into the list returned by
1358 /// `tcx.item_bounds` for any applicable bounds.
1359 #[instrument(level = "debug", skip(self))]
1360 fn match_projection_obligation_against_definition_bounds(
1362 obligation: &TraitObligation<'tcx>,
1363 ) -> smallvec::SmallVec<[usize; 2]> {
1364 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1365 let placeholder_trait_predicate =
1366 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1367 debug!(?placeholder_trait_predicate);
1369 let tcx = self.infcx.tcx;
1370 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1371 ty::Projection(ref data) => (data.item_def_id, data.substs),
1372 ty::Opaque(def_id, substs) => (def_id, substs),
1375 obligation.cause.span,
1376 "match_projection_obligation_against_definition_bounds() called \
1377 but self-ty is not a projection: {:?}",
1378 placeholder_trait_predicate.trait_ref.self_ty()
1382 let bounds = tcx.item_bounds(def_id).subst(tcx, substs);
1384 // The bounds returned by `item_bounds` may contain duplicates after
1385 // normalization, so try to deduplicate when possible to avoid
1386 // unnecessary ambiguity.
1387 let mut distinct_normalized_bounds = FxHashSet::default();
1389 let matching_bounds = bounds
1392 .filter_map(|(idx, bound)| {
1393 let bound_predicate = bound.kind();
1394 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1395 let bound = bound_predicate.rebind(pred.trait_ref);
1396 if self.infcx.probe(|_| {
1397 match self.match_normalize_trait_ref(
1400 placeholder_trait_predicate.trait_ref,
1403 Ok(Some(normalized_trait))
1404 if distinct_normalized_bounds.insert(normalized_trait) =>
1418 debug!(?matching_bounds);
1422 /// Equates the trait in `obligation` with trait bound. If the two traits
1423 /// can be equated and the normalized trait bound doesn't contain inference
1424 /// variables or placeholders, the normalized bound is returned.
1425 fn match_normalize_trait_ref(
1427 obligation: &TraitObligation<'tcx>,
1428 trait_bound: ty::PolyTraitRef<'tcx>,
1429 placeholder_trait_ref: ty::TraitRef<'tcx>,
1430 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1431 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1432 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1433 // Avoid unnecessary normalization
1437 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1438 project::normalize_with_depth(
1440 obligation.param_env,
1441 obligation.cause.clone(),
1442 obligation.recursion_depth + 1,
1447 .at(&obligation.cause, obligation.param_env)
1448 .define_opaque_types(false)
1449 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1450 .map(|InferOk { obligations: _, value: () }| {
1451 // This method is called within a probe, so we can't have
1452 // inference variables and placeholders escape.
1453 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1462 fn where_clause_may_apply<'o>(
1464 stack: &TraitObligationStack<'o, 'tcx>,
1465 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1466 ) -> Result<EvaluationResult, OverflowError> {
1467 self.evaluation_probe(|this| {
1468 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1469 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1470 Err(()) => Ok(EvaluatedToErr),
1475 /// Return `Yes` if the obligation's predicate type applies to the env_predicate, and
1476 /// `No` if it does not. Return `Ambiguous` in the case that the projection type is a GAT,
1477 /// and applying this env_predicate constrains any of the obligation's GAT substitutions.
1479 /// This behavior is a somewhat of a hack to prevent over-constraining inference variables
1480 /// in cases like #91762.
1481 pub(super) fn match_projection_projections(
1483 obligation: &ProjectionTyObligation<'tcx>,
1484 env_predicate: PolyProjectionPredicate<'tcx>,
1485 potentially_unnormalized_candidates: bool,
1486 ) -> ProjectionMatchesProjection {
1487 let mut nested_obligations = Vec::new();
1488 let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars(
1489 obligation.cause.span,
1490 LateBoundRegionConversionTime::HigherRankedType,
1493 let infer_projection = if potentially_unnormalized_candidates {
1494 ensure_sufficient_stack(|| {
1495 project::normalize_with_depth_to(
1497 obligation.param_env,
1498 obligation.cause.clone(),
1499 obligation.recursion_depth + 1,
1500 infer_predicate.projection_ty,
1501 &mut nested_obligations,
1505 infer_predicate.projection_ty
1510 .at(&obligation.cause, obligation.param_env)
1511 .define_opaque_types(false)
1512 .sup(obligation.predicate, infer_projection)
1513 .map_or(false, |InferOk { obligations, value: () }| {
1514 self.evaluate_predicates_recursively(
1515 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1516 nested_obligations.into_iter().chain(obligations),
1518 .map_or(false, |res| res.may_apply())
1522 let generics = self.tcx().generics_of(obligation.predicate.item_def_id);
1523 // FIXME(generic-associated-types): Addresses aggressive inference in #92917.
1524 // If this type is a GAT, and of the GAT substs resolve to something new,
1525 // that means that we must have newly inferred something about the GAT.
1526 // We should give up in that case.
1527 if !generics.params.is_empty()
1528 && obligation.predicate.substs[generics.parent_count..]
1530 .any(|&p| p.has_infer_types_or_consts() && self.infcx.shallow_resolve(p) != p)
1532 ProjectionMatchesProjection::Ambiguous
1534 ProjectionMatchesProjection::Yes
1537 ProjectionMatchesProjection::No
1541 ///////////////////////////////////////////////////////////////////////////
1544 // Winnowing is the process of attempting to resolve ambiguity by
1545 // probing further. During the winnowing process, we unify all
1546 // type variables and then we also attempt to evaluate recursive
1547 // bounds to see if they are satisfied.
1549 /// Returns `true` if `victim` should be dropped in favor of
1550 /// `other`. Generally speaking we will drop duplicate
1551 /// candidates and prefer where-clause candidates.
1553 /// See the comment for "SelectionCandidate" for more details.
1554 fn candidate_should_be_dropped_in_favor_of(
1556 sized_predicate: bool,
1557 victim: &EvaluatedCandidate<'tcx>,
1558 other: &EvaluatedCandidate<'tcx>,
1561 if victim.candidate == other.candidate {
1565 // Check if a bound would previously have been removed when normalizing
1566 // the param_env so that it can be given the lowest priority. See
1567 // #50825 for the motivation for this.
1568 let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| {
1569 cand.is_global() && !cand.has_late_bound_regions()
1572 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1573 // `DiscriminantKindCandidate`, and `ConstDestructCandidate` to anything else.
1575 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1576 // lifetime of a variable.
1577 match (&other.candidate, &victim.candidate) {
1578 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1580 "default implementations shouldn't be recorded \
1581 when there are other valid candidates"
1587 BuiltinCandidate { has_nested: false }
1588 | DiscriminantKindCandidate
1590 | ConstDestructCandidate(_),
1595 BuiltinCandidate { has_nested: false }
1596 | DiscriminantKindCandidate
1598 | ConstDestructCandidate(_),
1601 (ParamCandidate(other), ParamCandidate(victim)) => {
1602 let same_except_bound_vars = other.skip_binder().trait_ref
1603 == victim.skip_binder().trait_ref
1604 && other.skip_binder().constness == victim.skip_binder().constness
1605 && other.skip_binder().polarity == victim.skip_binder().polarity
1606 && !other.skip_binder().trait_ref.has_escaping_bound_vars();
1607 if same_except_bound_vars {
1608 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1609 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1610 // or the current one if tied (they should both evaluate to the same answer). This is
1611 // probably best characterized as a "hack", since we might prefer to just do our
1612 // best to *not* create essentially duplicate candidates in the first place.
1613 other.bound_vars().len() <= victim.bound_vars().len()
1614 } else if other.skip_binder().trait_ref == victim.skip_binder().trait_ref
1615 && victim.skip_binder().constness == ty::BoundConstness::NotConst
1616 && other.skip_binder().polarity == victim.skip_binder().polarity
1618 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1625 // Drop otherwise equivalent non-const fn pointer candidates
1626 (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
1628 // If obligation is a sized predicate or the where-clause bound is
1629 // global, prefer the projection or object candidate. See issue
1630 // #50825 and #89352.
1631 (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1632 sized_predicate || is_global(cand)
1634 (ParamCandidate(ref cand), ObjectCandidate(_) | ProjectionCandidate(_)) => {
1635 !(sized_predicate || is_global(cand))
1638 // Global bounds from the where clause should be ignored
1639 // here (see issue #50825). Otherwise, we have a where
1640 // clause so don't go around looking for impls.
1641 // Arbitrarily give param candidates priority
1642 // over projection and object candidates.
1644 ParamCandidate(ref cand),
1647 | GeneratorCandidate
1648 | FnPointerCandidate { .. }
1649 | BuiltinObjectCandidate
1650 | BuiltinUnsizeCandidate
1651 | TraitUpcastingUnsizeCandidate(_)
1652 | BuiltinCandidate { .. }
1653 | TraitAliasCandidate(..),
1654 ) => !is_global(cand),
1658 | GeneratorCandidate
1659 | FnPointerCandidate { .. }
1660 | BuiltinObjectCandidate
1661 | BuiltinUnsizeCandidate
1662 | TraitUpcastingUnsizeCandidate(_)
1663 | BuiltinCandidate { has_nested: true }
1664 | TraitAliasCandidate(..),
1665 ParamCandidate(ref cand),
1667 // Prefer these to a global where-clause bound
1668 // (see issue #50825).
1669 is_global(cand) && other.evaluation.must_apply_modulo_regions()
1672 (ProjectionCandidate(i), ProjectionCandidate(j))
1673 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1674 // Arbitrarily pick the lower numbered candidate for backwards
1675 // compatibility reasons. Don't let this affect inference.
1676 i < j && !needs_infer
1678 (ObjectCandidate(_), ProjectionCandidate(_))
1679 | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1680 bug!("Have both object and projection candidate")
1683 // Arbitrarily give projection and object candidates priority.
1685 ObjectCandidate(_) | ProjectionCandidate(_),
1688 | GeneratorCandidate
1689 | FnPointerCandidate { .. }
1690 | BuiltinObjectCandidate
1691 | BuiltinUnsizeCandidate
1692 | TraitUpcastingUnsizeCandidate(_)
1693 | BuiltinCandidate { .. }
1694 | TraitAliasCandidate(..),
1700 | GeneratorCandidate
1701 | FnPointerCandidate { .. }
1702 | BuiltinObjectCandidate
1703 | BuiltinUnsizeCandidate
1704 | TraitUpcastingUnsizeCandidate(_)
1705 | BuiltinCandidate { .. }
1706 | TraitAliasCandidate(..),
1707 ObjectCandidate(_) | ProjectionCandidate(_),
1710 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1711 // See if we can toss out `victim` based on specialization.
1712 // This requires us to know *for sure* that the `other` impl applies
1713 // i.e., `EvaluatedToOk`.
1715 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1716 // to me but is required for `std` to compile, so I didn't change it
1718 let tcx = self.tcx();
1719 if other.evaluation.must_apply_modulo_regions() {
1720 if tcx.specializes((other_def, victim_def)) {
1725 if other.evaluation.must_apply_considering_regions() {
1726 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1727 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1728 // Subtle: If the predicate we are evaluating has inference
1729 // variables, do *not* allow discarding candidates due to
1730 // marker trait impls.
1732 // Without this restriction, we could end up accidentally
1733 // constraining inference variables based on an arbitrarily
1734 // chosen trait impl.
1736 // Imagine we have the following code:
1739 // #[marker] trait MyTrait {}
1740 // impl MyTrait for u8 {}
1741 // impl MyTrait for bool {}
1744 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1746 // During selection, we will end up with one candidate for each
1747 // impl of `MyTrait`. If we were to discard one impl in favor
1748 // of the other, we would be left with one candidate, causing
1749 // us to "successfully" select the predicate, unifying
1750 // _#0t with (for example) `u8`.
1752 // However, we have no reason to believe that this unification
1753 // is correct - we've essentially just picked an arbitrary
1754 // *possibility* for _#0t, and required that this be the *only*
1757 // Eventually, we will either:
1758 // 1) Unify all inference variables in the predicate through
1759 // some other means (e.g. type-checking of a function). We will
1760 // then be in a position to drop marker trait candidates
1761 // without constraining inference variables (since there are
1762 // none left to constrain)
1763 // 2) Be left with some unconstrained inference variables. We
1764 // will then correctly report an inference error, since the
1765 // existence of multiple marker trait impls tells us nothing
1766 // about which one should actually apply.
1777 // Everything else is ambiguous
1781 | GeneratorCandidate
1782 | FnPointerCandidate { .. }
1783 | BuiltinObjectCandidate
1784 | BuiltinUnsizeCandidate
1785 | TraitUpcastingUnsizeCandidate(_)
1786 | BuiltinCandidate { has_nested: true }
1787 | TraitAliasCandidate(..),
1790 | GeneratorCandidate
1791 | FnPointerCandidate { .. }
1792 | BuiltinObjectCandidate
1793 | BuiltinUnsizeCandidate
1794 | TraitUpcastingUnsizeCandidate(_)
1795 | BuiltinCandidate { has_nested: true }
1796 | TraitAliasCandidate(..),
1801 fn sized_conditions(
1803 obligation: &TraitObligation<'tcx>,
1804 ) -> BuiltinImplConditions<'tcx> {
1805 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1807 // NOTE: binder moved to (*)
1808 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1810 match self_ty.kind() {
1811 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1822 | ty::GeneratorWitness(..)
1827 // safe for everything
1828 Where(ty::Binder::dummy(Vec::new()))
1831 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1833 ty::Tuple(tys) => Where(
1834 obligation.predicate.rebind(tys.last().map_or_else(Vec::new, |&last| vec![last])),
1837 ty::Adt(def, substs) => {
1838 let sized_crit = def.sized_constraint(self.tcx());
1839 // (*) binder moved here
1841 obligation.predicate.rebind({
1842 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1847 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1848 ty::Infer(ty::TyVar(_)) => Ambiguous,
1852 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1853 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1858 fn copy_clone_conditions(
1860 obligation: &TraitObligation<'tcx>,
1861 ) -> BuiltinImplConditions<'tcx> {
1862 // NOTE: binder moved to (*)
1863 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1865 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1867 match *self_ty.kind() {
1868 ty::Infer(ty::IntVar(_))
1869 | ty::Infer(ty::FloatVar(_))
1872 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1881 | ty::Ref(_, _, hir::Mutability::Not)
1882 | ty::Array(..) => {
1883 // Implementations provided in libcore
1891 | ty::GeneratorWitness(..)
1893 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1896 // (*) binder moved here
1897 Where(obligation.predicate.rebind(tys.iter().collect()))
1900 ty::Closure(_, substs) => {
1901 // (*) binder moved here
1902 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1903 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1904 // Not yet resolved.
1907 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1911 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1912 // Fallback to whatever user-defined impls exist in this case.
1916 ty::Infer(ty::TyVar(_)) => {
1917 // Unbound type variable. Might or might not have
1918 // applicable impls and so forth, depending on what
1919 // those type variables wind up being bound to.
1925 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1926 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1931 /// For default impls, we need to break apart a type into its
1932 /// "constituent types" -- meaning, the types that it contains.
1934 /// Here are some (simple) examples:
1937 /// (i32, u32) -> [i32, u32]
1938 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1939 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1940 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1942 fn constituent_types_for_ty(
1944 t: ty::Binder<'tcx, Ty<'tcx>>,
1945 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1946 match *t.skip_binder().kind() {
1955 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1957 | ty::Char => ty::Binder::dummy(Vec::new()),
1963 | ty::Projection(..)
1965 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1966 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1969 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1970 t.rebind(vec![element_ty])
1973 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
1975 ty::Tuple(ref tys) => {
1976 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1977 t.rebind(tys.iter().collect())
1980 ty::Closure(_, ref substs) => {
1981 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1985 ty::Generator(_, ref substs, _) => {
1986 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
1987 let witness = substs.as_generator().witness();
1988 t.rebind([ty].into_iter().chain(iter::once(witness)).collect())
1991 ty::GeneratorWitness(types) => {
1992 debug_assert!(!types.has_escaping_bound_vars());
1993 types.map_bound(|types| types.to_vec())
1996 // For `PhantomData<T>`, we pass `T`.
1997 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
1999 ty::Adt(def, substs) => {
2000 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
2003 ty::Opaque(def_id, substs) => {
2004 // We can resolve the `impl Trait` to its concrete type,
2005 // which enforces a DAG between the functions requiring
2006 // the auto trait bounds in question.
2007 t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
2012 fn collect_predicates_for_types(
2014 param_env: ty::ParamEnv<'tcx>,
2015 cause: ObligationCause<'tcx>,
2016 recursion_depth: usize,
2017 trait_def_id: DefId,
2018 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
2019 ) -> Vec<PredicateObligation<'tcx>> {
2020 // Because the types were potentially derived from
2021 // higher-ranked obligations they may reference late-bound
2022 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2023 // yield a type like `for<'a> &'a i32`. In general, we
2024 // maintain the invariant that we never manipulate bound
2025 // regions, so we have to process these bound regions somehow.
2027 // The strategy is to:
2029 // 1. Instantiate those regions to placeholder regions (e.g.,
2030 // `for<'a> &'a i32` becomes `&0 i32`.
2031 // 2. Produce something like `&'0 i32 : Copy`
2032 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2036 .skip_binder() // binder moved -\
2039 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(*ty); // <----/
2041 self.infcx.commit_unconditionally(|_| {
2042 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
2043 let Normalized { value: normalized_ty, mut obligations } =
2044 ensure_sufficient_stack(|| {
2045 project::normalize_with_depth(
2053 let placeholder_obligation = predicate_for_trait_def(
2062 obligations.push(placeholder_obligation);
2069 ///////////////////////////////////////////////////////////////////////////
2072 // Matching is a common path used for both evaluation and
2073 // confirmation. It basically unifies types that appear in impls
2074 // and traits. This does affect the surrounding environment;
2075 // therefore, when used during evaluation, match routines must be
2076 // run inside of a `probe()` so that their side-effects are
2082 obligation: &TraitObligation<'tcx>,
2083 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
2084 match self.match_impl(impl_def_id, obligation) {
2085 Ok(substs) => substs,
2087 self.infcx.tcx.sess.delay_span_bug(
2088 obligation.cause.span,
2090 "Impl {:?} was matchable against {:?} but now is not",
2091 impl_def_id, obligation
2094 let value = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2095 let err = self.tcx().ty_error();
2096 let value = value.fold_with(&mut BottomUpFolder {
2102 Normalized { value, obligations: vec![] }
2107 #[tracing::instrument(level = "debug", skip(self))]
2111 obligation: &TraitObligation<'tcx>,
2112 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2113 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2115 // Before we create the substitutions and everything, first
2116 // consider a "quick reject". This avoids creating more types
2117 // and so forth that we need to.
2118 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2122 let placeholder_obligation =
2123 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
2124 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2126 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2128 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2130 debug!(?impl_trait_ref);
2132 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2133 ensure_sufficient_stack(|| {
2134 project::normalize_with_depth(
2136 obligation.param_env,
2137 obligation.cause.clone(),
2138 obligation.recursion_depth + 1,
2143 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2145 let cause = ObligationCause::new(
2146 obligation.cause.span,
2147 obligation.cause.body_id,
2148 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2151 let InferOk { obligations, .. } = self
2153 .at(&cause, obligation.param_env)
2154 .define_opaque_types(false)
2155 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2156 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2157 nested_obligations.extend(obligations);
2160 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2162 debug!("match_impl: reservation impls only apply in intercrate mode");
2166 debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2167 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2170 fn fast_reject_trait_refs(
2172 obligation: &TraitObligation<'tcx>,
2173 impl_trait_ref: &ty::TraitRef<'tcx>,
2175 // We can avoid creating type variables and doing the full
2176 // substitution if we find that any of the input types, when
2177 // simplified, do not match.
2179 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
2180 |(obligation_arg, impl_arg)| {
2181 match (obligation_arg.unpack(), impl_arg.unpack()) {
2182 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
2183 // Note, we simplify parameters for the obligation but not the
2184 // impl so that we do not reject a blanket impl but do reject
2185 // more concrete impls if we're searching for `T: Trait`.
2186 let simplified_obligation_ty = fast_reject::simplify_type(
2189 TreatParams::AsBoundTypes,
2191 let simplified_impl_ty = fast_reject::simplify_type(
2194 TreatParams::AsPlaceholders,
2197 simplified_obligation_ty.is_some()
2198 && simplified_impl_ty.is_some()
2199 && simplified_obligation_ty != simplified_impl_ty
2201 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
2202 // Lifetimes can never cause a rejection.
2205 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
2206 // Conservatively ignore consts (i.e. assume they might
2207 // unify later) until we have `fast_reject` support for
2208 // them (if we'll ever need it, even).
2211 _ => unreachable!(),
2217 /// Normalize `where_clause_trait_ref` and try to match it against
2218 /// `obligation`. If successful, return any predicates that
2219 /// result from the normalization.
2220 fn match_where_clause_trait_ref(
2222 obligation: &TraitObligation<'tcx>,
2223 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2224 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2225 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2228 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2229 /// obligation is satisfied.
2230 #[instrument(skip(self), level = "debug")]
2231 fn match_poly_trait_ref(
2233 obligation: &TraitObligation<'tcx>,
2234 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2235 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2237 .at(&obligation.cause, obligation.param_env)
2238 // We don't want predicates for opaque types to just match all other types,
2239 // if there is an obligation on the opaque type, then that obligation must be met
2240 // opaquely. Otherwise we'd match any obligation to the opaque type and then error
2242 .define_opaque_types(false)
2243 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2244 .map(|InferOk { obligations, .. }| obligations)
2248 ///////////////////////////////////////////////////////////////////////////
2251 fn match_fresh_trait_refs(
2253 previous: ty::PolyTraitPredicate<'tcx>,
2254 current: ty::PolyTraitPredicate<'tcx>,
2255 param_env: ty::ParamEnv<'tcx>,
2257 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2258 matcher.relate(previous, current).is_ok()
2263 previous_stack: TraitObligationStackList<'o, 'tcx>,
2264 obligation: &'o TraitObligation<'tcx>,
2265 ) -> TraitObligationStack<'o, 'tcx> {
2266 let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
2268 let dfn = previous_stack.cache.next_dfn();
2269 let depth = previous_stack.depth() + 1;
2270 TraitObligationStack {
2273 reached_depth: Cell::new(depth),
2274 previous: previous_stack,
2280 #[instrument(skip(self), level = "debug")]
2281 fn closure_trait_ref_unnormalized(
2283 obligation: &TraitObligation<'tcx>,
2284 substs: SubstsRef<'tcx>,
2285 ) -> ty::PolyTraitRef<'tcx> {
2286 let closure_sig = substs.as_closure().sig();
2288 debug!(?closure_sig);
2290 // (1) Feels icky to skip the binder here, but OTOH we know
2291 // that the self-type is an unboxed closure type and hence is
2292 // in fact unparameterized (or at least does not reference any
2293 // regions bound in the obligation). Still probably some
2294 // refactoring could make this nicer.
2295 closure_trait_ref_and_return_type(
2297 obligation.predicate.def_id(),
2298 obligation.predicate.skip_binder().self_ty(), // (1)
2300 util::TupleArgumentsFlag::No,
2302 .map_bound(|(trait_ref, _)| trait_ref)
2305 fn generator_trait_ref_unnormalized(
2307 obligation: &TraitObligation<'tcx>,
2308 substs: SubstsRef<'tcx>,
2309 ) -> ty::PolyTraitRef<'tcx> {
2310 let gen_sig = substs.as_generator().poly_sig();
2312 // (1) Feels icky to skip the binder here, but OTOH we know
2313 // that the self-type is an generator type and hence is
2314 // in fact unparameterized (or at least does not reference any
2315 // regions bound in the obligation). Still probably some
2316 // refactoring could make this nicer.
2318 super::util::generator_trait_ref_and_outputs(
2320 obligation.predicate.def_id(),
2321 obligation.predicate.skip_binder().self_ty(), // (1)
2324 .map_bound(|(trait_ref, ..)| trait_ref)
2327 /// Returns the obligations that are implied by instantiating an
2328 /// impl or trait. The obligations are substituted and fully
2329 /// normalized. This is used when confirming an impl or default
2331 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2332 fn impl_or_trait_obligations(
2334 cause: &ObligationCause<'tcx>,
2335 recursion_depth: usize,
2336 param_env: ty::ParamEnv<'tcx>,
2337 def_id: DefId, // of impl or trait
2338 substs: SubstsRef<'tcx>, // for impl or trait
2339 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2340 ) -> Vec<PredicateObligation<'tcx>> {
2341 let tcx = self.tcx();
2343 // To allow for one-pass evaluation of the nested obligation,
2344 // each predicate must be preceded by the obligations required
2346 // for example, if we have:
2347 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2348 // the impl will have the following predicates:
2349 // <V as Iterator>::Item = U,
2350 // U: Iterator, U: Sized,
2351 // V: Iterator, V: Sized,
2352 // <U as Iterator>::Item: Copy
2353 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2354 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2355 // `$1: Copy`, so we must ensure the obligations are emitted in
2357 let predicates = tcx.predicates_of(def_id);
2358 debug!(?predicates);
2359 assert_eq!(predicates.parent, None);
2360 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2361 let parent_code = cause.clone_code();
2362 for (predicate, span) in predicates.predicates {
2365 DerivedObligationCause { parent_trait_pred, parent_code: parent_code.clone() };
2366 let code = ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
2368 impl_def_id: def_id,
2371 let cause = ObligationCause::new(cause.span, cause.body_id, code);
2372 let predicate = normalize_with_depth_to(
2377 predicate.subst(tcx, substs),
2380 obligations.push(Obligation { cause, recursion_depth, param_env, predicate });
2387 trait TraitObligationExt<'tcx> {
2390 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2391 ) -> ObligationCause<'tcx>;
2394 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2397 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2398 ) -> ObligationCause<'tcx> {
2400 * Creates a cause for obligations that are derived from
2401 * `obligation` by a recursive search (e.g., for a builtin
2402 * bound, or eventually a `auto trait Foo`). If `obligation`
2403 * is itself a derived obligation, this is just a clone, but
2404 * otherwise we create a "derived obligation" cause so as to
2405 * keep track of the original root obligation for error
2409 let obligation = self;
2411 // NOTE(flaper87): As of now, it keeps track of the whole error
2412 // chain. Ideally, we should have a way to configure this either
2413 // by using -Z verbose or just a CLI argument.
2414 let derived_cause = DerivedObligationCause {
2415 parent_trait_pred: obligation.predicate,
2416 parent_code: obligation.cause.clone_code(),
2418 let derived_code = variant(derived_cause);
2419 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2423 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2424 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2425 TraitObligationStackList::with(self)
2428 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2432 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2436 /// Indicates that attempting to evaluate this stack entry
2437 /// required accessing something from the stack at depth `reached_depth`.
2438 fn update_reached_depth(&self, reached_depth: usize) {
2440 self.depth >= reached_depth,
2441 "invoked `update_reached_depth` with something under this stack: \
2442 self.depth={} reached_depth={}",
2446 debug!(reached_depth, "update_reached_depth");
2448 while reached_depth < p.depth {
2449 debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
2450 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2451 p = p.previous.head.unwrap();
2456 /// The "provisional evaluation cache" is used to store intermediate cache results
2457 /// when solving auto traits. Auto traits are unusual in that they can support
2458 /// cycles. So, for example, a "proof tree" like this would be ok:
2460 /// - `Foo<T>: Send` :-
2461 /// - `Bar<T>: Send` :-
2462 /// - `Foo<T>: Send` -- cycle, but ok
2463 /// - `Baz<T>: Send`
2465 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2466 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2467 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2468 /// they are coinductive) it is considered ok.
2470 /// However, there is a complication: at the point where we have
2471 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2472 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2473 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2474 /// find out this assumption is wrong? Specifically, we could
2475 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2476 /// `Bar<T>: Send` didn't turn out to be true.
2478 /// In Issue #60010, we found a bug in rustc where it would cache
2479 /// these intermediate results. This was fixed in #60444 by disabling
2480 /// *all* caching for things involved in a cycle -- in our example,
2481 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2482 /// to large slowdowns.
2484 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2485 /// first requires proving `Bar<T>: Send` (which is true:
2487 /// - `Foo<T>: Send` :-
2488 /// - `Bar<T>: Send` :-
2489 /// - `Foo<T>: Send` -- cycle, but ok
2490 /// - `Baz<T>: Send`
2491 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2492 /// - `*const T: Send` -- but what if we later encounter an error?
2494 /// The *provisional evaluation cache* resolves this issue. It stores
2495 /// cache results that we've proven but which were involved in a cycle
2496 /// in some way. We track the minimal stack depth (i.e., the
2497 /// farthest from the top of the stack) that we are dependent on.
2498 /// The idea is that the cache results within are all valid -- so long as
2499 /// none of the nodes in between the current node and the node at that minimum
2500 /// depth result in an error (in which case the cached results are just thrown away).
2502 /// During evaluation, we consult this provisional cache and rely on
2503 /// it. Accessing a cached value is considered equivalent to accessing
2504 /// a result at `reached_depth`, so it marks the *current* solution as
2505 /// provisional as well. If an error is encountered, we toss out any
2506 /// provisional results added from the subtree that encountered the
2507 /// error. When we pop the node at `reached_depth` from the stack, we
2508 /// can commit all the things that remain in the provisional cache.
2509 struct ProvisionalEvaluationCache<'tcx> {
2510 /// next "depth first number" to issue -- just a counter
2513 /// Map from cache key to the provisionally evaluated thing.
2514 /// The cache entries contain the result but also the DFN in which they
2515 /// were added. The DFN is used to clear out values on failure.
2517 /// Imagine we have a stack like:
2519 /// - `A B C` and we add a cache for the result of C (DFN 2)
2520 /// - Then we have a stack `A B D` where `D` has DFN 3
2521 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2522 /// - `E` generates various cache entries which have cyclic dependencies on `B`
2523 /// - `A B D E F` and so forth
2524 /// - the DFN of `F` for example would be 5
2525 /// - then we determine that `E` is in error -- we will then clear
2526 /// all cache values whose DFN is >= 4 -- in this case, that
2527 /// means the cached value for `F`.
2528 map: RefCell<FxHashMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
2531 /// A cache value for the provisional cache: contains the depth-first
2532 /// number (DFN) and result.
2533 #[derive(Copy, Clone, Debug)]
2534 struct ProvisionalEvaluation {
2536 reached_depth: usize,
2537 result: EvaluationResult,
2538 /// The `DepNodeIndex` created for the `evaluate_stack` call for this provisional
2539 /// evaluation. When we create an entry in the evaluation cache using this provisional
2540 /// cache entry (see `on_completion`), we use this `dep_node` to ensure that future reads from
2541 /// the cache will have all of the necessary incr comp dependencies tracked.
2542 dep_node: DepNodeIndex,
2545 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2546 fn default() -> Self {
2547 Self { dfn: Cell::new(0), map: Default::default() }
2551 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2552 /// Get the next DFN in sequence (basically a counter).
2553 fn next_dfn(&self) -> usize {
2554 let result = self.dfn.get();
2555 self.dfn.set(result + 1);
2559 /// Check the provisional cache for any result for
2560 /// `fresh_trait_ref`. If there is a hit, then you must consider
2561 /// it an access to the stack slots at depth
2562 /// `reached_depth` (from the returned value).
2565 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2566 ) -> Option<ProvisionalEvaluation> {
2569 "get_provisional = {:#?}",
2570 self.map.borrow().get(&fresh_trait_pred),
2572 Some(*self.map.borrow().get(&fresh_trait_pred)?)
2575 /// Insert a provisional result into the cache. The result came
2576 /// from the node with the given DFN. It accessed a minimum depth
2577 /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
2578 /// and resulted in `result`.
2579 fn insert_provisional(
2582 reached_depth: usize,
2583 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2584 result: EvaluationResult,
2585 dep_node: DepNodeIndex,
2587 debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
2589 let mut map = self.map.borrow_mut();
2591 // Subtle: when we complete working on the DFN `from_dfn`, anything
2592 // that remains in the provisional cache must be dependent on some older
2593 // stack entry than `from_dfn`. We have to update their depth with our transitive
2594 // depth in that case or else it would be referring to some popped note.
2597 // A (reached depth 0)
2599 // B // depth 1 -- reached depth = 0
2600 // C // depth 2 -- reached depth = 1 (should be 0)
2603 // D (reached depth 1)
2604 // C (cache -- reached depth = 2)
2605 for (_k, v) in &mut *map {
2606 if v.from_dfn >= from_dfn {
2607 v.reached_depth = reached_depth.min(v.reached_depth);
2613 ProvisionalEvaluation { from_dfn, reached_depth, result, dep_node },
2617 /// Invoked when the node with dfn `dfn` does not get a successful
2618 /// result. This will clear out any provisional cache entries
2619 /// that were added since `dfn` was created. This is because the
2620 /// provisional entries are things which must assume that the
2621 /// things on the stack at the time of their creation succeeded --
2622 /// since the failing node is presently at the top of the stack,
2623 /// these provisional entries must either depend on it or some
2625 fn on_failure(&self, dfn: usize) {
2626 debug!(?dfn, "on_failure");
2627 self.map.borrow_mut().retain(|key, eval| {
2628 if !eval.from_dfn >= dfn {
2629 debug!("on_failure: removing {:?}", key);
2637 /// Invoked when the node at depth `depth` completed without
2638 /// depending on anything higher in the stack (if that completion
2639 /// was a failure, then `on_failure` should have been invoked
2640 /// already). The callback `op` will be invoked for each
2641 /// provisional entry that we can now confirm.
2643 /// Note that we may still have provisional cache items remaining
2644 /// in the cache when this is done. For example, if there is a
2647 /// * A depends on...
2648 /// * B depends on A
2649 /// * C depends on...
2650 /// * D depends on C
2653 /// Then as we complete the C node we will have a provisional cache
2654 /// with results for A, B, C, and D. This method would clear out
2655 /// the C and D results, but leave A and B provisional.
2657 /// This is determined based on the DFN: we remove any provisional
2658 /// results created since `dfn` started (e.g., in our example, dfn
2659 /// would be 2, representing the C node, and hence we would
2660 /// remove the result for D, which has DFN 3, but not the results for
2661 /// A and B, which have DFNs 0 and 1 respectively).
2665 mut op: impl FnMut(ty::PolyTraitPredicate<'tcx>, EvaluationResult, DepNodeIndex),
2667 debug!(?dfn, "on_completion");
2669 for (fresh_trait_pred, eval) in
2670 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2672 debug!(?fresh_trait_pred, ?eval, "on_completion");
2674 op(fresh_trait_pred, eval.result, eval.dep_node);
2679 #[derive(Copy, Clone)]
2680 struct TraitObligationStackList<'o, 'tcx> {
2681 cache: &'o ProvisionalEvaluationCache<'tcx>,
2682 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2685 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2686 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2687 TraitObligationStackList { cache, head: None }
2690 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2691 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2694 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2698 fn depth(&self) -> usize {
2699 if let Some(head) = self.head { head.depth } else { 0 }
2703 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2704 type Item = &'o TraitObligationStack<'o, 'tcx>;
2706 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2713 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2714 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2715 write!(f, "TraitObligationStack({:?})", self.obligation)
2719 pub enum ProjectionMatchesProjection {