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};
16 use super::DerivedObligationCause;
17 use super::Normalized;
18 use super::Obligation;
19 use super::ObligationCauseCode;
21 use super::SelectionResult;
22 use super::TraitQueryMode;
23 use super::{ErrorReporting, Overflow, SelectionError};
24 use super::{ObligationCause, PredicateObligation, TraitObligation};
26 use crate::infer::{InferCtxt, InferOk, TypeFreshener};
27 use crate::traits::error_reporting::InferCtxtExt;
28 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
29 use rustc_data_structures::stack::ensure_sufficient_stack;
30 use rustc_data_structures::sync::Lrc;
31 use rustc_errors::ErrorReported;
33 use rustc_hir::def_id::DefId;
34 use rustc_infer::infer::LateBoundRegionConversionTime;
35 use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
36 use rustc_middle::mir::interpret::ErrorHandled;
37 use rustc_middle::thir::abstract_const::NotConstEvaluatable;
38 use rustc_middle::ty::fast_reject;
39 use rustc_middle::ty::print::with_no_trimmed_paths;
40 use rustc_middle::ty::relate::TypeRelation;
41 use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef};
42 use rustc_middle::ty::WithConstness;
43 use rustc_middle::ty::{self, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate};
44 use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable};
45 use rustc_span::symbol::sym;
47 use std::cell::{Cell, RefCell};
49 use std::fmt::{self, Display};
52 pub use rustc_middle::traits::select::*;
54 mod candidate_assembly;
57 #[derive(Clone, Debug)]
58 pub enum IntercrateAmbiguityCause {
59 DownstreamCrate { trait_desc: String, self_desc: Option<String> },
60 UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
61 ReservationImpl { message: String },
64 impl IntercrateAmbiguityCause {
65 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
66 /// See #23980 for details.
67 pub fn add_intercrate_ambiguity_hint(&self, err: &mut rustc_errors::DiagnosticBuilder<'_>) {
68 err.note(&self.intercrate_ambiguity_hint());
71 pub fn intercrate_ambiguity_hint(&self) -> String {
73 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } => {
74 let self_desc = if let Some(ty) = self_desc {
75 format!(" for type `{}`", ty)
79 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
81 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc } => {
82 let self_desc = if let Some(ty) = self_desc {
83 format!(" for type `{}`", ty)
88 "upstream crates may add a new impl of trait `{}`{} \
93 IntercrateAmbiguityCause::ReservationImpl { message } => message.clone(),
98 pub struct SelectionContext<'cx, 'tcx> {
99 infcx: &'cx InferCtxt<'cx, 'tcx>,
101 /// Freshener used specifically for entries on the obligation
102 /// stack. This ensures that all entries on the stack at one time
103 /// will have the same set of placeholder entries, which is
104 /// important for checking for trait bounds that recursively
105 /// require themselves.
106 freshener: TypeFreshener<'cx, 'tcx>,
108 /// If `true`, indicates that the evaluation should be conservative
109 /// and consider the possibility of types outside this crate.
110 /// This comes up primarily when resolving ambiguity. Imagine
111 /// there is some trait reference `$0: Bar` where `$0` is an
112 /// inference variable. If `intercrate` is true, then we can never
113 /// say for sure that this reference is not implemented, even if
114 /// there are *no impls at all for `Bar`*, because `$0` could be
115 /// bound to some type that in a downstream crate that implements
116 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
117 /// though, we set this to false, because we are only interested
118 /// in types that the user could actually have written --- in
119 /// other words, we consider `$0: Bar` to be unimplemented if
120 /// there is no type that the user could *actually name* that
121 /// would satisfy it. This avoids crippling inference, basically.
124 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
126 /// Controls whether or not to filter out negative impls when selecting.
127 /// This is used in librustdoc to distinguish between the lack of an impl
128 /// and a negative impl
129 allow_negative_impls: bool,
131 /// Are we in a const context that needs `~const` bounds to be const?
132 is_in_const_context: bool,
134 /// The mode that trait queries run in, which informs our error handling
135 /// policy. In essence, canonicalized queries need their errors propagated
136 /// rather than immediately reported because we do not have accurate spans.
137 query_mode: TraitQueryMode,
140 // A stack that walks back up the stack frame.
141 struct TraitObligationStack<'prev, 'tcx> {
142 obligation: &'prev TraitObligation<'tcx>,
144 /// The trait ref from `obligation` but "freshened" with the
145 /// selection-context's freshener. Used to check for recursion.
146 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
148 /// Starts out equal to `depth` -- if, during evaluation, we
149 /// encounter a cycle, then we will set this flag to the minimum
150 /// depth of that cycle for all participants in the cycle. These
151 /// participants will then forego caching their results. This is
152 /// not the most efficient solution, but it addresses #60010. The
153 /// problem we are trying to prevent:
155 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
156 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
157 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
159 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
160 /// is `EvaluatedToOk`; this is because they were only considered
161 /// ok on the premise that if `A: AutoTrait` held, but we indeed
162 /// encountered a problem (later on) with `A: AutoTrait. So we
163 /// currently set a flag on the stack node for `B: AutoTrait` (as
164 /// well as the second instance of `A: AutoTrait`) to suppress
167 /// This is a simple, targeted fix. A more-performant fix requires
168 /// deeper changes, but would permit more caching: we could
169 /// basically defer caching until we have fully evaluated the
170 /// tree, and then cache the entire tree at once. In any case, the
171 /// performance impact here shouldn't be so horrible: every time
172 /// this is hit, we do cache at least one trait, so we only
173 /// evaluate each member of a cycle up to N times, where N is the
174 /// length of the cycle. This means the performance impact is
175 /// bounded and we shouldn't have any terrible worst-cases.
176 reached_depth: Cell<usize>,
178 previous: TraitObligationStackList<'prev, 'tcx>,
180 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
183 /// The depth-first number of this node in the search graph -- a
184 /// pre-order index. Basically, a freshly incremented counter.
188 struct SelectionCandidateSet<'tcx> {
189 // A list of candidates that definitely apply to the current
190 // obligation (meaning: types unify).
191 vec: Vec<SelectionCandidate<'tcx>>,
193 // If `true`, then there were candidates that might or might
194 // not have applied, but we couldn't tell. This occurs when some
195 // of the input types are type variables, in which case there are
196 // various "builtin" rules that might or might not trigger.
200 #[derive(PartialEq, Eq, Debug, Clone)]
201 struct EvaluatedCandidate<'tcx> {
202 candidate: SelectionCandidate<'tcx>,
203 evaluation: EvaluationResult,
206 /// 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 allow_negative_impls: false,
225 is_in_const_context: false,
226 query_mode: TraitQueryMode::Standard,
230 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
233 freshener: infcx.freshener_keep_static(),
235 intercrate_ambiguity_causes: None,
236 allow_negative_impls: false,
237 is_in_const_context: false,
238 query_mode: TraitQueryMode::Standard,
242 pub fn with_negative(
243 infcx: &'cx InferCtxt<'cx, 'tcx>,
244 allow_negative_impls: bool,
245 ) -> SelectionContext<'cx, 'tcx> {
246 debug!(?allow_negative_impls, "with_negative");
249 freshener: infcx.freshener_keep_static(),
251 intercrate_ambiguity_causes: None,
252 allow_negative_impls,
253 is_in_const_context: false,
254 query_mode: TraitQueryMode::Standard,
258 pub fn with_query_mode(
259 infcx: &'cx InferCtxt<'cx, 'tcx>,
260 query_mode: TraitQueryMode,
261 ) -> SelectionContext<'cx, 'tcx> {
262 debug!(?query_mode, "with_query_mode");
265 freshener: infcx.freshener_keep_static(),
267 intercrate_ambiguity_causes: None,
268 allow_negative_impls: false,
269 is_in_const_context: false,
274 pub fn with_constness(
275 infcx: &'cx InferCtxt<'cx, 'tcx>,
276 constness: hir::Constness,
277 ) -> SelectionContext<'cx, 'tcx> {
280 freshener: infcx.freshener_keep_static(),
282 intercrate_ambiguity_causes: None,
283 allow_negative_impls: false,
284 is_in_const_context: matches!(constness, hir::Constness::Const),
285 query_mode: TraitQueryMode::Standard,
289 /// Enables tracking of intercrate ambiguity causes. These are
290 /// used in coherence to give improved diagnostics. We don't do
291 /// this until we detect a coherence error because it can lead to
292 /// false overflow results (#47139) and because it costs
293 /// computation time.
294 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
295 assert!(self.intercrate);
296 assert!(self.intercrate_ambiguity_causes.is_none());
297 self.intercrate_ambiguity_causes = Some(vec![]);
298 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
301 /// Gets the intercrate ambiguity causes collected since tracking
302 /// was enabled and disables tracking at the same time. If
303 /// tracking is not enabled, just returns an empty vector.
304 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
305 assert!(self.intercrate);
306 self.intercrate_ambiguity_causes.take().unwrap_or_default()
309 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
313 pub fn tcx(&self) -> TyCtxt<'tcx> {
317 pub fn is_intercrate(&self) -> bool {
321 /// Returns `true` if the trait predicate is considerd `const` to this selection context.
322 pub fn is_trait_predicate_const(&self, pred: ty::TraitPredicate<'_>) -> bool {
323 match pred.constness {
324 ty::BoundConstness::ConstIfConst if self.is_in_const_context => true,
329 /// Returns `true` if the predicate is considered `const` to
330 /// this selection context.
331 pub fn is_predicate_const(&self, pred: ty::Predicate<'_>) -> bool {
332 match pred.kind().skip_binder() {
333 ty::PredicateKind::Trait(pred) => self.is_trait_predicate_const(pred),
338 ///////////////////////////////////////////////////////////////////////////
341 // The selection phase tries to identify *how* an obligation will
342 // be resolved. For example, it will identify which impl or
343 // parameter bound is to be used. The process can be inconclusive
344 // if the self type in the obligation is not fully inferred. Selection
345 // can result in an error in one of two ways:
347 // 1. If no applicable impl or parameter bound can be found.
348 // 2. If the output type parameters in the obligation do not match
349 // those specified by the impl/bound. For example, if the obligation
350 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
351 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
353 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
354 /// type environment by performing unification.
355 #[instrument(level = "debug", skip(self))]
358 obligation: &TraitObligation<'tcx>,
359 ) -> SelectionResult<'tcx, Selection<'tcx>> {
360 let candidate = match self.select_from_obligation(obligation) {
361 Err(SelectionError::Overflow) => {
362 // In standard mode, overflow must have been caught and reported
364 assert!(self.query_mode == TraitQueryMode::Canonical);
365 return Err(SelectionError::Overflow);
367 Err(SelectionError::Ambiguous(_)) => {
376 Ok(Some(candidate)) => candidate,
379 match self.confirm_candidate(obligation, candidate) {
380 Err(SelectionError::Overflow) => {
381 assert!(self.query_mode == TraitQueryMode::Canonical);
382 Err(SelectionError::Overflow)
392 crate fn select_from_obligation(
394 obligation: &TraitObligation<'tcx>,
395 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
396 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
398 let pec = &ProvisionalEvaluationCache::default();
399 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
401 self.candidate_from_obligation(&stack)
404 ///////////////////////////////////////////////////////////////////////////
407 // Tests whether an obligation can be selected or whether an impl
408 // can be applied to particular types. It skips the "confirmation"
409 // step and hence completely ignores output type parameters.
411 // The result is "true" if the obligation *may* hold and "false" if
412 // we can be sure it does not.
414 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
415 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
416 debug!(?obligation, "predicate_may_hold_fatal");
418 // This fatal query is a stopgap that should only be used in standard mode,
419 // where we do not expect overflow to be propagated.
420 assert!(self.query_mode == TraitQueryMode::Standard);
422 self.evaluate_root_obligation(obligation)
423 .expect("Overflow should be caught earlier in standard query mode")
427 /// Evaluates whether the obligation `obligation` can be satisfied
428 /// and returns an `EvaluationResult`. This is meant for the
430 pub fn evaluate_root_obligation(
432 obligation: &PredicateObligation<'tcx>,
433 ) -> Result<EvaluationResult, OverflowError> {
434 self.evaluation_probe(|this| {
435 this.evaluate_predicate_recursively(
436 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
444 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
445 ) -> Result<EvaluationResult, OverflowError> {
446 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
447 let result = op(self)?;
449 match self.infcx.leak_check(true, snapshot) {
451 Err(_) => return Ok(EvaluatedToErr),
454 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
456 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
461 /// Evaluates the predicates in `predicates` recursively. Note that
462 /// this applies projections in the predicates, and therefore
463 /// is run within an inference probe.
464 #[instrument(skip(self, stack), level = "debug")]
465 fn evaluate_predicates_recursively<'o, I>(
467 stack: TraitObligationStackList<'o, 'tcx>,
469 ) -> Result<EvaluationResult, OverflowError>
471 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
473 let mut result = EvaluatedToOk;
474 for obligation in predicates {
475 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
476 if let EvaluatedToErr = eval {
477 // fast-path - EvaluatedToErr is the top of the lattice,
478 // so we don't need to look on the other predicates.
479 return Ok(EvaluatedToErr);
481 result = cmp::max(result, eval);
489 skip(self, previous_stack),
490 fields(previous_stack = ?previous_stack.head())
492 fn evaluate_predicate_recursively<'o>(
494 previous_stack: TraitObligationStackList<'o, 'tcx>,
495 obligation: PredicateObligation<'tcx>,
496 ) -> Result<EvaluationResult, OverflowError> {
497 // `previous_stack` stores a `TraitObligation`, while `obligation` is
498 // a `PredicateObligation`. These are distinct types, so we can't
499 // use any `Option` combinator method that would force them to be
501 match previous_stack.head() {
502 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
503 None => self.check_recursion_limit(&obligation, &obligation)?,
506 let result = ensure_sufficient_stack(|| {
507 let bound_predicate = obligation.predicate.kind();
508 match bound_predicate.skip_binder() {
509 ty::PredicateKind::Trait(t) => {
510 let t = bound_predicate.rebind(t);
511 debug_assert!(!t.has_escaping_bound_vars());
512 let obligation = obligation.with(t);
513 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
516 ty::PredicateKind::Subtype(p) => {
517 let p = bound_predicate.rebind(p);
518 // Does this code ever run?
519 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
520 Some(Ok(InferOk { mut obligations, .. })) => {
521 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
522 self.evaluate_predicates_recursively(
524 obligations.into_iter(),
527 Some(Err(_)) => Ok(EvaluatedToErr),
528 None => Ok(EvaluatedToAmbig),
532 ty::PredicateKind::Coerce(p) => {
533 let p = bound_predicate.rebind(p);
534 // Does this code ever run?
535 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
536 Some(Ok(InferOk { mut obligations, .. })) => {
537 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
538 self.evaluate_predicates_recursively(
540 obligations.into_iter(),
543 Some(Err(_)) => Ok(EvaluatedToErr),
544 None => Ok(EvaluatedToAmbig),
548 ty::PredicateKind::WellFormed(arg) => match wf::obligations(
550 obligation.param_env,
551 obligation.cause.body_id,
552 obligation.recursion_depth + 1,
554 obligation.cause.span,
556 Some(mut obligations) => {
557 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
558 self.evaluate_predicates_recursively(previous_stack, obligations)
560 None => Ok(EvaluatedToAmbig),
563 ty::PredicateKind::TypeOutlives(pred) => {
564 if pred.0.is_known_global() {
567 Ok(EvaluatedToOkModuloRegions)
571 ty::PredicateKind::RegionOutlives(..) => {
572 // We do not consider region relationships when evaluating trait matches.
573 Ok(EvaluatedToOkModuloRegions)
576 ty::PredicateKind::ObjectSafe(trait_def_id) => {
577 if self.tcx().is_object_safe(trait_def_id) {
584 ty::PredicateKind::Projection(data) => {
585 let data = bound_predicate.rebind(data);
586 let project_obligation = obligation.with(data);
587 match project::poly_project_and_unify_type(self, &project_obligation) {
588 Ok(Ok(Some(mut subobligations))) => {
589 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
590 self.evaluate_predicates_recursively(previous_stack, subobligations)
592 Ok(Ok(None)) => Ok(EvaluatedToAmbig),
593 Ok(Err(project::InProgress)) => Ok(EvaluatedToRecur),
594 Err(_) => Ok(EvaluatedToErr),
598 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
599 match self.infcx.closure_kind(closure_substs) {
600 Some(closure_kind) => {
601 if closure_kind.extends(kind) {
607 None => Ok(EvaluatedToAmbig),
611 ty::PredicateKind::ConstEvaluatable(uv) => {
612 match const_evaluatable::is_const_evaluatable(
615 obligation.param_env,
616 obligation.cause.span,
618 Ok(()) => Ok(EvaluatedToOk),
619 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
620 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
621 Err(_) => Ok(EvaluatedToErr),
625 ty::PredicateKind::ConstEquate(c1, c2) => {
626 debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
628 if self.tcx().features().generic_const_exprs {
629 // FIXME: we probably should only try to unify abstract constants
630 // if the constants depend on generic parameters.
632 // Let's just see where this breaks :shrug:
633 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
636 if self.infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
637 return Ok(EvaluatedToOk);
642 let evaluate = |c: &'tcx ty::Const<'tcx>| {
643 if let ty::ConstKind::Unevaluated(unevaluated) = c.val {
646 obligation.param_env,
648 Some(obligation.cause.span),
650 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty))
656 match (evaluate(c1), evaluate(c2)) {
657 (Ok(c1), Ok(c2)) => {
660 .at(&obligation.cause, obligation.param_env)
663 Ok(_) => Ok(EvaluatedToOk),
664 Err(_) => Ok(EvaluatedToErr),
667 (Err(ErrorHandled::Reported(ErrorReported)), _)
668 | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
669 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
671 obligation.cause.span(self.tcx()),
672 "ConstEquate: const_eval_resolve returned an unexpected error"
675 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
676 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
679 // Two different constants using generic parameters ~> error.
685 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
686 bug!("TypeWellFormedFromEnv is only used for chalk")
691 debug!("finished: {:?} from {:?}", result, obligation);
696 #[instrument(skip(self, previous_stack), level = "debug")]
697 fn evaluate_trait_predicate_recursively<'o>(
699 previous_stack: TraitObligationStackList<'o, 'tcx>,
700 mut obligation: TraitObligation<'tcx>,
701 ) -> Result<EvaluationResult, OverflowError> {
703 && obligation.is_global(self.tcx())
708 .all(|bound| bound.definitely_needs_subst(self.tcx()))
710 // If a param env has no global bounds, global obligations do not
711 // depend on its particular value in order to work, so we can clear
712 // out the param env and get better caching.
714 obligation.param_env = obligation.param_env.without_caller_bounds();
717 let stack = self.push_stack(previous_stack, &obligation);
718 let fresh_trait_ref = stack.fresh_trait_ref;
720 debug!(?fresh_trait_ref);
722 if let Some(result) = self.check_evaluation_cache(
723 obligation.param_env,
725 obligation.polarity(),
727 debug!(?result, "CACHE HIT");
731 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
732 debug!(?result, "PROVISIONAL CACHE HIT");
733 stack.update_reached_depth(result.reached_depth);
734 return Ok(result.result);
737 // Check if this is a match for something already on the
738 // stack. If so, we don't want to insert the result into the
739 // main cache (it is cycle dependent) nor the provisional
740 // cache (which is meant for things that have completed but
741 // for a "backedge" -- this result *is* the backedge).
742 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
743 return Ok(cycle_result);
746 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
747 let result = result?;
749 if !result.must_apply_modulo_regions() {
750 stack.cache().on_failure(stack.dfn);
753 let reached_depth = stack.reached_depth.get();
754 if reached_depth >= stack.depth {
755 debug!(?result, "CACHE MISS");
756 self.insert_evaluation_cache(
757 obligation.param_env,
759 obligation.polarity(),
764 stack.cache().on_completion(stack.dfn, |fresh_trait_ref, provisional_result| {
765 self.insert_evaluation_cache(
766 obligation.param_env,
768 obligation.polarity(),
770 provisional_result.max(result),
774 debug!(?result, "PROVISIONAL");
776 "caching provisionally because {:?} \
777 is a cycle participant (at depth {}, reached depth {})",
778 fresh_trait_ref, stack.depth, reached_depth,
781 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
787 /// If there is any previous entry on the stack that precisely
788 /// matches this obligation, then we can assume that the
789 /// obligation is satisfied for now (still all other conditions
790 /// must be met of course). One obvious case this comes up is
791 /// marker traits like `Send`. Think of a linked list:
793 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
795 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
796 /// `Option<Box<List<T>>>` is `Send`, and in turn
797 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
800 /// Note that we do this comparison using the `fresh_trait_ref`
801 /// fields. Because these have all been freshened using
802 /// `self.freshener`, we can be sure that (a) this will not
803 /// affect the inferencer state and (b) that if we see two
804 /// fresh regions with the same index, they refer to the same
805 /// unbound type variable.
806 fn check_evaluation_cycle(
808 stack: &TraitObligationStack<'_, 'tcx>,
809 ) -> Option<EvaluationResult> {
810 if let Some(cycle_depth) = stack
812 .skip(1) // Skip top-most frame.
814 stack.obligation.param_env == prev.obligation.param_env
815 && stack.fresh_trait_ref == prev.fresh_trait_ref
817 .map(|stack| stack.depth)
819 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
821 // If we have a stack like `A B C D E A`, where the top of
822 // the stack is the final `A`, then this will iterate over
823 // `A, E, D, C, B` -- i.e., all the participants apart
824 // from the cycle head. We mark them as participating in a
825 // cycle. This suppresses caching for those nodes. See
826 // `in_cycle` field for more details.
827 stack.update_reached_depth(cycle_depth);
829 // Subtle: when checking for a coinductive cycle, we do
830 // not compare using the "freshened trait refs" (which
831 // have erased regions) but rather the fully explicit
832 // trait refs. This is important because it's only a cycle
833 // if the regions match exactly.
834 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
835 let tcx = self.tcx();
836 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
837 if self.coinductive_match(cycle) {
838 debug!("evaluate_stack --> recursive, coinductive");
841 debug!("evaluate_stack --> recursive, inductive");
842 Some(EvaluatedToRecur)
849 fn evaluate_stack<'o>(
851 stack: &TraitObligationStack<'o, 'tcx>,
852 ) -> Result<EvaluationResult, OverflowError> {
853 // In intercrate mode, whenever any of the generics are unbound,
854 // there can always be an impl. Even if there are no impls in
855 // this crate, perhaps the type would be unified with
856 // something from another crate that does provide an impl.
858 // In intra mode, we must still be conservative. The reason is
859 // that we want to avoid cycles. Imagine an impl like:
861 // impl<T:Eq> Eq for Vec<T>
863 // and a trait reference like `$0 : Eq` where `$0` is an
864 // unbound variable. When we evaluate this trait-reference, we
865 // will unify `$0` with `Vec<$1>` (for some fresh variable
866 // `$1`), on the condition that `$1 : Eq`. We will then wind
867 // up with many candidates (since that are other `Eq` impls
868 // that apply) and try to winnow things down. This results in
869 // a recursive evaluation that `$1 : Eq` -- as you can
870 // imagine, this is just where we started. To avoid that, we
871 // check for unbound variables and return an ambiguous (hence possible)
872 // match if we've seen this trait before.
874 // This suffices to allow chains like `FnMut` implemented in
875 // terms of `Fn` etc, but we could probably make this more
877 let unbound_input_types =
878 stack.fresh_trait_ref.value.skip_binder().substs.types().any(|ty| ty.is_fresh());
880 if stack.obligation.polarity() != ty::ImplPolarity::Negative {
881 // This check was an imperfect workaround for a bug in the old
882 // intercrate mode; it should be removed when that goes away.
883 if unbound_input_types && self.intercrate {
884 debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
885 // Heuristics: show the diagnostics when there are no candidates in crate.
886 if self.intercrate_ambiguity_causes.is_some() {
887 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
888 if let Ok(candidate_set) = self.assemble_candidates(stack) {
889 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
890 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
891 let self_ty = trait_ref.self_ty();
892 let cause = with_no_trimmed_paths(|| {
893 IntercrateAmbiguityCause::DownstreamCrate {
894 trait_desc: trait_ref.print_only_trait_path().to_string(),
895 self_desc: if self_ty.has_concrete_skeleton() {
896 Some(self_ty.to_string())
903 debug!(?cause, "evaluate_stack: pushing cause");
904 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
908 return Ok(EvaluatedToAmbig);
912 if unbound_input_types
913 && stack.iter().skip(1).any(|prev| {
914 stack.obligation.param_env == prev.obligation.param_env
915 && self.match_fresh_trait_refs(
916 stack.fresh_trait_ref,
917 prev.fresh_trait_ref,
918 prev.obligation.param_env,
922 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
923 return Ok(EvaluatedToUnknown);
926 match self.candidate_from_obligation(stack) {
927 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
928 Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig),
929 Ok(None) => Ok(EvaluatedToAmbig),
930 Err(Overflow) => Err(OverflowError::Canonical),
931 Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
932 Err(..) => Ok(EvaluatedToErr),
936 /// For defaulted traits, we use a co-inductive strategy to solve, so
937 /// that recursion is ok. This routine returns `true` if the top of the
938 /// stack (`cycle[0]`):
940 /// - is a defaulted trait,
941 /// - it also appears in the backtrace at some position `X`,
942 /// - all the predicates at positions `X..` between `X` and the top are
943 /// also defaulted traits.
944 pub fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
946 I: Iterator<Item = ty::Predicate<'tcx>>,
948 cycle.all(|predicate| self.coinductive_predicate(predicate))
951 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
952 let result = match predicate.kind().skip_binder() {
953 ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
956 debug!(?predicate, ?result, "coinductive_predicate");
960 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
961 /// obligations are met. Returns whether `candidate` remains viable after this further
966 fields(depth = stack.obligation.recursion_depth)
968 fn evaluate_candidate<'o>(
970 stack: &TraitObligationStack<'o, 'tcx>,
971 candidate: &SelectionCandidate<'tcx>,
972 ) -> Result<EvaluationResult, OverflowError> {
973 let mut result = self.evaluation_probe(|this| {
974 let candidate = (*candidate).clone();
975 match this.confirm_candidate(stack.obligation, candidate) {
978 this.evaluate_predicates_recursively(
980 selection.nested_obligations().into_iter(),
983 Err(..) => Ok(EvaluatedToErr),
987 // If we erased any lifetimes, then we want to use
988 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
989 // as your final result. The result will be cached using
990 // the freshened trait predicate as a key, so we need
991 // our result to be correct by *any* choice of original lifetimes,
992 // not just the lifetime choice for this particular (non-erased)
995 if stack.fresh_trait_ref.has_erased_regions() {
996 result = result.max(EvaluatedToOkModuloRegions);
1003 fn check_evaluation_cache(
1005 param_env: ty::ParamEnv<'tcx>,
1006 trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
1007 polarity: ty::ImplPolarity,
1008 ) -> Option<EvaluationResult> {
1009 // Neither the global nor local cache is aware of intercrate
1010 // mode, so don't do any caching. In particular, we might
1011 // re-use the same `InferCtxt` with both an intercrate
1012 // and non-intercrate `SelectionContext`
1013 if self.intercrate {
1017 let tcx = self.tcx();
1018 if self.can_use_global_caches(param_env) {
1019 if let Some(res) = tcx.evaluation_cache.get(&(param_env.and(trait_ref), polarity), tcx)
1024 self.infcx.evaluation_cache.get(&(param_env.and(trait_ref), polarity), tcx)
1027 fn insert_evaluation_cache(
1029 param_env: ty::ParamEnv<'tcx>,
1030 trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
1031 polarity: ty::ImplPolarity,
1032 dep_node: DepNodeIndex,
1033 result: EvaluationResult,
1035 // Avoid caching results that depend on more than just the trait-ref
1036 // - the stack can create recursion.
1037 if result.is_stack_dependent() {
1041 // Neither the global nor local cache is aware of intercrate
1042 // mode, so don't do any caching. In particular, we might
1043 // re-use the same `InferCtxt` with both an intercrate
1044 // and non-intercrate `SelectionContext`
1045 if self.intercrate {
1049 if self.can_use_global_caches(param_env) {
1050 if !trait_ref.needs_infer() {
1051 debug!(?trait_ref, ?result, "insert_evaluation_cache global");
1052 // This may overwrite the cache with the same value
1053 // FIXME: Due to #50507 this overwrites the different values
1054 // This should be changed to use HashMapExt::insert_same
1055 // when that is fixed
1056 self.tcx().evaluation_cache.insert(
1057 (param_env.and(trait_ref), polarity),
1065 debug!(?trait_ref, ?result, "insert_evaluation_cache");
1066 self.infcx.evaluation_cache.insert((param_env.and(trait_ref), polarity), dep_node, result);
1069 /// For various reasons, it's possible for a subobligation
1070 /// to have a *lower* recursion_depth than the obligation used to create it.
1071 /// Projection sub-obligations may be returned from the projection cache,
1072 /// which results in obligations with an 'old' `recursion_depth`.
1073 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1074 /// subobligations without taking in a 'parent' depth, causing the
1075 /// generated subobligations to have a `recursion_depth` of `0`.
1077 /// To ensure that obligation_depth never decreases, we force all subobligations
1078 /// to have at least the depth of the original obligation.
1079 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1084 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1087 fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
1090 error_obligation: &Obligation<'tcx, T>,
1091 ) -> Result<(), OverflowError> {
1092 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1093 match self.query_mode {
1094 TraitQueryMode::Standard => {
1095 if self.infcx.is_tainted_by_errors() {
1096 return Err(OverflowError::ErrorReporting);
1098 self.infcx.report_overflow_error(error_obligation, true);
1100 TraitQueryMode::Canonical => {
1101 return Err(OverflowError::Canonical);
1108 /// Checks that the recursion limit has not been exceeded.
1110 /// The weird return type of this function allows it to be used with the `try` (`?`)
1111 /// operator within certain functions.
1113 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1115 obligation: &Obligation<'tcx, T>,
1116 error_obligation: &Obligation<'tcx, V>,
1117 ) -> Result<(), OverflowError> {
1118 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1121 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1123 OP: FnOnce(&mut Self) -> R,
1125 let (result, dep_node) =
1126 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1127 self.tcx().dep_graph.read_index(dep_node);
1131 /// filter_impls filters constant trait obligations and candidates that have a positive impl
1132 /// for a negative goal and a negative impl for a positive goal
1133 #[instrument(level = "debug", skip(self))]
1136 candidates: Vec<SelectionCandidate<'tcx>>,
1137 obligation: &TraitObligation<'tcx>,
1138 ) -> Vec<SelectionCandidate<'tcx>> {
1139 let tcx = self.tcx();
1140 let mut result = Vec::with_capacity(candidates.len());
1142 for candidate in candidates {
1143 // Respect const trait obligations
1144 if self.is_trait_predicate_const(obligation.predicate.skip_binder()) {
1147 ImplCandidate(def_id)
1148 if tcx.impl_constness(def_id) == hir::Constness::Const => {}
1151 ty::ConstnessAnd { constness: ty::BoundConstness::ConstIfConst, .. },
1155 AutoImplCandidate(..) => {}
1156 // generator, this will raise error in other places
1157 // or ignore error with const_async_blocks feature
1158 GeneratorCandidate => {}
1159 // FnDef where the function is const
1160 FnPointerCandidate { is_const: true } => {}
1161 ConstDropCandidate => {}
1163 // reject all other types of candidates
1169 if let ImplCandidate(def_id) = candidate {
1170 if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id)
1171 || obligation.polarity() == tcx.impl_polarity(def_id)
1172 || self.allow_negative_impls
1174 result.push(candidate);
1177 result.push(candidate);
1184 /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1185 #[instrument(level = "debug", skip(self))]
1186 fn filter_reservation_impls(
1188 candidate: SelectionCandidate<'tcx>,
1189 obligation: &TraitObligation<'tcx>,
1190 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1191 let tcx = self.tcx();
1192 // Treat reservation impls as ambiguity.
1193 if let ImplCandidate(def_id) = candidate {
1194 if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
1195 if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1196 let attrs = tcx.get_attrs(def_id);
1197 let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
1198 let value = attr.and_then(|a| a.value_str());
1199 if let Some(value) = value {
1201 "filter_reservation_impls: \
1202 reservation impl ambiguity on {:?}",
1205 intercrate_ambiguity_clauses.push(
1206 IntercrateAmbiguityCause::ReservationImpl {
1207 message: value.to_string(),
1218 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1219 debug!("is_knowable(intercrate={:?})", self.intercrate);
1221 if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative {
1225 let obligation = &stack.obligation;
1226 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1228 // Okay to skip binder because of the nature of the
1229 // trait-ref-is-knowable check, which does not care about
1231 let trait_ref = predicate.skip_binder().trait_ref;
1233 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1236 /// Returns `true` if the global caches can be used.
1237 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1238 // If there are any inference variables in the `ParamEnv`, then we
1239 // always use a cache local to this particular scope. Otherwise, we
1240 // switch to a global cache.
1241 if param_env.needs_infer() {
1245 // Avoid using the master cache during coherence and just rely
1246 // on the local cache. This effectively disables caching
1247 // during coherence. It is really just a simplification to
1248 // avoid us having to fear that coherence results "pollute"
1249 // the master cache. Since coherence executes pretty quickly,
1250 // it's not worth going to more trouble to increase the
1251 // hit-rate, I don't think.
1252 if self.intercrate {
1256 // Otherwise, we can use the global cache.
1260 fn check_candidate_cache(
1262 param_env: ty::ParamEnv<'tcx>,
1263 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1264 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1265 // Neither the global nor local cache is aware of intercrate
1266 // mode, so don't do any caching. In particular, we might
1267 // re-use the same `InferCtxt` with both an intercrate
1268 // and non-intercrate `SelectionContext`
1269 if self.intercrate {
1272 let tcx = self.tcx();
1273 let pred = &cache_fresh_trait_pred.skip_binder();
1274 let trait_ref = pred.trait_ref;
1275 if self.can_use_global_caches(param_env) {
1276 if let Some(res) = tcx
1278 .get(&(param_env.and(trait_ref).with_constness(pred.constness), pred.polarity), tcx)
1285 .get(&(param_env.and(trait_ref).with_constness(pred.constness), pred.polarity), tcx)
1288 /// Determines whether can we safely cache the result
1289 /// of selecting an obligation. This is almost always `true`,
1290 /// except when dealing with certain `ParamCandidate`s.
1292 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1293 /// since it was usually produced directly from a `DefId`. However,
1294 /// certain cases (currently only librustdoc's blanket impl finder),
1295 /// a `ParamEnv` may be explicitly constructed with inference types.
1296 /// When this is the case, we do *not* want to cache the resulting selection
1297 /// candidate. This is due to the fact that it might not always be possible
1298 /// to equate the obligation's trait ref and the candidate's trait ref,
1299 /// if more constraints end up getting added to an inference variable.
1301 /// Because of this, we always want to re-run the full selection
1302 /// process for our obligation the next time we see it, since
1303 /// we might end up picking a different `SelectionCandidate` (or none at all).
1304 fn can_cache_candidate(
1306 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1308 // Neither the global nor local cache is aware of intercrate
1309 // mode, so don't do any caching. In particular, we might
1310 // re-use the same `InferCtxt` with both an intercrate
1311 // and non-intercrate `SelectionContext`
1312 if self.intercrate {
1316 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1321 fn insert_candidate_cache(
1323 param_env: ty::ParamEnv<'tcx>,
1324 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1325 dep_node: DepNodeIndex,
1326 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1328 let tcx = self.tcx();
1329 let pred = cache_fresh_trait_pred.skip_binder();
1330 let trait_ref = pred.trait_ref;
1332 if !self.can_cache_candidate(&candidate) {
1333 debug!(?trait_ref, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1337 if self.can_use_global_caches(param_env) {
1338 if let Err(Overflow) = candidate {
1339 // Don't cache overflow globally; we only produce this in certain modes.
1340 } else if !trait_ref.needs_infer() {
1341 if !candidate.needs_infer() {
1342 debug!(?trait_ref, ?candidate, "insert_candidate_cache global");
1343 // This may overwrite the cache with the same value.
1344 tcx.selection_cache.insert(
1345 (param_env.and(trait_ref).with_constness(pred.constness), pred.polarity),
1354 debug!(?trait_ref, ?candidate, "insert_candidate_cache local");
1355 self.infcx.selection_cache.insert(
1356 (param_env.and(trait_ref).with_constness(pred.constness), pred.polarity),
1362 /// Matches a predicate against the bounds of its self type.
1364 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1365 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1366 /// `Baz` bound. We return indexes into the list returned by
1367 /// `tcx.item_bounds` for any applicable bounds.
1368 fn match_projection_obligation_against_definition_bounds(
1370 obligation: &TraitObligation<'tcx>,
1371 ) -> smallvec::SmallVec<[usize; 2]> {
1372 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1373 let placeholder_trait_predicate =
1374 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1376 ?placeholder_trait_predicate,
1377 "match_projection_obligation_against_definition_bounds"
1380 let tcx = self.infcx.tcx;
1381 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1382 ty::Projection(ref data) => (data.item_def_id, data.substs),
1383 ty::Opaque(def_id, substs) => (def_id, substs),
1386 obligation.cause.span,
1387 "match_projection_obligation_against_definition_bounds() called \
1388 but self-ty is not a projection: {:?}",
1389 placeholder_trait_predicate.trait_ref.self_ty()
1393 let bounds = tcx.item_bounds(def_id).subst(tcx, substs);
1395 // The bounds returned by `item_bounds` may contain duplicates after
1396 // normalization, so try to deduplicate when possible to avoid
1397 // unnecessary ambiguity.
1398 let mut distinct_normalized_bounds = FxHashSet::default();
1400 let matching_bounds = bounds
1403 .filter_map(|(idx, bound)| {
1404 let bound_predicate = bound.kind();
1405 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1406 let bound = bound_predicate.rebind(pred.trait_ref);
1407 if self.infcx.probe(|_| {
1408 match self.match_normalize_trait_ref(
1411 placeholder_trait_predicate.trait_ref,
1414 Ok(Some(normalized_trait))
1415 if distinct_normalized_bounds.insert(normalized_trait) =>
1429 debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds");
1433 /// Equates the trait in `obligation` with trait bound. If the two traits
1434 /// can be equated and the normalized trait bound doesn't contain inference
1435 /// variables or placeholders, the normalized bound is returned.
1436 fn match_normalize_trait_ref(
1438 obligation: &TraitObligation<'tcx>,
1439 trait_bound: ty::PolyTraitRef<'tcx>,
1440 placeholder_trait_ref: ty::TraitRef<'tcx>,
1441 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1442 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1443 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1444 // Avoid unnecessary normalization
1448 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1449 project::normalize_with_depth(
1451 obligation.param_env,
1452 obligation.cause.clone(),
1453 obligation.recursion_depth + 1,
1458 .at(&obligation.cause, obligation.param_env)
1459 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1460 .map(|InferOk { obligations: _, value: () }| {
1461 // This method is called within a probe, so we can't have
1462 // inference variables and placeholders escape.
1463 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1472 fn evaluate_where_clause<'o>(
1474 stack: &TraitObligationStack<'o, 'tcx>,
1475 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1476 ) -> Result<EvaluationResult, OverflowError> {
1477 self.evaluation_probe(|this| {
1478 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1479 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1480 Err(()) => Ok(EvaluatedToErr),
1485 pub(super) fn match_projection_projections(
1487 obligation: &ProjectionTyObligation<'tcx>,
1488 env_predicate: PolyProjectionPredicate<'tcx>,
1489 potentially_unnormalized_candidates: bool,
1491 let mut nested_obligations = Vec::new();
1492 let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars(
1493 obligation.cause.span,
1494 LateBoundRegionConversionTime::HigherRankedType,
1497 let infer_projection = if potentially_unnormalized_candidates {
1498 ensure_sufficient_stack(|| {
1499 project::normalize_with_depth_to(
1501 obligation.param_env,
1502 obligation.cause.clone(),
1503 obligation.recursion_depth + 1,
1504 infer_predicate.projection_ty,
1505 &mut nested_obligations,
1509 infer_predicate.projection_ty
1513 .at(&obligation.cause, obligation.param_env)
1514 .sup(obligation.predicate, infer_projection)
1515 .map_or(false, |InferOk { obligations, value: () }| {
1516 self.evaluate_predicates_recursively(
1517 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1518 nested_obligations.into_iter().chain(obligations),
1520 .map_or(false, |res| res.may_apply())
1524 ///////////////////////////////////////////////////////////////////////////
1527 // Winnowing is the process of attempting to resolve ambiguity by
1528 // probing further. During the winnowing process, we unify all
1529 // type variables and then we also attempt to evaluate recursive
1530 // bounds to see if they are satisfied.
1532 /// Returns `true` if `victim` should be dropped in favor of
1533 /// `other`. Generally speaking we will drop duplicate
1534 /// candidates and prefer where-clause candidates.
1536 /// See the comment for "SelectionCandidate" for more details.
1537 fn candidate_should_be_dropped_in_favor_of(
1539 victim: &EvaluatedCandidate<'tcx>,
1540 other: &EvaluatedCandidate<'tcx>,
1543 if victim.candidate == other.candidate {
1547 // Check if a bound would previously have been removed when normalizing
1548 // the param_env so that it can be given the lowest priority. See
1549 // #50825 for the motivation for this.
1550 let is_global = |cand: &ty::PolyTraitRef<'tcx>| {
1551 cand.is_global(self.infcx.tcx) && !cand.has_late_bound_regions()
1554 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1555 // and `DiscriminantKindCandidate` to anything else.
1557 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1558 // lifetime of a variable.
1559 match (&other.candidate, &victim.candidate) {
1560 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1562 "default implementations shouldn't be recorded \
1563 when there are other valid candidates"
1569 BuiltinCandidate { has_nested: false }
1570 | DiscriminantKindCandidate
1572 | ConstDropCandidate,
1577 BuiltinCandidate { has_nested: false }
1578 | DiscriminantKindCandidate
1580 | ConstDropCandidate,
1584 ParamCandidate((other, other_polarity)),
1585 ParamCandidate((victim, victim_polarity)),
1587 let same_except_bound_vars = other.value.skip_binder()
1588 == victim.value.skip_binder()
1589 && other.constness == victim.constness
1590 && other_polarity == victim_polarity
1591 && !other.value.skip_binder().has_escaping_bound_vars();
1592 if same_except_bound_vars {
1593 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1594 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1595 // or the current one if tied (they should both evaluate to the same answer). This is
1596 // probably best characterized as a "hack", since we might prefer to just do our
1597 // best to *not* create essentially duplicate candidates in the first place.
1598 other.value.bound_vars().len() <= victim.value.bound_vars().len()
1599 } else if other.value == victim.value
1600 && victim.constness == ty::BoundConstness::NotConst
1601 && other_polarity == victim_polarity
1603 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1610 // Drop otherwise equivalent non-const fn pointer candidates
1611 (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
1613 // Global bounds from the where clause should be ignored
1614 // here (see issue #50825). Otherwise, we have a where
1615 // clause so don't go around looking for impls.
1616 // Arbitrarily give param candidates priority
1617 // over projection and object candidates.
1619 ParamCandidate(ref cand),
1622 | GeneratorCandidate
1623 | FnPointerCandidate { .. }
1624 | BuiltinObjectCandidate
1625 | BuiltinUnsizeCandidate
1626 | TraitUpcastingUnsizeCandidate(_)
1627 | BuiltinCandidate { .. }
1628 | TraitAliasCandidate(..)
1629 | ObjectCandidate(_)
1630 | ProjectionCandidate(_),
1631 ) => !is_global(&cand.0.value),
1632 (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1633 // Prefer these to a global where-clause bound
1634 // (see issue #50825).
1635 is_global(&cand.0.value)
1640 | GeneratorCandidate
1641 | FnPointerCandidate { .. }
1642 | BuiltinObjectCandidate
1643 | BuiltinUnsizeCandidate
1644 | TraitUpcastingUnsizeCandidate(_)
1645 | BuiltinCandidate { has_nested: true }
1646 | TraitAliasCandidate(..),
1647 ParamCandidate(ref cand),
1649 // Prefer these to a global where-clause bound
1650 // (see issue #50825).
1651 is_global(&cand.0.value) && other.evaluation.must_apply_modulo_regions()
1654 (ProjectionCandidate(i), ProjectionCandidate(j))
1655 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1656 // Arbitrarily pick the lower numbered candidate for backwards
1657 // compatibility reasons. Don't let this affect inference.
1658 i < j && !needs_infer
1660 (ObjectCandidate(_), ProjectionCandidate(_))
1661 | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1662 bug!("Have both object and projection candidate")
1665 // Arbitrarily give projection and object candidates priority.
1667 ObjectCandidate(_) | ProjectionCandidate(_),
1670 | GeneratorCandidate
1671 | FnPointerCandidate { .. }
1672 | BuiltinObjectCandidate
1673 | BuiltinUnsizeCandidate
1674 | TraitUpcastingUnsizeCandidate(_)
1675 | BuiltinCandidate { .. }
1676 | TraitAliasCandidate(..),
1682 | GeneratorCandidate
1683 | FnPointerCandidate { .. }
1684 | BuiltinObjectCandidate
1685 | BuiltinUnsizeCandidate
1686 | TraitUpcastingUnsizeCandidate(_)
1687 | BuiltinCandidate { .. }
1688 | TraitAliasCandidate(..),
1689 ObjectCandidate(_) | ProjectionCandidate(_),
1692 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1693 // See if we can toss out `victim` based on specialization.
1694 // This requires us to know *for sure* that the `other` impl applies
1695 // i.e., `EvaluatedToOk`.
1697 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1698 // to me but is required for `std` to compile, so I didn't change it
1700 let tcx = self.tcx();
1701 if other.evaluation.must_apply_modulo_regions() {
1702 if tcx.specializes((other_def, victim_def)) {
1707 if other.evaluation.must_apply_considering_regions() {
1708 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1709 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1710 // Subtle: If the predicate we are evaluating has inference
1711 // variables, do *not* allow discarding candidates due to
1712 // marker trait impls.
1714 // Without this restriction, we could end up accidentally
1715 // constrainting inference variables based on an arbitrarily
1716 // chosen trait impl.
1718 // Imagine we have the following code:
1721 // #[marker] trait MyTrait {}
1722 // impl MyTrait for u8 {}
1723 // impl MyTrait for bool {}
1726 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1728 // During selection, we will end up with one candidate for each
1729 // impl of `MyTrait`. If we were to discard one impl in favor
1730 // of the other, we would be left with one candidate, causing
1731 // us to "successfully" select the predicate, unifying
1732 // _#0t with (for example) `u8`.
1734 // However, we have no reason to believe that this unification
1735 // is correct - we've essentially just picked an arbitrary
1736 // *possibility* for _#0t, and required that this be the *only*
1739 // Eventually, we will either:
1740 // 1) Unify all inference variables in the predicate through
1741 // some other means (e.g. type-checking of a function). We will
1742 // then be in a position to drop marker trait candidates
1743 // without constraining inference variables (since there are
1744 // none left to constrin)
1745 // 2) Be left with some unconstrained inference variables. We
1746 // will then correctly report an inference error, since the
1747 // existence of multiple marker trait impls tells us nothing
1748 // about which one should actually apply.
1759 // Everything else is ambiguous
1763 | GeneratorCandidate
1764 | FnPointerCandidate { .. }
1765 | BuiltinObjectCandidate
1766 | BuiltinUnsizeCandidate
1767 | TraitUpcastingUnsizeCandidate(_)
1768 | BuiltinCandidate { has_nested: true }
1769 | TraitAliasCandidate(..),
1772 | GeneratorCandidate
1773 | FnPointerCandidate { .. }
1774 | BuiltinObjectCandidate
1775 | BuiltinUnsizeCandidate
1776 | TraitUpcastingUnsizeCandidate(_)
1777 | BuiltinCandidate { has_nested: true }
1778 | TraitAliasCandidate(..),
1783 fn sized_conditions(
1785 obligation: &TraitObligation<'tcx>,
1786 ) -> BuiltinImplConditions<'tcx> {
1787 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1789 // NOTE: binder moved to (*)
1790 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1792 match self_ty.kind() {
1793 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1804 | ty::GeneratorWitness(..)
1809 // safe for everything
1810 Where(ty::Binder::dummy(Vec::new()))
1813 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1815 ty::Tuple(tys) => Where(
1818 .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()),
1821 ty::Adt(def, substs) => {
1822 let sized_crit = def.sized_constraint(self.tcx());
1823 // (*) binder moved here
1825 obligation.predicate.rebind({
1826 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1831 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1832 ty::Infer(ty::TyVar(_)) => Ambiguous,
1836 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1837 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1842 fn copy_clone_conditions(
1844 obligation: &TraitObligation<'tcx>,
1845 ) -> BuiltinImplConditions<'tcx> {
1846 // NOTE: binder moved to (*)
1847 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1849 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1851 match *self_ty.kind() {
1852 ty::Infer(ty::IntVar(_))
1853 | ty::Infer(ty::FloatVar(_))
1856 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1865 | ty::Ref(_, _, hir::Mutability::Not) => {
1866 // Implementations provided in libcore
1874 | ty::GeneratorWitness(..)
1876 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1878 ty::Array(element_ty, _) => {
1879 // (*) binder moved here
1880 Where(obligation.predicate.rebind(vec![element_ty]))
1884 // (*) binder moved here
1885 Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect()))
1888 ty::Closure(_, substs) => {
1889 // (*) binder moved here
1890 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1891 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1892 // Not yet resolved.
1895 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1899 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1900 // Fallback to whatever user-defined impls exist in this case.
1904 ty::Infer(ty::TyVar(_)) => {
1905 // Unbound type variable. Might or might not have
1906 // applicable impls and so forth, depending on what
1907 // those type variables wind up being bound to.
1913 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1914 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1919 /// For default impls, we need to break apart a type into its
1920 /// "constituent types" -- meaning, the types that it contains.
1922 /// Here are some (simple) examples:
1925 /// (i32, u32) -> [i32, u32]
1926 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1927 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1928 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1930 fn constituent_types_for_ty(
1932 t: ty::Binder<'tcx, Ty<'tcx>>,
1933 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1934 match *t.skip_binder().kind() {
1943 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1945 | ty::Char => ty::Binder::dummy(Vec::new()),
1951 | ty::Projection(..)
1953 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1954 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1957 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1958 t.rebind(vec![element_ty])
1961 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
1963 ty::Tuple(ref tys) => {
1964 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1965 t.rebind(tys.iter().map(|k| k.expect_ty()).collect())
1968 ty::Closure(_, ref substs) => {
1969 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1973 ty::Generator(_, ref substs, _) => {
1974 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
1975 let witness = substs.as_generator().witness();
1976 t.rebind(vec![ty].into_iter().chain(iter::once(witness)).collect())
1979 ty::GeneratorWitness(types) => {
1980 debug_assert!(!types.has_escaping_bound_vars());
1981 types.map_bound(|types| types.to_vec())
1984 // For `PhantomData<T>`, we pass `T`.
1985 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
1987 ty::Adt(def, substs) => {
1988 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
1991 ty::Opaque(def_id, substs) => {
1992 // We can resolve the `impl Trait` to its concrete type,
1993 // which enforces a DAG between the functions requiring
1994 // the auto trait bounds in question.
1995 t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
2000 fn collect_predicates_for_types(
2002 param_env: ty::ParamEnv<'tcx>,
2003 cause: ObligationCause<'tcx>,
2004 recursion_depth: usize,
2005 trait_def_id: DefId,
2006 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
2007 ) -> Vec<PredicateObligation<'tcx>> {
2008 // Because the types were potentially derived from
2009 // higher-ranked obligations they may reference late-bound
2010 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2011 // yield a type like `for<'a> &'a i32`. In general, we
2012 // maintain the invariant that we never manipulate bound
2013 // regions, so we have to process these bound regions somehow.
2015 // The strategy is to:
2017 // 1. Instantiate those regions to placeholder regions (e.g.,
2018 // `for<'a> &'a i32` becomes `&0 i32`.
2019 // 2. Produce something like `&'0 i32 : Copy`
2020 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2024 .skip_binder() // binder moved -\
2027 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(ty); // <----/
2029 self.infcx.commit_unconditionally(|_| {
2030 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
2031 let Normalized { value: normalized_ty, mut obligations } =
2032 ensure_sufficient_stack(|| {
2033 project::normalize_with_depth(
2041 let placeholder_obligation = predicate_for_trait_def(
2050 obligations.push(placeholder_obligation);
2057 ///////////////////////////////////////////////////////////////////////////
2060 // Matching is a common path used for both evaluation and
2061 // confirmation. It basically unifies types that appear in impls
2062 // and traits. This does affect the surrounding environment;
2063 // therefore, when used during evaluation, match routines must be
2064 // run inside of a `probe()` so that their side-effects are
2070 obligation: &TraitObligation<'tcx>,
2071 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
2072 match self.match_impl(impl_def_id, obligation) {
2073 Ok(substs) => substs,
2076 "Impl {:?} was matchable against {:?} but now is not",
2084 #[tracing::instrument(level = "debug", skip(self))]
2088 obligation: &TraitObligation<'tcx>,
2089 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2090 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2092 // Before we create the substitutions and everything, first
2093 // consider a "quick reject". This avoids creating more types
2094 // and so forth that we need to.
2095 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2099 let placeholder_obligation =
2100 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
2101 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2103 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2105 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2107 debug!(?impl_trait_ref);
2109 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2110 ensure_sufficient_stack(|| {
2111 project::normalize_with_depth(
2113 obligation.param_env,
2114 obligation.cause.clone(),
2115 obligation.recursion_depth + 1,
2120 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2122 let cause = ObligationCause::new(
2123 obligation.cause.span,
2124 obligation.cause.body_id,
2125 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2128 let InferOk { obligations, .. } = self
2130 .at(&cause, obligation.param_env)
2131 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2132 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2133 nested_obligations.extend(obligations);
2136 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2138 debug!("match_impl: reservation impls only apply in intercrate mode");
2142 debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2143 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2146 fn fast_reject_trait_refs(
2148 obligation: &TraitObligation<'_>,
2149 impl_trait_ref: &ty::TraitRef<'_>,
2151 // We can avoid creating type variables and doing the full
2152 // substitution if we find that any of the input types, when
2153 // simplified, do not match.
2155 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
2156 |(obligation_arg, impl_arg)| {
2157 match (obligation_arg.unpack(), impl_arg.unpack()) {
2158 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
2159 let simplified_obligation_ty =
2160 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2161 let simplified_impl_ty =
2162 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2164 simplified_obligation_ty.is_some()
2165 && simplified_impl_ty.is_some()
2166 && simplified_obligation_ty != simplified_impl_ty
2168 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
2169 // Lifetimes can never cause a rejection.
2172 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
2173 // Conservatively ignore consts (i.e. assume they might
2174 // unify later) until we have `fast_reject` support for
2175 // them (if we'll ever need it, even).
2178 _ => unreachable!(),
2184 /// Normalize `where_clause_trait_ref` and try to match it against
2185 /// `obligation`. If successful, return any predicates that
2186 /// result from the normalization.
2187 fn match_where_clause_trait_ref(
2189 obligation: &TraitObligation<'tcx>,
2190 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2191 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2192 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2195 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2196 /// obligation is satisfied.
2197 #[instrument(skip(self), level = "debug")]
2198 fn match_poly_trait_ref(
2200 obligation: &TraitObligation<'tcx>,
2201 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2202 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2204 .at(&obligation.cause, obligation.param_env)
2205 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2206 .map(|InferOk { obligations, .. }| obligations)
2210 ///////////////////////////////////////////////////////////////////////////
2213 fn match_fresh_trait_refs(
2215 previous: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2216 current: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2217 param_env: ty::ParamEnv<'tcx>,
2219 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2220 matcher.relate(previous, current).is_ok()
2225 previous_stack: TraitObligationStackList<'o, 'tcx>,
2226 obligation: &'o TraitObligation<'tcx>,
2227 ) -> TraitObligationStack<'o, 'tcx> {
2228 let fresh_trait_ref = obligation
2230 .to_poly_trait_ref()
2231 .fold_with(&mut self.freshener)
2232 .with_constness(obligation.predicate.skip_binder().constness);
2234 let dfn = previous_stack.cache.next_dfn();
2235 let depth = previous_stack.depth() + 1;
2236 TraitObligationStack {
2239 reached_depth: Cell::new(depth),
2240 previous: previous_stack,
2246 #[instrument(skip(self), level = "debug")]
2247 fn closure_trait_ref_unnormalized(
2249 obligation: &TraitObligation<'tcx>,
2250 substs: SubstsRef<'tcx>,
2251 ) -> ty::PolyTraitRef<'tcx> {
2252 let closure_sig = substs.as_closure().sig();
2254 debug!(?closure_sig);
2256 // (1) Feels icky to skip the binder here, but OTOH we know
2257 // that the self-type is an unboxed closure type and hence is
2258 // in fact unparameterized (or at least does not reference any
2259 // regions bound in the obligation). Still probably some
2260 // refactoring could make this nicer.
2261 closure_trait_ref_and_return_type(
2263 obligation.predicate.def_id(),
2264 obligation.predicate.skip_binder().self_ty(), // (1)
2266 util::TupleArgumentsFlag::No,
2268 .map_bound(|(trait_ref, _)| trait_ref)
2271 fn generator_trait_ref_unnormalized(
2273 obligation: &TraitObligation<'tcx>,
2274 substs: SubstsRef<'tcx>,
2275 ) -> ty::PolyTraitRef<'tcx> {
2276 let gen_sig = substs.as_generator().poly_sig();
2278 // (1) Feels icky to skip the binder here, but OTOH we know
2279 // that the self-type is an generator type and hence is
2280 // in fact unparameterized (or at least does not reference any
2281 // regions bound in the obligation). Still probably some
2282 // refactoring could make this nicer.
2284 super::util::generator_trait_ref_and_outputs(
2286 obligation.predicate.def_id(),
2287 obligation.predicate.skip_binder().self_ty(), // (1)
2290 .map_bound(|(trait_ref, ..)| trait_ref)
2293 /// Returns the obligations that are implied by instantiating an
2294 /// impl or trait. The obligations are substituted and fully
2295 /// normalized. This is used when confirming an impl or default
2297 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2298 fn impl_or_trait_obligations(
2300 cause: ObligationCause<'tcx>,
2301 recursion_depth: usize,
2302 param_env: ty::ParamEnv<'tcx>,
2303 def_id: DefId, // of impl or trait
2304 substs: SubstsRef<'tcx>, // for impl or trait
2305 ) -> Vec<PredicateObligation<'tcx>> {
2306 let tcx = self.tcx();
2308 // To allow for one-pass evaluation of the nested obligation,
2309 // each predicate must be preceded by the obligations required
2311 // for example, if we have:
2312 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2313 // the impl will have the following predicates:
2314 // <V as Iterator>::Item = U,
2315 // U: Iterator, U: Sized,
2316 // V: Iterator, V: Sized,
2317 // <U as Iterator>::Item: Copy
2318 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2319 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2320 // `$1: Copy`, so we must ensure the obligations are emitted in
2322 let predicates = tcx.predicates_of(def_id);
2323 debug!(?predicates);
2324 assert_eq!(predicates.parent, None);
2325 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2326 for (predicate, _) in predicates.predicates {
2328 let predicate = normalize_with_depth_to(
2333 predicate.subst(tcx, substs),
2336 obligations.push(Obligation {
2337 cause: cause.clone(),
2344 // We are performing deduplication here to avoid exponential blowups
2345 // (#38528) from happening, but the real cause of the duplication is
2346 // unknown. What we know is that the deduplication avoids exponential
2347 // amount of predicates being propagated when processing deeply nested
2350 // This code is hot enough that it's worth avoiding the allocation
2351 // required for the FxHashSet when possible. Special-casing lengths 0,
2352 // 1 and 2 covers roughly 75-80% of the cases.
2353 if obligations.len() <= 1 {
2354 // No possibility of duplicates.
2355 } else if obligations.len() == 2 {
2356 // Only two elements. Drop the second if they are equal.
2357 if obligations[0] == obligations[1] {
2358 obligations.truncate(1);
2361 // Three or more elements. Use a general deduplication process.
2362 let mut seen = FxHashSet::default();
2363 obligations.retain(|i| seen.insert(i.clone()));
2370 trait TraitObligationExt<'tcx> {
2373 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2374 ) -> ObligationCause<'tcx>;
2377 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2380 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2381 ) -> ObligationCause<'tcx> {
2383 * Creates a cause for obligations that are derived from
2384 * `obligation` by a recursive search (e.g., for a builtin
2385 * bound, or eventually a `auto trait Foo`). If `obligation`
2386 * is itself a derived obligation, this is just a clone, but
2387 * otherwise we create a "derived obligation" cause so as to
2388 * keep track of the original root obligation for error
2392 let obligation = self;
2394 // NOTE(flaper87): As of now, it keeps track of the whole error
2395 // chain. Ideally, we should have a way to configure this either
2396 // by using -Z verbose or just a CLI argument.
2397 let derived_cause = DerivedObligationCause {
2398 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2399 parent_code: Lrc::new(obligation.cause.code.clone()),
2401 let derived_code = variant(derived_cause);
2402 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2406 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2407 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2408 TraitObligationStackList::with(self)
2411 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2415 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2419 /// Indicates that attempting to evaluate this stack entry
2420 /// required accessing something from the stack at depth `reached_depth`.
2421 fn update_reached_depth(&self, reached_depth: usize) {
2423 self.depth >= reached_depth,
2424 "invoked `update_reached_depth` with something under this stack: \
2425 self.depth={} reached_depth={}",
2429 debug!(reached_depth, "update_reached_depth");
2431 while reached_depth < p.depth {
2432 debug!(?p.fresh_trait_ref, "update_reached_depth: marking as cycle participant");
2433 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2434 p = p.previous.head.unwrap();
2439 /// The "provisional evaluation cache" is used to store intermediate cache results
2440 /// when solving auto traits. Auto traits are unusual in that they can support
2441 /// cycles. So, for example, a "proof tree" like this would be ok:
2443 /// - `Foo<T>: Send` :-
2444 /// - `Bar<T>: Send` :-
2445 /// - `Foo<T>: Send` -- cycle, but ok
2446 /// - `Baz<T>: Send`
2448 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2449 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2450 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2451 /// they are coinductive) it is considered ok.
2453 /// However, there is a complication: at the point where we have
2454 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2455 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2456 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2457 /// find out this assumption is wrong? Specifically, we could
2458 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2459 /// `Bar<T>: Send` didn't turn out to be true.
2461 /// In Issue #60010, we found a bug in rustc where it would cache
2462 /// these intermediate results. This was fixed in #60444 by disabling
2463 /// *all* caching for things involved in a cycle -- in our example,
2464 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2465 /// to large slowdowns.
2467 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2468 /// first requires proving `Bar<T>: Send` (which is true:
2470 /// - `Foo<T>: Send` :-
2471 /// - `Bar<T>: Send` :-
2472 /// - `Foo<T>: Send` -- cycle, but ok
2473 /// - `Baz<T>: Send`
2474 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2475 /// - `*const T: Send` -- but what if we later encounter an error?
2477 /// The *provisional evaluation cache* resolves this issue. It stores
2478 /// cache results that we've proven but which were involved in a cycle
2479 /// in some way. We track the minimal stack depth (i.e., the
2480 /// farthest from the top of the stack) that we are dependent on.
2481 /// The idea is that the cache results within are all valid -- so long as
2482 /// none of the nodes in between the current node and the node at that minimum
2483 /// depth result in an error (in which case the cached results are just thrown away).
2485 /// During evaluation, we consult this provisional cache and rely on
2486 /// it. Accessing a cached value is considered equivalent to accessing
2487 /// a result at `reached_depth`, so it marks the *current* solution as
2488 /// provisional as well. If an error is encountered, we toss out any
2489 /// provisional results added from the subtree that encountered the
2490 /// error. When we pop the node at `reached_depth` from the stack, we
2491 /// can commit all the things that remain in the provisional cache.
2492 struct ProvisionalEvaluationCache<'tcx> {
2493 /// next "depth first number" to issue -- just a counter
2496 /// Map from cache key to the provisionally evaluated thing.
2497 /// The cache entries contain the result but also the DFN in which they
2498 /// were added. The DFN is used to clear out values on failure.
2500 /// Imagine we have a stack like:
2502 /// - `A B C` and we add a cache for the result of C (DFN 2)
2503 /// - Then we have a stack `A B D` where `D` has DFN 3
2504 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2505 /// - `E` generates various cache entries which have cyclic dependices on `B`
2506 /// - `A B D E F` and so forth
2507 /// - the DFN of `F` for example would be 5
2508 /// - then we determine that `E` is in error -- we will then clear
2509 /// all cache values whose DFN is >= 4 -- in this case, that
2510 /// means the cached value for `F`.
2511 map: RefCell<FxHashMap<ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, ProvisionalEvaluation>>,
2514 /// A cache value for the provisional cache: contains the depth-first
2515 /// number (DFN) and result.
2516 #[derive(Copy, Clone, Debug)]
2517 struct ProvisionalEvaluation {
2519 reached_depth: usize,
2520 result: EvaluationResult,
2523 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2524 fn default() -> Self {
2525 Self { dfn: Cell::new(0), map: Default::default() }
2529 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2530 /// Get the next DFN in sequence (basically a counter).
2531 fn next_dfn(&self) -> usize {
2532 let result = self.dfn.get();
2533 self.dfn.set(result + 1);
2537 /// Check the provisional cache for any result for
2538 /// `fresh_trait_ref`. If there is a hit, then you must consider
2539 /// it an access to the stack slots at depth
2540 /// `reached_depth` (from the returned value).
2543 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2544 ) -> Option<ProvisionalEvaluation> {
2547 "get_provisional = {:#?}",
2548 self.map.borrow().get(&fresh_trait_ref),
2550 Some(*self.map.borrow().get(&fresh_trait_ref)?)
2553 /// Insert a provisional result into the cache. The result came
2554 /// from the node with the given DFN. It accessed a minimum depth
2555 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
2556 /// and resulted in `result`.
2557 fn insert_provisional(
2560 reached_depth: usize,
2561 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2562 result: EvaluationResult,
2564 debug!(?from_dfn, ?fresh_trait_ref, ?result, "insert_provisional");
2566 let mut map = self.map.borrow_mut();
2568 // Subtle: when we complete working on the DFN `from_dfn`, anything
2569 // that remains in the provisional cache must be dependent on some older
2570 // stack entry than `from_dfn`. We have to update their depth with our transitive
2571 // depth in that case or else it would be referring to some popped note.
2574 // A (reached depth 0)
2576 // B // depth 1 -- reached depth = 0
2577 // C // depth 2 -- reached depth = 1 (should be 0)
2580 // D (reached depth 1)
2581 // C (cache -- reached depth = 2)
2582 for (_k, v) in &mut *map {
2583 if v.from_dfn >= from_dfn {
2584 v.reached_depth = reached_depth.min(v.reached_depth);
2588 map.insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, reached_depth, result });
2591 /// Invoked when the node with dfn `dfn` does not get a successful
2592 /// result. This will clear out any provisional cache entries
2593 /// that were added since `dfn` was created. This is because the
2594 /// provisional entries are things which must assume that the
2595 /// things on the stack at the time of their creation succeeded --
2596 /// since the failing node is presently at the top of the stack,
2597 /// these provisional entries must either depend on it or some
2599 fn on_failure(&self, dfn: usize) {
2600 debug!(?dfn, "on_failure");
2601 self.map.borrow_mut().retain(|key, eval| {
2602 if !eval.from_dfn >= dfn {
2603 debug!("on_failure: removing {:?}", key);
2611 /// Invoked when the node at depth `depth` completed without
2612 /// depending on anything higher in the stack (if that completion
2613 /// was a failure, then `on_failure` should have been invoked
2614 /// already). The callback `op` will be invoked for each
2615 /// provisional entry that we can now confirm.
2617 /// Note that we may still have provisional cache items remaining
2618 /// in the cache when this is done. For example, if there is a
2621 /// * A depends on...
2622 /// * B depends on A
2623 /// * C depends on...
2624 /// * D depends on C
2627 /// Then as we complete the C node we will have a provisional cache
2628 /// with results for A, B, C, and D. This method would clear out
2629 /// the C and D results, but leave A and B provisional.
2631 /// This is determined based on the DFN: we remove any provisional
2632 /// results created since `dfn` started (e.g., in our example, dfn
2633 /// would be 2, representing the C node, and hence we would
2634 /// remove the result for D, which has DFN 3, but not the results for
2635 /// A and B, which have DFNs 0 and 1 respectively).
2639 mut op: impl FnMut(ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, EvaluationResult),
2641 debug!(?dfn, "on_completion");
2643 for (fresh_trait_ref, eval) in
2644 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2646 debug!(?fresh_trait_ref, ?eval, "on_completion");
2648 op(fresh_trait_ref, eval.result);
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)