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::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, Eq, PartialEq, Hash)]
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<FxIndexSet<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(FxIndexSet::default());
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) -> FxIndexSet<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 if self.infcx.opaque_types_added_in_snapshot(snapshot) {
398 return Ok(result.max(EvaluatedToOkModuloOpaqueTypes));
401 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
403 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
408 /// Evaluates the predicates in `predicates` recursively. Note that
409 /// this applies projections in the predicates, and therefore
410 /// is run within an inference probe.
411 #[instrument(skip(self, stack), level = "debug")]
412 fn evaluate_predicates_recursively<'o, I>(
414 stack: TraitObligationStackList<'o, 'tcx>,
416 ) -> Result<EvaluationResult, OverflowError>
418 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
420 let mut result = EvaluatedToOk;
421 for obligation in predicates {
422 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
423 if let EvaluatedToErr = eval {
424 // fast-path - EvaluatedToErr is the top of the lattice,
425 // so we don't need to look on the other predicates.
426 return Ok(EvaluatedToErr);
428 result = cmp::max(result, eval);
436 skip(self, previous_stack),
437 fields(previous_stack = ?previous_stack.head())
439 fn evaluate_predicate_recursively<'o>(
441 previous_stack: TraitObligationStackList<'o, 'tcx>,
442 obligation: PredicateObligation<'tcx>,
443 ) -> Result<EvaluationResult, OverflowError> {
444 // `previous_stack` stores a `TraitObligation`, while `obligation` is
445 // a `PredicateObligation`. These are distinct types, so we can't
446 // use any `Option` combinator method that would force them to be
448 match previous_stack.head() {
449 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
450 None => self.check_recursion_limit(&obligation, &obligation)?,
453 let result = ensure_sufficient_stack(|| {
454 let bound_predicate = obligation.predicate.kind();
455 match bound_predicate.skip_binder() {
456 ty::PredicateKind::Trait(t) => {
457 let t = bound_predicate.rebind(t);
458 debug_assert!(!t.has_escaping_bound_vars());
459 let obligation = obligation.with(t);
460 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
463 ty::PredicateKind::Subtype(p) => {
464 let p = bound_predicate.rebind(p);
465 // Does this code ever run?
466 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
467 Some(Ok(InferOk { mut obligations, .. })) => {
468 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
469 self.evaluate_predicates_recursively(
471 obligations.into_iter(),
474 Some(Err(_)) => Ok(EvaluatedToErr),
475 None => Ok(EvaluatedToAmbig),
479 ty::PredicateKind::Coerce(p) => {
480 let p = bound_predicate.rebind(p);
481 // Does this code ever run?
482 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
483 Some(Ok(InferOk { mut obligations, .. })) => {
484 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
485 self.evaluate_predicates_recursively(
487 obligations.into_iter(),
490 Some(Err(_)) => Ok(EvaluatedToErr),
491 None => Ok(EvaluatedToAmbig),
495 ty::PredicateKind::WellFormed(arg) => {
496 // So, there is a bit going on here. First, `WellFormed` predicates
497 // are coinductive, like trait predicates with auto traits.
498 // This means that we need to detect if we have recursively
499 // evaluated `WellFormed(X)`. Otherwise, we would run into
500 // a "natural" overflow error.
502 // Now, the next question is whether we need to do anything
503 // special with caching. Considering the following tree:
508 // In this case, the innermost `WF(Foo<T>)` should return
509 // `EvaluatedToOk`, since it's coinductive. Then if
510 // `Bar<T>: Send` is resolved to `EvaluatedToOk`, it can be
511 // inserted into a cache (because without thinking about `WF`
512 // goals, it isn't in a cycle). If `Foo<T>: Trait` later doesn't
513 // hold, then `Bar<T>: Send` shouldn't hold. Therefore, we
514 // *do* need to keep track of coinductive cycles.
516 let cache = previous_stack.cache;
517 let dfn = cache.next_dfn();
519 for stack_arg in previous_stack.cache.wf_args.borrow().iter().rev() {
520 if stack_arg.0 != arg {
523 debug!("WellFormed({:?}) on stack", arg);
524 if let Some(stack) = previous_stack.head {
525 // Okay, let's imagine we have two different stacks:
526 // `T: NonAutoTrait -> WF(T) -> T: NonAutoTrait`
527 // `WF(T) -> T: NonAutoTrait -> WF(T)`
528 // Because of this, we need to check that all
529 // predicates between the WF goals are coinductive.
530 // Otherwise, we can say that `T: NonAutoTrait` is
532 // Let's imagine we have a predicate stack like
533 // `Foo: Bar -> WF(T) -> T: NonAutoTrait -> T: Auto
535 // and the current predicate is `WF(T)`. `wf_args`
536 // would contain `(T, 1)`. We want to check all
537 // trait predicates greater than `1`. The previous
538 // stack would be `T: Auto`.
539 let cycle = stack.iter().take_while(|s| s.depth > stack_arg.1);
540 let tcx = self.tcx();
542 cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
543 if self.coinductive_match(cycle) {
544 stack.update_reached_depth(stack_arg.1);
545 return Ok(EvaluatedToOk);
547 return Ok(EvaluatedToRecur);
550 return Ok(EvaluatedToOk);
553 match wf::obligations(
555 obligation.param_env,
556 obligation.cause.body_id,
557 obligation.recursion_depth + 1,
559 obligation.cause.span,
561 Some(mut obligations) => {
562 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
564 cache.wf_args.borrow_mut().push((arg, previous_stack.depth()));
566 self.evaluate_predicates_recursively(previous_stack, obligations);
567 cache.wf_args.borrow_mut().pop();
569 let result = result?;
571 if !result.must_apply_modulo_regions() {
572 cache.on_failure(dfn);
575 cache.on_completion(dfn);
579 None => Ok(EvaluatedToAmbig),
583 ty::PredicateKind::TypeOutlives(pred) => {
584 // A global type with no late-bound regions can only
585 // contain the "'static" lifetime (any other lifetime
586 // would either be late-bound or local), so it is guaranteed
587 // to outlive any other lifetime
588 if pred.0.is_global() && !pred.0.has_late_bound_regions() {
591 Ok(EvaluatedToOkModuloRegions)
595 ty::PredicateKind::RegionOutlives(..) => {
596 // We do not consider region relationships when evaluating trait matches.
597 Ok(EvaluatedToOkModuloRegions)
600 ty::PredicateKind::ObjectSafe(trait_def_id) => {
601 if self.tcx().is_object_safe(trait_def_id) {
608 ty::PredicateKind::Projection(data) => {
609 let data = bound_predicate.rebind(data);
610 let project_obligation = obligation.with(data);
611 match project::poly_project_and_unify_type(self, &project_obligation) {
612 ProjectAndUnifyResult::Holds(mut subobligations) => {
614 // If we've previously marked this projection as 'complete', then
615 // use the final cached result (either `EvaluatedToOk` or
616 // `EvaluatedToOkModuloRegions`), and skip re-evaluating the
619 ProjectionCacheKey::from_poly_projection_predicate(self, data)
621 if let Some(cached_res) = self
628 break 'compute_res Ok(cached_res);
633 subobligations.iter_mut(),
634 obligation.recursion_depth,
636 let res = self.evaluate_predicates_recursively(
640 if let Ok(eval_rslt) = res
641 && (eval_rslt == EvaluatedToOk || eval_rslt == EvaluatedToOkModuloRegions)
643 ProjectionCacheKey::from_poly_projection_predicate(
647 // If the result is something that we can cache, then mark this
648 // entry as 'complete'. This will allow us to skip evaluating the
649 // subobligations at all the next time we evaluate the projection
655 .complete(key, eval_rslt);
660 ProjectAndUnifyResult::FailedNormalization => Ok(EvaluatedToAmbig),
661 ProjectAndUnifyResult::Recursive => Ok(EvaluatedToRecur),
662 ProjectAndUnifyResult::MismatchedProjectionTypes(_) => Ok(EvaluatedToErr),
666 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
667 match self.infcx.closure_kind(closure_substs) {
668 Some(closure_kind) => {
669 if closure_kind.extends(kind) {
675 None => Ok(EvaluatedToAmbig),
679 ty::PredicateKind::ConstEvaluatable(uv) => {
680 match const_evaluatable::is_const_evaluatable(
683 obligation.param_env,
684 obligation.cause.span,
686 Ok(()) => Ok(EvaluatedToOk),
687 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
688 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
689 Err(_) => Ok(EvaluatedToErr),
693 ty::PredicateKind::ConstEquate(c1, c2) => {
694 debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
696 if self.tcx().features().generic_const_exprs {
697 // FIXME: we probably should only try to unify abstract constants
698 // if the constants depend on generic parameters.
700 // Let's just see where this breaks :shrug:
701 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
702 (c1.kind(), c2.kind())
704 if self.infcx.try_unify_abstract_consts(
707 obligation.param_env,
709 return Ok(EvaluatedToOk);
714 let evaluate = |c: ty::Const<'tcx>| {
715 if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() {
716 match self.infcx.try_const_eval_resolve(
717 obligation.param_env,
720 Some(obligation.cause.span),
730 match (evaluate(c1), evaluate(c2)) {
731 (Ok(c1), Ok(c2)) => {
734 .at(&obligation.cause, obligation.param_env)
737 Ok(_) => Ok(EvaluatedToOk),
738 Err(_) => Ok(EvaluatedToErr),
741 (Err(ErrorHandled::Reported(_)), _)
742 | (_, Err(ErrorHandled::Reported(_))) => Ok(EvaluatedToErr),
743 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
745 obligation.cause.span(),
746 "ConstEquate: const_eval_resolve returned an unexpected error"
749 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
750 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
753 // Two different constants using generic parameters ~> error.
759 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
760 bug!("TypeWellFormedFromEnv is only used for chalk")
765 debug!("finished: {:?} from {:?}", result, obligation);
770 #[instrument(skip(self, previous_stack), level = "debug")]
771 fn evaluate_trait_predicate_recursively<'o>(
773 previous_stack: TraitObligationStackList<'o, 'tcx>,
774 mut obligation: TraitObligation<'tcx>,
775 ) -> Result<EvaluationResult, OverflowError> {
777 && obligation.is_global()
778 && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst())
780 // If a param env has no global bounds, global obligations do not
781 // depend on its particular value in order to work, so we can clear
782 // out the param env and get better caching.
784 obligation.param_env = obligation.param_env.without_caller_bounds();
787 let stack = self.push_stack(previous_stack, &obligation);
788 let mut fresh_trait_pred = stack.fresh_trait_pred;
789 let mut param_env = obligation.param_env;
791 fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| {
792 pred.remap_constness(&mut param_env);
796 debug!(?fresh_trait_pred);
798 // If a trait predicate is in the (local or global) evaluation cache,
799 // then we know it holds without cycles.
800 if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
801 debug!(?result, "CACHE HIT");
805 if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
806 debug!(?result, "PROVISIONAL CACHE HIT");
807 stack.update_reached_depth(result.reached_depth);
808 return Ok(result.result);
811 // Check if this is a match for something already on the
812 // stack. If so, we don't want to insert the result into the
813 // main cache (it is cycle dependent) nor the provisional
814 // cache (which is meant for things that have completed but
815 // for a "backedge" -- this result *is* the backedge).
816 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
817 return Ok(cycle_result);
820 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
821 let result = result?;
823 if !result.must_apply_modulo_regions() {
824 stack.cache().on_failure(stack.dfn);
827 let reached_depth = stack.reached_depth.get();
828 if reached_depth >= stack.depth {
829 debug!(?result, "CACHE MISS");
830 self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
831 stack.cache().on_completion(stack.dfn);
833 debug!(?result, "PROVISIONAL");
835 "caching provisionally because {:?} \
836 is a cycle participant (at depth {}, reached depth {})",
837 fresh_trait_pred, stack.depth, reached_depth,
840 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_pred, result);
846 /// If there is any previous entry on the stack that precisely
847 /// matches this obligation, then we can assume that the
848 /// obligation is satisfied for now (still all other conditions
849 /// must be met of course). One obvious case this comes up is
850 /// marker traits like `Send`. Think of a linked list:
852 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
854 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
855 /// `Option<Box<List<T>>>` is `Send`, and in turn
856 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
859 /// Note that we do this comparison using the `fresh_trait_ref`
860 /// fields. Because these have all been freshened using
861 /// `self.freshener`, we can be sure that (a) this will not
862 /// affect the inferencer state and (b) that if we see two
863 /// fresh regions with the same index, they refer to the same
864 /// unbound type variable.
865 fn check_evaluation_cycle(
867 stack: &TraitObligationStack<'_, 'tcx>,
868 ) -> Option<EvaluationResult> {
869 if let Some(cycle_depth) = stack
871 .skip(1) // Skip top-most frame.
873 stack.obligation.param_env == prev.obligation.param_env
874 && stack.fresh_trait_pred == prev.fresh_trait_pred
876 .map(|stack| stack.depth)
878 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
880 // If we have a stack like `A B C D E A`, where the top of
881 // the stack is the final `A`, then this will iterate over
882 // `A, E, D, C, B` -- i.e., all the participants apart
883 // from the cycle head. We mark them as participating in a
884 // cycle. This suppresses caching for those nodes. See
885 // `in_cycle` field for more details.
886 stack.update_reached_depth(cycle_depth);
888 // Subtle: when checking for a coinductive cycle, we do
889 // not compare using the "freshened trait refs" (which
890 // have erased regions) but rather the fully explicit
891 // trait refs. This is important because it's only a cycle
892 // if the regions match exactly.
893 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
894 let tcx = self.tcx();
895 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
896 if self.coinductive_match(cycle) {
897 debug!("evaluate_stack --> recursive, coinductive");
900 debug!("evaluate_stack --> recursive, inductive");
901 Some(EvaluatedToRecur)
908 fn evaluate_stack<'o>(
910 stack: &TraitObligationStack<'o, 'tcx>,
911 ) -> Result<EvaluationResult, OverflowError> {
912 // In intercrate mode, whenever any of the generics are unbound,
913 // there can always be an impl. Even if there are no impls in
914 // this crate, perhaps the type would be unified with
915 // something from another crate that does provide an impl.
917 // In intra mode, we must still be conservative. The reason is
918 // that we want to avoid cycles. Imagine an impl like:
920 // impl<T:Eq> Eq for Vec<T>
922 // and a trait reference like `$0 : Eq` where `$0` is an
923 // unbound variable. When we evaluate this trait-reference, we
924 // will unify `$0` with `Vec<$1>` (for some fresh variable
925 // `$1`), on the condition that `$1 : Eq`. We will then wind
926 // up with many candidates (since that are other `Eq` impls
927 // that apply) and try to winnow things down. This results in
928 // a recursive evaluation that `$1 : Eq` -- as you can
929 // imagine, this is just where we started. To avoid that, we
930 // check for unbound variables and return an ambiguous (hence possible)
931 // match if we've seen this trait before.
933 // This suffices to allow chains like `FnMut` implemented in
934 // terms of `Fn` etc, but we could probably make this more
936 let unbound_input_types =
937 stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh());
939 if stack.obligation.polarity() != ty::ImplPolarity::Negative {
940 // This check was an imperfect workaround for a bug in the old
941 // intercrate mode; it should be removed when that goes away.
942 if unbound_input_types && self.intercrate {
943 debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
944 // Heuristics: show the diagnostics when there are no candidates in crate.
945 if self.intercrate_ambiguity_causes.is_some() {
946 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
947 if let Ok(candidate_set) = self.assemble_candidates(stack) {
948 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
949 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
950 let self_ty = trait_ref.self_ty();
951 let cause = with_no_trimmed_paths!({
952 IntercrateAmbiguityCause::DownstreamCrate {
953 trait_desc: trait_ref.print_only_trait_path().to_string(),
954 self_desc: if self_ty.has_concrete_skeleton() {
955 Some(self_ty.to_string())
962 debug!(?cause, "evaluate_stack: pushing cause");
963 self.intercrate_ambiguity_causes.as_mut().unwrap().insert(cause);
967 return Ok(EvaluatedToAmbig);
971 if unbound_input_types
972 && stack.iter().skip(1).any(|prev| {
973 stack.obligation.param_env == prev.obligation.param_env
974 && self.match_fresh_trait_refs(
975 stack.fresh_trait_pred,
976 prev.fresh_trait_pred,
977 prev.obligation.param_env,
981 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
982 return Ok(EvaluatedToUnknown);
985 match self.candidate_from_obligation(stack) {
986 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
987 Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig),
988 Ok(None) => Ok(EvaluatedToAmbig),
989 Err(Overflow(OverflowError::Canonical)) => Err(OverflowError::Canonical),
990 Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
991 Err(..) => Ok(EvaluatedToErr),
995 /// For defaulted traits, we use a co-inductive strategy to solve, so
996 /// that recursion is ok. This routine returns `true` if the top of the
997 /// stack (`cycle[0]`):
999 /// - is a defaulted trait,
1000 /// - it also appears in the backtrace at some position `X`,
1001 /// - all the predicates at positions `X..` between `X` and the top are
1002 /// also defaulted traits.
1003 pub(crate) fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
1005 I: Iterator<Item = ty::Predicate<'tcx>>,
1007 cycle.all(|predicate| self.coinductive_predicate(predicate))
1010 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1011 let result = match predicate.kind().skip_binder() {
1012 ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1013 ty::PredicateKind::WellFormed(_) => true,
1016 debug!(?predicate, ?result, "coinductive_predicate");
1020 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
1021 /// obligations are met. Returns whether `candidate` remains viable after this further
1026 fields(depth = stack.obligation.recursion_depth)
1028 fn evaluate_candidate<'o>(
1030 stack: &TraitObligationStack<'o, 'tcx>,
1031 candidate: &SelectionCandidate<'tcx>,
1032 ) -> Result<EvaluationResult, OverflowError> {
1033 let mut result = self.evaluation_probe(|this| {
1034 let candidate = (*candidate).clone();
1035 match this.confirm_candidate(stack.obligation, candidate) {
1038 this.evaluate_predicates_recursively(
1040 selection.nested_obligations().into_iter(),
1043 Err(..) => Ok(EvaluatedToErr),
1047 // If we erased any lifetimes, then we want to use
1048 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
1049 // as your final result. The result will be cached using
1050 // the freshened trait predicate as a key, so we need
1051 // our result to be correct by *any* choice of original lifetimes,
1052 // not just the lifetime choice for this particular (non-erased)
1055 if stack.fresh_trait_pred.has_erased_regions() {
1056 result = result.max(EvaluatedToOkModuloRegions);
1063 fn check_evaluation_cache(
1065 param_env: ty::ParamEnv<'tcx>,
1066 trait_pred: ty::PolyTraitPredicate<'tcx>,
1067 ) -> Option<EvaluationResult> {
1068 // Neither the global nor local cache is aware of intercrate
1069 // mode, so don't do any caching. In particular, we might
1070 // re-use the same `InferCtxt` with both an intercrate
1071 // and non-intercrate `SelectionContext`
1072 if self.intercrate {
1076 let tcx = self.tcx();
1077 if self.can_use_global_caches(param_env) {
1078 if let Some(res) = tcx.evaluation_cache.get(&(param_env, trait_pred), tcx) {
1082 self.infcx.evaluation_cache.get(&(param_env, trait_pred), tcx)
1085 fn insert_evaluation_cache(
1087 param_env: ty::ParamEnv<'tcx>,
1088 trait_pred: ty::PolyTraitPredicate<'tcx>,
1089 dep_node: DepNodeIndex,
1090 result: EvaluationResult,
1092 // Avoid caching results that depend on more than just the trait-ref
1093 // - the stack can create recursion.
1094 if result.is_stack_dependent() {
1098 // Neither the global nor local cache is aware of intercrate
1099 // mode, so don't do any caching. In particular, we might
1100 // re-use the same `InferCtxt` with both an intercrate
1101 // and non-intercrate `SelectionContext`
1102 if self.intercrate {
1106 if self.can_use_global_caches(param_env) {
1107 if !trait_pred.needs_infer() {
1108 debug!(?trait_pred, ?result, "insert_evaluation_cache global");
1109 // This may overwrite the cache with the same value
1110 // FIXME: Due to #50507 this overwrites the different values
1111 // This should be changed to use HashMapExt::insert_same
1112 // when that is fixed
1113 self.tcx().evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1118 debug!(?trait_pred, ?result, "insert_evaluation_cache");
1119 self.infcx.evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1122 /// For various reasons, it's possible for a subobligation
1123 /// to have a *lower* recursion_depth than the obligation used to create it.
1124 /// Projection sub-obligations may be returned from the projection cache,
1125 /// which results in obligations with an 'old' `recursion_depth`.
1126 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1127 /// subobligations without taking in a 'parent' depth, causing the
1128 /// generated subobligations to have a `recursion_depth` of `0`.
1130 /// To ensure that obligation_depth never decreases, we force all subobligations
1131 /// to have at least the depth of the original obligation.
1132 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1137 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1140 fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
1143 error_obligation: &Obligation<'tcx, T>,
1144 ) -> Result<(), OverflowError> {
1145 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1146 match self.query_mode {
1147 TraitQueryMode::Standard => {
1148 if self.infcx.is_tainted_by_errors() {
1149 return Err(OverflowError::Error(
1150 ErrorGuaranteed::unchecked_claim_error_was_emitted(),
1153 self.infcx.report_overflow_error(error_obligation, true);
1155 TraitQueryMode::Canonical => {
1156 return Err(OverflowError::Canonical);
1163 /// Checks that the recursion limit has not been exceeded.
1165 /// The weird return type of this function allows it to be used with the `try` (`?`)
1166 /// operator within certain functions.
1168 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1170 obligation: &Obligation<'tcx, T>,
1171 error_obligation: &Obligation<'tcx, V>,
1172 ) -> Result<(), OverflowError> {
1173 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1176 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1178 OP: FnOnce(&mut Self) -> R,
1180 let (result, dep_node) =
1181 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1182 self.tcx().dep_graph.read_index(dep_node);
1186 /// filter_impls filters constant trait obligations and candidates that have a positive impl
1187 /// for a negative goal and a negative impl for a positive goal
1188 #[instrument(level = "debug", skip(self))]
1191 candidates: Vec<SelectionCandidate<'tcx>>,
1192 obligation: &TraitObligation<'tcx>,
1193 ) -> Vec<SelectionCandidate<'tcx>> {
1194 let tcx = self.tcx();
1195 let mut result = Vec::with_capacity(candidates.len());
1197 for candidate in candidates {
1198 // Respect const trait obligations
1199 if obligation.is_const() {
1202 ImplCandidate(def_id) if tcx.constness(def_id) == hir::Constness::Const => {}
1204 ParamCandidate(trait_pred) if trait_pred.is_const_if_const() => {}
1206 AutoImplCandidate(..) => {}
1207 // generator, this will raise error in other places
1208 // or ignore error with const_async_blocks feature
1209 GeneratorCandidate => {}
1210 // FnDef where the function is const
1211 FnPointerCandidate { is_const: true } => {}
1212 ConstDestructCandidate(_) => {}
1214 // reject all other types of candidates
1220 if let ImplCandidate(def_id) = candidate {
1221 if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id)
1222 || obligation.polarity() == tcx.impl_polarity(def_id)
1224 result.push(candidate);
1227 result.push(candidate);
1234 /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1235 #[instrument(level = "debug", skip(self))]
1236 fn filter_reservation_impls(
1238 candidate: SelectionCandidate<'tcx>,
1239 obligation: &TraitObligation<'tcx>,
1240 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1241 let tcx = self.tcx();
1242 // Treat reservation impls as ambiguity.
1243 if let ImplCandidate(def_id) = candidate {
1244 if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
1245 if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1247 .get_attr(def_id, sym::rustc_reservation_impl)
1248 .and_then(|a| a.value_str());
1249 if let Some(value) = value {
1251 "filter_reservation_impls: \
1252 reservation impl ambiguity on {:?}",
1255 intercrate_ambiguity_clauses.insert(
1256 IntercrateAmbiguityCause::ReservationImpl {
1257 message: value.to_string(),
1268 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1269 debug!("is_knowable(intercrate={:?})", self.intercrate);
1271 if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative {
1275 let obligation = &stack.obligation;
1276 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1278 // Okay to skip binder because of the nature of the
1279 // trait-ref-is-knowable check, which does not care about
1281 let trait_ref = predicate.skip_binder().trait_ref;
1283 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1286 /// Returns `true` if the global caches can be used.
1287 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1288 // If there are any inference variables in the `ParamEnv`, then we
1289 // always use a cache local to this particular scope. Otherwise, we
1290 // switch to a global cache.
1291 if param_env.needs_infer() {
1295 // Avoid using the master cache during coherence and just rely
1296 // on the local cache. This effectively disables caching
1297 // during coherence. It is really just a simplification to
1298 // avoid us having to fear that coherence results "pollute"
1299 // the master cache. Since coherence executes pretty quickly,
1300 // it's not worth going to more trouble to increase the
1301 // hit-rate, I don't think.
1302 if self.intercrate {
1306 // Otherwise, we can use the global cache.
1310 fn check_candidate_cache(
1312 mut param_env: ty::ParamEnv<'tcx>,
1313 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1314 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1315 // Neither the global nor local cache is aware of intercrate
1316 // mode, so don't do any caching. In particular, we might
1317 // re-use the same `InferCtxt` with both an intercrate
1318 // and non-intercrate `SelectionContext`
1319 if self.intercrate {
1322 let tcx = self.tcx();
1323 let mut pred = cache_fresh_trait_pred.skip_binder();
1324 pred.remap_constness(&mut param_env);
1326 if self.can_use_global_caches(param_env) {
1327 if let Some(res) = tcx.selection_cache.get(&(param_env, pred), tcx) {
1331 self.infcx.selection_cache.get(&(param_env, pred), tcx)
1334 /// Determines whether can we safely cache the result
1335 /// of selecting an obligation. This is almost always `true`,
1336 /// except when dealing with certain `ParamCandidate`s.
1338 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1339 /// since it was usually produced directly from a `DefId`. However,
1340 /// certain cases (currently only librustdoc's blanket impl finder),
1341 /// a `ParamEnv` may be explicitly constructed with inference types.
1342 /// When this is the case, we do *not* want to cache the resulting selection
1343 /// candidate. This is due to the fact that it might not always be possible
1344 /// to equate the obligation's trait ref and the candidate's trait ref,
1345 /// if more constraints end up getting added to an inference variable.
1347 /// Because of this, we always want to re-run the full selection
1348 /// process for our obligation the next time we see it, since
1349 /// we might end up picking a different `SelectionCandidate` (or none at all).
1350 fn can_cache_candidate(
1352 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1354 // Neither the global nor local cache is aware of intercrate
1355 // mode, so don't do any caching. In particular, we might
1356 // re-use the same `InferCtxt` with both an intercrate
1357 // and non-intercrate `SelectionContext`
1358 if self.intercrate {
1362 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1367 #[instrument(skip(self, param_env, cache_fresh_trait_pred, dep_node), level = "debug")]
1368 fn insert_candidate_cache(
1370 mut param_env: ty::ParamEnv<'tcx>,
1371 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1372 dep_node: DepNodeIndex,
1373 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1375 let tcx = self.tcx();
1376 let mut pred = cache_fresh_trait_pred.skip_binder();
1378 pred.remap_constness(&mut param_env);
1380 if !self.can_cache_candidate(&candidate) {
1381 debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1385 if self.can_use_global_caches(param_env) {
1386 if let Err(Overflow(OverflowError::Canonical)) = candidate {
1387 // Don't cache overflow globally; we only produce this in certain modes.
1388 } else if !pred.needs_infer() {
1389 if !candidate.needs_infer() {
1390 debug!(?pred, ?candidate, "insert_candidate_cache global");
1391 // This may overwrite the cache with the same value.
1392 tcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1398 debug!(?pred, ?candidate, "insert_candidate_cache local");
1399 self.infcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1402 /// Matches a predicate against the bounds of its self type.
1404 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1405 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1406 /// `Baz` bound. We return indexes into the list returned by
1407 /// `tcx.item_bounds` for any applicable bounds.
1408 #[instrument(level = "debug", skip(self))]
1409 fn match_projection_obligation_against_definition_bounds(
1411 obligation: &TraitObligation<'tcx>,
1412 ) -> smallvec::SmallVec<[usize; 2]> {
1413 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1414 let placeholder_trait_predicate =
1415 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1416 debug!(?placeholder_trait_predicate);
1418 let tcx = self.infcx.tcx;
1419 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1420 ty::Projection(ref data) => (data.item_def_id, data.substs),
1421 ty::Opaque(def_id, substs) => (def_id, substs),
1424 obligation.cause.span,
1425 "match_projection_obligation_against_definition_bounds() called \
1426 but self-ty is not a projection: {:?}",
1427 placeholder_trait_predicate.trait_ref.self_ty()
1431 let bounds = tcx.bound_item_bounds(def_id).subst(tcx, substs);
1433 // The bounds returned by `item_bounds` may contain duplicates after
1434 // normalization, so try to deduplicate when possible to avoid
1435 // unnecessary ambiguity.
1436 let mut distinct_normalized_bounds = FxHashSet::default();
1438 let matching_bounds = bounds
1441 .filter_map(|(idx, bound)| {
1442 let bound_predicate = bound.kind();
1443 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1444 let bound = bound_predicate.rebind(pred.trait_ref);
1445 if self.infcx.probe(|_| {
1446 match self.match_normalize_trait_ref(
1449 placeholder_trait_predicate.trait_ref,
1452 Ok(Some(normalized_trait))
1453 if distinct_normalized_bounds.insert(normalized_trait) =>
1467 debug!(?matching_bounds);
1471 /// Equates the trait in `obligation` with trait bound. If the two traits
1472 /// can be equated and the normalized trait bound doesn't contain inference
1473 /// variables or placeholders, the normalized bound is returned.
1474 fn match_normalize_trait_ref(
1476 obligation: &TraitObligation<'tcx>,
1477 trait_bound: ty::PolyTraitRef<'tcx>,
1478 placeholder_trait_ref: ty::TraitRef<'tcx>,
1479 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1480 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1481 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1482 // Avoid unnecessary normalization
1486 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1487 project::normalize_with_depth(
1489 obligation.param_env,
1490 obligation.cause.clone(),
1491 obligation.recursion_depth + 1,
1496 .at(&obligation.cause, obligation.param_env)
1497 .define_opaque_types(false)
1498 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1499 .map(|InferOk { obligations: _, value: () }| {
1500 // This method is called within a probe, so we can't have
1501 // inference variables and placeholders escape.
1502 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1511 fn where_clause_may_apply<'o>(
1513 stack: &TraitObligationStack<'o, 'tcx>,
1514 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1515 ) -> Result<EvaluationResult, OverflowError> {
1516 self.evaluation_probe(|this| {
1517 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1518 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1519 Err(()) => Ok(EvaluatedToErr),
1524 /// Return `Yes` if the obligation's predicate type applies to the env_predicate, and
1525 /// `No` if it does not. Return `Ambiguous` in the case that the projection type is a GAT,
1526 /// and applying this env_predicate constrains any of the obligation's GAT substitutions.
1528 /// This behavior is a somewhat of a hack to prevent over-constraining inference variables
1529 /// in cases like #91762.
1530 pub(super) fn match_projection_projections(
1532 obligation: &ProjectionTyObligation<'tcx>,
1533 env_predicate: PolyProjectionPredicate<'tcx>,
1534 potentially_unnormalized_candidates: bool,
1535 ) -> ProjectionMatchesProjection {
1536 let mut nested_obligations = Vec::new();
1537 let infer_predicate = self.infcx.replace_bound_vars_with_fresh_vars(
1538 obligation.cause.span,
1539 LateBoundRegionConversionTime::HigherRankedType,
1542 let infer_projection = if potentially_unnormalized_candidates {
1543 ensure_sufficient_stack(|| {
1544 project::normalize_with_depth_to(
1546 obligation.param_env,
1547 obligation.cause.clone(),
1548 obligation.recursion_depth + 1,
1549 infer_predicate.projection_ty,
1550 &mut nested_obligations,
1554 infer_predicate.projection_ty
1559 .at(&obligation.cause, obligation.param_env)
1560 .define_opaque_types(false)
1561 .sup(obligation.predicate, infer_projection)
1562 .map_or(false, |InferOk { obligations, value: () }| {
1563 self.evaluate_predicates_recursively(
1564 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1565 nested_obligations.into_iter().chain(obligations),
1567 .map_or(false, |res| res.may_apply())
1571 let generics = self.tcx().generics_of(obligation.predicate.item_def_id);
1572 // FIXME(generic-associated-types): Addresses aggressive inference in #92917.
1573 // If this type is a GAT, and of the GAT substs resolve to something new,
1574 // that means that we must have newly inferred something about the GAT.
1575 // We should give up in that case.
1576 if !generics.params.is_empty()
1577 && obligation.predicate.substs[generics.parent_count..]
1579 .any(|&p| p.has_infer_types_or_consts() && self.infcx.shallow_resolve(p) != p)
1581 ProjectionMatchesProjection::Ambiguous
1583 ProjectionMatchesProjection::Yes
1586 ProjectionMatchesProjection::No
1590 ///////////////////////////////////////////////////////////////////////////
1593 // Winnowing is the process of attempting to resolve ambiguity by
1594 // probing further. During the winnowing process, we unify all
1595 // type variables and then we also attempt to evaluate recursive
1596 // bounds to see if they are satisfied.
1598 /// Returns `true` if `victim` should be dropped in favor of
1599 /// `other`. Generally speaking we will drop duplicate
1600 /// candidates and prefer where-clause candidates.
1602 /// See the comment for "SelectionCandidate" for more details.
1603 fn candidate_should_be_dropped_in_favor_of(
1605 victim: &EvaluatedCandidate<'tcx>,
1606 other: &EvaluatedCandidate<'tcx>,
1609 if victim.candidate == other.candidate {
1613 // Check if a bound would previously have been removed when normalizing
1614 // the param_env so that it can be given the lowest priority. See
1615 // #50825 for the motivation for this.
1616 let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| {
1617 cand.is_global() && !cand.has_late_bound_regions()
1620 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1621 // `DiscriminantKindCandidate`, and `ConstDestructCandidate` to anything else.
1623 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1624 // lifetime of a variable.
1625 match (&other.candidate, &victim.candidate) {
1626 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1628 "default implementations shouldn't be recorded \
1629 when there are other valid candidates"
1635 BuiltinCandidate { has_nested: false }
1636 | DiscriminantKindCandidate
1638 | ConstDestructCandidate(_),
1643 BuiltinCandidate { has_nested: false }
1644 | DiscriminantKindCandidate
1646 | ConstDestructCandidate(_),
1649 (ParamCandidate(other), ParamCandidate(victim)) => {
1650 let same_except_bound_vars = other.skip_binder().trait_ref
1651 == victim.skip_binder().trait_ref
1652 && other.skip_binder().constness == victim.skip_binder().constness
1653 && other.skip_binder().polarity == victim.skip_binder().polarity
1654 && !other.skip_binder().trait_ref.has_escaping_bound_vars();
1655 if same_except_bound_vars {
1656 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1657 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1658 // or the current one if tied (they should both evaluate to the same answer). This is
1659 // probably best characterized as a "hack", since we might prefer to just do our
1660 // best to *not* create essentially duplicate candidates in the first place.
1661 other.bound_vars().len() <= victim.bound_vars().len()
1662 } else if other.skip_binder().trait_ref == victim.skip_binder().trait_ref
1663 && victim.skip_binder().constness == ty::BoundConstness::NotConst
1664 && other.skip_binder().polarity == victim.skip_binder().polarity
1666 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1673 // Drop otherwise equivalent non-const fn pointer candidates
1674 (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
1676 // Global bounds from the where clause should be ignored
1677 // here (see issue #50825). Otherwise, we have a where
1678 // clause so don't go around looking for impls.
1679 // Arbitrarily give param candidates priority
1680 // over projection and object candidates.
1682 ParamCandidate(ref cand),
1685 | GeneratorCandidate
1686 | FnPointerCandidate { .. }
1687 | BuiltinObjectCandidate
1688 | BuiltinUnsizeCandidate
1689 | TraitUpcastingUnsizeCandidate(_)
1690 | BuiltinCandidate { .. }
1691 | TraitAliasCandidate(..)
1692 | ObjectCandidate(_)
1693 | ProjectionCandidate(_),
1694 ) => !is_global(cand),
1695 (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1696 // Prefer these to a global where-clause bound
1697 // (see issue #50825).
1703 | GeneratorCandidate
1704 | FnPointerCandidate { .. }
1705 | BuiltinObjectCandidate
1706 | BuiltinUnsizeCandidate
1707 | TraitUpcastingUnsizeCandidate(_)
1708 | BuiltinCandidate { has_nested: true }
1709 | TraitAliasCandidate(..),
1710 ParamCandidate(ref cand),
1712 // Prefer these to a global where-clause bound
1713 // (see issue #50825).
1714 is_global(cand) && other.evaluation.must_apply_modulo_regions()
1717 (ProjectionCandidate(i), ProjectionCandidate(j))
1718 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1719 // Arbitrarily pick the lower numbered candidate for backwards
1720 // compatibility reasons. Don't let this affect inference.
1721 i < j && !needs_infer
1723 (ObjectCandidate(_), ProjectionCandidate(_))
1724 | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1725 bug!("Have both object and projection candidate")
1728 // Arbitrarily give projection and object candidates priority.
1730 ObjectCandidate(_) | ProjectionCandidate(_),
1733 | GeneratorCandidate
1734 | FnPointerCandidate { .. }
1735 | BuiltinObjectCandidate
1736 | BuiltinUnsizeCandidate
1737 | TraitUpcastingUnsizeCandidate(_)
1738 | BuiltinCandidate { .. }
1739 | TraitAliasCandidate(..),
1745 | GeneratorCandidate
1746 | FnPointerCandidate { .. }
1747 | BuiltinObjectCandidate
1748 | BuiltinUnsizeCandidate
1749 | TraitUpcastingUnsizeCandidate(_)
1750 | BuiltinCandidate { .. }
1751 | TraitAliasCandidate(..),
1752 ObjectCandidate(_) | ProjectionCandidate(_),
1755 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1756 // See if we can toss out `victim` based on specialization.
1757 // This requires us to know *for sure* that the `other` impl applies
1758 // i.e., `EvaluatedToOk`.
1760 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1761 // to me but is required for `std` to compile, so I didn't change it
1763 let tcx = self.tcx();
1764 if other.evaluation.must_apply_modulo_regions() {
1765 if tcx.specializes((other_def, victim_def)) {
1770 if other.evaluation.must_apply_considering_regions() {
1771 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1772 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1773 // Subtle: If the predicate we are evaluating has inference
1774 // variables, do *not* allow discarding candidates due to
1775 // marker trait impls.
1777 // Without this restriction, we could end up accidentally
1778 // constraining inference variables based on an arbitrarily
1779 // chosen trait impl.
1781 // Imagine we have the following code:
1784 // #[marker] trait MyTrait {}
1785 // impl MyTrait for u8 {}
1786 // impl MyTrait for bool {}
1789 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1791 // During selection, we will end up with one candidate for each
1792 // impl of `MyTrait`. If we were to discard one impl in favor
1793 // of the other, we would be left with one candidate, causing
1794 // us to "successfully" select the predicate, unifying
1795 // _#0t with (for example) `u8`.
1797 // However, we have no reason to believe that this unification
1798 // is correct - we've essentially just picked an arbitrary
1799 // *possibility* for _#0t, and required that this be the *only*
1802 // Eventually, we will either:
1803 // 1) Unify all inference variables in the predicate through
1804 // some other means (e.g. type-checking of a function). We will
1805 // then be in a position to drop marker trait candidates
1806 // without constraining inference variables (since there are
1807 // none left to constrain)
1808 // 2) Be left with some unconstrained inference variables. We
1809 // will then correctly report an inference error, since the
1810 // existence of multiple marker trait impls tells us nothing
1811 // about which one should actually apply.
1822 // Everything else is ambiguous
1826 | GeneratorCandidate
1827 | FnPointerCandidate { .. }
1828 | BuiltinObjectCandidate
1829 | BuiltinUnsizeCandidate
1830 | TraitUpcastingUnsizeCandidate(_)
1831 | BuiltinCandidate { has_nested: true }
1832 | TraitAliasCandidate(..),
1835 | GeneratorCandidate
1836 | FnPointerCandidate { .. }
1837 | BuiltinObjectCandidate
1838 | BuiltinUnsizeCandidate
1839 | TraitUpcastingUnsizeCandidate(_)
1840 | BuiltinCandidate { has_nested: true }
1841 | TraitAliasCandidate(..),
1846 fn sized_conditions(
1848 obligation: &TraitObligation<'tcx>,
1849 ) -> BuiltinImplConditions<'tcx> {
1850 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1852 // NOTE: binder moved to (*)
1853 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1855 match self_ty.kind() {
1856 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1867 | ty::GeneratorWitness(..)
1872 // safe for everything
1873 Where(ty::Binder::dummy(Vec::new()))
1876 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1878 ty::Tuple(tys) => Where(
1879 obligation.predicate.rebind(tys.last().map_or_else(Vec::new, |&last| vec![last])),
1882 ty::Adt(def, substs) => {
1883 let sized_crit = def.sized_constraint(self.tcx());
1884 // (*) binder moved here
1885 Where(obligation.predicate.rebind({
1889 .map(|ty| sized_crit.rebind(*ty).subst(self.tcx(), substs))
1894 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1895 ty::Infer(ty::TyVar(_)) => Ambiguous,
1899 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1900 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1905 fn copy_clone_conditions(
1907 obligation: &TraitObligation<'tcx>,
1908 ) -> BuiltinImplConditions<'tcx> {
1909 // NOTE: binder moved to (*)
1910 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1912 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1914 match *self_ty.kind() {
1915 ty::Infer(ty::IntVar(_))
1916 | ty::Infer(ty::FloatVar(_))
1919 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1928 | ty::Ref(_, _, hir::Mutability::Not)
1929 | ty::Array(..) => {
1930 // Implementations provided in libcore
1938 | ty::GeneratorWitness(..)
1940 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1943 // (*) binder moved here
1944 Where(obligation.predicate.rebind(tys.iter().collect()))
1947 ty::Closure(_, substs) => {
1948 // (*) binder moved here
1949 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1950 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1951 // Not yet resolved.
1954 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1958 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1959 // Fallback to whatever user-defined impls exist in this case.
1963 ty::Infer(ty::TyVar(_)) => {
1964 // Unbound type variable. Might or might not have
1965 // applicable impls and so forth, depending on what
1966 // those type variables wind up being bound to.
1972 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1973 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1978 /// For default impls, we need to break apart a type into its
1979 /// "constituent types" -- meaning, the types that it contains.
1981 /// Here are some (simple) examples:
1983 /// ```ignore (illustrative)
1984 /// (i32, u32) -> [i32, u32]
1985 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1986 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1987 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1989 fn constituent_types_for_ty(
1991 t: ty::Binder<'tcx, Ty<'tcx>>,
1992 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1993 match *t.skip_binder().kind() {
2002 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2004 | ty::Char => ty::Binder::dummy(Vec::new()),
2010 | ty::Projection(..)
2012 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2013 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2016 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2017 t.rebind(vec![element_ty])
2020 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
2022 ty::Tuple(ref tys) => {
2023 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2024 t.rebind(tys.iter().collect())
2027 ty::Closure(_, ref substs) => {
2028 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
2032 ty::Generator(_, ref substs, _) => {
2033 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
2034 let witness = substs.as_generator().witness();
2035 t.rebind([ty].into_iter().chain(iter::once(witness)).collect())
2038 ty::GeneratorWitness(types) => {
2039 debug_assert!(!types.has_escaping_bound_vars());
2040 types.map_bound(|types| types.to_vec())
2043 // For `PhantomData<T>`, we pass `T`.
2044 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
2046 ty::Adt(def, substs) => {
2047 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
2050 ty::Opaque(def_id, substs) => {
2051 // We can resolve the `impl Trait` to its concrete type,
2052 // which enforces a DAG between the functions requiring
2053 // the auto trait bounds in question.
2054 t.rebind(vec![self.tcx().bound_type_of(def_id).subst(self.tcx(), substs)])
2059 fn collect_predicates_for_types(
2061 param_env: ty::ParamEnv<'tcx>,
2062 cause: ObligationCause<'tcx>,
2063 recursion_depth: usize,
2064 trait_def_id: DefId,
2065 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
2066 ) -> Vec<PredicateObligation<'tcx>> {
2067 // Because the types were potentially derived from
2068 // higher-ranked obligations they may reference late-bound
2069 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2070 // yield a type like `for<'a> &'a i32`. In general, we
2071 // maintain the invariant that we never manipulate bound
2072 // regions, so we have to process these bound regions somehow.
2074 // The strategy is to:
2076 // 1. Instantiate those regions to placeholder regions (e.g.,
2077 // `for<'a> &'a i32` becomes `&0 i32`.
2078 // 2. Produce something like `&'0 i32 : Copy`
2079 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2083 .skip_binder() // binder moved -\
2086 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(*ty); // <----/
2088 self.infcx.commit_unconditionally(|_| {
2089 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
2090 let Normalized { value: normalized_ty, mut obligations } =
2091 ensure_sufficient_stack(|| {
2092 project::normalize_with_depth(
2100 let placeholder_obligation = predicate_for_trait_def(
2109 obligations.push(placeholder_obligation);
2116 ///////////////////////////////////////////////////////////////////////////
2119 // Matching is a common path used for both evaluation and
2120 // confirmation. It basically unifies types that appear in impls
2121 // and traits. This does affect the surrounding environment;
2122 // therefore, when used during evaluation, match routines must be
2123 // run inside of a `probe()` so that their side-effects are
2129 obligation: &TraitObligation<'tcx>,
2130 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
2131 let impl_trait_ref = self.tcx().bound_impl_trait_ref(impl_def_id).unwrap();
2132 match self.match_impl(impl_def_id, impl_trait_ref, obligation) {
2133 Ok(substs) => substs,
2135 self.infcx.tcx.sess.delay_span_bug(
2136 obligation.cause.span,
2138 "Impl {:?} was matchable against {:?} but now is not",
2139 impl_def_id, obligation
2142 let value = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2143 let err = self.tcx().ty_error();
2144 let value = value.fold_with(&mut BottomUpFolder {
2150 Normalized { value, obligations: vec![] }
2155 #[tracing::instrument(level = "debug", skip(self))]
2159 impl_trait_ref: EarlyBinder<ty::TraitRef<'tcx>>,
2160 obligation: &TraitObligation<'tcx>,
2161 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2162 let placeholder_obligation =
2163 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
2164 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2166 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2168 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2170 debug!(?impl_trait_ref);
2172 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2173 ensure_sufficient_stack(|| {
2174 project::normalize_with_depth(
2176 obligation.param_env,
2177 obligation.cause.clone(),
2178 obligation.recursion_depth + 1,
2183 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2185 let cause = ObligationCause::new(
2186 obligation.cause.span,
2187 obligation.cause.body_id,
2188 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2191 let InferOk { obligations, .. } = self
2193 .at(&cause, obligation.param_env)
2194 .define_opaque_types(false)
2195 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2196 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2197 nested_obligations.extend(obligations);
2200 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2202 debug!("match_impl: reservation impls only apply in intercrate mode");
2206 debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2207 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2210 fn fast_reject_trait_refs(
2212 obligation: &TraitObligation<'tcx>,
2213 impl_trait_ref: &ty::TraitRef<'tcx>,
2215 // We can avoid creating type variables and doing the full
2216 // substitution if we find that any of the input types, when
2217 // simplified, do not match.
2218 let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsPlaceholder };
2219 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs)
2220 .any(|(obl, imp)| !drcx.generic_args_may_unify(obl, imp))
2223 /// Normalize `where_clause_trait_ref` and try to match it against
2224 /// `obligation`. If successful, return any predicates that
2225 /// result from the normalization.
2226 fn match_where_clause_trait_ref(
2228 obligation: &TraitObligation<'tcx>,
2229 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2230 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2231 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2234 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2235 /// obligation is satisfied.
2236 #[instrument(skip(self), level = "debug")]
2237 fn match_poly_trait_ref(
2239 obligation: &TraitObligation<'tcx>,
2240 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2241 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2243 .at(&obligation.cause, obligation.param_env)
2244 // We don't want predicates for opaque types to just match all other types,
2245 // if there is an obligation on the opaque type, then that obligation must be met
2246 // opaquely. Otherwise we'd match any obligation to the opaque type and then error
2248 .define_opaque_types(false)
2249 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2250 .map(|InferOk { obligations, .. }| obligations)
2254 ///////////////////////////////////////////////////////////////////////////
2257 fn match_fresh_trait_refs(
2259 previous: ty::PolyTraitPredicate<'tcx>,
2260 current: ty::PolyTraitPredicate<'tcx>,
2261 param_env: ty::ParamEnv<'tcx>,
2263 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2264 matcher.relate(previous, current).is_ok()
2269 previous_stack: TraitObligationStackList<'o, 'tcx>,
2270 obligation: &'o TraitObligation<'tcx>,
2271 ) -> TraitObligationStack<'o, 'tcx> {
2272 let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
2274 let dfn = previous_stack.cache.next_dfn();
2275 let depth = previous_stack.depth() + 1;
2276 TraitObligationStack {
2279 reached_depth: Cell::new(depth),
2280 previous: previous_stack,
2286 #[instrument(skip(self), level = "debug")]
2287 fn closure_trait_ref_unnormalized(
2289 obligation: &TraitObligation<'tcx>,
2290 substs: SubstsRef<'tcx>,
2291 ) -> ty::PolyTraitRef<'tcx> {
2292 let closure_sig = substs.as_closure().sig();
2294 debug!(?closure_sig);
2296 // (1) Feels icky to skip the binder here, but OTOH we know
2297 // that the self-type is an unboxed closure type and hence is
2298 // in fact unparameterized (or at least does not reference any
2299 // regions bound in the obligation). Still probably some
2300 // refactoring could make this nicer.
2301 closure_trait_ref_and_return_type(
2303 obligation.predicate.def_id(),
2304 obligation.predicate.skip_binder().self_ty(), // (1)
2306 util::TupleArgumentsFlag::No,
2308 .map_bound(|(trait_ref, _)| trait_ref)
2311 fn generator_trait_ref_unnormalized(
2313 obligation: &TraitObligation<'tcx>,
2314 substs: SubstsRef<'tcx>,
2315 ) -> ty::PolyTraitRef<'tcx> {
2316 let gen_sig = substs.as_generator().poly_sig();
2318 // (1) Feels icky to skip the binder here, but OTOH we know
2319 // that the self-type is an generator type and hence is
2320 // in fact unparameterized (or at least does not reference any
2321 // regions bound in the obligation). Still probably some
2322 // refactoring could make this nicer.
2324 super::util::generator_trait_ref_and_outputs(
2326 obligation.predicate.def_id(),
2327 obligation.predicate.skip_binder().self_ty(), // (1)
2330 .map_bound(|(trait_ref, ..)| trait_ref)
2333 /// Returns the obligations that are implied by instantiating an
2334 /// impl or trait. The obligations are substituted and fully
2335 /// normalized. This is used when confirming an impl or default
2337 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2338 fn impl_or_trait_obligations(
2340 cause: &ObligationCause<'tcx>,
2341 recursion_depth: usize,
2342 param_env: ty::ParamEnv<'tcx>,
2343 def_id: DefId, // of impl or trait
2344 substs: SubstsRef<'tcx>, // for impl or trait
2345 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2346 ) -> Vec<PredicateObligation<'tcx>> {
2347 let tcx = self.tcx();
2349 // To allow for one-pass evaluation of the nested obligation,
2350 // each predicate must be preceded by the obligations required
2352 // for example, if we have:
2353 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2354 // the impl will have the following predicates:
2355 // <V as Iterator>::Item = U,
2356 // U: Iterator, U: Sized,
2357 // V: Iterator, V: Sized,
2358 // <U as Iterator>::Item: Copy
2359 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2360 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2361 // `$1: Copy`, so we must ensure the obligations are emitted in
2363 let predicates = tcx.bound_predicates_of(def_id);
2364 debug!(?predicates);
2365 assert_eq!(predicates.0.parent, None);
2366 let mut obligations = Vec::with_capacity(predicates.0.predicates.len());
2367 for (predicate, span) in predicates.0.predicates {
2369 let cause = cause.clone().derived_cause(parent_trait_pred, |derived| {
2370 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
2372 impl_def_id: def_id,
2376 let predicate = normalize_with_depth_to(
2381 predicates.rebind(*predicate).subst(tcx, substs),
2384 obligations.push(Obligation { cause, recursion_depth, param_env, predicate });
2391 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2392 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2393 TraitObligationStackList::with(self)
2396 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2400 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2404 /// Indicates that attempting to evaluate this stack entry
2405 /// required accessing something from the stack at depth `reached_depth`.
2406 fn update_reached_depth(&self, reached_depth: usize) {
2408 self.depth >= reached_depth,
2409 "invoked `update_reached_depth` with something under this stack: \
2410 self.depth={} reached_depth={}",
2414 debug!(reached_depth, "update_reached_depth");
2416 while reached_depth < p.depth {
2417 debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
2418 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2419 p = p.previous.head.unwrap();
2424 /// The "provisional evaluation cache" is used to store intermediate cache results
2425 /// when solving auto traits. Auto traits are unusual in that they can support
2426 /// cycles. So, for example, a "proof tree" like this would be ok:
2428 /// - `Foo<T>: Send` :-
2429 /// - `Bar<T>: Send` :-
2430 /// - `Foo<T>: Send` -- cycle, but ok
2431 /// - `Baz<T>: Send`
2433 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2434 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2435 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2436 /// they are coinductive) it is considered ok.
2438 /// However, there is a complication: at the point where we have
2439 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2440 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2441 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2442 /// find out this assumption is wrong? Specifically, we could
2443 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2444 /// `Bar<T>: Send` didn't turn out to be true.
2446 /// In Issue #60010, we found a bug in rustc where it would cache
2447 /// these intermediate results. This was fixed in #60444 by disabling
2448 /// *all* caching for things involved in a cycle -- in our example,
2449 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2450 /// to large slowdowns.
2452 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2453 /// first requires proving `Bar<T>: Send` (which is true:
2455 /// - `Foo<T>: Send` :-
2456 /// - `Bar<T>: Send` :-
2457 /// - `Foo<T>: Send` -- cycle, but ok
2458 /// - `Baz<T>: Send`
2459 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2460 /// - `*const T: Send` -- but what if we later encounter an error?
2462 /// The *provisional evaluation cache* resolves this issue. It stores
2463 /// cache results that we've proven but which were involved in a cycle
2464 /// in some way. We track the minimal stack depth (i.e., the
2465 /// farthest from the top of the stack) that we are dependent on.
2466 /// The idea is that the cache results within are all valid -- so long as
2467 /// none of the nodes in between the current node and the node at that minimum
2468 /// depth result in an error (in which case the cached results are just thrown away).
2470 /// During evaluation, we consult this provisional cache and rely on
2471 /// it. Accessing a cached value is considered equivalent to accessing
2472 /// a result at `reached_depth`, so it marks the *current* solution as
2473 /// provisional as well. If an error is encountered, we toss out any
2474 /// provisional results added from the subtree that encountered the
2475 /// error. When we pop the node at `reached_depth` from the stack, we
2476 /// can commit all the things that remain in the provisional cache.
2477 struct ProvisionalEvaluationCache<'tcx> {
2478 /// next "depth first number" to issue -- just a counter
2481 /// Map from cache key to the provisionally evaluated thing.
2482 /// The cache entries contain the result but also the DFN in which they
2483 /// were added. The DFN is used to clear out values on failure.
2485 /// Imagine we have a stack like:
2487 /// - `A B C` and we add a cache for the result of C (DFN 2)
2488 /// - Then we have a stack `A B D` where `D` has DFN 3
2489 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2490 /// - `E` generates various cache entries which have cyclic dependencies on `B`
2491 /// - `A B D E F` and so forth
2492 /// - the DFN of `F` for example would be 5
2493 /// - then we determine that `E` is in error -- we will then clear
2494 /// all cache values whose DFN is >= 4 -- in this case, that
2495 /// means the cached value for `F`.
2496 map: RefCell<FxHashMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
2498 /// The stack of args that we assume to be true because a `WF(arg)` predicate
2499 /// is on the stack above (and because of wellformedness is coinductive).
2500 /// In an "ideal" world, this would share a stack with trait predicates in
2501 /// `TraitObligationStack`. However, trait predicates are *much* hotter than
2502 /// `WellFormed` predicates, and it's very likely that the additional matches
2503 /// will have a perf effect. The value here is the well-formed `GenericArg`
2504 /// and the depth of the trait predicate *above* that well-formed predicate.
2505 wf_args: RefCell<Vec<(ty::GenericArg<'tcx>, usize)>>,
2508 /// A cache value for the provisional cache: contains the depth-first
2509 /// number (DFN) and result.
2510 #[derive(Copy, Clone, Debug)]
2511 struct ProvisionalEvaluation {
2513 reached_depth: usize,
2514 result: EvaluationResult,
2517 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2518 fn default() -> Self {
2519 Self { dfn: Cell::new(0), map: Default::default(), wf_args: Default::default() }
2523 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2524 /// Get the next DFN in sequence (basically a counter).
2525 fn next_dfn(&self) -> usize {
2526 let result = self.dfn.get();
2527 self.dfn.set(result + 1);
2531 /// Check the provisional cache for any result for
2532 /// `fresh_trait_ref`. If there is a hit, then you must consider
2533 /// it an access to the stack slots at depth
2534 /// `reached_depth` (from the returned value).
2537 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2538 ) -> Option<ProvisionalEvaluation> {
2541 "get_provisional = {:#?}",
2542 self.map.borrow().get(&fresh_trait_pred),
2544 Some(*self.map.borrow().get(&fresh_trait_pred)?)
2547 /// Insert a provisional result into the cache. The result came
2548 /// from the node with the given DFN. It accessed a minimum depth
2549 /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
2550 /// and resulted in `result`.
2551 fn insert_provisional(
2554 reached_depth: usize,
2555 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2556 result: EvaluationResult,
2558 debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
2560 let mut map = self.map.borrow_mut();
2562 // Subtle: when we complete working on the DFN `from_dfn`, anything
2563 // that remains in the provisional cache must be dependent on some older
2564 // stack entry than `from_dfn`. We have to update their depth with our transitive
2565 // depth in that case or else it would be referring to some popped note.
2568 // A (reached depth 0)
2570 // B // depth 1 -- reached depth = 0
2571 // C // depth 2 -- reached depth = 1 (should be 0)
2574 // D (reached depth 1)
2575 // C (cache -- reached depth = 2)
2576 for (_k, v) in &mut *map {
2577 if v.from_dfn >= from_dfn {
2578 v.reached_depth = reached_depth.min(v.reached_depth);
2582 map.insert(fresh_trait_pred, ProvisionalEvaluation { from_dfn, reached_depth, result });
2585 /// Invoked when the node with dfn `dfn` does not get a successful
2586 /// result. This will clear out any provisional cache entries
2587 /// that were added since `dfn` was created. This is because the
2588 /// provisional entries are things which must assume that the
2589 /// things on the stack at the time of their creation succeeded --
2590 /// since the failing node is presently at the top of the stack,
2591 /// these provisional entries must either depend on it or some
2593 fn on_failure(&self, dfn: usize) {
2594 debug!(?dfn, "on_failure");
2595 self.map.borrow_mut().retain(|key, eval| {
2596 if !eval.from_dfn >= dfn {
2597 debug!("on_failure: removing {:?}", key);
2605 /// Invoked when the node at depth `depth` completed without
2606 /// depending on anything higher in the stack (if that completion
2607 /// was a failure, then `on_failure` should have been invoked
2610 /// Note that we may still have provisional cache items remaining
2611 /// in the cache when this is done. For example, if there is a
2614 /// * A depends on...
2615 /// * B depends on A
2616 /// * C depends on...
2617 /// * D depends on C
2620 /// Then as we complete the C node we will have a provisional cache
2621 /// with results for A, B, C, and D. This method would clear out
2622 /// the C and D results, but leave A and B provisional.
2624 /// This is determined based on the DFN: we remove any provisional
2625 /// results created since `dfn` started (e.g., in our example, dfn
2626 /// would be 2, representing the C node, and hence we would
2627 /// remove the result for D, which has DFN 3, but not the results for
2628 /// A and B, which have DFNs 0 and 1 respectively).
2630 /// Note that we *do not* attempt to cache these cycle participants
2631 /// in the evaluation cache. Doing so would require carefully computing
2632 /// the correct `DepNode` to store in the cache entry:
2633 /// cycle participants may implicitly depend on query results
2634 /// related to other participants in the cycle, due to our logic
2635 /// which examines the evaluation stack.
2637 /// We used to try to perform this caching,
2638 /// but it lead to multiple incremental compilation ICEs
2639 /// (see #92987 and #96319), and was very hard to understand.
2640 /// Fortunately, removing the caching didn't seem to
2641 /// have a performance impact in practice.
2642 fn on_completion(&self, dfn: usize) {
2643 debug!(?dfn, "on_completion");
2645 for (fresh_trait_pred, eval) in
2646 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2648 debug!(?fresh_trait_pred, ?eval, "on_completion");
2653 #[derive(Copy, Clone)]
2654 struct TraitObligationStackList<'o, 'tcx> {
2655 cache: &'o ProvisionalEvaluationCache<'tcx>,
2656 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2659 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2660 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2661 TraitObligationStackList { cache, head: None }
2664 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2665 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2668 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2672 fn depth(&self) -> usize {
2673 if let Some(head) = self.head { head.depth } else { 0 }
2677 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2678 type Item = &'o TraitObligationStack<'o, 'tcx>;
2680 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2687 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2688 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2689 write!(f, "TraitObligationStack({:?})", self.obligation)
2693 pub enum ProjectionMatchesProjection {