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 ErrorReporting, ImplDerivedObligation, ImplDerivedObligationCause, Normalized, Obligation,
18 ObligationCause, ObligationCauseCode, Overflow, PredicateObligation, Selection, SelectionError,
19 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, FxIndexSet};
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::ty::abstract_const::NotConstEvaluatable;
36 use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
37 use rustc_middle::ty::fold::BottomUpFolder;
38 use rustc_middle::ty::relate::TypeRelation;
39 use rustc_middle::ty::SubstsRef;
40 use rustc_middle::ty::{self, EarlyBinder, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate};
41 use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable, TypeVisitable};
42 use rustc_span::symbol::sym;
44 use std::cell::{Cell, RefCell};
46 use std::fmt::{self, Display};
49 pub use rustc_middle::traits::select::*;
51 mod candidate_assembly;
54 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
55 pub enum IntercrateAmbiguityCause {
56 DownstreamCrate { trait_desc: String, self_desc: Option<String> },
57 UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
58 ReservationImpl { message: String },
61 impl IntercrateAmbiguityCause {
62 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
63 /// See #23980 for details.
64 pub fn add_intercrate_ambiguity_hint(&self, err: &mut Diagnostic) {
65 err.note(&self.intercrate_ambiguity_hint());
68 pub fn intercrate_ambiguity_hint(&self) -> String {
70 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } => {
71 let self_desc = if let Some(ty) = self_desc {
72 format!(" for type `{}`", ty)
76 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
78 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc } => {
79 let self_desc = if let Some(ty) = self_desc {
80 format!(" for type `{}`", ty)
85 "upstream crates may add a new impl of trait `{}`{} \
90 IntercrateAmbiguityCause::ReservationImpl { message } => message.clone(),
95 pub struct SelectionContext<'cx, 'tcx> {
96 infcx: &'cx InferCtxt<'cx, 'tcx>,
98 /// Freshener used specifically for entries on the obligation
99 /// stack. This ensures that all entries on the stack at one time
100 /// will have the same set of placeholder entries, which is
101 /// important for checking for trait bounds that recursively
102 /// require themselves.
103 freshener: TypeFreshener<'cx, 'tcx>,
105 /// During coherence we have to assume that other crates may add
106 /// additional impls which we currently don't know about.
108 /// To deal with this evaluation should be conservative
109 /// and consider the possibility of impls from outside this crate.
110 /// This comes up primarily when resolving ambiguity. Imagine
111 /// there is some trait reference `$0: Bar` where `$0` is an
112 /// inference variable. If `intercrate` is true, then we can never
113 /// say for sure that this reference is not implemented, even if
114 /// there are *no impls at all for `Bar`*, because `$0` could be
115 /// bound to some type that in a downstream crate that implements
118 /// Outside of coherence we set this to false because we are only
119 /// interested in types that the user could actually have written.
120 /// In other words, we consider `$0: Bar` to be unimplemented if
121 /// there is no type that the user could *actually name* that
122 /// would satisfy it. This avoids crippling inference, basically.
124 /// If `intercrate` is set, we remember predicates which were
125 /// considered ambiguous because of impls potentially added in other crates.
126 /// This is used in coherence to give improved diagnostics.
127 /// We don't do his until we detect a coherence error because it can
128 /// lead to false overflow results (#47139) and because always
129 /// computing it may negatively impact performance.
130 intercrate_ambiguity_causes: Option<FxIndexSet<IntercrateAmbiguityCause>>,
132 /// The mode that trait queries run in, which informs our error handling
133 /// policy. In essence, canonicalized queries need their errors propagated
134 /// rather than immediately reported because we do not have accurate spans.
135 query_mode: TraitQueryMode,
138 // A stack that walks back up the stack frame.
139 struct TraitObligationStack<'prev, 'tcx> {
140 obligation: &'prev TraitObligation<'tcx>,
142 /// The trait predicate from `obligation` but "freshened" with the
143 /// selection-context's freshener. Used to check for recursion.
144 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
146 /// Starts out equal to `depth` -- if, during evaluation, we
147 /// encounter a cycle, then we will set this flag to the minimum
148 /// depth of that cycle for all participants in the cycle. These
149 /// participants will then forego caching their results. This is
150 /// not the most efficient solution, but it addresses #60010. The
151 /// problem we are trying to prevent:
153 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
154 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
155 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
157 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
158 /// is `EvaluatedToOk`; this is because they were only considered
159 /// ok on the premise that if `A: AutoTrait` held, but we indeed
160 /// encountered a problem (later on) with `A: AutoTrait. So we
161 /// currently set a flag on the stack node for `B: AutoTrait` (as
162 /// well as the second instance of `A: AutoTrait`) to suppress
165 /// This is a simple, targeted fix. A more-performant fix requires
166 /// deeper changes, but would permit more caching: we could
167 /// basically defer caching until we have fully evaluated the
168 /// tree, and then cache the entire tree at once. In any case, the
169 /// performance impact here shouldn't be so horrible: every time
170 /// this is hit, we do cache at least one trait, so we only
171 /// evaluate each member of a cycle up to N times, where N is the
172 /// length of the cycle. This means the performance impact is
173 /// bounded and we shouldn't have any terrible worst-cases.
174 reached_depth: Cell<usize>,
176 previous: TraitObligationStackList<'prev, 'tcx>,
178 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
181 /// The depth-first number of this node in the search graph -- a
182 /// pre-order index. Basically, a freshly incremented counter.
186 struct SelectionCandidateSet<'tcx> {
187 // A list of candidates that definitely apply to the current
188 // obligation (meaning: types unify).
189 vec: Vec<SelectionCandidate<'tcx>>,
191 // If `true`, then there were candidates that might or might
192 // not have applied, but we couldn't tell. This occurs when some
193 // of the input types are type variables, in which case there are
194 // various "builtin" rules that might or might not trigger.
198 #[derive(PartialEq, Eq, Debug, Clone)]
199 struct EvaluatedCandidate<'tcx> {
200 candidate: SelectionCandidate<'tcx>,
201 evaluation: EvaluationResult,
204 /// When does the builtin impl for `T: Trait` apply?
206 enum BuiltinImplConditions<'tcx> {
207 /// The impl is conditional on `T1, T2, ...: Trait`.
208 Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
209 /// There is no built-in impl. There may be some other
210 /// candidate (a where-clause or user-defined impl).
212 /// It is unknown whether there is an impl.
216 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
217 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
220 freshener: infcx.freshener_keep_static(),
222 intercrate_ambiguity_causes: None,
223 query_mode: TraitQueryMode::Standard,
227 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
228 SelectionContext { intercrate: true, ..SelectionContext::new(infcx) }
231 pub fn with_query_mode(
232 infcx: &'cx InferCtxt<'cx, 'tcx>,
233 query_mode: TraitQueryMode,
234 ) -> SelectionContext<'cx, 'tcx> {
235 debug!(?query_mode, "with_query_mode");
236 SelectionContext { query_mode, ..SelectionContext::new(infcx) }
239 /// Enables tracking of intercrate ambiguity causes. See
240 /// the documentation of [`Self::intercrate_ambiguity_causes`] for more.
241 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
242 assert!(self.intercrate);
243 assert!(self.intercrate_ambiguity_causes.is_none());
244 self.intercrate_ambiguity_causes = Some(FxIndexSet::default());
245 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
248 /// Gets the intercrate ambiguity causes collected since tracking
249 /// was enabled and disables tracking at the same time. If
250 /// tracking is not enabled, just returns an empty vector.
251 pub fn take_intercrate_ambiguity_causes(&mut self) -> FxIndexSet<IntercrateAmbiguityCause> {
252 assert!(self.intercrate);
253 self.intercrate_ambiguity_causes.take().unwrap_or_default()
256 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
260 pub fn tcx(&self) -> TyCtxt<'tcx> {
264 pub fn is_intercrate(&self) -> bool {
268 ///////////////////////////////////////////////////////////////////////////
271 // The selection phase tries to identify *how* an obligation will
272 // be resolved. For example, it will identify which impl or
273 // parameter bound is to be used. The process can be inconclusive
274 // if the self type in the obligation is not fully inferred. Selection
275 // can result in an error in one of two ways:
277 // 1. If no applicable impl or parameter bound can be found.
278 // 2. If the output type parameters in the obligation do not match
279 // those specified by the impl/bound. For example, if the obligation
280 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
281 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
283 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
284 /// type environment by performing unification.
285 #[instrument(level = "debug", skip(self), ret)]
288 obligation: &TraitObligation<'tcx>,
289 ) -> SelectionResult<'tcx, Selection<'tcx>> {
290 let candidate = match self.select_from_obligation(obligation) {
291 Err(SelectionError::Overflow(OverflowError::Canonical)) => {
292 // In standard mode, overflow must have been caught and reported
294 assert!(self.query_mode == TraitQueryMode::Canonical);
295 return Err(SelectionError::Overflow(OverflowError::Canonical));
297 Err(SelectionError::Ambiguous(_)) => {
306 Ok(Some(candidate)) => candidate,
309 match self.confirm_candidate(obligation, candidate) {
310 Err(SelectionError::Overflow(OverflowError::Canonical)) => {
311 assert!(self.query_mode == TraitQueryMode::Canonical);
312 Err(SelectionError::Overflow(OverflowError::Canonical))
315 Ok(candidate) => Ok(Some(candidate)),
319 pub(crate) fn select_from_obligation(
321 obligation: &TraitObligation<'tcx>,
322 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
323 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
325 let pec = &ProvisionalEvaluationCache::default();
326 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
328 self.candidate_from_obligation(&stack)
331 ///////////////////////////////////////////////////////////////////////////
334 // Tests whether an obligation can be selected or whether an impl
335 // can be applied to particular types. It skips the "confirmation"
336 // step and hence completely ignores output type parameters.
338 // The result is "true" if the obligation *may* hold and "false" if
339 // we can be sure it does not.
341 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
342 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
343 debug!(?obligation, "predicate_may_hold_fatal");
345 // This fatal query is a stopgap that should only be used in standard mode,
346 // where we do not expect overflow to be propagated.
347 assert!(self.query_mode == TraitQueryMode::Standard);
349 self.evaluate_root_obligation(obligation)
350 .expect("Overflow should be caught earlier in standard query mode")
354 /// Evaluates whether the obligation `obligation` can be satisfied
355 /// and returns an `EvaluationResult`. This is meant for the
357 pub fn evaluate_root_obligation(
359 obligation: &PredicateObligation<'tcx>,
360 ) -> Result<EvaluationResult, OverflowError> {
361 self.evaluation_probe(|this| {
362 this.evaluate_predicate_recursively(
363 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
371 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
372 ) -> Result<EvaluationResult, OverflowError> {
373 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
374 let result = op(self)?;
376 match self.infcx.leak_check(true, snapshot) {
378 Err(_) => return Ok(EvaluatedToErr),
381 if self.infcx.opaque_types_added_in_snapshot(snapshot) {
382 return Ok(result.max(EvaluatedToOkModuloOpaqueTypes));
385 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
387 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
392 /// Evaluates the predicates in `predicates` recursively. Note that
393 /// this applies projections in the predicates, and therefore
394 /// is run within an inference probe.
395 #[instrument(skip(self, stack), level = "debug")]
396 fn evaluate_predicates_recursively<'o, I>(
398 stack: TraitObligationStackList<'o, 'tcx>,
400 ) -> Result<EvaluationResult, OverflowError>
402 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
404 let mut result = EvaluatedToOk;
405 for obligation in predicates {
406 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
407 if let EvaluatedToErr = eval {
408 // fast-path - EvaluatedToErr is the top of the lattice,
409 // so we don't need to look on the other predicates.
410 return Ok(EvaluatedToErr);
412 result = cmp::max(result, eval);
420 skip(self, previous_stack),
421 fields(previous_stack = ?previous_stack.head())
424 fn evaluate_predicate_recursively<'o>(
426 previous_stack: TraitObligationStackList<'o, 'tcx>,
427 obligation: PredicateObligation<'tcx>,
428 ) -> Result<EvaluationResult, OverflowError> {
429 // `previous_stack` stores a `TraitObligation`, while `obligation` is
430 // a `PredicateObligation`. These are distinct types, so we can't
431 // use any `Option` combinator method that would force them to be
433 match previous_stack.head() {
434 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
435 None => self.check_recursion_limit(&obligation, &obligation)?,
438 ensure_sufficient_stack(|| {
439 let bound_predicate = obligation.predicate.kind();
440 match bound_predicate.skip_binder() {
441 ty::PredicateKind::Trait(t) => {
442 let t = bound_predicate.rebind(t);
443 debug_assert!(!t.has_escaping_bound_vars());
444 let obligation = obligation.with(t);
445 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
448 ty::PredicateKind::Subtype(p) => {
449 let p = bound_predicate.rebind(p);
450 // Does this code ever run?
451 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
452 Ok(Ok(InferOk { mut obligations, .. })) => {
453 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
454 self.evaluate_predicates_recursively(
456 obligations.into_iter(),
459 Ok(Err(_)) => Ok(EvaluatedToErr),
460 Err(..) => Ok(EvaluatedToAmbig),
464 ty::PredicateKind::Coerce(p) => {
465 let p = bound_predicate.rebind(p);
466 // Does this code ever run?
467 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
468 Ok(Ok(InferOk { mut obligations, .. })) => {
469 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
470 self.evaluate_predicates_recursively(
472 obligations.into_iter(),
475 Ok(Err(_)) => Ok(EvaluatedToErr),
476 Err(..) => Ok(EvaluatedToAmbig),
480 ty::PredicateKind::WellFormed(arg) => {
481 // So, there is a bit going on here. First, `WellFormed` predicates
482 // are coinductive, like trait predicates with auto traits.
483 // This means that we need to detect if we have recursively
484 // evaluated `WellFormed(X)`. Otherwise, we would run into
485 // a "natural" overflow error.
487 // Now, the next question is whether we need to do anything
488 // special with caching. Considering the following tree:
493 // In this case, the innermost `WF(Foo<T>)` should return
494 // `EvaluatedToOk`, since it's coinductive. Then if
495 // `Bar<T>: Send` is resolved to `EvaluatedToOk`, it can be
496 // inserted into a cache (because without thinking about `WF`
497 // goals, it isn't in a cycle). If `Foo<T>: Trait` later doesn't
498 // hold, then `Bar<T>: Send` shouldn't hold. Therefore, we
499 // *do* need to keep track of coinductive cycles.
501 let cache = previous_stack.cache;
502 let dfn = cache.next_dfn();
504 for stack_arg in previous_stack.cache.wf_args.borrow().iter().rev() {
505 if stack_arg.0 != arg {
508 debug!("WellFormed({:?}) on stack", arg);
509 if let Some(stack) = previous_stack.head {
510 // Okay, let's imagine we have two different stacks:
511 // `T: NonAutoTrait -> WF(T) -> T: NonAutoTrait`
512 // `WF(T) -> T: NonAutoTrait -> WF(T)`
513 // Because of this, we need to check that all
514 // predicates between the WF goals are coinductive.
515 // Otherwise, we can say that `T: NonAutoTrait` is
517 // Let's imagine we have a predicate stack like
518 // `Foo: Bar -> WF(T) -> T: NonAutoTrait -> T: Auto
520 // and the current predicate is `WF(T)`. `wf_args`
521 // would contain `(T, 1)`. We want to check all
522 // trait predicates greater than `1`. The previous
523 // stack would be `T: Auto`.
524 let cycle = stack.iter().take_while(|s| s.depth > stack_arg.1);
525 let tcx = self.tcx();
527 cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
528 if self.coinductive_match(cycle) {
529 stack.update_reached_depth(stack_arg.1);
530 return Ok(EvaluatedToOk);
532 return Ok(EvaluatedToRecur);
535 return Ok(EvaluatedToOk);
538 match wf::obligations(
540 obligation.param_env,
541 obligation.cause.body_id,
542 obligation.recursion_depth + 1,
544 obligation.cause.span,
546 Some(mut obligations) => {
547 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
549 cache.wf_args.borrow_mut().push((arg, previous_stack.depth()));
551 self.evaluate_predicates_recursively(previous_stack, obligations);
552 cache.wf_args.borrow_mut().pop();
554 let result = result?;
556 if !result.must_apply_modulo_regions() {
557 cache.on_failure(dfn);
560 cache.on_completion(dfn);
564 None => Ok(EvaluatedToAmbig),
568 ty::PredicateKind::TypeOutlives(pred) => {
569 // A global type with no late-bound regions can only
570 // contain the "'static" lifetime (any other lifetime
571 // would either be late-bound or local), so it is guaranteed
572 // to outlive any other lifetime
573 if pred.0.is_global() && !pred.0.has_late_bound_regions() {
576 Ok(EvaluatedToOkModuloRegions)
580 ty::PredicateKind::RegionOutlives(..) => {
581 // We do not consider region relationships when evaluating trait matches.
582 Ok(EvaluatedToOkModuloRegions)
585 ty::PredicateKind::ObjectSafe(trait_def_id) => {
586 if self.tcx().is_object_safe(trait_def_id) {
593 ty::PredicateKind::Projection(data) => {
594 let data = bound_predicate.rebind(data);
595 let project_obligation = obligation.with(data);
596 match project::poly_project_and_unify_type(self, &project_obligation) {
597 ProjectAndUnifyResult::Holds(mut subobligations) => {
599 // If we've previously marked this projection as 'complete', then
600 // use the final cached result (either `EvaluatedToOk` or
601 // `EvaluatedToOkModuloRegions`), and skip re-evaluating the
604 ProjectionCacheKey::from_poly_projection_predicate(self, data)
606 if let Some(cached_res) = self
613 break 'compute_res Ok(cached_res);
618 subobligations.iter_mut(),
619 obligation.recursion_depth,
621 let res = self.evaluate_predicates_recursively(
625 if let Ok(eval_rslt) = res
626 && (eval_rslt == EvaluatedToOk || eval_rslt == EvaluatedToOkModuloRegions)
628 ProjectionCacheKey::from_poly_projection_predicate(
632 // If the result is something that we can cache, then mark this
633 // entry as 'complete'. This will allow us to skip evaluating the
634 // subobligations at all the next time we evaluate the projection
640 .complete(key, eval_rslt);
645 ProjectAndUnifyResult::FailedNormalization => Ok(EvaluatedToAmbig),
646 ProjectAndUnifyResult::Recursive => Ok(EvaluatedToRecur),
647 ProjectAndUnifyResult::MismatchedProjectionTypes(_) => Ok(EvaluatedToErr),
651 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
652 match self.infcx.closure_kind(closure_substs) {
653 Some(closure_kind) => {
654 if closure_kind.extends(kind) {
660 None => Ok(EvaluatedToAmbig),
664 ty::PredicateKind::ConstEvaluatable(uv) => {
665 match const_evaluatable::is_const_evaluatable(
668 obligation.param_env,
669 obligation.cause.span,
671 Ok(()) => Ok(EvaluatedToOk),
672 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
673 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
674 Err(_) => Ok(EvaluatedToErr),
678 ty::PredicateKind::ConstEquate(c1, c2) => {
679 debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
681 if self.tcx().features().generic_const_exprs {
682 // FIXME: we probably should only try to unify abstract constants
683 // if the constants depend on generic parameters.
685 // Let's just see where this breaks :shrug:
686 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
687 (c1.kind(), c2.kind())
689 if self.infcx.try_unify_abstract_consts(a, b, obligation.param_env) {
690 return Ok(EvaluatedToOk);
695 let evaluate = |c: ty::Const<'tcx>| {
696 if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() {
697 match self.infcx.try_const_eval_resolve(
698 obligation.param_env,
701 Some(obligation.cause.span),
711 match (evaluate(c1), evaluate(c2)) {
712 (Ok(c1), Ok(c2)) => {
715 .at(&obligation.cause, obligation.param_env)
718 Ok(_) => Ok(EvaluatedToOk),
719 Err(_) => Ok(EvaluatedToErr),
722 (Err(ErrorHandled::Reported(_)), _)
723 | (_, Err(ErrorHandled::Reported(_))) => Ok(EvaluatedToErr),
724 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
726 obligation.cause.span(),
727 "ConstEquate: const_eval_resolve returned an unexpected error"
730 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
731 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
734 // Two different constants using generic parameters ~> error.
740 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
741 bug!("TypeWellFormedFromEnv is only used for chalk")
747 #[instrument(skip(self, previous_stack), level = "debug", ret)]
748 fn evaluate_trait_predicate_recursively<'o>(
750 previous_stack: TraitObligationStackList<'o, 'tcx>,
751 mut obligation: TraitObligation<'tcx>,
752 ) -> Result<EvaluationResult, OverflowError> {
754 && obligation.is_global()
755 && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst())
757 // If a param env has no global bounds, global obligations do not
758 // depend on its particular value in order to work, so we can clear
759 // out the param env and get better caching.
761 obligation.param_env = obligation.param_env.without_caller_bounds();
764 let stack = self.push_stack(previous_stack, &obligation);
765 let mut fresh_trait_pred = stack.fresh_trait_pred;
766 let mut param_env = obligation.param_env;
768 fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| {
769 pred.remap_constness(&mut param_env);
773 debug!(?fresh_trait_pred);
775 // If a trait predicate is in the (local or global) evaluation cache,
776 // then we know it holds without cycles.
777 if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
782 if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
783 debug!("PROVISIONAL CACHE HIT");
784 stack.update_reached_depth(result.reached_depth);
785 return Ok(result.result);
788 // Check if this is a match for something already on the
789 // stack. If so, we don't want to insert the result into the
790 // main cache (it is cycle dependent) nor the provisional
791 // cache (which is meant for things that have completed but
792 // for a "backedge" -- this result *is* the backedge).
793 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
794 return Ok(cycle_result);
797 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
798 let result = result?;
800 if !result.must_apply_modulo_regions() {
801 stack.cache().on_failure(stack.dfn);
804 let reached_depth = stack.reached_depth.get();
805 if reached_depth >= stack.depth {
806 debug!("CACHE MISS");
807 self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
808 stack.cache().on_completion(stack.dfn);
810 debug!("PROVISIONAL");
812 "caching provisionally because {:?} \
813 is a cycle participant (at depth {}, reached depth {})",
814 fresh_trait_pred, stack.depth, reached_depth,
817 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_pred, result);
823 /// If there is any previous entry on the stack that precisely
824 /// matches this obligation, then we can assume that the
825 /// obligation is satisfied for now (still all other conditions
826 /// must be met of course). One obvious case this comes up is
827 /// marker traits like `Send`. Think of a linked list:
829 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
831 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
832 /// `Option<Box<List<T>>>` is `Send`, and in turn
833 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
836 /// Note that we do this comparison using the `fresh_trait_ref`
837 /// fields. Because these have all been freshened using
838 /// `self.freshener`, we can be sure that (a) this will not
839 /// affect the inferencer state and (b) that if we see two
840 /// fresh regions with the same index, they refer to the same
841 /// unbound type variable.
842 fn check_evaluation_cycle(
844 stack: &TraitObligationStack<'_, 'tcx>,
845 ) -> Option<EvaluationResult> {
846 if let Some(cycle_depth) = stack
848 .skip(1) // Skip top-most frame.
850 stack.obligation.param_env == prev.obligation.param_env
851 && stack.fresh_trait_pred == prev.fresh_trait_pred
853 .map(|stack| stack.depth)
855 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
857 // If we have a stack like `A B C D E A`, where the top of
858 // the stack is the final `A`, then this will iterate over
859 // `A, E, D, C, B` -- i.e., all the participants apart
860 // from the cycle head. We mark them as participating in a
861 // cycle. This suppresses caching for those nodes. See
862 // `in_cycle` field for more details.
863 stack.update_reached_depth(cycle_depth);
865 // Subtle: when checking for a coinductive cycle, we do
866 // not compare using the "freshened trait refs" (which
867 // have erased regions) but rather the fully explicit
868 // trait refs. This is important because it's only a cycle
869 // if the regions match exactly.
870 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
871 let tcx = self.tcx();
872 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
873 if self.coinductive_match(cycle) {
874 debug!("evaluate_stack --> recursive, coinductive");
877 debug!("evaluate_stack --> recursive, inductive");
878 Some(EvaluatedToRecur)
885 fn evaluate_stack<'o>(
887 stack: &TraitObligationStack<'o, 'tcx>,
888 ) -> Result<EvaluationResult, OverflowError> {
889 // In intercrate mode, whenever any of the generics are unbound,
890 // there can always be an impl. Even if there are no impls in
891 // this crate, perhaps the type would be unified with
892 // something from another crate that does provide an impl.
894 // In intra mode, we must still be conservative. The reason is
895 // that we want to avoid cycles. Imagine an impl like:
897 // impl<T:Eq> Eq for Vec<T>
899 // and a trait reference like `$0 : Eq` where `$0` is an
900 // unbound variable. When we evaluate this trait-reference, we
901 // will unify `$0` with `Vec<$1>` (for some fresh variable
902 // `$1`), on the condition that `$1 : Eq`. We will then wind
903 // up with many candidates (since that are other `Eq` impls
904 // that apply) and try to winnow things down. This results in
905 // a recursive evaluation that `$1 : Eq` -- as you can
906 // imagine, this is just where we started. To avoid that, we
907 // check for unbound variables and return an ambiguous (hence possible)
908 // match if we've seen this trait before.
910 // This suffices to allow chains like `FnMut` implemented in
911 // terms of `Fn` etc, but we could probably make this more
913 let unbound_input_types =
914 stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh());
916 if unbound_input_types
917 && stack.iter().skip(1).any(|prev| {
918 stack.obligation.param_env == prev.obligation.param_env
919 && self.match_fresh_trait_refs(
920 stack.fresh_trait_pred,
921 prev.fresh_trait_pred,
922 prev.obligation.param_env,
926 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
927 return Ok(EvaluatedToUnknown);
930 match self.candidate_from_obligation(stack) {
931 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
932 Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig),
933 Ok(None) => Ok(EvaluatedToAmbig),
934 Err(Overflow(OverflowError::Canonical)) => Err(OverflowError::Canonical),
935 Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
936 Err(..) => Ok(EvaluatedToErr),
940 /// For defaulted traits, we use a co-inductive strategy to solve, so
941 /// that recursion is ok. This routine returns `true` if the top of the
942 /// stack (`cycle[0]`):
944 /// - is a defaulted trait,
945 /// - it also appears in the backtrace at some position `X`,
946 /// - all the predicates at positions `X..` between `X` and the top are
947 /// also defaulted traits.
948 pub(crate) fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
950 I: Iterator<Item = ty::Predicate<'tcx>>,
952 cycle.all(|predicate| self.coinductive_predicate(predicate))
955 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
956 let result = match predicate.kind().skip_binder() {
957 ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
958 ty::PredicateKind::WellFormed(_) => true,
961 debug!(?predicate, ?result, "coinductive_predicate");
965 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
966 /// obligations are met. Returns whether `candidate` remains viable after this further
971 fields(depth = stack.obligation.recursion_depth),
974 fn evaluate_candidate<'o>(
976 stack: &TraitObligationStack<'o, 'tcx>,
977 candidate: &SelectionCandidate<'tcx>,
978 ) -> Result<EvaluationResult, OverflowError> {
979 let mut result = self.evaluation_probe(|this| {
980 let candidate = (*candidate).clone();
981 match this.confirm_candidate(stack.obligation, candidate) {
984 this.evaluate_predicates_recursively(
986 selection.nested_obligations().into_iter(),
989 Err(..) => Ok(EvaluatedToErr),
993 // If we erased any lifetimes, then we want to use
994 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
995 // as your final result. The result will be cached using
996 // the freshened trait predicate as a key, so we need
997 // our result to be correct by *any* choice of original lifetimes,
998 // not just the lifetime choice for this particular (non-erased)
1001 if stack.fresh_trait_pred.has_erased_regions() {
1002 result = result.max(EvaluatedToOkModuloRegions);
1008 fn check_evaluation_cache(
1010 param_env: ty::ParamEnv<'tcx>,
1011 trait_pred: ty::PolyTraitPredicate<'tcx>,
1012 ) -> Option<EvaluationResult> {
1013 // Neither the global nor local cache is aware of intercrate
1014 // mode, so don't do any caching. In particular, we might
1015 // re-use the same `InferCtxt` with both an intercrate
1016 // and non-intercrate `SelectionContext`
1017 if self.intercrate {
1021 let tcx = self.tcx();
1022 if self.can_use_global_caches(param_env) {
1023 if let Some(res) = tcx.evaluation_cache.get(&(param_env, trait_pred), tcx) {
1027 self.infcx.evaluation_cache.get(&(param_env, trait_pred), tcx)
1030 fn insert_evaluation_cache(
1032 param_env: ty::ParamEnv<'tcx>,
1033 trait_pred: ty::PolyTraitPredicate<'tcx>,
1034 dep_node: DepNodeIndex,
1035 result: EvaluationResult,
1037 // Avoid caching results that depend on more than just the trait-ref
1038 // - the stack can create recursion.
1039 if result.is_stack_dependent() {
1043 // Neither the global nor local cache is aware of intercrate
1044 // mode, so don't do any caching. In particular, we might
1045 // re-use the same `InferCtxt` with both an intercrate
1046 // and non-intercrate `SelectionContext`
1047 if self.intercrate {
1051 if self.can_use_global_caches(param_env) {
1052 if !trait_pred.needs_infer() {
1053 debug!(?trait_pred, ?result, "insert_evaluation_cache global");
1054 // This may overwrite the cache with the same value
1055 // FIXME: Due to #50507 this overwrites the different values
1056 // This should be changed to use HashMapExt::insert_same
1057 // when that is fixed
1058 self.tcx().evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1063 debug!(?trait_pred, ?result, "insert_evaluation_cache");
1064 self.infcx.evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1067 /// For various reasons, it's possible for a subobligation
1068 /// to have a *lower* recursion_depth than the obligation used to create it.
1069 /// Projection sub-obligations may be returned from the projection cache,
1070 /// which results in obligations with an 'old' `recursion_depth`.
1071 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1072 /// subobligations without taking in a 'parent' depth, causing the
1073 /// generated subobligations to have a `recursion_depth` of `0`.
1075 /// To ensure that obligation_depth never decreases, we force all subobligations
1076 /// to have at least the depth of the original obligation.
1077 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1082 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1085 fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
1088 error_obligation: &Obligation<'tcx, T>,
1089 ) -> Result<(), OverflowError> {
1090 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1091 match self.query_mode {
1092 TraitQueryMode::Standard => {
1093 if self.infcx.is_tainted_by_errors() {
1094 return Err(OverflowError::Error(
1095 ErrorGuaranteed::unchecked_claim_error_was_emitted(),
1098 self.infcx.report_overflow_error(error_obligation, true);
1100 TraitQueryMode::Canonical => {
1101 return Err(OverflowError::Canonical);
1108 /// Checks that the recursion limit has not been exceeded.
1110 /// The weird return type of this function allows it to be used with the `try` (`?`)
1111 /// operator within certain functions.
1113 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1115 obligation: &Obligation<'tcx, T>,
1116 error_obligation: &Obligation<'tcx, V>,
1117 ) -> Result<(), OverflowError> {
1118 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1121 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1123 OP: FnOnce(&mut Self) -> R,
1125 let (result, dep_node) =
1126 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1127 self.tcx().dep_graph.read_index(dep_node);
1131 /// filter_impls filters constant trait obligations and candidates that have a positive impl
1132 /// for a negative goal and a negative impl for a positive goal
1133 #[instrument(level = "debug", skip(self))]
1136 candidates: Vec<SelectionCandidate<'tcx>>,
1137 obligation: &TraitObligation<'tcx>,
1138 ) -> Vec<SelectionCandidate<'tcx>> {
1139 let tcx = self.tcx();
1140 let mut result = Vec::with_capacity(candidates.len());
1142 for candidate in candidates {
1143 // Respect const trait obligations
1144 if obligation.is_const() {
1147 ImplCandidate(def_id) if tcx.constness(def_id) == hir::Constness::Const => {}
1149 ParamCandidate(trait_pred) if trait_pred.is_const_if_const() => {}
1151 ProjectionCandidate(_, ty::BoundConstness::ConstIfConst) => {}
1153 AutoImplCandidate(..) => {}
1154 // generator, this will raise error in other places
1155 // or ignore error with const_async_blocks feature
1156 GeneratorCandidate => {}
1157 // FnDef where the function is const
1158 FnPointerCandidate { is_const: true } => {}
1159 ConstDestructCandidate(_) => {}
1161 // reject all other types of candidates
1167 if let ImplCandidate(def_id) = candidate {
1168 if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id)
1169 || obligation.polarity() == tcx.impl_polarity(def_id)
1171 result.push(candidate);
1174 result.push(candidate);
1181 /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1182 #[instrument(level = "debug", skip(self))]
1183 fn filter_reservation_impls(
1185 candidate: SelectionCandidate<'tcx>,
1186 obligation: &TraitObligation<'tcx>,
1187 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1188 let tcx = self.tcx();
1189 // Treat reservation impls as ambiguity.
1190 if let ImplCandidate(def_id) = candidate {
1191 if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
1192 if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1194 .get_attr(def_id, sym::rustc_reservation_impl)
1195 .and_then(|a| a.value_str());
1196 if let Some(value) = value {
1198 "filter_reservation_impls: \
1199 reservation impl ambiguity on {:?}",
1202 intercrate_ambiguity_clauses.insert(
1203 IntercrateAmbiguityCause::ReservationImpl {
1204 message: value.to_string(),
1215 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Result<(), Conflict> {
1216 debug!("is_knowable(intercrate={:?})", self.intercrate);
1218 if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative {
1222 let obligation = &stack.obligation;
1223 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1225 // Okay to skip binder because of the nature of the
1226 // trait-ref-is-knowable check, which does not care about
1228 let trait_ref = predicate.skip_binder().trait_ref;
1230 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1233 /// Returns `true` if the global caches can be used.
1234 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1235 // If there are any inference variables in the `ParamEnv`, then we
1236 // always use a cache local to this particular scope. Otherwise, we
1237 // switch to a global cache.
1238 if param_env.needs_infer() {
1242 // Avoid using the master cache during coherence and just rely
1243 // on the local cache. This effectively disables caching
1244 // during coherence. It is really just a simplification to
1245 // avoid us having to fear that coherence results "pollute"
1246 // the master cache. Since coherence executes pretty quickly,
1247 // it's not worth going to more trouble to increase the
1248 // hit-rate, I don't think.
1249 if self.intercrate {
1253 // Otherwise, we can use the global cache.
1257 fn check_candidate_cache(
1259 mut param_env: ty::ParamEnv<'tcx>,
1260 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1261 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1262 // Neither the global nor local cache is aware of intercrate
1263 // mode, so don't do any caching. In particular, we might
1264 // re-use the same `InferCtxt` with both an intercrate
1265 // and non-intercrate `SelectionContext`
1266 if self.intercrate {
1269 let tcx = self.tcx();
1270 let mut pred = cache_fresh_trait_pred.skip_binder();
1271 pred.remap_constness(&mut param_env);
1273 if self.can_use_global_caches(param_env) {
1274 if let Some(res) = tcx.selection_cache.get(&(param_env, pred), tcx) {
1278 self.infcx.selection_cache.get(&(param_env, pred), tcx)
1281 /// Determines whether can we safely cache the result
1282 /// of selecting an obligation. This is almost always `true`,
1283 /// except when dealing with certain `ParamCandidate`s.
1285 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1286 /// since it was usually produced directly from a `DefId`. However,
1287 /// certain cases (currently only librustdoc's blanket impl finder),
1288 /// a `ParamEnv` may be explicitly constructed with inference types.
1289 /// When this is the case, we do *not* want to cache the resulting selection
1290 /// candidate. This is due to the fact that it might not always be possible
1291 /// to equate the obligation's trait ref and the candidate's trait ref,
1292 /// if more constraints end up getting added to an inference variable.
1294 /// Because of this, we always want to re-run the full selection
1295 /// process for our obligation the next time we see it, since
1296 /// we might end up picking a different `SelectionCandidate` (or none at all).
1297 fn can_cache_candidate(
1299 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1301 // Neither the global nor local cache is aware of intercrate
1302 // mode, so don't do any caching. In particular, we might
1303 // re-use the same `InferCtxt` with both an intercrate
1304 // and non-intercrate `SelectionContext`
1305 if self.intercrate {
1309 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1314 #[instrument(skip(self, param_env, cache_fresh_trait_pred, dep_node), level = "debug")]
1315 fn insert_candidate_cache(
1317 mut param_env: ty::ParamEnv<'tcx>,
1318 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1319 dep_node: DepNodeIndex,
1320 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1322 let tcx = self.tcx();
1323 let mut pred = cache_fresh_trait_pred.skip_binder();
1325 pred.remap_constness(&mut param_env);
1327 if !self.can_cache_candidate(&candidate) {
1328 debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1332 if self.can_use_global_caches(param_env) {
1333 if let Err(Overflow(OverflowError::Canonical)) = candidate {
1334 // Don't cache overflow globally; we only produce this in certain modes.
1335 } else if !pred.needs_infer() {
1336 if !candidate.needs_infer() {
1337 debug!(?pred, ?candidate, "insert_candidate_cache global");
1338 // This may overwrite the cache with the same value.
1339 tcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1345 debug!(?pred, ?candidate, "insert_candidate_cache local");
1346 self.infcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1349 /// Matches a predicate against the bounds of its self type.
1351 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1352 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1353 /// `Baz` bound. We return indexes into the list returned by
1354 /// `tcx.item_bounds` for any applicable bounds.
1355 #[instrument(level = "debug", skip(self), ret)]
1356 fn match_projection_obligation_against_definition_bounds(
1358 obligation: &TraitObligation<'tcx>,
1359 ) -> smallvec::SmallVec<[(usize, ty::BoundConstness); 2]> {
1360 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1361 let placeholder_trait_predicate =
1362 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1363 debug!(?placeholder_trait_predicate);
1365 let tcx = self.infcx.tcx;
1366 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1367 ty::Projection(ref data) => (data.item_def_id, data.substs),
1368 ty::Opaque(def_id, substs) => (def_id, substs),
1371 obligation.cause.span,
1372 "match_projection_obligation_against_definition_bounds() called \
1373 but self-ty is not a projection: {:?}",
1374 placeholder_trait_predicate.trait_ref.self_ty()
1378 let bounds = tcx.bound_item_bounds(def_id).subst(tcx, substs);
1380 // The bounds returned by `item_bounds` may contain duplicates after
1381 // normalization, so try to deduplicate when possible to avoid
1382 // unnecessary ambiguity.
1383 let mut distinct_normalized_bounds = FxHashSet::default();
1388 .filter_map(|(idx, bound)| {
1389 let bound_predicate = bound.kind();
1390 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1391 let bound = bound_predicate.rebind(pred.trait_ref);
1392 if self.infcx.probe(|_| {
1393 match self.match_normalize_trait_ref(
1396 placeholder_trait_predicate.trait_ref,
1399 Ok(Some(normalized_trait))
1400 if distinct_normalized_bounds.insert(normalized_trait) =>
1407 return Some((idx, pred.constness));
1415 /// Equates the trait in `obligation` with trait bound. If the two traits
1416 /// can be equated and the normalized trait bound doesn't contain inference
1417 /// variables or placeholders, the normalized bound is returned.
1418 fn match_normalize_trait_ref(
1420 obligation: &TraitObligation<'tcx>,
1421 trait_bound: ty::PolyTraitRef<'tcx>,
1422 placeholder_trait_ref: ty::TraitRef<'tcx>,
1423 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1424 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1425 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1426 // Avoid unnecessary normalization
1430 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1431 project::normalize_with_depth(
1433 obligation.param_env,
1434 obligation.cause.clone(),
1435 obligation.recursion_depth + 1,
1440 .at(&obligation.cause, obligation.param_env)
1441 .define_opaque_types(false)
1442 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1443 .map(|InferOk { obligations: _, value: () }| {
1444 // This method is called within a probe, so we can't have
1445 // inference variables and placeholders escape.
1446 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1455 fn where_clause_may_apply<'o>(
1457 stack: &TraitObligationStack<'o, 'tcx>,
1458 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1459 ) -> Result<EvaluationResult, OverflowError> {
1460 self.evaluation_probe(|this| {
1461 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1462 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1463 Err(()) => Ok(EvaluatedToErr),
1468 /// Return `Yes` if the obligation's predicate type applies to the env_predicate, and
1469 /// `No` if it does not. Return `Ambiguous` in the case that the projection type is a GAT,
1470 /// and applying this env_predicate constrains any of the obligation's GAT substitutions.
1472 /// This behavior is a somewhat of a hack to prevent over-constraining inference variables
1473 /// in cases like #91762.
1474 pub(super) fn match_projection_projections(
1476 obligation: &ProjectionTyObligation<'tcx>,
1477 env_predicate: PolyProjectionPredicate<'tcx>,
1478 potentially_unnormalized_candidates: bool,
1479 ) -> ProjectionMatchesProjection {
1480 let mut nested_obligations = Vec::new();
1481 let infer_predicate = self.infcx.replace_bound_vars_with_fresh_vars(
1482 obligation.cause.span,
1483 LateBoundRegionConversionTime::HigherRankedType,
1486 let infer_projection = if potentially_unnormalized_candidates {
1487 ensure_sufficient_stack(|| {
1488 project::normalize_with_depth_to(
1490 obligation.param_env,
1491 obligation.cause.clone(),
1492 obligation.recursion_depth + 1,
1493 infer_predicate.projection_ty,
1494 &mut nested_obligations,
1498 infer_predicate.projection_ty
1503 .at(&obligation.cause, obligation.param_env)
1504 .define_opaque_types(false)
1505 .sup(obligation.predicate, infer_projection)
1506 .map_or(false, |InferOk { obligations, value: () }| {
1507 self.evaluate_predicates_recursively(
1508 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1509 nested_obligations.into_iter().chain(obligations),
1511 .map_or(false, |res| res.may_apply())
1515 let generics = self.tcx().generics_of(obligation.predicate.item_def_id);
1516 // FIXME(generic-associated-types): Addresses aggressive inference in #92917.
1517 // If this type is a GAT, and of the GAT substs resolve to something new,
1518 // that means that we must have newly inferred something about the GAT.
1519 // We should give up in that case.
1520 if !generics.params.is_empty()
1521 && obligation.predicate.substs[generics.parent_count..]
1523 .any(|&p| p.has_infer_types_or_consts() && self.infcx.shallow_resolve(p) != p)
1525 ProjectionMatchesProjection::Ambiguous
1527 ProjectionMatchesProjection::Yes
1530 ProjectionMatchesProjection::No
1534 ///////////////////////////////////////////////////////////////////////////
1537 // Winnowing is the process of attempting to resolve ambiguity by
1538 // probing further. During the winnowing process, we unify all
1539 // type variables and then we also attempt to evaluate recursive
1540 // bounds to see if they are satisfied.
1542 /// Returns `true` if `victim` should be dropped in favor of
1543 /// `other`. Generally speaking we will drop duplicate
1544 /// candidates and prefer where-clause candidates.
1546 /// See the comment for "SelectionCandidate" for more details.
1547 fn candidate_should_be_dropped_in_favor_of(
1549 victim: &EvaluatedCandidate<'tcx>,
1550 other: &EvaluatedCandidate<'tcx>,
1553 if victim.candidate == other.candidate {
1557 // Check if a bound would previously have been removed when normalizing
1558 // the param_env so that it can be given the lowest priority. See
1559 // #50825 for the motivation for this.
1560 let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| {
1561 cand.is_global() && !cand.has_late_bound_regions()
1564 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1565 // `DiscriminantKindCandidate`, `ConstDestructCandidate`, and `TupleCandidate`
1566 // to anything else.
1568 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1569 // lifetime of a variable.
1570 match (&other.candidate, &victim.candidate) {
1571 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1573 "default implementations shouldn't be recorded \
1574 when there are other valid candidates"
1578 // FIXME(@jswrenn): this should probably be more sophisticated
1579 (TransmutabilityCandidate, _) | (_, TransmutabilityCandidate) => false,
1583 BuiltinCandidate { has_nested: false }
1584 | DiscriminantKindCandidate
1586 | ConstDestructCandidate(_)
1592 BuiltinCandidate { has_nested: false }
1593 | DiscriminantKindCandidate
1595 | ConstDestructCandidate(_)
1599 (ParamCandidate(other), ParamCandidate(victim)) => {
1600 let same_except_bound_vars = other.skip_binder().trait_ref
1601 == victim.skip_binder().trait_ref
1602 && other.skip_binder().constness == victim.skip_binder().constness
1603 && other.skip_binder().polarity == victim.skip_binder().polarity
1604 && !other.skip_binder().trait_ref.has_escaping_bound_vars();
1605 if same_except_bound_vars {
1606 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1607 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1608 // or the current one if tied (they should both evaluate to the same answer). This is
1609 // probably best characterized as a "hack", since we might prefer to just do our
1610 // best to *not* create essentially duplicate candidates in the first place.
1611 other.bound_vars().len() <= victim.bound_vars().len()
1612 } else if other.skip_binder().trait_ref == victim.skip_binder().trait_ref
1613 && victim.skip_binder().constness == ty::BoundConstness::NotConst
1614 && other.skip_binder().polarity == victim.skip_binder().polarity
1616 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1623 // Drop otherwise equivalent non-const fn pointer candidates
1624 (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
1626 // Global bounds from the where clause should be ignored
1627 // here (see issue #50825). Otherwise, we have a where
1628 // clause so don't go around looking for impls.
1629 // Arbitrarily give param candidates priority
1630 // over projection and object candidates.
1632 ParamCandidate(ref cand),
1635 | GeneratorCandidate
1636 | FnPointerCandidate { .. }
1637 | BuiltinObjectCandidate
1638 | BuiltinUnsizeCandidate
1639 | TraitUpcastingUnsizeCandidate(_)
1640 | BuiltinCandidate { .. }
1641 | TraitAliasCandidate(..)
1642 | ObjectCandidate(_)
1643 | ProjectionCandidate(..),
1644 ) => !is_global(cand),
1645 (ObjectCandidate(_) | ProjectionCandidate(..), ParamCandidate(ref cand)) => {
1646 // Prefer these to a global where-clause bound
1647 // (see issue #50825).
1653 | GeneratorCandidate
1654 | FnPointerCandidate { .. }
1655 | BuiltinObjectCandidate
1656 | BuiltinUnsizeCandidate
1657 | TraitUpcastingUnsizeCandidate(_)
1658 | BuiltinCandidate { has_nested: true }
1659 | TraitAliasCandidate(..),
1660 ParamCandidate(ref cand),
1662 // Prefer these to a global where-clause bound
1663 // (see issue #50825).
1664 is_global(cand) && other.evaluation.must_apply_modulo_regions()
1667 (ProjectionCandidate(i, _), ProjectionCandidate(j, _))
1668 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1669 // Arbitrarily pick the lower numbered candidate for backwards
1670 // compatibility reasons. Don't let this affect inference.
1671 i < j && !needs_infer
1673 (ObjectCandidate(_), ProjectionCandidate(..))
1674 | (ProjectionCandidate(..), ObjectCandidate(_)) => {
1675 bug!("Have both object and projection candidate")
1678 // Arbitrarily give projection and object candidates priority.
1680 ObjectCandidate(_) | ProjectionCandidate(..),
1683 | GeneratorCandidate
1684 | FnPointerCandidate { .. }
1685 | BuiltinObjectCandidate
1686 | BuiltinUnsizeCandidate
1687 | TraitUpcastingUnsizeCandidate(_)
1688 | BuiltinCandidate { .. }
1689 | TraitAliasCandidate(..),
1695 | GeneratorCandidate
1696 | FnPointerCandidate { .. }
1697 | BuiltinObjectCandidate
1698 | BuiltinUnsizeCandidate
1699 | TraitUpcastingUnsizeCandidate(_)
1700 | BuiltinCandidate { .. }
1701 | TraitAliasCandidate(..),
1702 ObjectCandidate(_) | ProjectionCandidate(..),
1705 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1706 // See if we can toss out `victim` based on specialization.
1707 // While this requires us to know *for sure* that the `other` impl applies
1708 // we still use modulo regions here.
1710 // This is fine as specialization currently assumes that specializing
1711 // impls have to be always applicable, meaning that the only allowed
1712 // region constraints may be constraints also present on the default impl.
1713 let tcx = self.tcx();
1714 if other.evaluation.must_apply_modulo_regions() {
1715 if tcx.specializes((other_def, victim_def)) {
1720 if other.evaluation.must_apply_considering_regions() {
1721 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1722 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1723 // Subtle: If the predicate we are evaluating has inference
1724 // variables, do *not* allow discarding candidates due to
1725 // marker trait impls.
1727 // Without this restriction, we could end up accidentally
1728 // constraining inference variables based on an arbitrarily
1729 // chosen trait impl.
1731 // Imagine we have the following code:
1734 // #[marker] trait MyTrait {}
1735 // impl MyTrait for u8 {}
1736 // impl MyTrait for bool {}
1739 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1741 // During selection, we will end up with one candidate for each
1742 // impl of `MyTrait`. If we were to discard one impl in favor
1743 // of the other, we would be left with one candidate, causing
1744 // us to "successfully" select the predicate, unifying
1745 // _#0t with (for example) `u8`.
1747 // However, we have no reason to believe that this unification
1748 // is correct - we've essentially just picked an arbitrary
1749 // *possibility* for _#0t, and required that this be the *only*
1752 // Eventually, we will either:
1753 // 1) Unify all inference variables in the predicate through
1754 // some other means (e.g. type-checking of a function). We will
1755 // then be in a position to drop marker trait candidates
1756 // without constraining inference variables (since there are
1757 // none left to constrain)
1758 // 2) Be left with some unconstrained inference variables. We
1759 // will then correctly report an inference error, since the
1760 // existence of multiple marker trait impls tells us nothing
1761 // about which one should actually apply.
1772 // Everything else is ambiguous
1776 | GeneratorCandidate
1777 | FnPointerCandidate { .. }
1778 | BuiltinObjectCandidate
1779 | BuiltinUnsizeCandidate
1780 | TraitUpcastingUnsizeCandidate(_)
1781 | BuiltinCandidate { has_nested: true }
1782 | TraitAliasCandidate(..),
1785 | GeneratorCandidate
1786 | FnPointerCandidate { .. }
1787 | BuiltinObjectCandidate
1788 | BuiltinUnsizeCandidate
1789 | TraitUpcastingUnsizeCandidate(_)
1790 | BuiltinCandidate { has_nested: true }
1791 | TraitAliasCandidate(..),
1796 fn sized_conditions(
1798 obligation: &TraitObligation<'tcx>,
1799 ) -> BuiltinImplConditions<'tcx> {
1800 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1802 // NOTE: binder moved to (*)
1803 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1805 match self_ty.kind() {
1806 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1817 | ty::GeneratorWitness(..)
1821 | ty::Dynamic(_, _, ty::DynStar)
1823 // safe for everything
1824 Where(ty::Binder::dummy(Vec::new()))
1827 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1829 ty::Tuple(tys) => Where(
1830 obligation.predicate.rebind(tys.last().map_or_else(Vec::new, |&last| vec![last])),
1833 ty::Adt(def, substs) => {
1834 let sized_crit = def.sized_constraint(self.tcx());
1835 // (*) binder moved here
1836 Where(obligation.predicate.rebind({
1840 .map(|ty| sized_crit.rebind(*ty).subst(self.tcx(), substs))
1845 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1846 ty::Infer(ty::TyVar(_)) => Ambiguous,
1850 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1851 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1856 fn copy_clone_conditions(
1858 obligation: &TraitObligation<'tcx>,
1859 ) -> BuiltinImplConditions<'tcx> {
1860 // NOTE: binder moved to (*)
1861 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1863 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1865 match *self_ty.kind() {
1866 ty::Infer(ty::IntVar(_))
1867 | ty::Infer(ty::FloatVar(_))
1870 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1879 | ty::Ref(_, _, hir::Mutability::Not)
1880 | ty::Array(..) => {
1881 // Implementations provided in libcore
1888 | ty::Generator(_, _, hir::Movability::Static)
1890 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1893 // (*) binder moved here
1894 Where(obligation.predicate.rebind(tys.iter().collect()))
1897 ty::Generator(_, substs, hir::Movability::Movable) => {
1898 if self.tcx().features().generator_clone {
1899 let resolved_upvars =
1900 self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
1901 let resolved_witness =
1902 self.infcx.shallow_resolve(substs.as_generator().witness());
1903 if resolved_upvars.is_ty_var() || resolved_witness.is_ty_var() {
1904 // Not yet resolved.
1910 .chain(iter::once(substs.as_generator().witness()))
1911 .collect::<Vec<_>>();
1912 Where(obligation.predicate.rebind(all))
1919 ty::GeneratorWitness(binder) => {
1920 let witness_tys = binder.skip_binder();
1921 for witness_ty in witness_tys.iter() {
1922 let resolved = self.infcx.shallow_resolve(witness_ty);
1923 if resolved.is_ty_var() {
1927 // (*) binder moved here
1928 let all_vars = self.tcx().mk_bound_variable_kinds(
1929 obligation.predicate.bound_vars().iter().chain(binder.bound_vars().iter()),
1931 Where(ty::Binder::bind_with_vars(witness_tys.to_vec(), all_vars))
1934 ty::Closure(_, substs) => {
1935 // (*) binder moved here
1936 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1937 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1938 // Not yet resolved.
1941 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1945 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1946 // Fallback to whatever user-defined impls exist in this case.
1950 ty::Infer(ty::TyVar(_)) => {
1951 // Unbound type variable. Might or might not have
1952 // applicable impls and so forth, depending on what
1953 // those type variables wind up being bound to.
1959 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1960 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1965 /// For default impls, we need to break apart a type into its
1966 /// "constituent types" -- meaning, the types that it contains.
1968 /// Here are some (simple) examples:
1970 /// ```ignore (illustrative)
1971 /// (i32, u32) -> [i32, u32]
1972 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1973 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1974 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1976 fn constituent_types_for_ty(
1978 t: ty::Binder<'tcx, Ty<'tcx>>,
1979 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1980 match *t.skip_binder().kind() {
1989 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1991 | ty::Char => ty::Binder::dummy(Vec::new()),
1997 | ty::Projection(..)
1999 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2000 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2003 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2004 t.rebind(vec![element_ty])
2007 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
2009 ty::Tuple(ref tys) => {
2010 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2011 t.rebind(tys.iter().collect())
2014 ty::Closure(_, ref substs) => {
2015 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
2019 ty::Generator(_, ref substs, _) => {
2020 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
2021 let witness = substs.as_generator().witness();
2022 t.rebind([ty].into_iter().chain(iter::once(witness)).collect())
2025 ty::GeneratorWitness(types) => {
2026 debug_assert!(!types.has_escaping_bound_vars());
2027 types.map_bound(|types| types.to_vec())
2030 // For `PhantomData<T>`, we pass `T`.
2031 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
2033 ty::Adt(def, substs) => {
2034 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
2037 ty::Opaque(def_id, substs) => {
2038 // We can resolve the `impl Trait` to its concrete type,
2039 // which enforces a DAG between the functions requiring
2040 // the auto trait bounds in question.
2041 t.rebind(vec![self.tcx().bound_type_of(def_id).subst(self.tcx(), substs)])
2046 fn collect_predicates_for_types(
2048 param_env: ty::ParamEnv<'tcx>,
2049 cause: ObligationCause<'tcx>,
2050 recursion_depth: usize,
2051 trait_def_id: DefId,
2052 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
2053 ) -> Vec<PredicateObligation<'tcx>> {
2054 // Because the types were potentially derived from
2055 // higher-ranked obligations they may reference late-bound
2056 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2057 // yield a type like `for<'a> &'a i32`. In general, we
2058 // maintain the invariant that we never manipulate bound
2059 // regions, so we have to process these bound regions somehow.
2061 // The strategy is to:
2063 // 1. Instantiate those regions to placeholder regions (e.g.,
2064 // `for<'a> &'a i32` becomes `&0 i32`.
2065 // 2. Produce something like `&'0 i32 : Copy`
2066 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2070 .skip_binder() // binder moved -\
2073 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(*ty); // <----/
2075 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
2076 let Normalized { value: normalized_ty, mut obligations } =
2077 ensure_sufficient_stack(|| {
2078 project::normalize_with_depth(
2086 let placeholder_obligation = predicate_for_trait_def(
2095 obligations.push(placeholder_obligation);
2101 ///////////////////////////////////////////////////////////////////////////
2104 // Matching is a common path used for both evaluation and
2105 // confirmation. It basically unifies types that appear in impls
2106 // and traits. This does affect the surrounding environment;
2107 // therefore, when used during evaluation, match routines must be
2108 // run inside of a `probe()` so that their side-effects are
2114 obligation: &TraitObligation<'tcx>,
2115 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
2116 let impl_trait_ref = self.tcx().bound_impl_trait_ref(impl_def_id).unwrap();
2117 match self.match_impl(impl_def_id, impl_trait_ref, obligation) {
2118 Ok(substs) => substs,
2120 self.infcx.tcx.sess.delay_span_bug(
2121 obligation.cause.span,
2123 "Impl {:?} was matchable against {:?} but now is not",
2124 impl_def_id, obligation
2127 let value = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2128 let err = self.tcx().ty_error();
2129 let value = value.fold_with(&mut BottomUpFolder {
2135 Normalized { value, obligations: vec![] }
2140 #[instrument(level = "debug", skip(self), ret)]
2144 impl_trait_ref: EarlyBinder<ty::TraitRef<'tcx>>,
2145 obligation: &TraitObligation<'tcx>,
2146 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2147 let placeholder_obligation =
2148 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
2149 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2151 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2153 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2155 debug!(?impl_trait_ref);
2157 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2158 ensure_sufficient_stack(|| {
2159 project::normalize_with_depth(
2161 obligation.param_env,
2162 obligation.cause.clone(),
2163 obligation.recursion_depth + 1,
2168 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2170 let cause = ObligationCause::new(
2171 obligation.cause.span,
2172 obligation.cause.body_id,
2173 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2176 let InferOk { obligations, .. } = self
2178 .at(&cause, obligation.param_env)
2179 .define_opaque_types(false)
2180 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2181 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{e}`"))?;
2182 nested_obligations.extend(obligations);
2185 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2187 debug!("reservation impls only apply in intercrate mode");
2191 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2194 fn fast_reject_trait_refs(
2196 obligation: &TraitObligation<'tcx>,
2197 impl_trait_ref: &ty::TraitRef<'tcx>,
2199 // We can avoid creating type variables and doing the full
2200 // substitution if we find that any of the input types, when
2201 // simplified, do not match.
2202 let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsPlaceholder };
2203 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs)
2204 .any(|(obl, imp)| !drcx.generic_args_may_unify(obl, imp))
2207 /// Normalize `where_clause_trait_ref` and try to match it against
2208 /// `obligation`. If successful, return any predicates that
2209 /// result from the normalization.
2210 fn match_where_clause_trait_ref(
2212 obligation: &TraitObligation<'tcx>,
2213 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2214 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2215 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2218 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2219 /// obligation is satisfied.
2220 #[instrument(skip(self), level = "debug")]
2221 fn match_poly_trait_ref(
2223 obligation: &TraitObligation<'tcx>,
2224 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2225 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2227 .at(&obligation.cause, obligation.param_env)
2228 // We don't want predicates for opaque types to just match all other types,
2229 // if there is an obligation on the opaque type, then that obligation must be met
2230 // opaquely. Otherwise we'd match any obligation to the opaque type and then error
2232 .define_opaque_types(false)
2233 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2234 .map(|InferOk { obligations, .. }| obligations)
2238 ///////////////////////////////////////////////////////////////////////////
2241 fn match_fresh_trait_refs(
2243 previous: ty::PolyTraitPredicate<'tcx>,
2244 current: ty::PolyTraitPredicate<'tcx>,
2245 param_env: ty::ParamEnv<'tcx>,
2247 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2248 matcher.relate(previous, current).is_ok()
2253 previous_stack: TraitObligationStackList<'o, 'tcx>,
2254 obligation: &'o TraitObligation<'tcx>,
2255 ) -> TraitObligationStack<'o, 'tcx> {
2256 let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
2258 let dfn = previous_stack.cache.next_dfn();
2259 let depth = previous_stack.depth() + 1;
2260 TraitObligationStack {
2263 reached_depth: Cell::new(depth),
2264 previous: previous_stack,
2270 #[instrument(skip(self), level = "debug")]
2271 fn closure_trait_ref_unnormalized(
2273 obligation: &TraitObligation<'tcx>,
2274 substs: SubstsRef<'tcx>,
2275 ) -> ty::PolyTraitRef<'tcx> {
2276 let closure_sig = substs.as_closure().sig();
2278 debug!(?closure_sig);
2280 // (1) Feels icky to skip the binder here, but OTOH we know
2281 // that the self-type is an unboxed closure type and hence is
2282 // in fact unparameterized (or at least does not reference any
2283 // regions bound in the obligation). Still probably some
2284 // refactoring could make this nicer.
2285 closure_trait_ref_and_return_type(
2287 obligation.predicate.def_id(),
2288 obligation.predicate.skip_binder().self_ty(), // (1)
2290 util::TupleArgumentsFlag::No,
2292 .map_bound(|(trait_ref, _)| trait_ref)
2295 fn generator_trait_ref_unnormalized(
2297 obligation: &TraitObligation<'tcx>,
2298 substs: SubstsRef<'tcx>,
2299 ) -> ty::PolyTraitRef<'tcx> {
2300 let gen_sig = substs.as_generator().poly_sig();
2302 // (1) Feels icky to skip the binder here, but OTOH we know
2303 // that the self-type is an generator type and hence is
2304 // in fact unparameterized (or at least does not reference any
2305 // regions bound in the obligation). Still probably some
2306 // refactoring could make this nicer.
2308 super::util::generator_trait_ref_and_outputs(
2310 obligation.predicate.def_id(),
2311 obligation.predicate.skip_binder().self_ty(), // (1)
2314 .map_bound(|(trait_ref, ..)| trait_ref)
2317 /// Returns the obligations that are implied by instantiating an
2318 /// impl or trait. The obligations are substituted and fully
2319 /// normalized. This is used when confirming an impl or default
2321 #[instrument(level = "debug", skip(self, cause, param_env))]
2322 fn impl_or_trait_obligations(
2324 cause: &ObligationCause<'tcx>,
2325 recursion_depth: usize,
2326 param_env: ty::ParamEnv<'tcx>,
2327 def_id: DefId, // of impl or trait
2328 substs: SubstsRef<'tcx>, // for impl or trait
2329 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2330 ) -> Vec<PredicateObligation<'tcx>> {
2331 let tcx = self.tcx();
2333 // To allow for one-pass evaluation of the nested obligation,
2334 // each predicate must be preceded by the obligations required
2336 // for example, if we have:
2337 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2338 // the impl will have the following predicates:
2339 // <V as Iterator>::Item = U,
2340 // U: Iterator, U: Sized,
2341 // V: Iterator, V: Sized,
2342 // <U as Iterator>::Item: Copy
2343 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2344 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2345 // `$1: Copy`, so we must ensure the obligations are emitted in
2347 let predicates = tcx.bound_predicates_of(def_id);
2348 debug!(?predicates);
2349 assert_eq!(predicates.0.parent, None);
2350 let mut obligations = Vec::with_capacity(predicates.0.predicates.len());
2351 for (predicate, span) in predicates.0.predicates {
2353 let cause = cause.clone().derived_cause(parent_trait_pred, |derived| {
2354 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
2356 impl_def_id: def_id,
2360 let predicate = normalize_with_depth_to(
2365 predicates.rebind(*predicate).subst(tcx, substs),
2368 obligations.push(Obligation { cause, recursion_depth, param_env, predicate });
2375 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2376 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2377 TraitObligationStackList::with(self)
2380 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2384 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2388 /// Indicates that attempting to evaluate this stack entry
2389 /// required accessing something from the stack at depth `reached_depth`.
2390 fn update_reached_depth(&self, reached_depth: usize) {
2392 self.depth >= reached_depth,
2393 "invoked `update_reached_depth` with something under this stack: \
2394 self.depth={} reached_depth={}",
2398 debug!(reached_depth, "update_reached_depth");
2400 while reached_depth < p.depth {
2401 debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
2402 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2403 p = p.previous.head.unwrap();
2408 /// The "provisional evaluation cache" is used to store intermediate cache results
2409 /// when solving auto traits. Auto traits are unusual in that they can support
2410 /// cycles. So, for example, a "proof tree" like this would be ok:
2412 /// - `Foo<T>: Send` :-
2413 /// - `Bar<T>: Send` :-
2414 /// - `Foo<T>: Send` -- cycle, but ok
2415 /// - `Baz<T>: Send`
2417 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2418 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2419 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2420 /// they are coinductive) it is considered ok.
2422 /// However, there is a complication: at the point where we have
2423 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2424 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2425 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2426 /// find out this assumption is wrong? Specifically, we could
2427 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2428 /// `Bar<T>: Send` didn't turn out to be true.
2430 /// In Issue #60010, we found a bug in rustc where it would cache
2431 /// these intermediate results. This was fixed in #60444 by disabling
2432 /// *all* caching for things involved in a cycle -- in our example,
2433 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2434 /// to large slowdowns.
2436 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2437 /// first requires proving `Bar<T>: Send` (which is true:
2439 /// - `Foo<T>: Send` :-
2440 /// - `Bar<T>: Send` :-
2441 /// - `Foo<T>: Send` -- cycle, but ok
2442 /// - `Baz<T>: Send`
2443 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2444 /// - `*const T: Send` -- but what if we later encounter an error?
2446 /// The *provisional evaluation cache* resolves this issue. It stores
2447 /// cache results that we've proven but which were involved in a cycle
2448 /// in some way. We track the minimal stack depth (i.e., the
2449 /// farthest from the top of the stack) that we are dependent on.
2450 /// The idea is that the cache results within are all valid -- so long as
2451 /// none of the nodes in between the current node and the node at that minimum
2452 /// depth result in an error (in which case the cached results are just thrown away).
2454 /// During evaluation, we consult this provisional cache and rely on
2455 /// it. Accessing a cached value is considered equivalent to accessing
2456 /// a result at `reached_depth`, so it marks the *current* solution as
2457 /// provisional as well. If an error is encountered, we toss out any
2458 /// provisional results added from the subtree that encountered the
2459 /// error. When we pop the node at `reached_depth` from the stack, we
2460 /// can commit all the things that remain in the provisional cache.
2461 struct ProvisionalEvaluationCache<'tcx> {
2462 /// next "depth first number" to issue -- just a counter
2465 /// Map from cache key to the provisionally evaluated thing.
2466 /// The cache entries contain the result but also the DFN in which they
2467 /// were added. The DFN is used to clear out values on failure.
2469 /// Imagine we have a stack like:
2471 /// - `A B C` and we add a cache for the result of C (DFN 2)
2472 /// - Then we have a stack `A B D` where `D` has DFN 3
2473 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2474 /// - `E` generates various cache entries which have cyclic dependencies on `B`
2475 /// - `A B D E F` and so forth
2476 /// - the DFN of `F` for example would be 5
2477 /// - then we determine that `E` is in error -- we will then clear
2478 /// all cache values whose DFN is >= 4 -- in this case, that
2479 /// means the cached value for `F`.
2480 map: RefCell<FxHashMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
2482 /// The stack of args that we assume to be true because a `WF(arg)` predicate
2483 /// is on the stack above (and because of wellformedness is coinductive).
2484 /// In an "ideal" world, this would share a stack with trait predicates in
2485 /// `TraitObligationStack`. However, trait predicates are *much* hotter than
2486 /// `WellFormed` predicates, and it's very likely that the additional matches
2487 /// will have a perf effect. The value here is the well-formed `GenericArg`
2488 /// and the depth of the trait predicate *above* that well-formed predicate.
2489 wf_args: RefCell<Vec<(ty::GenericArg<'tcx>, usize)>>,
2492 /// A cache value for the provisional cache: contains the depth-first
2493 /// number (DFN) and result.
2494 #[derive(Copy, Clone, Debug)]
2495 struct ProvisionalEvaluation {
2497 reached_depth: usize,
2498 result: EvaluationResult,
2501 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2502 fn default() -> Self {
2503 Self { dfn: Cell::new(0), map: Default::default(), wf_args: Default::default() }
2507 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2508 /// Get the next DFN in sequence (basically a counter).
2509 fn next_dfn(&self) -> usize {
2510 let result = self.dfn.get();
2511 self.dfn.set(result + 1);
2515 /// Check the provisional cache for any result for
2516 /// `fresh_trait_ref`. If there is a hit, then you must consider
2517 /// it an access to the stack slots at depth
2518 /// `reached_depth` (from the returned value).
2521 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2522 ) -> Option<ProvisionalEvaluation> {
2525 "get_provisional = {:#?}",
2526 self.map.borrow().get(&fresh_trait_pred),
2528 Some(*self.map.borrow().get(&fresh_trait_pred)?)
2531 /// Insert a provisional result into the cache. The result came
2532 /// from the node with the given DFN. It accessed a minimum depth
2533 /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
2534 /// and resulted in `result`.
2535 fn insert_provisional(
2538 reached_depth: usize,
2539 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2540 result: EvaluationResult,
2542 debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
2544 let mut map = self.map.borrow_mut();
2546 // Subtle: when we complete working on the DFN `from_dfn`, anything
2547 // that remains in the provisional cache must be dependent on some older
2548 // stack entry than `from_dfn`. We have to update their depth with our transitive
2549 // depth in that case or else it would be referring to some popped note.
2552 // A (reached depth 0)
2554 // B // depth 1 -- reached depth = 0
2555 // C // depth 2 -- reached depth = 1 (should be 0)
2558 // D (reached depth 1)
2559 // C (cache -- reached depth = 2)
2560 for (_k, v) in &mut *map {
2561 if v.from_dfn >= from_dfn {
2562 v.reached_depth = reached_depth.min(v.reached_depth);
2566 map.insert(fresh_trait_pred, ProvisionalEvaluation { from_dfn, reached_depth, result });
2569 /// Invoked when the node with dfn `dfn` does not get a successful
2570 /// result. This will clear out any provisional cache entries
2571 /// that were added since `dfn` was created. This is because the
2572 /// provisional entries are things which must assume that the
2573 /// things on the stack at the time of their creation succeeded --
2574 /// since the failing node is presently at the top of the stack,
2575 /// these provisional entries must either depend on it or some
2577 fn on_failure(&self, dfn: usize) {
2578 debug!(?dfn, "on_failure");
2579 self.map.borrow_mut().retain(|key, eval| {
2580 if !eval.from_dfn >= dfn {
2581 debug!("on_failure: removing {:?}", key);
2589 /// Invoked when the node at depth `depth` completed without
2590 /// depending on anything higher in the stack (if that completion
2591 /// was a failure, then `on_failure` should have been invoked
2594 /// Note that we may still have provisional cache items remaining
2595 /// in the cache when this is done. For example, if there is a
2598 /// * A depends on...
2599 /// * B depends on A
2600 /// * C depends on...
2601 /// * D depends on C
2604 /// Then as we complete the C node we will have a provisional cache
2605 /// with results for A, B, C, and D. This method would clear out
2606 /// the C and D results, but leave A and B provisional.
2608 /// This is determined based on the DFN: we remove any provisional
2609 /// results created since `dfn` started (e.g., in our example, dfn
2610 /// would be 2, representing the C node, and hence we would
2611 /// remove the result for D, which has DFN 3, but not the results for
2612 /// A and B, which have DFNs 0 and 1 respectively).
2614 /// Note that we *do not* attempt to cache these cycle participants
2615 /// in the evaluation cache. Doing so would require carefully computing
2616 /// the correct `DepNode` to store in the cache entry:
2617 /// cycle participants may implicitly depend on query results
2618 /// related to other participants in the cycle, due to our logic
2619 /// which examines the evaluation stack.
2621 /// We used to try to perform this caching,
2622 /// but it lead to multiple incremental compilation ICEs
2623 /// (see #92987 and #96319), and was very hard to understand.
2624 /// Fortunately, removing the caching didn't seem to
2625 /// have a performance impact in practice.
2626 fn on_completion(&self, dfn: usize) {
2627 debug!(?dfn, "on_completion");
2629 for (fresh_trait_pred, eval) in
2630 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2632 debug!(?fresh_trait_pred, ?eval, "on_completion");
2637 #[derive(Copy, Clone)]
2638 struct TraitObligationStackList<'o, 'tcx> {
2639 cache: &'o ProvisionalEvaluationCache<'tcx>,
2640 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2643 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2644 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2645 TraitObligationStackList { cache, head: None }
2648 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2649 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2652 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2656 fn depth(&self) -> usize {
2657 if let Some(head) = self.head { head.depth } else { 0 }
2661 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2662 type Item = &'o TraitObligationStack<'o, 'tcx>;
2664 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2671 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2672 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2673 write!(f, "TraitObligationStack({:?})", self.obligation)
2677 pub enum ProjectionMatchesProjection {