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};
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::{DeepRejectCtxt, 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::{Subst, SubstsRef};
41 use rustc_middle::ty::{self, EarlyBinder, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate};
42 use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable, TypeVisitable};
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 /// During coherence we have to assume that other crates may add
107 /// additional impls which we currently don't know about.
109 /// To deal with this evaluation should be conservative
110 /// and consider the possibility of impls from outside this crate.
111 /// This comes up primarily when resolving ambiguity. Imagine
112 /// there is some trait reference `$0: Bar` where `$0` is an
113 /// inference variable. If `intercrate` is true, then we can never
114 /// say for sure that this reference is not implemented, even if
115 /// there are *no impls at all for `Bar`*, because `$0` could be
116 /// bound to some type that in a downstream crate that implements
119 /// Outside of coherence we set this to false because we are only
120 /// interested in types that the user could actually have written.
121 /// In other words, we consider `$0: Bar` to be unimplemented if
122 /// there is no type that the user could *actually name* that
123 /// would satisfy it. This avoids crippling inference, basically.
125 /// If `intercrate` is set, we remember predicates which were
126 /// considered ambiguous because of impls potentially added in other crates.
127 /// This is used in coherence to give improved diagnostics.
128 /// We don't do his until we detect a coherence error because it can
129 /// lead to false overflow results (#47139) and because always
130 /// computing it may negatively impact performance.
131 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
133 /// The mode that trait queries run in, which informs our error handling
134 /// policy. In essence, canonicalized queries need their errors propagated
135 /// rather than immediately reported because we do not have accurate spans.
136 query_mode: TraitQueryMode,
139 // A stack that walks back up the stack frame.
140 struct TraitObligationStack<'prev, 'tcx> {
141 obligation: &'prev TraitObligation<'tcx>,
143 /// The trait predicate from `obligation` but "freshened" with the
144 /// selection-context's freshener. Used to check for recursion.
145 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
147 /// Starts out equal to `depth` -- if, during evaluation, we
148 /// encounter a cycle, then we will set this flag to the minimum
149 /// depth of that cycle for all participants in the cycle. These
150 /// participants will then forego caching their results. This is
151 /// not the most efficient solution, but it addresses #60010. The
152 /// problem we are trying to prevent:
154 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
155 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
156 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
158 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
159 /// is `EvaluatedToOk`; this is because they were only considered
160 /// ok on the premise that if `A: AutoTrait` held, but we indeed
161 /// encountered a problem (later on) with `A: AutoTrait. So we
162 /// currently set a flag on the stack node for `B: AutoTrait` (as
163 /// well as the second instance of `A: AutoTrait`) to suppress
166 /// This is a simple, targeted fix. A more-performant fix requires
167 /// deeper changes, but would permit more caching: we could
168 /// basically defer caching until we have fully evaluated the
169 /// tree, and then cache the entire tree at once. In any case, the
170 /// performance impact here shouldn't be so horrible: every time
171 /// this is hit, we do cache at least one trait, so we only
172 /// evaluate each member of a cycle up to N times, where N is the
173 /// length of the cycle. This means the performance impact is
174 /// bounded and we shouldn't have any terrible worst-cases.
175 reached_depth: Cell<usize>,
177 previous: TraitObligationStackList<'prev, 'tcx>,
179 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
182 /// The depth-first number of this node in the search graph -- a
183 /// pre-order index. Basically, a freshly incremented counter.
187 struct SelectionCandidateSet<'tcx> {
188 // A list of candidates that definitely apply to the current
189 // obligation (meaning: types unify).
190 vec: Vec<SelectionCandidate<'tcx>>,
192 // If `true`, then there were candidates that might or might
193 // not have applied, but we couldn't tell. This occurs when some
194 // of the input types are type variables, in which case there are
195 // various "builtin" rules that might or might not trigger.
199 #[derive(PartialEq, Eq, Debug, Clone)]
200 struct EvaluatedCandidate<'tcx> {
201 candidate: SelectionCandidate<'tcx>,
202 evaluation: EvaluationResult,
205 /// When does the builtin impl for `T: Trait` apply?
207 enum BuiltinImplConditions<'tcx> {
208 /// The impl is conditional on `T1, T2, ...: Trait`.
209 Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
210 /// There is no built-in impl. There may be some other
211 /// candidate (a where-clause or user-defined impl).
213 /// It is unknown whether there is an impl.
217 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
218 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
221 freshener: infcx.freshener_keep_static(),
223 intercrate_ambiguity_causes: None,
224 query_mode: TraitQueryMode::Standard,
228 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
231 freshener: infcx.freshener_keep_static(),
233 intercrate_ambiguity_causes: None,
234 query_mode: TraitQueryMode::Standard,
238 pub fn with_query_mode(
239 infcx: &'cx InferCtxt<'cx, 'tcx>,
240 query_mode: TraitQueryMode,
241 ) -> SelectionContext<'cx, 'tcx> {
242 debug!(?query_mode, "with_query_mode");
245 freshener: infcx.freshener_keep_static(),
247 intercrate_ambiguity_causes: None,
252 /// Enables tracking of intercrate ambiguity causes. See
253 /// the documentation of [`Self::intercrate_ambiguity_causes`] for more.
254 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
255 assert!(self.intercrate);
256 assert!(self.intercrate_ambiguity_causes.is_none());
257 self.intercrate_ambiguity_causes = Some(vec![]);
258 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
261 /// Gets the intercrate ambiguity causes collected since tracking
262 /// was enabled and disables tracking at the same time. If
263 /// tracking is not enabled, just returns an empty vector.
264 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
265 assert!(self.intercrate);
266 self.intercrate_ambiguity_causes.take().unwrap_or_default()
269 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
273 pub fn tcx(&self) -> TyCtxt<'tcx> {
277 pub fn is_intercrate(&self) -> bool {
281 ///////////////////////////////////////////////////////////////////////////
284 // The selection phase tries to identify *how* an obligation will
285 // be resolved. For example, it will identify which impl or
286 // parameter bound is to be used. The process can be inconclusive
287 // if the self type in the obligation is not fully inferred. Selection
288 // can result in an error in one of two ways:
290 // 1. If no applicable impl or parameter bound can be found.
291 // 2. If the output type parameters in the obligation do not match
292 // those specified by the impl/bound. For example, if the obligation
293 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
294 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
296 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
297 /// type environment by performing unification.
298 #[instrument(level = "debug", skip(self))]
301 obligation: &TraitObligation<'tcx>,
302 ) -> SelectionResult<'tcx, Selection<'tcx>> {
303 let candidate = match self.select_from_obligation(obligation) {
304 Err(SelectionError::Overflow(OverflowError::Canonical)) => {
305 // In standard mode, overflow must have been caught and reported
307 assert!(self.query_mode == TraitQueryMode::Canonical);
308 return Err(SelectionError::Overflow(OverflowError::Canonical));
310 Err(SelectionError::Ambiguous(_)) => {
319 Ok(Some(candidate)) => candidate,
322 match self.confirm_candidate(obligation, candidate) {
323 Err(SelectionError::Overflow(OverflowError::Canonical)) => {
324 assert!(self.query_mode == TraitQueryMode::Canonical);
325 Err(SelectionError::Overflow(OverflowError::Canonical))
329 debug!(?candidate, "confirmed");
335 pub(crate) fn select_from_obligation(
337 obligation: &TraitObligation<'tcx>,
338 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
339 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
341 let pec = &ProvisionalEvaluationCache::default();
342 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
344 self.candidate_from_obligation(&stack)
347 ///////////////////////////////////////////////////////////////////////////
350 // Tests whether an obligation can be selected or whether an impl
351 // can be applied to particular types. It skips the "confirmation"
352 // step and hence completely ignores output type parameters.
354 // The result is "true" if the obligation *may* hold and "false" if
355 // we can be sure it does not.
357 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
358 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
359 debug!(?obligation, "predicate_may_hold_fatal");
361 // This fatal query is a stopgap that should only be used in standard mode,
362 // where we do not expect overflow to be propagated.
363 assert!(self.query_mode == TraitQueryMode::Standard);
365 self.evaluate_root_obligation(obligation)
366 .expect("Overflow should be caught earlier in standard query mode")
370 /// Evaluates whether the obligation `obligation` can be satisfied
371 /// and returns an `EvaluationResult`. This is meant for the
373 pub fn evaluate_root_obligation(
375 obligation: &PredicateObligation<'tcx>,
376 ) -> Result<EvaluationResult, OverflowError> {
377 self.evaluation_probe(|this| {
378 this.evaluate_predicate_recursively(
379 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
387 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
388 ) -> Result<EvaluationResult, OverflowError> {
389 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
390 let result = op(self)?;
392 match self.infcx.leak_check(true, snapshot) {
394 Err(_) => return Ok(EvaluatedToErr),
397 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
399 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
404 /// Evaluates the predicates in `predicates` recursively. Note that
405 /// this applies projections in the predicates, and therefore
406 /// is run within an inference probe.
407 #[instrument(skip(self, stack), level = "debug")]
408 fn evaluate_predicates_recursively<'o, I>(
410 stack: TraitObligationStackList<'o, 'tcx>,
412 ) -> Result<EvaluationResult, OverflowError>
414 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
416 let mut result = EvaluatedToOk;
417 for obligation in predicates {
418 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
419 if let EvaluatedToErr = eval {
420 // fast-path - EvaluatedToErr is the top of the lattice,
421 // so we don't need to look on the other predicates.
422 return Ok(EvaluatedToErr);
424 result = cmp::max(result, eval);
432 skip(self, previous_stack),
433 fields(previous_stack = ?previous_stack.head())
435 fn evaluate_predicate_recursively<'o>(
437 previous_stack: TraitObligationStackList<'o, 'tcx>,
438 obligation: PredicateObligation<'tcx>,
439 ) -> Result<EvaluationResult, OverflowError> {
440 // `previous_stack` stores a `TraitObligation`, while `obligation` is
441 // a `PredicateObligation`. These are distinct types, so we can't
442 // use any `Option` combinator method that would force them to be
444 match previous_stack.head() {
445 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
446 None => self.check_recursion_limit(&obligation, &obligation)?,
449 let result = ensure_sufficient_stack(|| {
450 let bound_predicate = obligation.predicate.kind();
451 match bound_predicate.skip_binder() {
452 ty::PredicateKind::Trait(t) => {
453 let t = bound_predicate.rebind(t);
454 debug_assert!(!t.has_escaping_bound_vars());
455 let obligation = obligation.with(t);
456 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
459 ty::PredicateKind::Subtype(p) => {
460 let p = bound_predicate.rebind(p);
461 // Does this code ever run?
462 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
463 Some(Ok(InferOk { mut obligations, .. })) => {
464 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
465 self.evaluate_predicates_recursively(
467 obligations.into_iter(),
470 Some(Err(_)) => Ok(EvaluatedToErr),
471 None => Ok(EvaluatedToAmbig),
475 ty::PredicateKind::Coerce(p) => {
476 let p = bound_predicate.rebind(p);
477 // Does this code ever run?
478 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
479 Some(Ok(InferOk { mut obligations, .. })) => {
480 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
481 self.evaluate_predicates_recursively(
483 obligations.into_iter(),
486 Some(Err(_)) => Ok(EvaluatedToErr),
487 None => Ok(EvaluatedToAmbig),
491 ty::PredicateKind::WellFormed(arg) => {
492 // So, there is a bit going on here. First, `WellFormed` predicates
493 // are coinductive, like trait predicates with auto traits.
494 // This means that we need to detect if we have recursively
495 // evaluated `WellFormed(X)`. Otherwise, we would run into
496 // a "natural" overflow error.
498 // Now, the next question is whether we need to do anything
499 // special with caching. Considering the following tree:
504 // In this case, the innermost `WF(Foo<T>)` should return
505 // `EvaluatedToOk`, since it's coinductive. Then if
506 // `Bar<T>: Send` is resolved to `EvaluatedToOk`, it can be
507 // inserted into a cache (because without thinking about `WF`
508 // goals, it isn't in a cycle). If `Foo<T>: Trait` later doesn't
509 // hold, then `Bar<T>: Send` shouldn't hold. Therefore, we
510 // *do* need to keep track of coinductive cycles.
512 let cache = previous_stack.cache;
513 let dfn = cache.next_dfn();
515 for stack_arg in previous_stack.cache.wf_args.borrow().iter().rev() {
516 if stack_arg.0 != arg {
519 debug!("WellFormed({:?}) on stack", arg);
520 if let Some(stack) = previous_stack.head {
521 // Okay, let's imagine we have two different stacks:
522 // `T: NonAutoTrait -> WF(T) -> T: NonAutoTrait`
523 // `WF(T) -> T: NonAutoTrait -> WF(T)`
524 // Because of this, we need to check that all
525 // predicates between the WF goals are coinductive.
526 // Otherwise, we can say that `T: NonAutoTrait` is
528 // Let's imagine we have a predicate stack like
529 // `Foo: Bar -> WF(T) -> T: NonAutoTrait -> T: Auto
531 // and the current predicate is `WF(T)`. `wf_args`
532 // would contain `(T, 1)`. We want to check all
533 // trait predicates greater than `1`. The previous
534 // stack would be `T: Auto`.
535 let cycle = stack.iter().take_while(|s| s.depth > stack_arg.1);
536 let tcx = self.tcx();
538 cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
539 if self.coinductive_match(cycle) {
540 stack.update_reached_depth(stack_arg.1);
541 return Ok(EvaluatedToOk);
543 return Ok(EvaluatedToRecur);
546 return Ok(EvaluatedToOk);
549 match wf::obligations(
551 obligation.param_env,
552 obligation.cause.body_id,
553 obligation.recursion_depth + 1,
555 obligation.cause.span,
557 Some(mut obligations) => {
558 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
560 cache.wf_args.borrow_mut().push((arg, previous_stack.depth()));
562 self.evaluate_predicates_recursively(previous_stack, obligations);
563 cache.wf_args.borrow_mut().pop();
565 let result = result?;
567 if !result.must_apply_modulo_regions() {
568 cache.on_failure(dfn);
571 cache.on_completion(dfn);
575 None => Ok(EvaluatedToAmbig),
579 ty::PredicateKind::TypeOutlives(pred) => {
580 // A global type with no late-bound regions can only
581 // contain the "'static" lifetime (any other lifetime
582 // would either be late-bound or local), so it is guaranteed
583 // to outlive any other lifetime
584 if pred.0.is_global() && !pred.0.has_late_bound_regions() {
587 Ok(EvaluatedToOkModuloRegions)
591 ty::PredicateKind::RegionOutlives(..) => {
592 // We do not consider region relationships when evaluating trait matches.
593 Ok(EvaluatedToOkModuloRegions)
596 ty::PredicateKind::ObjectSafe(trait_def_id) => {
597 if self.tcx().is_object_safe(trait_def_id) {
604 ty::PredicateKind::Projection(data) => {
605 let data = bound_predicate.rebind(data);
606 let project_obligation = obligation.with(data);
607 match project::poly_project_and_unify_type(self, &project_obligation) {
608 ProjectAndUnifyResult::Holds(mut subobligations) => {
610 // If we've previously marked this projection as 'complete', then
611 // use the final cached result (either `EvaluatedToOk` or
612 // `EvaluatedToOkModuloRegions`), and skip re-evaluating the
615 ProjectionCacheKey::from_poly_projection_predicate(self, data)
617 if let Some(cached_res) = self
624 break 'compute_res Ok(cached_res);
629 subobligations.iter_mut(),
630 obligation.recursion_depth,
632 let res = self.evaluate_predicates_recursively(
636 if let Ok(eval_rslt) = res
637 && (eval_rslt == EvaluatedToOk || eval_rslt == EvaluatedToOkModuloRegions)
639 ProjectionCacheKey::from_poly_projection_predicate(
643 // If the result is something that we can cache, then mark this
644 // entry as 'complete'. This will allow us to skip evaluating the
645 // subobligations at all the next time we evaluate the projection
651 .complete(key, eval_rslt);
656 ProjectAndUnifyResult::FailedNormalization => Ok(EvaluatedToAmbig),
657 ProjectAndUnifyResult::Recursive => Ok(EvaluatedToRecur),
658 ProjectAndUnifyResult::MismatchedProjectionTypes(_) => Ok(EvaluatedToErr),
662 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
663 match self.infcx.closure_kind(closure_substs) {
664 Some(closure_kind) => {
665 if closure_kind.extends(kind) {
671 None => Ok(EvaluatedToAmbig),
675 ty::PredicateKind::ConstEvaluatable(uv) => {
676 match const_evaluatable::is_const_evaluatable(
679 obligation.param_env,
680 obligation.cause.span,
682 Ok(()) => Ok(EvaluatedToOk),
683 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
684 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
685 Err(_) => Ok(EvaluatedToErr),
689 ty::PredicateKind::ConstEquate(c1, c2) => {
690 debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
692 if self.tcx().features().generic_const_exprs {
693 // FIXME: we probably should only try to unify abstract constants
694 // if the constants depend on generic parameters.
696 // Let's just see where this breaks :shrug:
697 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
698 (c1.kind(), c2.kind())
700 if self.infcx.try_unify_abstract_consts(
703 obligation.param_env,
705 return Ok(EvaluatedToOk);
710 let evaluate = |c: ty::Const<'tcx>| {
711 if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() {
712 match self.infcx.try_const_eval_resolve(
713 obligation.param_env,
716 Some(obligation.cause.span),
726 match (evaluate(c1), evaluate(c2)) {
727 (Ok(c1), Ok(c2)) => {
730 .at(&obligation.cause, obligation.param_env)
733 Ok(_) => Ok(EvaluatedToOk),
734 Err(_) => Ok(EvaluatedToErr),
737 (Err(ErrorHandled::Reported(_)), _)
738 | (_, Err(ErrorHandled::Reported(_))) => Ok(EvaluatedToErr),
739 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
741 obligation.cause.span(self.tcx()),
742 "ConstEquate: const_eval_resolve returned an unexpected error"
745 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
746 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
749 // Two different constants using generic parameters ~> error.
755 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
756 bug!("TypeWellFormedFromEnv is only used for chalk")
761 debug!("finished: {:?} from {:?}", result, obligation);
766 #[instrument(skip(self, previous_stack), level = "debug")]
767 fn evaluate_trait_predicate_recursively<'o>(
769 previous_stack: TraitObligationStackList<'o, 'tcx>,
770 mut obligation: TraitObligation<'tcx>,
771 ) -> Result<EvaluationResult, OverflowError> {
773 && obligation.is_global()
774 && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst())
776 // If a param env has no global bounds, global obligations do not
777 // depend on its particular value in order to work, so we can clear
778 // out the param env and get better caching.
780 obligation.param_env = obligation.param_env.without_caller_bounds();
783 let stack = self.push_stack(previous_stack, &obligation);
784 let mut fresh_trait_pred = stack.fresh_trait_pred;
785 let mut param_env = obligation.param_env;
787 fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| {
788 pred.remap_constness(self.tcx(), &mut param_env);
792 debug!(?fresh_trait_pred);
794 // If a trait predicate is in the (local or global) evaluation cache,
795 // then we know it holds without cycles.
796 if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
797 debug!(?result, "CACHE HIT");
801 if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
802 debug!(?result, "PROVISIONAL CACHE HIT");
803 stack.update_reached_depth(result.reached_depth);
804 return Ok(result.result);
807 // Check if this is a match for something already on the
808 // stack. If so, we don't want to insert the result into the
809 // main cache (it is cycle dependent) nor the provisional
810 // cache (which is meant for things that have completed but
811 // for a "backedge" -- this result *is* the backedge).
812 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
813 return Ok(cycle_result);
816 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
817 let result = result?;
819 if !result.must_apply_modulo_regions() {
820 stack.cache().on_failure(stack.dfn);
823 let reached_depth = stack.reached_depth.get();
824 if reached_depth >= stack.depth {
825 debug!(?result, "CACHE MISS");
826 self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
827 stack.cache().on_completion(stack.dfn);
829 debug!(?result, "PROVISIONAL");
831 "caching provisionally because {:?} \
832 is a cycle participant (at depth {}, reached depth {})",
833 fresh_trait_pred, stack.depth, reached_depth,
836 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_pred, result);
842 /// If there is any previous entry on the stack that precisely
843 /// matches this obligation, then we can assume that the
844 /// obligation is satisfied for now (still all other conditions
845 /// must be met of course). One obvious case this comes up is
846 /// marker traits like `Send`. Think of a linked list:
848 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
850 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
851 /// `Option<Box<List<T>>>` is `Send`, and in turn
852 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
855 /// Note that we do this comparison using the `fresh_trait_ref`
856 /// fields. Because these have all been freshened using
857 /// `self.freshener`, we can be sure that (a) this will not
858 /// affect the inferencer state and (b) that if we see two
859 /// fresh regions with the same index, they refer to the same
860 /// unbound type variable.
861 fn check_evaluation_cycle(
863 stack: &TraitObligationStack<'_, 'tcx>,
864 ) -> Option<EvaluationResult> {
865 if let Some(cycle_depth) = stack
867 .skip(1) // Skip top-most frame.
869 stack.obligation.param_env == prev.obligation.param_env
870 && stack.fresh_trait_pred == prev.fresh_trait_pred
872 .map(|stack| stack.depth)
874 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
876 // If we have a stack like `A B C D E A`, where the top of
877 // the stack is the final `A`, then this will iterate over
878 // `A, E, D, C, B` -- i.e., all the participants apart
879 // from the cycle head. We mark them as participating in a
880 // cycle. This suppresses caching for those nodes. See
881 // `in_cycle` field for more details.
882 stack.update_reached_depth(cycle_depth);
884 // Subtle: when checking for a coinductive cycle, we do
885 // not compare using the "freshened trait refs" (which
886 // have erased regions) but rather the fully explicit
887 // trait refs. This is important because it's only a cycle
888 // if the regions match exactly.
889 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
890 let tcx = self.tcx();
891 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
892 if self.coinductive_match(cycle) {
893 debug!("evaluate_stack --> recursive, coinductive");
896 debug!("evaluate_stack --> recursive, inductive");
897 Some(EvaluatedToRecur)
904 fn evaluate_stack<'o>(
906 stack: &TraitObligationStack<'o, 'tcx>,
907 ) -> Result<EvaluationResult, OverflowError> {
908 // In intercrate mode, whenever any of the generics are unbound,
909 // there can always be an impl. Even if there are no impls in
910 // this crate, perhaps the type would be unified with
911 // something from another crate that does provide an impl.
913 // In intra mode, we must still be conservative. The reason is
914 // that we want to avoid cycles. Imagine an impl like:
916 // impl<T:Eq> Eq for Vec<T>
918 // and a trait reference like `$0 : Eq` where `$0` is an
919 // unbound variable. When we evaluate this trait-reference, we
920 // will unify `$0` with `Vec<$1>` (for some fresh variable
921 // `$1`), on the condition that `$1 : Eq`. We will then wind
922 // up with many candidates (since that are other `Eq` impls
923 // that apply) and try to winnow things down. This results in
924 // a recursive evaluation that `$1 : Eq` -- as you can
925 // imagine, this is just where we started. To avoid that, we
926 // check for unbound variables and return an ambiguous (hence possible)
927 // match if we've seen this trait before.
929 // This suffices to allow chains like `FnMut` implemented in
930 // terms of `Fn` etc, but we could probably make this more
932 let unbound_input_types =
933 stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh());
935 if stack.obligation.polarity() != ty::ImplPolarity::Negative {
936 // This check was an imperfect workaround for a bug in the old
937 // intercrate mode; it should be removed when that goes away.
938 if unbound_input_types && self.intercrate {
939 debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
940 // Heuristics: show the diagnostics when there are no candidates in crate.
941 if self.intercrate_ambiguity_causes.is_some() {
942 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
943 if let Ok(candidate_set) = self.assemble_candidates(stack) {
944 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
945 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
946 let self_ty = trait_ref.self_ty();
947 let cause = with_no_trimmed_paths!({
948 IntercrateAmbiguityCause::DownstreamCrate {
949 trait_desc: trait_ref.print_only_trait_path().to_string(),
950 self_desc: if self_ty.has_concrete_skeleton() {
951 Some(self_ty.to_string())
958 debug!(?cause, "evaluate_stack: pushing cause");
959 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
963 return Ok(EvaluatedToAmbig);
967 if unbound_input_types
968 && stack.iter().skip(1).any(|prev| {
969 stack.obligation.param_env == prev.obligation.param_env
970 && self.match_fresh_trait_refs(
971 stack.fresh_trait_pred,
972 prev.fresh_trait_pred,
973 prev.obligation.param_env,
977 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
978 return Ok(EvaluatedToUnknown);
981 match self.candidate_from_obligation(stack) {
982 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
983 Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig),
984 Ok(None) => Ok(EvaluatedToAmbig),
985 Err(Overflow(OverflowError::Canonical)) => Err(OverflowError::Canonical),
986 Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
987 Err(..) => Ok(EvaluatedToErr),
991 /// For defaulted traits, we use a co-inductive strategy to solve, so
992 /// that recursion is ok. This routine returns `true` if the top of the
993 /// stack (`cycle[0]`):
995 /// - is a defaulted trait,
996 /// - it also appears in the backtrace at some position `X`,
997 /// - all the predicates at positions `X..` between `X` and the top are
998 /// also defaulted traits.
999 pub(crate) fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
1001 I: Iterator<Item = ty::Predicate<'tcx>>,
1003 cycle.all(|predicate| self.coinductive_predicate(predicate))
1006 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1007 let result = match predicate.kind().skip_binder() {
1008 ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1009 ty::PredicateKind::WellFormed(_) => true,
1012 debug!(?predicate, ?result, "coinductive_predicate");
1016 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
1017 /// obligations are met. Returns whether `candidate` remains viable after this further
1022 fields(depth = stack.obligation.recursion_depth)
1024 fn evaluate_candidate<'o>(
1026 stack: &TraitObligationStack<'o, 'tcx>,
1027 candidate: &SelectionCandidate<'tcx>,
1028 ) -> Result<EvaluationResult, OverflowError> {
1029 let mut result = self.evaluation_probe(|this| {
1030 let candidate = (*candidate).clone();
1031 match this.confirm_candidate(stack.obligation, candidate) {
1034 this.evaluate_predicates_recursively(
1036 selection.nested_obligations().into_iter(),
1039 Err(..) => Ok(EvaluatedToErr),
1043 // If we erased any lifetimes, then we want to use
1044 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
1045 // as your final result. The result will be cached using
1046 // the freshened trait predicate as a key, so we need
1047 // our result to be correct by *any* choice of original lifetimes,
1048 // not just the lifetime choice for this particular (non-erased)
1051 if stack.fresh_trait_pred.has_erased_regions() {
1052 result = result.max(EvaluatedToOkModuloRegions);
1059 fn check_evaluation_cache(
1061 param_env: ty::ParamEnv<'tcx>,
1062 trait_pred: ty::PolyTraitPredicate<'tcx>,
1063 ) -> Option<EvaluationResult> {
1064 // Neither the global nor local cache is aware of intercrate
1065 // mode, so don't do any caching. In particular, we might
1066 // re-use the same `InferCtxt` with both an intercrate
1067 // and non-intercrate `SelectionContext`
1068 if self.intercrate {
1072 let tcx = self.tcx();
1073 if self.can_use_global_caches(param_env) {
1074 if let Some(res) = tcx.evaluation_cache.get(&(param_env, trait_pred), tcx) {
1078 self.infcx.evaluation_cache.get(&(param_env, trait_pred), tcx)
1081 fn insert_evaluation_cache(
1083 param_env: ty::ParamEnv<'tcx>,
1084 trait_pred: ty::PolyTraitPredicate<'tcx>,
1085 dep_node: DepNodeIndex,
1086 result: EvaluationResult,
1088 // Avoid caching results that depend on more than just the trait-ref
1089 // - the stack can create recursion.
1090 if result.is_stack_dependent() {
1094 // Neither the global nor local cache is aware of intercrate
1095 // mode, so don't do any caching. In particular, we might
1096 // re-use the same `InferCtxt` with both an intercrate
1097 // and non-intercrate `SelectionContext`
1098 if self.intercrate {
1102 if self.can_use_global_caches(param_env) {
1103 if !trait_pred.needs_infer() {
1104 debug!(?trait_pred, ?result, "insert_evaluation_cache global");
1105 // This may overwrite the cache with the same value
1106 // FIXME: Due to #50507 this overwrites the different values
1107 // This should be changed to use HashMapExt::insert_same
1108 // when that is fixed
1109 self.tcx().evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1114 debug!(?trait_pred, ?result, "insert_evaluation_cache");
1115 self.infcx.evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1118 /// For various reasons, it's possible for a subobligation
1119 /// to have a *lower* recursion_depth than the obligation used to create it.
1120 /// Projection sub-obligations may be returned from the projection cache,
1121 /// which results in obligations with an 'old' `recursion_depth`.
1122 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1123 /// subobligations without taking in a 'parent' depth, causing the
1124 /// generated subobligations to have a `recursion_depth` of `0`.
1126 /// To ensure that obligation_depth never decreases, we force all subobligations
1127 /// to have at least the depth of the original obligation.
1128 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1133 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1136 fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
1139 error_obligation: &Obligation<'tcx, T>,
1140 ) -> Result<(), OverflowError> {
1141 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1142 match self.query_mode {
1143 TraitQueryMode::Standard => {
1144 if self.infcx.is_tainted_by_errors() {
1145 return Err(OverflowError::Error(
1146 ErrorGuaranteed::unchecked_claim_error_was_emitted(),
1149 self.infcx.report_overflow_error(error_obligation, true);
1151 TraitQueryMode::Canonical => {
1152 return Err(OverflowError::Canonical);
1159 /// Checks that the recursion limit has not been exceeded.
1161 /// The weird return type of this function allows it to be used with the `try` (`?`)
1162 /// operator within certain functions.
1164 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1166 obligation: &Obligation<'tcx, T>,
1167 error_obligation: &Obligation<'tcx, V>,
1168 ) -> Result<(), OverflowError> {
1169 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1172 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1174 OP: FnOnce(&mut Self) -> R,
1176 let (result, dep_node) =
1177 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1178 self.tcx().dep_graph.read_index(dep_node);
1182 /// filter_impls filters constant trait obligations and candidates that have a positive impl
1183 /// for a negative goal and a negative impl for a positive goal
1184 #[instrument(level = "debug", skip(self))]
1187 candidates: Vec<SelectionCandidate<'tcx>>,
1188 obligation: &TraitObligation<'tcx>,
1189 ) -> Vec<SelectionCandidate<'tcx>> {
1190 let tcx = self.tcx();
1191 let mut result = Vec::with_capacity(candidates.len());
1193 for candidate in candidates {
1194 // Respect const trait obligations
1195 if obligation.is_const() {
1198 ImplCandidate(def_id) if tcx.constness(def_id) == hir::Constness::Const => {}
1200 ParamCandidate(trait_pred) if trait_pred.is_const_if_const() => {}
1202 AutoImplCandidate(..) => {}
1203 // generator, this will raise error in other places
1204 // or ignore error with const_async_blocks feature
1205 GeneratorCandidate => {}
1206 // FnDef where the function is const
1207 FnPointerCandidate { is_const: true } => {}
1208 ConstDestructCandidate(_) => {}
1210 // reject all other types of candidates
1216 if let ImplCandidate(def_id) = candidate {
1217 if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id)
1218 || obligation.polarity() == tcx.impl_polarity(def_id)
1220 result.push(candidate);
1223 result.push(candidate);
1230 /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1231 #[instrument(level = "debug", skip(self))]
1232 fn filter_reservation_impls(
1234 candidate: SelectionCandidate<'tcx>,
1235 obligation: &TraitObligation<'tcx>,
1236 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1237 let tcx = self.tcx();
1238 // Treat reservation impls as ambiguity.
1239 if let ImplCandidate(def_id) = candidate {
1240 if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
1241 if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1243 .get_attr(def_id, sym::rustc_reservation_impl)
1244 .and_then(|a| a.value_str());
1245 if let Some(value) = value {
1247 "filter_reservation_impls: \
1248 reservation impl ambiguity on {:?}",
1251 intercrate_ambiguity_clauses.push(
1252 IntercrateAmbiguityCause::ReservationImpl {
1253 message: value.to_string(),
1264 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1265 debug!("is_knowable(intercrate={:?})", self.intercrate);
1267 if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative {
1271 let obligation = &stack.obligation;
1272 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1274 // Okay to skip binder because of the nature of the
1275 // trait-ref-is-knowable check, which does not care about
1277 let trait_ref = predicate.skip_binder().trait_ref;
1279 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1282 /// Returns `true` if the global caches can be used.
1283 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1284 // If there are any inference variables in the `ParamEnv`, then we
1285 // always use a cache local to this particular scope. Otherwise, we
1286 // switch to a global cache.
1287 if param_env.needs_infer() {
1291 // Avoid using the master cache during coherence and just rely
1292 // on the local cache. This effectively disables caching
1293 // during coherence. It is really just a simplification to
1294 // avoid us having to fear that coherence results "pollute"
1295 // the master cache. Since coherence executes pretty quickly,
1296 // it's not worth going to more trouble to increase the
1297 // hit-rate, I don't think.
1298 if self.intercrate {
1302 // Otherwise, we can use the global cache.
1306 fn check_candidate_cache(
1308 mut param_env: ty::ParamEnv<'tcx>,
1309 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1310 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1311 // Neither the global nor local cache is aware of intercrate
1312 // mode, so don't do any caching. In particular, we might
1313 // re-use the same `InferCtxt` with both an intercrate
1314 // and non-intercrate `SelectionContext`
1315 if self.intercrate {
1318 let tcx = self.tcx();
1319 let mut pred = cache_fresh_trait_pred.skip_binder();
1320 pred.remap_constness(tcx, &mut param_env);
1322 if self.can_use_global_caches(param_env) {
1323 if let Some(res) = tcx.selection_cache.get(&(param_env, pred), tcx) {
1327 self.infcx.selection_cache.get(&(param_env, pred), tcx)
1330 /// Determines whether can we safely cache the result
1331 /// of selecting an obligation. This is almost always `true`,
1332 /// except when dealing with certain `ParamCandidate`s.
1334 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1335 /// since it was usually produced directly from a `DefId`. However,
1336 /// certain cases (currently only librustdoc's blanket impl finder),
1337 /// a `ParamEnv` may be explicitly constructed with inference types.
1338 /// When this is the case, we do *not* want to cache the resulting selection
1339 /// candidate. This is due to the fact that it might not always be possible
1340 /// to equate the obligation's trait ref and the candidate's trait ref,
1341 /// if more constraints end up getting added to an inference variable.
1343 /// Because of this, we always want to re-run the full selection
1344 /// process for our obligation the next time we see it, since
1345 /// we might end up picking a different `SelectionCandidate` (or none at all).
1346 fn can_cache_candidate(
1348 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1350 // Neither the global nor local cache is aware of intercrate
1351 // mode, so don't do any caching. In particular, we might
1352 // re-use the same `InferCtxt` with both an intercrate
1353 // and non-intercrate `SelectionContext`
1354 if self.intercrate {
1358 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1363 #[instrument(skip(self, param_env, cache_fresh_trait_pred, dep_node), level = "debug")]
1364 fn insert_candidate_cache(
1366 mut param_env: ty::ParamEnv<'tcx>,
1367 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1368 dep_node: DepNodeIndex,
1369 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1371 let tcx = self.tcx();
1372 let mut pred = cache_fresh_trait_pred.skip_binder();
1374 pred.remap_constness(tcx, &mut param_env);
1376 if !self.can_cache_candidate(&candidate) {
1377 debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1381 if self.can_use_global_caches(param_env) {
1382 if let Err(Overflow(OverflowError::Canonical)) = candidate {
1383 // Don't cache overflow globally; we only produce this in certain modes.
1384 } else if !pred.needs_infer() {
1385 if !candidate.needs_infer() {
1386 debug!(?pred, ?candidate, "insert_candidate_cache global");
1387 // This may overwrite the cache with the same value.
1388 tcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1394 debug!(?pred, ?candidate, "insert_candidate_cache local");
1395 self.infcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1398 /// Matches a predicate against the bounds of its self type.
1400 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1401 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1402 /// `Baz` bound. We return indexes into the list returned by
1403 /// `tcx.item_bounds` for any applicable bounds.
1404 #[instrument(level = "debug", skip(self))]
1405 fn match_projection_obligation_against_definition_bounds(
1407 obligation: &TraitObligation<'tcx>,
1408 ) -> smallvec::SmallVec<[usize; 2]> {
1409 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1410 let placeholder_trait_predicate =
1411 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1412 debug!(?placeholder_trait_predicate);
1414 let tcx = self.infcx.tcx;
1415 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1416 ty::Projection(ref data) => (data.item_def_id, data.substs),
1417 ty::Opaque(def_id, substs) => (def_id, substs),
1420 obligation.cause.span,
1421 "match_projection_obligation_against_definition_bounds() called \
1422 but self-ty is not a projection: {:?}",
1423 placeholder_trait_predicate.trait_ref.self_ty()
1427 let bounds = tcx.bound_item_bounds(def_id).subst(tcx, substs);
1429 // The bounds returned by `item_bounds` may contain duplicates after
1430 // normalization, so try to deduplicate when possible to avoid
1431 // unnecessary ambiguity.
1432 let mut distinct_normalized_bounds = FxHashSet::default();
1434 let matching_bounds = bounds
1437 .filter_map(|(idx, bound)| {
1438 let bound_predicate = bound.kind();
1439 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1440 let bound = bound_predicate.rebind(pred.trait_ref);
1441 if self.infcx.probe(|_| {
1442 match self.match_normalize_trait_ref(
1445 placeholder_trait_predicate.trait_ref,
1448 Ok(Some(normalized_trait))
1449 if distinct_normalized_bounds.insert(normalized_trait) =>
1463 debug!(?matching_bounds);
1467 /// Equates the trait in `obligation` with trait bound. If the two traits
1468 /// can be equated and the normalized trait bound doesn't contain inference
1469 /// variables or placeholders, the normalized bound is returned.
1470 fn match_normalize_trait_ref(
1472 obligation: &TraitObligation<'tcx>,
1473 trait_bound: ty::PolyTraitRef<'tcx>,
1474 placeholder_trait_ref: ty::TraitRef<'tcx>,
1475 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1476 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1477 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1478 // Avoid unnecessary normalization
1482 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1483 project::normalize_with_depth(
1485 obligation.param_env,
1486 obligation.cause.clone(),
1487 obligation.recursion_depth + 1,
1492 .at(&obligation.cause, obligation.param_env)
1493 .define_opaque_types(false)
1494 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1495 .map(|InferOk { obligations: _, value: () }| {
1496 // This method is called within a probe, so we can't have
1497 // inference variables and placeholders escape.
1498 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1507 fn where_clause_may_apply<'o>(
1509 stack: &TraitObligationStack<'o, 'tcx>,
1510 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1511 ) -> Result<EvaluationResult, OverflowError> {
1512 self.evaluation_probe(|this| {
1513 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1514 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1515 Err(()) => Ok(EvaluatedToErr),
1520 /// Return `Yes` if the obligation's predicate type applies to the env_predicate, and
1521 /// `No` if it does not. Return `Ambiguous` in the case that the projection type is a GAT,
1522 /// and applying this env_predicate constrains any of the obligation's GAT substitutions.
1524 /// This behavior is a somewhat of a hack to prevent over-constraining inference variables
1525 /// in cases like #91762.
1526 pub(super) fn match_projection_projections(
1528 obligation: &ProjectionTyObligation<'tcx>,
1529 env_predicate: PolyProjectionPredicate<'tcx>,
1530 potentially_unnormalized_candidates: bool,
1531 ) -> ProjectionMatchesProjection {
1532 let mut nested_obligations = Vec::new();
1533 let infer_predicate = self.infcx.replace_bound_vars_with_fresh_vars(
1534 obligation.cause.span,
1535 LateBoundRegionConversionTime::HigherRankedType,
1538 let infer_projection = if potentially_unnormalized_candidates {
1539 ensure_sufficient_stack(|| {
1540 project::normalize_with_depth_to(
1542 obligation.param_env,
1543 obligation.cause.clone(),
1544 obligation.recursion_depth + 1,
1545 infer_predicate.projection_ty,
1546 &mut nested_obligations,
1550 infer_predicate.projection_ty
1555 .at(&obligation.cause, obligation.param_env)
1556 .define_opaque_types(false)
1557 .sup(obligation.predicate, infer_projection)
1558 .map_or(false, |InferOk { obligations, value: () }| {
1559 self.evaluate_predicates_recursively(
1560 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1561 nested_obligations.into_iter().chain(obligations),
1563 .map_or(false, |res| res.may_apply())
1567 let generics = self.tcx().generics_of(obligation.predicate.item_def_id);
1568 // FIXME(generic-associated-types): Addresses aggressive inference in #92917.
1569 // If this type is a GAT, and of the GAT substs resolve to something new,
1570 // that means that we must have newly inferred something about the GAT.
1571 // We should give up in that case.
1572 if !generics.params.is_empty()
1573 && obligation.predicate.substs[generics.parent_count..]
1575 .any(|&p| p.has_infer_types_or_consts() && self.infcx.shallow_resolve(p) != p)
1577 ProjectionMatchesProjection::Ambiguous
1579 ProjectionMatchesProjection::Yes
1582 ProjectionMatchesProjection::No
1586 ///////////////////////////////////////////////////////////////////////////
1589 // Winnowing is the process of attempting to resolve ambiguity by
1590 // probing further. During the winnowing process, we unify all
1591 // type variables and then we also attempt to evaluate recursive
1592 // bounds to see if they are satisfied.
1594 /// Returns `true` if `victim` should be dropped in favor of
1595 /// `other`. Generally speaking we will drop duplicate
1596 /// candidates and prefer where-clause candidates.
1598 /// See the comment for "SelectionCandidate" for more details.
1599 fn candidate_should_be_dropped_in_favor_of(
1601 victim: &EvaluatedCandidate<'tcx>,
1602 other: &EvaluatedCandidate<'tcx>,
1605 if victim.candidate == other.candidate {
1609 // Check if a bound would previously have been removed when normalizing
1610 // the param_env so that it can be given the lowest priority. See
1611 // #50825 for the motivation for this.
1612 let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| {
1613 cand.is_global() && !cand.has_late_bound_regions()
1616 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1617 // `DiscriminantKindCandidate`, and `ConstDestructCandidate` to anything else.
1619 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1620 // lifetime of a variable.
1621 match (&other.candidate, &victim.candidate) {
1622 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1624 "default implementations shouldn't be recorded \
1625 when there are other valid candidates"
1631 BuiltinCandidate { has_nested: false }
1632 | DiscriminantKindCandidate
1634 | ConstDestructCandidate(_),
1639 BuiltinCandidate { has_nested: false }
1640 | DiscriminantKindCandidate
1642 | ConstDestructCandidate(_),
1645 (ParamCandidate(other), ParamCandidate(victim)) => {
1646 let same_except_bound_vars = other.skip_binder().trait_ref
1647 == victim.skip_binder().trait_ref
1648 && other.skip_binder().constness == victim.skip_binder().constness
1649 && other.skip_binder().polarity == victim.skip_binder().polarity
1650 && !other.skip_binder().trait_ref.has_escaping_bound_vars();
1651 if same_except_bound_vars {
1652 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1653 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1654 // or the current one if tied (they should both evaluate to the same answer). This is
1655 // probably best characterized as a "hack", since we might prefer to just do our
1656 // best to *not* create essentially duplicate candidates in the first place.
1657 other.bound_vars().len() <= victim.bound_vars().len()
1658 } else if other.skip_binder().trait_ref == victim.skip_binder().trait_ref
1659 && victim.skip_binder().constness == ty::BoundConstness::NotConst
1660 && other.skip_binder().polarity == victim.skip_binder().polarity
1662 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1669 // Drop otherwise equivalent non-const fn pointer candidates
1670 (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
1672 // Global bounds from the where clause should be ignored
1673 // here (see issue #50825). Otherwise, we have a where
1674 // clause so don't go around looking for impls.
1675 // Arbitrarily give param candidates priority
1676 // over projection and object candidates.
1678 ParamCandidate(ref cand),
1681 | GeneratorCandidate
1682 | FnPointerCandidate { .. }
1683 | BuiltinObjectCandidate
1684 | BuiltinUnsizeCandidate
1685 | TraitUpcastingUnsizeCandidate(_)
1686 | BuiltinCandidate { .. }
1687 | TraitAliasCandidate(..)
1688 | ObjectCandidate(_)
1689 | ProjectionCandidate(_),
1690 ) => !is_global(cand),
1691 (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1692 // Prefer these to a global where-clause bound
1693 // (see issue #50825).
1699 | GeneratorCandidate
1700 | FnPointerCandidate { .. }
1701 | BuiltinObjectCandidate
1702 | BuiltinUnsizeCandidate
1703 | TraitUpcastingUnsizeCandidate(_)
1704 | BuiltinCandidate { has_nested: true }
1705 | TraitAliasCandidate(..),
1706 ParamCandidate(ref cand),
1708 // Prefer these to a global where-clause bound
1709 // (see issue #50825).
1710 is_global(cand) && other.evaluation.must_apply_modulo_regions()
1713 (ProjectionCandidate(i), ProjectionCandidate(j))
1714 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1715 // Arbitrarily pick the lower numbered candidate for backwards
1716 // compatibility reasons. Don't let this affect inference.
1717 i < j && !needs_infer
1719 (ObjectCandidate(_), ProjectionCandidate(_))
1720 | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1721 bug!("Have both object and projection candidate")
1724 // Arbitrarily give projection and object candidates priority.
1726 ObjectCandidate(_) | ProjectionCandidate(_),
1729 | GeneratorCandidate
1730 | FnPointerCandidate { .. }
1731 | BuiltinObjectCandidate
1732 | BuiltinUnsizeCandidate
1733 | TraitUpcastingUnsizeCandidate(_)
1734 | BuiltinCandidate { .. }
1735 | TraitAliasCandidate(..),
1741 | GeneratorCandidate
1742 | FnPointerCandidate { .. }
1743 | BuiltinObjectCandidate
1744 | BuiltinUnsizeCandidate
1745 | TraitUpcastingUnsizeCandidate(_)
1746 | BuiltinCandidate { .. }
1747 | TraitAliasCandidate(..),
1748 ObjectCandidate(_) | ProjectionCandidate(_),
1751 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1752 // See if we can toss out `victim` based on specialization.
1753 // This requires us to know *for sure* that the `other` impl applies
1754 // i.e., `EvaluatedToOk`.
1756 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1757 // to me but is required for `std` to compile, so I didn't change it
1759 let tcx = self.tcx();
1760 if other.evaluation.must_apply_modulo_regions() {
1761 if tcx.specializes((other_def, victim_def)) {
1766 if other.evaluation.must_apply_considering_regions() {
1767 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1768 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1769 // Subtle: If the predicate we are evaluating has inference
1770 // variables, do *not* allow discarding candidates due to
1771 // marker trait impls.
1773 // Without this restriction, we could end up accidentally
1774 // constraining inference variables based on an arbitrarily
1775 // chosen trait impl.
1777 // Imagine we have the following code:
1780 // #[marker] trait MyTrait {}
1781 // impl MyTrait for u8 {}
1782 // impl MyTrait for bool {}
1785 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1787 // During selection, we will end up with one candidate for each
1788 // impl of `MyTrait`. If we were to discard one impl in favor
1789 // of the other, we would be left with one candidate, causing
1790 // us to "successfully" select the predicate, unifying
1791 // _#0t with (for example) `u8`.
1793 // However, we have no reason to believe that this unification
1794 // is correct - we've essentially just picked an arbitrary
1795 // *possibility* for _#0t, and required that this be the *only*
1798 // Eventually, we will either:
1799 // 1) Unify all inference variables in the predicate through
1800 // some other means (e.g. type-checking of a function). We will
1801 // then be in a position to drop marker trait candidates
1802 // without constraining inference variables (since there are
1803 // none left to constrain)
1804 // 2) Be left with some unconstrained inference variables. We
1805 // will then correctly report an inference error, since the
1806 // existence of multiple marker trait impls tells us nothing
1807 // about which one should actually apply.
1818 // Everything else is ambiguous
1822 | GeneratorCandidate
1823 | FnPointerCandidate { .. }
1824 | BuiltinObjectCandidate
1825 | BuiltinUnsizeCandidate
1826 | TraitUpcastingUnsizeCandidate(_)
1827 | BuiltinCandidate { has_nested: true }
1828 | TraitAliasCandidate(..),
1831 | GeneratorCandidate
1832 | FnPointerCandidate { .. }
1833 | BuiltinObjectCandidate
1834 | BuiltinUnsizeCandidate
1835 | TraitUpcastingUnsizeCandidate(_)
1836 | BuiltinCandidate { has_nested: true }
1837 | TraitAliasCandidate(..),
1842 fn sized_conditions(
1844 obligation: &TraitObligation<'tcx>,
1845 ) -> BuiltinImplConditions<'tcx> {
1846 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1848 // NOTE: binder moved to (*)
1849 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1851 match self_ty.kind() {
1852 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1863 | ty::GeneratorWitness(..)
1868 // safe for everything
1869 Where(ty::Binder::dummy(Vec::new()))
1872 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1874 ty::Tuple(tys) => Where(
1875 obligation.predicate.rebind(tys.last().map_or_else(Vec::new, |&last| vec![last])),
1878 ty::Adt(def, substs) => {
1879 let sized_crit = def.sized_constraint(self.tcx());
1880 // (*) binder moved here
1881 Where(obligation.predicate.rebind({
1882 sized_crit.iter().map(|ty| EarlyBinder(*ty).subst(self.tcx(), substs)).collect()
1886 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1887 ty::Infer(ty::TyVar(_)) => Ambiguous,
1891 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1892 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1897 fn copy_clone_conditions(
1899 obligation: &TraitObligation<'tcx>,
1900 ) -> BuiltinImplConditions<'tcx> {
1901 // NOTE: binder moved to (*)
1902 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1904 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1906 match *self_ty.kind() {
1907 ty::Infer(ty::IntVar(_))
1908 | ty::Infer(ty::FloatVar(_))
1911 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1920 | ty::Ref(_, _, hir::Mutability::Not)
1921 | ty::Array(..) => {
1922 // Implementations provided in libcore
1930 | ty::GeneratorWitness(..)
1932 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1935 // (*) binder moved here
1936 Where(obligation.predicate.rebind(tys.iter().collect()))
1939 ty::Closure(_, substs) => {
1940 // (*) binder moved here
1941 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1942 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1943 // Not yet resolved.
1946 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1950 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1951 // Fallback to whatever user-defined impls exist in this case.
1955 ty::Infer(ty::TyVar(_)) => {
1956 // Unbound type variable. Might or might not have
1957 // applicable impls and so forth, depending on what
1958 // those type variables wind up being bound to.
1964 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1965 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1970 /// For default impls, we need to break apart a type into its
1971 /// "constituent types" -- meaning, the types that it contains.
1973 /// Here are some (simple) examples:
1975 /// ```ignore (illustrative)
1976 /// (i32, u32) -> [i32, u32]
1977 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1978 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1979 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1981 fn constituent_types_for_ty(
1983 t: ty::Binder<'tcx, Ty<'tcx>>,
1984 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1985 match *t.skip_binder().kind() {
1994 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1996 | ty::Char => ty::Binder::dummy(Vec::new()),
2002 | ty::Projection(..)
2004 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2005 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2008 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2009 t.rebind(vec![element_ty])
2012 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
2014 ty::Tuple(ref tys) => {
2015 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2016 t.rebind(tys.iter().collect())
2019 ty::Closure(_, ref substs) => {
2020 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
2024 ty::Generator(_, ref substs, _) => {
2025 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
2026 let witness = substs.as_generator().witness();
2027 t.rebind([ty].into_iter().chain(iter::once(witness)).collect())
2030 ty::GeneratorWitness(types) => {
2031 debug_assert!(!types.has_escaping_bound_vars());
2032 types.map_bound(|types| types.to_vec())
2035 // For `PhantomData<T>`, we pass `T`.
2036 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
2038 ty::Adt(def, substs) => {
2039 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
2042 ty::Opaque(def_id, substs) => {
2043 // We can resolve the `impl Trait` to its concrete type,
2044 // which enforces a DAG between the functions requiring
2045 // the auto trait bounds in question.
2046 t.rebind(vec![self.tcx().bound_type_of(def_id).subst(self.tcx(), substs)])
2051 fn collect_predicates_for_types(
2053 param_env: ty::ParamEnv<'tcx>,
2054 cause: ObligationCause<'tcx>,
2055 recursion_depth: usize,
2056 trait_def_id: DefId,
2057 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
2058 ) -> Vec<PredicateObligation<'tcx>> {
2059 // Because the types were potentially derived from
2060 // higher-ranked obligations they may reference late-bound
2061 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2062 // yield a type like `for<'a> &'a i32`. In general, we
2063 // maintain the invariant that we never manipulate bound
2064 // regions, so we have to process these bound regions somehow.
2066 // The strategy is to:
2068 // 1. Instantiate those regions to placeholder regions (e.g.,
2069 // `for<'a> &'a i32` becomes `&0 i32`.
2070 // 2. Produce something like `&'0 i32 : Copy`
2071 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2075 .skip_binder() // binder moved -\
2078 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(*ty); // <----/
2080 self.infcx.commit_unconditionally(|_| {
2081 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
2082 let Normalized { value: normalized_ty, mut obligations } =
2083 ensure_sufficient_stack(|| {
2084 project::normalize_with_depth(
2092 let placeholder_obligation = predicate_for_trait_def(
2101 obligations.push(placeholder_obligation);
2108 ///////////////////////////////////////////////////////////////////////////
2111 // Matching is a common path used for both evaluation and
2112 // confirmation. It basically unifies types that appear in impls
2113 // and traits. This does affect the surrounding environment;
2114 // therefore, when used during evaluation, match routines must be
2115 // run inside of a `probe()` so that their side-effects are
2121 obligation: &TraitObligation<'tcx>,
2122 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
2123 let impl_trait_ref = self.tcx().bound_impl_trait_ref(impl_def_id).unwrap();
2124 match self.match_impl(impl_def_id, impl_trait_ref, obligation) {
2125 Ok(substs) => substs,
2127 self.infcx.tcx.sess.delay_span_bug(
2128 obligation.cause.span,
2130 "Impl {:?} was matchable against {:?} but now is not",
2131 impl_def_id, obligation
2134 let value = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2135 let err = self.tcx().ty_error();
2136 let value = value.fold_with(&mut BottomUpFolder {
2142 Normalized { value, obligations: vec![] }
2147 #[tracing::instrument(level = "debug", skip(self))]
2151 impl_trait_ref: EarlyBinder<ty::TraitRef<'tcx>>,
2152 obligation: &TraitObligation<'tcx>,
2153 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2154 let placeholder_obligation =
2155 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
2156 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2158 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2160 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2162 debug!(?impl_trait_ref);
2164 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2165 ensure_sufficient_stack(|| {
2166 project::normalize_with_depth(
2168 obligation.param_env,
2169 obligation.cause.clone(),
2170 obligation.recursion_depth + 1,
2175 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2177 let cause = ObligationCause::new(
2178 obligation.cause.span,
2179 obligation.cause.body_id,
2180 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2183 let InferOk { obligations, .. } = self
2185 .at(&cause, obligation.param_env)
2186 .define_opaque_types(false)
2187 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2188 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2189 nested_obligations.extend(obligations);
2192 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2194 debug!("match_impl: reservation impls only apply in intercrate mode");
2198 debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2199 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2202 fn fast_reject_trait_refs(
2204 obligation: &TraitObligation<'tcx>,
2205 impl_trait_ref: &ty::TraitRef<'tcx>,
2207 // We can avoid creating type variables and doing the full
2208 // substitution if we find that any of the input types, when
2209 // simplified, do not match.
2210 let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsPlaceholder };
2211 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs)
2212 .any(|(obl, imp)| !drcx.generic_args_may_unify(obl, imp))
2215 /// Normalize `where_clause_trait_ref` and try to match it against
2216 /// `obligation`. If successful, return any predicates that
2217 /// result from the normalization.
2218 fn match_where_clause_trait_ref(
2220 obligation: &TraitObligation<'tcx>,
2221 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2222 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2223 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2226 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2227 /// obligation is satisfied.
2228 #[instrument(skip(self), level = "debug")]
2229 fn match_poly_trait_ref(
2231 obligation: &TraitObligation<'tcx>,
2232 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2233 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2235 .at(&obligation.cause, obligation.param_env)
2236 // We don't want predicates for opaque types to just match all other types,
2237 // if there is an obligation on the opaque type, then that obligation must be met
2238 // opaquely. Otherwise we'd match any obligation to the opaque type and then error
2240 .define_opaque_types(false)
2241 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2242 .map(|InferOk { obligations, .. }| obligations)
2246 ///////////////////////////////////////////////////////////////////////////
2249 fn match_fresh_trait_refs(
2251 previous: ty::PolyTraitPredicate<'tcx>,
2252 current: ty::PolyTraitPredicate<'tcx>,
2253 param_env: ty::ParamEnv<'tcx>,
2255 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2256 matcher.relate(previous, current).is_ok()
2261 previous_stack: TraitObligationStackList<'o, 'tcx>,
2262 obligation: &'o TraitObligation<'tcx>,
2263 ) -> TraitObligationStack<'o, 'tcx> {
2264 let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
2266 let dfn = previous_stack.cache.next_dfn();
2267 let depth = previous_stack.depth() + 1;
2268 TraitObligationStack {
2271 reached_depth: Cell::new(depth),
2272 previous: previous_stack,
2278 #[instrument(skip(self), level = "debug")]
2279 fn closure_trait_ref_unnormalized(
2281 obligation: &TraitObligation<'tcx>,
2282 substs: SubstsRef<'tcx>,
2283 ) -> ty::PolyTraitRef<'tcx> {
2284 let closure_sig = substs.as_closure().sig();
2286 debug!(?closure_sig);
2288 // (1) Feels icky to skip the binder here, but OTOH we know
2289 // that the self-type is an unboxed closure type and hence is
2290 // in fact unparameterized (or at least does not reference any
2291 // regions bound in the obligation). Still probably some
2292 // refactoring could make this nicer.
2293 closure_trait_ref_and_return_type(
2295 obligation.predicate.def_id(),
2296 obligation.predicate.skip_binder().self_ty(), // (1)
2298 util::TupleArgumentsFlag::No,
2300 .map_bound(|(trait_ref, _)| trait_ref)
2303 fn generator_trait_ref_unnormalized(
2305 obligation: &TraitObligation<'tcx>,
2306 substs: SubstsRef<'tcx>,
2307 ) -> ty::PolyTraitRef<'tcx> {
2308 let gen_sig = substs.as_generator().poly_sig();
2310 // (1) Feels icky to skip the binder here, but OTOH we know
2311 // that the self-type is an generator type and hence is
2312 // in fact unparameterized (or at least does not reference any
2313 // regions bound in the obligation). Still probably some
2314 // refactoring could make this nicer.
2316 super::util::generator_trait_ref_and_outputs(
2318 obligation.predicate.def_id(),
2319 obligation.predicate.skip_binder().self_ty(), // (1)
2322 .map_bound(|(trait_ref, ..)| trait_ref)
2325 /// Returns the obligations that are implied by instantiating an
2326 /// impl or trait. The obligations are substituted and fully
2327 /// normalized. This is used when confirming an impl or default
2329 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2330 fn impl_or_trait_obligations(
2332 cause: &ObligationCause<'tcx>,
2333 recursion_depth: usize,
2334 param_env: ty::ParamEnv<'tcx>,
2335 def_id: DefId, // of impl or trait
2336 substs: SubstsRef<'tcx>, // for impl or trait
2337 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2338 ) -> Vec<PredicateObligation<'tcx>> {
2339 let tcx = self.tcx();
2341 // To allow for one-pass evaluation of the nested obligation,
2342 // each predicate must be preceded by the obligations required
2344 // for example, if we have:
2345 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2346 // the impl will have the following predicates:
2347 // <V as Iterator>::Item = U,
2348 // U: Iterator, U: Sized,
2349 // V: Iterator, V: Sized,
2350 // <U as Iterator>::Item: Copy
2351 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2352 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2353 // `$1: Copy`, so we must ensure the obligations are emitted in
2355 let predicates = tcx.predicates_of(def_id);
2356 debug!(?predicates);
2357 assert_eq!(predicates.parent, None);
2358 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2359 for (predicate, span) in predicates.predicates {
2361 let cause = cause.clone().derived_cause(parent_trait_pred, |derived| {
2362 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
2364 impl_def_id: def_id,
2368 let predicate = normalize_with_depth_to(
2373 EarlyBinder(*predicate).subst(tcx, substs),
2376 obligations.push(Obligation { cause, recursion_depth, param_env, predicate });
2383 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2384 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2385 TraitObligationStackList::with(self)
2388 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2392 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2396 /// Indicates that attempting to evaluate this stack entry
2397 /// required accessing something from the stack at depth `reached_depth`.
2398 fn update_reached_depth(&self, reached_depth: usize) {
2400 self.depth >= reached_depth,
2401 "invoked `update_reached_depth` with something under this stack: \
2402 self.depth={} reached_depth={}",
2406 debug!(reached_depth, "update_reached_depth");
2408 while reached_depth < p.depth {
2409 debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
2410 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2411 p = p.previous.head.unwrap();
2416 /// The "provisional evaluation cache" is used to store intermediate cache results
2417 /// when solving auto traits. Auto traits are unusual in that they can support
2418 /// cycles. So, for example, a "proof tree" like this would be ok:
2420 /// - `Foo<T>: Send` :-
2421 /// - `Bar<T>: Send` :-
2422 /// - `Foo<T>: Send` -- cycle, but ok
2423 /// - `Baz<T>: Send`
2425 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2426 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2427 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2428 /// they are coinductive) it is considered ok.
2430 /// However, there is a complication: at the point where we have
2431 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2432 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2433 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2434 /// find out this assumption is wrong? Specifically, we could
2435 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2436 /// `Bar<T>: Send` didn't turn out to be true.
2438 /// In Issue #60010, we found a bug in rustc where it would cache
2439 /// these intermediate results. This was fixed in #60444 by disabling
2440 /// *all* caching for things involved in a cycle -- in our example,
2441 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2442 /// to large slowdowns.
2444 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2445 /// first requires proving `Bar<T>: Send` (which is true:
2447 /// - `Foo<T>: Send` :-
2448 /// - `Bar<T>: Send` :-
2449 /// - `Foo<T>: Send` -- cycle, but ok
2450 /// - `Baz<T>: Send`
2451 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2452 /// - `*const T: Send` -- but what if we later encounter an error?
2454 /// The *provisional evaluation cache* resolves this issue. It stores
2455 /// cache results that we've proven but which were involved in a cycle
2456 /// in some way. We track the minimal stack depth (i.e., the
2457 /// farthest from the top of the stack) that we are dependent on.
2458 /// The idea is that the cache results within are all valid -- so long as
2459 /// none of the nodes in between the current node and the node at that minimum
2460 /// depth result in an error (in which case the cached results are just thrown away).
2462 /// During evaluation, we consult this provisional cache and rely on
2463 /// it. Accessing a cached value is considered equivalent to accessing
2464 /// a result at `reached_depth`, so it marks the *current* solution as
2465 /// provisional as well. If an error is encountered, we toss out any
2466 /// provisional results added from the subtree that encountered the
2467 /// error. When we pop the node at `reached_depth` from the stack, we
2468 /// can commit all the things that remain in the provisional cache.
2469 struct ProvisionalEvaluationCache<'tcx> {
2470 /// next "depth first number" to issue -- just a counter
2473 /// Map from cache key to the provisionally evaluated thing.
2474 /// The cache entries contain the result but also the DFN in which they
2475 /// were added. The DFN is used to clear out values on failure.
2477 /// Imagine we have a stack like:
2479 /// - `A B C` and we add a cache for the result of C (DFN 2)
2480 /// - Then we have a stack `A B D` where `D` has DFN 3
2481 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2482 /// - `E` generates various cache entries which have cyclic dependencies on `B`
2483 /// - `A B D E F` and so forth
2484 /// - the DFN of `F` for example would be 5
2485 /// - then we determine that `E` is in error -- we will then clear
2486 /// all cache values whose DFN is >= 4 -- in this case, that
2487 /// means the cached value for `F`.
2488 map: RefCell<FxHashMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
2490 /// The stack of args that we assume to be true because a `WF(arg)` predicate
2491 /// is on the stack above (and because of wellformedness is coinductive).
2492 /// In an "ideal" world, this would share a stack with trait predicates in
2493 /// `TraitObligationStack`. However, trait predicates are *much* hotter than
2494 /// `WellFormed` predicates, and it's very likely that the additional matches
2495 /// will have a perf effect. The value here is the well-formed `GenericArg`
2496 /// and the depth of the trait predicate *above* that well-formed predicate.
2497 wf_args: RefCell<Vec<(ty::GenericArg<'tcx>, usize)>>,
2500 /// A cache value for the provisional cache: contains the depth-first
2501 /// number (DFN) and result.
2502 #[derive(Copy, Clone, Debug)]
2503 struct ProvisionalEvaluation {
2505 reached_depth: usize,
2506 result: EvaluationResult,
2509 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2510 fn default() -> Self {
2511 Self { dfn: Cell::new(0), map: Default::default(), wf_args: Default::default() }
2515 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2516 /// Get the next DFN in sequence (basically a counter).
2517 fn next_dfn(&self) -> usize {
2518 let result = self.dfn.get();
2519 self.dfn.set(result + 1);
2523 /// Check the provisional cache for any result for
2524 /// `fresh_trait_ref`. If there is a hit, then you must consider
2525 /// it an access to the stack slots at depth
2526 /// `reached_depth` (from the returned value).
2529 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2530 ) -> Option<ProvisionalEvaluation> {
2533 "get_provisional = {:#?}",
2534 self.map.borrow().get(&fresh_trait_pred),
2536 Some(*self.map.borrow().get(&fresh_trait_pred)?)
2539 /// Insert a provisional result into the cache. The result came
2540 /// from the node with the given DFN. It accessed a minimum depth
2541 /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
2542 /// and resulted in `result`.
2543 fn insert_provisional(
2546 reached_depth: usize,
2547 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2548 result: EvaluationResult,
2550 debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
2552 let mut map = self.map.borrow_mut();
2554 // Subtle: when we complete working on the DFN `from_dfn`, anything
2555 // that remains in the provisional cache must be dependent on some older
2556 // stack entry than `from_dfn`. We have to update their depth with our transitive
2557 // depth in that case or else it would be referring to some popped note.
2560 // A (reached depth 0)
2562 // B // depth 1 -- reached depth = 0
2563 // C // depth 2 -- reached depth = 1 (should be 0)
2566 // D (reached depth 1)
2567 // C (cache -- reached depth = 2)
2568 for (_k, v) in &mut *map {
2569 if v.from_dfn >= from_dfn {
2570 v.reached_depth = reached_depth.min(v.reached_depth);
2574 map.insert(fresh_trait_pred, ProvisionalEvaluation { from_dfn, reached_depth, result });
2577 /// Invoked when the node with dfn `dfn` does not get a successful
2578 /// result. This will clear out any provisional cache entries
2579 /// that were added since `dfn` was created. This is because the
2580 /// provisional entries are things which must assume that the
2581 /// things on the stack at the time of their creation succeeded --
2582 /// since the failing node is presently at the top of the stack,
2583 /// these provisional entries must either depend on it or some
2585 fn on_failure(&self, dfn: usize) {
2586 debug!(?dfn, "on_failure");
2587 self.map.borrow_mut().retain(|key, eval| {
2588 if !eval.from_dfn >= dfn {
2589 debug!("on_failure: removing {:?}", key);
2597 /// Invoked when the node at depth `depth` completed without
2598 /// depending on anything higher in the stack (if that completion
2599 /// was a failure, then `on_failure` should have been invoked
2602 /// Note that we may still have provisional cache items remaining
2603 /// in the cache when this is done. For example, if there is a
2606 /// * A depends on...
2607 /// * B depends on A
2608 /// * C depends on...
2609 /// * D depends on C
2612 /// Then as we complete the C node we will have a provisional cache
2613 /// with results for A, B, C, and D. This method would clear out
2614 /// the C and D results, but leave A and B provisional.
2616 /// This is determined based on the DFN: we remove any provisional
2617 /// results created since `dfn` started (e.g., in our example, dfn
2618 /// would be 2, representing the C node, and hence we would
2619 /// remove the result for D, which has DFN 3, but not the results for
2620 /// A and B, which have DFNs 0 and 1 respectively).
2622 /// Note that we *do not* attempt to cache these cycle participants
2623 /// in the evaluation cache. Doing so would require carefully computing
2624 /// the correct `DepNode` to store in the cache entry:
2625 /// cycle participants may implicitly depend on query results
2626 /// related to other participants in the cycle, due to our logic
2627 /// which examines the evaluation stack.
2629 /// We used to try to perform this caching,
2630 /// but it lead to multiple incremental compilation ICEs
2631 /// (see #92987 and #96319), and was very hard to understand.
2632 /// Fortunately, removing the caching didn't seem to
2633 /// have a performance impact in practice.
2634 fn on_completion(&self, dfn: usize) {
2635 debug!(?dfn, "on_completion");
2637 for (fresh_trait_pred, eval) in
2638 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2640 debug!(?fresh_trait_pred, ?eval, "on_completion");
2645 #[derive(Copy, Clone)]
2646 struct TraitObligationStackList<'o, 'tcx> {
2647 cache: &'o ProvisionalEvaluationCache<'tcx>,
2648 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2651 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2652 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2653 TraitObligationStackList { cache, head: None }
2656 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2657 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2660 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2664 fn depth(&self) -> usize {
2665 if let Some(head) = self.head { head.depth } else { 0 }
2669 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2670 type Item = &'o TraitObligationStack<'o, 'tcx>;
2672 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2679 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2680 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2681 write!(f, "TraitObligationStack({:?})", self.obligation)
2685 pub enum ProjectionMatchesProjection {