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::Obligation;
18 use super::ObligationCauseCode;
20 use super::SelectionResult;
21 use super::TraitQueryMode;
22 use super::{Normalized, ProjectionCacheKey};
23 use super::{ObligationCause, PredicateObligation, TraitObligation};
24 use super::{Overflow, SelectionError, Unimplemented};
26 use crate::infer::{InferCtxt, InferOk, TypeFreshener};
27 use crate::traits::error_reporting::InferCtxtExt;
28 use crate::traits::project::ProjectionCacheKeyExt;
29 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
30 use rustc_data_structures::stack::ensure_sufficient_stack;
31 use rustc_data_structures::sync::Lrc;
32 use rustc_errors::ErrorReported;
34 use rustc_hir::def_id::DefId;
35 use rustc_infer::infer::LateBoundRegionConversionTime;
36 use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
37 use rustc_middle::mir::interpret::ErrorHandled;
38 use rustc_middle::thir::abstract_const::NotConstEvaluatable;
39 use rustc_middle::ty::fast_reject;
40 use rustc_middle::ty::print::with_no_trimmed_paths;
41 use rustc_middle::ty::relate::TypeRelation;
42 use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef};
43 use rustc_middle::ty::WithConstness;
44 use rustc_middle::ty::{self, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate};
45 use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable};
46 use rustc_span::symbol::sym;
48 use std::cell::{Cell, RefCell};
50 use std::fmt::{self, Display};
53 pub use rustc_middle::traits::select::*;
55 mod candidate_assembly;
58 #[derive(Clone, Debug)]
59 pub enum IntercrateAmbiguityCause {
60 DownstreamCrate { trait_desc: String, self_desc: Option<String> },
61 UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
62 ReservationImpl { message: String },
65 impl IntercrateAmbiguityCause {
66 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
67 /// See #23980 for details.
68 pub fn add_intercrate_ambiguity_hint(&self, err: &mut rustc_errors::DiagnosticBuilder<'_>) {
69 err.note(&self.intercrate_ambiguity_hint());
72 pub fn intercrate_ambiguity_hint(&self) -> String {
74 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } => {
75 let self_desc = if let Some(ty) = self_desc {
76 format!(" for type `{}`", ty)
80 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
82 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc } => {
83 let self_desc = if let Some(ty) = self_desc {
84 format!(" for type `{}`", ty)
89 "upstream crates may add a new impl of trait `{}`{} \
94 IntercrateAmbiguityCause::ReservationImpl { message } => message.clone(),
99 pub struct SelectionContext<'cx, 'tcx> {
100 infcx: &'cx InferCtxt<'cx, 'tcx>,
102 /// Freshener used specifically for entries on the obligation
103 /// stack. This ensures that all entries on the stack at one time
104 /// will have the same set of placeholder entries, which is
105 /// important for checking for trait bounds that recursively
106 /// require themselves.
107 freshener: TypeFreshener<'cx, 'tcx>,
109 /// If `true`, indicates that the evaluation should be conservative
110 /// and consider the possibility of types 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
117 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
118 /// though, we set this to false, because we are only interested
119 /// in types that the user could actually have written --- in
120 /// other words, we consider `$0: Bar` to be unimplemented if
121 /// there is no type that the user could *actually name* that
122 /// would satisfy it. This avoids crippling inference, basically.
125 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
127 /// Controls whether or not to filter out negative impls when selecting.
128 /// This is used in librustdoc to distinguish between the lack of an impl
129 /// and a negative impl
130 allow_negative_impls: bool,
132 /// Are we in a const context that needs `~const` bounds to be const?
133 is_in_const_context: bool,
135 /// The mode that trait queries run in, which informs our error handling
136 /// policy. In essence, canonicalized queries need their errors propagated
137 /// rather than immediately reported because we do not have accurate spans.
138 query_mode: TraitQueryMode,
141 // A stack that walks back up the stack frame.
142 struct TraitObligationStack<'prev, 'tcx> {
143 obligation: &'prev TraitObligation<'tcx>,
145 /// The trait ref from `obligation` but "freshened" with the
146 /// selection-context's freshener. Used to check for recursion.
147 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
149 /// Starts out equal to `depth` -- if, during evaluation, we
150 /// encounter a cycle, then we will set this flag to the minimum
151 /// depth of that cycle for all participants in the cycle. These
152 /// participants will then forego caching their results. This is
153 /// not the most efficient solution, but it addresses #60010. The
154 /// problem we are trying to prevent:
156 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
157 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
158 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
160 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
161 /// is `EvaluatedToOk`; this is because they were only considered
162 /// ok on the premise that if `A: AutoTrait` held, but we indeed
163 /// encountered a problem (later on) with `A: AutoTrait. So we
164 /// currently set a flag on the stack node for `B: AutoTrait` (as
165 /// well as the second instance of `A: AutoTrait`) to suppress
168 /// This is a simple, targeted fix. A more-performant fix requires
169 /// deeper changes, but would permit more caching: we could
170 /// basically defer caching until we have fully evaluated the
171 /// tree, and then cache the entire tree at once. In any case, the
172 /// performance impact here shouldn't be so horrible: every time
173 /// this is hit, we do cache at least one trait, so we only
174 /// evaluate each member of a cycle up to N times, where N is the
175 /// length of the cycle. This means the performance impact is
176 /// bounded and we shouldn't have any terrible worst-cases.
177 reached_depth: Cell<usize>,
179 previous: TraitObligationStackList<'prev, 'tcx>,
181 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
184 /// The depth-first number of this node in the search graph -- a
185 /// pre-order index. Basically, a freshly incremented counter.
189 struct SelectionCandidateSet<'tcx> {
190 // A list of candidates that definitely apply to the current
191 // obligation (meaning: types unify).
192 vec: Vec<SelectionCandidate<'tcx>>,
194 // If `true`, then there were candidates that might or might
195 // not have applied, but we couldn't tell. This occurs when some
196 // of the input types are type variables, in which case there are
197 // various "builtin" rules that might or might not trigger.
201 #[derive(PartialEq, Eq, Debug, Clone)]
202 struct EvaluatedCandidate<'tcx> {
203 candidate: SelectionCandidate<'tcx>,
204 evaluation: EvaluationResult,
207 /// When does the builtin impl for `T: Trait` apply?
208 enum BuiltinImplConditions<'tcx> {
209 /// The impl is conditional on `T1, T2, ...: Trait`.
210 Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
211 /// There is no built-in impl. There may be some other
212 /// candidate (a where-clause or user-defined impl).
214 /// It is unknown whether there is an impl.
218 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
219 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
222 freshener: infcx.freshener_keep_static(),
224 intercrate_ambiguity_causes: None,
225 allow_negative_impls: false,
226 is_in_const_context: false,
227 query_mode: TraitQueryMode::Standard,
231 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
234 freshener: infcx.freshener_keep_static(),
236 intercrate_ambiguity_causes: None,
237 allow_negative_impls: false,
238 is_in_const_context: false,
239 query_mode: TraitQueryMode::Standard,
243 pub fn with_negative(
244 infcx: &'cx InferCtxt<'cx, 'tcx>,
245 allow_negative_impls: bool,
246 ) -> SelectionContext<'cx, 'tcx> {
247 debug!(?allow_negative_impls, "with_negative");
250 freshener: infcx.freshener_keep_static(),
252 intercrate_ambiguity_causes: None,
253 allow_negative_impls,
254 is_in_const_context: false,
255 query_mode: TraitQueryMode::Standard,
259 pub fn with_query_mode(
260 infcx: &'cx InferCtxt<'cx, 'tcx>,
261 query_mode: TraitQueryMode,
262 ) -> SelectionContext<'cx, 'tcx> {
263 debug!(?query_mode, "with_query_mode");
266 freshener: infcx.freshener_keep_static(),
268 intercrate_ambiguity_causes: None,
269 allow_negative_impls: false,
270 is_in_const_context: false,
275 pub fn with_constness(
276 infcx: &'cx InferCtxt<'cx, 'tcx>,
277 constness: hir::Constness,
278 ) -> SelectionContext<'cx, 'tcx> {
281 freshener: infcx.freshener_keep_static(),
283 intercrate_ambiguity_causes: None,
284 allow_negative_impls: false,
285 is_in_const_context: matches!(constness, hir::Constness::Const),
286 query_mode: TraitQueryMode::Standard,
290 /// Enables tracking of intercrate ambiguity causes. These are
291 /// used in coherence to give improved diagnostics. We don't do
292 /// this until we detect a coherence error because it can lead to
293 /// false overflow results (#47139) and because it costs
294 /// computation time.
295 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
296 assert!(self.intercrate);
297 assert!(self.intercrate_ambiguity_causes.is_none());
298 self.intercrate_ambiguity_causes = Some(vec![]);
299 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
302 /// Gets the intercrate ambiguity causes collected since tracking
303 /// was enabled and disables tracking at the same time. If
304 /// tracking is not enabled, just returns an empty vector.
305 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
306 assert!(self.intercrate);
307 self.intercrate_ambiguity_causes.take().unwrap_or_default()
310 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
314 pub fn tcx(&self) -> TyCtxt<'tcx> {
318 /// Returns `true` if the trait predicate is considerd `const` to this selection context.
319 pub fn is_trait_predicate_const(&self, pred: ty::TraitPredicate<'_>) -> bool {
320 match pred.constness {
321 ty::BoundConstness::ConstIfConst if self.is_in_const_context => true,
326 /// Returns `true` if the predicate is considered `const` to
327 /// this selection context.
328 pub fn is_predicate_const(&self, pred: ty::Predicate<'_>) -> bool {
329 match pred.kind().skip_binder() {
330 ty::PredicateKind::Trait(pred) => self.is_trait_predicate_const(pred),
335 ///////////////////////////////////////////////////////////////////////////
338 // The selection phase tries to identify *how* an obligation will
339 // be resolved. For example, it will identify which impl or
340 // parameter bound is to be used. The process can be inconclusive
341 // if the self type in the obligation is not fully inferred. Selection
342 // can result in an error in one of two ways:
344 // 1. If no applicable impl or parameter bound can be found.
345 // 2. If the output type parameters in the obligation do not match
346 // those specified by the impl/bound. For example, if the obligation
347 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
348 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
350 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
351 /// type environment by performing unification.
352 #[instrument(level = "debug", skip(self))]
355 obligation: &TraitObligation<'tcx>,
356 ) -> SelectionResult<'tcx, Selection<'tcx>> {
357 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
359 let pec = &ProvisionalEvaluationCache::default();
360 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
362 let candidate = match self.candidate_from_obligation(&stack) {
363 Err(SelectionError::Overflow) => {
364 // In standard mode, overflow must have been caught and reported
366 assert!(self.query_mode == TraitQueryMode::Canonical);
367 return Err(SelectionError::Overflow);
375 Ok(Some(candidate)) => candidate,
378 match self.confirm_candidate(obligation, candidate) {
379 Err(SelectionError::Overflow) => {
380 assert!(self.query_mode == TraitQueryMode::Canonical);
381 Err(SelectionError::Overflow)
391 ///////////////////////////////////////////////////////////////////////////
394 // Tests whether an obligation can be selected or whether an impl
395 // can be applied to particular types. It skips the "confirmation"
396 // step and hence completely ignores output type parameters.
398 // The result is "true" if the obligation *may* hold and "false" if
399 // we can be sure it does not.
401 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
402 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
403 debug!(?obligation, "predicate_may_hold_fatal");
405 // This fatal query is a stopgap that should only be used in standard mode,
406 // where we do not expect overflow to be propagated.
407 assert!(self.query_mode == TraitQueryMode::Standard);
409 self.evaluate_root_obligation(obligation)
410 .expect("Overflow should be caught earlier in standard query mode")
414 /// Evaluates whether the obligation `obligation` can be satisfied
415 /// and returns an `EvaluationResult`. This is meant for the
417 pub fn evaluate_root_obligation(
419 obligation: &PredicateObligation<'tcx>,
420 ) -> Result<EvaluationResult, OverflowError> {
421 self.evaluation_probe(|this| {
422 this.evaluate_predicate_recursively(
423 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
431 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
432 ) -> Result<EvaluationResult, OverflowError> {
433 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
434 let result = op(self)?;
436 match self.infcx.leak_check(true, snapshot) {
438 Err(_) => return Ok(EvaluatedToErr),
441 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
443 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
448 /// Evaluates the predicates in `predicates` recursively. Note that
449 /// this applies projections in the predicates, and therefore
450 /// is run within an inference probe.
451 fn evaluate_predicates_recursively<'o, I>(
453 stack: TraitObligationStackList<'o, 'tcx>,
455 ) -> Result<EvaluationResult, OverflowError>
457 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
459 let mut result = EvaluatedToOk;
460 debug!(?predicates, "evaluate_predicates_recursively");
461 for obligation in predicates {
462 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
463 if let EvaluatedToErr = eval {
464 // fast-path - EvaluatedToErr is the top of the lattice,
465 // so we don't need to look on the other predicates.
466 return Ok(EvaluatedToErr);
468 result = cmp::max(result, eval);
476 skip(self, previous_stack),
477 fields(previous_stack = ?previous_stack.head())
479 fn evaluate_predicate_recursively<'o>(
481 previous_stack: TraitObligationStackList<'o, 'tcx>,
482 obligation: PredicateObligation<'tcx>,
483 ) -> Result<EvaluationResult, OverflowError> {
484 // `previous_stack` stores a `TraitObligation`, while `obligation` is
485 // a `PredicateObligation`. These are distinct types, so we can't
486 // use any `Option` combinator method that would force them to be
488 match previous_stack.head() {
489 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
490 None => self.check_recursion_limit(&obligation, &obligation)?,
493 let result = ensure_sufficient_stack(|| {
494 let bound_predicate = obligation.predicate.kind();
495 match bound_predicate.skip_binder() {
496 ty::PredicateKind::Trait(t) => {
497 let t = bound_predicate.rebind(t);
498 debug_assert!(!t.has_escaping_bound_vars());
499 let obligation = obligation.with(t);
500 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
503 ty::PredicateKind::Subtype(p) => {
504 let p = bound_predicate.rebind(p);
505 // Does this code ever run?
506 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
507 Some(Ok(InferOk { mut obligations, .. })) => {
508 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
509 self.evaluate_predicates_recursively(
511 obligations.into_iter(),
514 Some(Err(_)) => Ok(EvaluatedToErr),
515 None => Ok(EvaluatedToAmbig),
519 ty::PredicateKind::Coerce(p) => {
520 let p = bound_predicate.rebind(p);
521 // Does this code ever run?
522 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
523 Some(Ok(InferOk { mut obligations, .. })) => {
524 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
525 self.evaluate_predicates_recursively(
527 obligations.into_iter(),
530 Some(Err(_)) => Ok(EvaluatedToErr),
531 None => Ok(EvaluatedToAmbig),
535 ty::PredicateKind::WellFormed(arg) => match wf::obligations(
537 obligation.param_env,
538 obligation.cause.body_id,
539 obligation.recursion_depth + 1,
541 obligation.cause.span,
543 Some(mut obligations) => {
544 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
545 self.evaluate_predicates_recursively(previous_stack, obligations)
547 None => Ok(EvaluatedToAmbig),
550 ty::PredicateKind::TypeOutlives(pred) => {
551 if pred.0.is_known_global() {
554 Ok(EvaluatedToOkModuloRegions)
558 ty::PredicateKind::RegionOutlives(..) => {
559 // We do not consider region relationships when evaluating trait matches.
560 Ok(EvaluatedToOkModuloRegions)
563 ty::PredicateKind::ObjectSafe(trait_def_id) => {
564 if self.tcx().is_object_safe(trait_def_id) {
571 ty::PredicateKind::Projection(data) => {
572 let data = bound_predicate.rebind(data);
573 let project_obligation = obligation.with(data);
574 match project::poly_project_and_unify_type(self, &project_obligation) {
575 Ok(Ok(Some(mut subobligations))) => {
576 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
578 .evaluate_predicates_recursively(previous_stack, subobligations);
580 ProjectionCacheKey::from_poly_projection_predicate(self, data)
582 self.infcx.inner.borrow_mut().projection_cache().complete(key);
586 Ok(Ok(None)) => Ok(EvaluatedToAmbig),
587 Ok(Err(project::InProgress)) => Ok(EvaluatedToRecur),
588 Err(_) => Ok(EvaluatedToErr),
592 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
593 match self.infcx.closure_kind(closure_substs) {
594 Some(closure_kind) => {
595 if closure_kind.extends(kind) {
601 None => Ok(EvaluatedToAmbig),
605 ty::PredicateKind::ConstEvaluatable(uv) => {
606 match const_evaluatable::is_const_evaluatable(
609 obligation.param_env,
610 obligation.cause.span,
612 Ok(()) => Ok(EvaluatedToOk),
613 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
614 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
615 Err(_) => Ok(EvaluatedToErr),
619 ty::PredicateKind::ConstEquate(c1, c2) => {
620 debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
622 if self.tcx().features().generic_const_exprs {
623 // FIXME: we probably should only try to unify abstract constants
624 // if the constants depend on generic parameters.
626 // Let's just see where this breaks :shrug:
627 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
630 if self.infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
631 return Ok(EvaluatedToOk);
636 let evaluate = |c: &'tcx ty::Const<'tcx>| {
637 if let ty::ConstKind::Unevaluated(unevaluated) = c.val {
640 obligation.param_env,
642 Some(obligation.cause.span),
644 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty))
650 match (evaluate(c1), evaluate(c2)) {
651 (Ok(c1), Ok(c2)) => {
654 .at(&obligation.cause, obligation.param_env)
657 Ok(_) => Ok(EvaluatedToOk),
658 Err(_) => Ok(EvaluatedToErr),
661 (Err(ErrorHandled::Reported(ErrorReported)), _)
662 | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
663 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
665 obligation.cause.span(self.tcx()),
666 "ConstEquate: const_eval_resolve returned an unexpected error"
669 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
670 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
673 // Two different constants using generic parameters ~> error.
679 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
680 bug!("TypeWellFormedFromEnv is only used for chalk")
685 debug!("finished: {:?} from {:?}", result, obligation);
690 fn evaluate_trait_predicate_recursively<'o>(
692 previous_stack: TraitObligationStackList<'o, 'tcx>,
693 mut obligation: TraitObligation<'tcx>,
694 ) -> Result<EvaluationResult, OverflowError> {
695 debug!(?obligation, "evaluate_trait_predicate_recursively");
698 && obligation.is_global(self.tcx())
703 .all(|bound| bound.definitely_needs_subst(self.tcx()))
705 // If a param env has no global bounds, global obligations do not
706 // depend on its particular value in order to work, so we can clear
707 // out the param env and get better caching.
708 debug!("evaluate_trait_predicate_recursively - in global");
709 obligation.param_env = obligation.param_env.without_caller_bounds();
712 let stack = self.push_stack(previous_stack, &obligation);
713 let fresh_trait_ref = stack.fresh_trait_ref;
715 debug!(?fresh_trait_ref);
717 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
718 debug!(?result, "CACHE HIT");
722 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
723 debug!(?result, "PROVISIONAL CACHE HIT");
724 stack.update_reached_depth(result.reached_depth);
725 return Ok(result.result);
728 // Check if this is a match for something already on the
729 // stack. If so, we don't want to insert the result into the
730 // main cache (it is cycle dependent) nor the provisional
731 // cache (which is meant for things that have completed but
732 // for a "backedge" -- this result *is* the backedge).
733 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
734 return Ok(cycle_result);
737 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
738 let result = result?;
740 if !result.must_apply_modulo_regions() {
741 stack.cache().on_failure(stack.dfn);
744 let reached_depth = stack.reached_depth.get();
745 if reached_depth >= stack.depth {
746 debug!(?result, "CACHE MISS");
747 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
749 stack.cache().on_completion(stack.dfn, |fresh_trait_ref, provisional_result| {
750 self.insert_evaluation_cache(
751 obligation.param_env,
754 provisional_result.max(result),
758 debug!(?result, "PROVISIONAL");
760 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
761 is a cycle participant (at depth {}, reached depth {})",
762 fresh_trait_ref, stack.depth, reached_depth,
765 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
771 /// If there is any previous entry on the stack that precisely
772 /// matches this obligation, then we can assume that the
773 /// obligation is satisfied for now (still all other conditions
774 /// must be met of course). One obvious case this comes up is
775 /// marker traits like `Send`. Think of a linked list:
777 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
779 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
780 /// `Option<Box<List<T>>>` is `Send`, and in turn
781 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
784 /// Note that we do this comparison using the `fresh_trait_ref`
785 /// fields. Because these have all been freshened using
786 /// `self.freshener`, we can be sure that (a) this will not
787 /// affect the inferencer state and (b) that if we see two
788 /// fresh regions with the same index, they refer to the same
789 /// unbound type variable.
790 fn check_evaluation_cycle(
792 stack: &TraitObligationStack<'_, 'tcx>,
793 ) -> Option<EvaluationResult> {
794 if let Some(cycle_depth) = stack
796 .skip(1) // Skip top-most frame.
798 stack.obligation.param_env == prev.obligation.param_env
799 && stack.fresh_trait_ref == prev.fresh_trait_ref
801 .map(|stack| stack.depth)
803 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
805 // If we have a stack like `A B C D E A`, where the top of
806 // the stack is the final `A`, then this will iterate over
807 // `A, E, D, C, B` -- i.e., all the participants apart
808 // from the cycle head. We mark them as participating in a
809 // cycle. This suppresses caching for those nodes. See
810 // `in_cycle` field for more details.
811 stack.update_reached_depth(cycle_depth);
813 // Subtle: when checking for a coinductive cycle, we do
814 // not compare using the "freshened trait refs" (which
815 // have erased regions) but rather the fully explicit
816 // trait refs. This is important because it's only a cycle
817 // if the regions match exactly.
818 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
819 let tcx = self.tcx();
820 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
821 if self.coinductive_match(cycle) {
822 debug!("evaluate_stack --> recursive, coinductive");
825 debug!("evaluate_stack --> recursive, inductive");
826 Some(EvaluatedToRecur)
833 fn evaluate_stack<'o>(
835 stack: &TraitObligationStack<'o, 'tcx>,
836 ) -> Result<EvaluationResult, OverflowError> {
837 // In intercrate mode, whenever any of the generics are unbound,
838 // there can always be an impl. Even if there are no impls in
839 // this crate, perhaps the type would be unified with
840 // something from another crate that does provide an impl.
842 // In intra mode, we must still be conservative. The reason is
843 // that we want to avoid cycles. Imagine an impl like:
845 // impl<T:Eq> Eq for Vec<T>
847 // and a trait reference like `$0 : Eq` where `$0` is an
848 // unbound variable. When we evaluate this trait-reference, we
849 // will unify `$0` with `Vec<$1>` (for some fresh variable
850 // `$1`), on the condition that `$1 : Eq`. We will then wind
851 // up with many candidates (since that are other `Eq` impls
852 // that apply) and try to winnow things down. This results in
853 // a recursive evaluation that `$1 : Eq` -- as you can
854 // imagine, this is just where we started. To avoid that, we
855 // check for unbound variables and return an ambiguous (hence possible)
856 // match if we've seen this trait before.
858 // This suffices to allow chains like `FnMut` implemented in
859 // terms of `Fn` etc, but we could probably make this more
861 let unbound_input_types =
862 stack.fresh_trait_ref.value.skip_binder().substs.types().any(|ty| ty.is_fresh());
863 // This check was an imperfect workaround for a bug in the old
864 // intercrate mode; it should be removed when that goes away.
865 if unbound_input_types && self.intercrate {
866 debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
867 // Heuristics: show the diagnostics when there are no candidates in crate.
868 if self.intercrate_ambiguity_causes.is_some() {
869 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
870 if let Ok(candidate_set) = self.assemble_candidates(stack) {
871 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
872 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
873 let self_ty = trait_ref.self_ty();
875 with_no_trimmed_paths(|| IntercrateAmbiguityCause::DownstreamCrate {
876 trait_desc: trait_ref.print_only_trait_path().to_string(),
877 self_desc: if self_ty.has_concrete_skeleton() {
878 Some(self_ty.to_string())
884 debug!(?cause, "evaluate_stack: pushing cause");
885 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
889 return Ok(EvaluatedToAmbig);
891 if unbound_input_types
892 && stack.iter().skip(1).any(|prev| {
893 stack.obligation.param_env == prev.obligation.param_env
894 && self.match_fresh_trait_refs(
895 stack.fresh_trait_ref,
896 prev.fresh_trait_ref,
897 prev.obligation.param_env,
901 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
902 return Ok(EvaluatedToUnknown);
905 match self.candidate_from_obligation(stack) {
906 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
907 Ok(None) => Ok(EvaluatedToAmbig),
908 Err(Overflow) => Err(OverflowError),
909 Err(..) => Ok(EvaluatedToErr),
913 /// For defaulted traits, we use a co-inductive strategy to solve, so
914 /// that recursion is ok. This routine returns `true` if the top of the
915 /// stack (`cycle[0]`):
917 /// - is a defaulted trait,
918 /// - it also appears in the backtrace at some position `X`,
919 /// - all the predicates at positions `X..` between `X` and the top are
920 /// also defaulted traits.
921 pub fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
923 I: Iterator<Item = ty::Predicate<'tcx>>,
925 cycle.all(|predicate| self.coinductive_predicate(predicate))
928 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
929 let result = match predicate.kind().skip_binder() {
930 ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
933 debug!(?predicate, ?result, "coinductive_predicate");
937 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
938 /// obligations are met. Returns whether `candidate` remains viable after this further
943 fields(depth = stack.obligation.recursion_depth)
945 fn evaluate_candidate<'o>(
947 stack: &TraitObligationStack<'o, 'tcx>,
948 candidate: &SelectionCandidate<'tcx>,
949 ) -> Result<EvaluationResult, OverflowError> {
950 let mut result = self.evaluation_probe(|this| {
951 let candidate = (*candidate).clone();
952 match this.confirm_candidate(stack.obligation, candidate) {
955 this.evaluate_predicates_recursively(
957 selection.nested_obligations().into_iter(),
960 Err(..) => Ok(EvaluatedToErr),
964 // If we erased any lifetimes, then we want to use
965 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
966 // as your final result. The result will be cached using
967 // the freshened trait predicate as a key, so we need
968 // our result to be correct by *any* choice of original lifetimes,
969 // not just the lifetime choice for this particular (non-erased)
972 if stack.fresh_trait_ref.has_erased_regions() {
973 result = result.max(EvaluatedToOkModuloRegions);
980 fn check_evaluation_cache(
982 param_env: ty::ParamEnv<'tcx>,
983 trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
984 ) -> Option<EvaluationResult> {
985 let tcx = self.tcx();
986 if self.can_use_global_caches(param_env) {
987 if let Some(res) = tcx.evaluation_cache.get(¶m_env.and(trait_ref), tcx) {
991 self.infcx.evaluation_cache.get(¶m_env.and(trait_ref), tcx)
994 fn insert_evaluation_cache(
996 param_env: ty::ParamEnv<'tcx>,
997 trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
998 dep_node: DepNodeIndex,
999 result: EvaluationResult,
1001 // Avoid caching results that depend on more than just the trait-ref
1002 // - the stack can create recursion.
1003 if result.is_stack_dependent() {
1007 if self.can_use_global_caches(param_env) {
1008 if !trait_ref.needs_infer() {
1009 debug!(?trait_ref, ?result, "insert_evaluation_cache global");
1010 // This may overwrite the cache with the same value
1011 // FIXME: Due to #50507 this overwrites the different values
1012 // This should be changed to use HashMapExt::insert_same
1013 // when that is fixed
1014 self.tcx().evaluation_cache.insert(param_env.and(trait_ref), dep_node, result);
1019 debug!(?trait_ref, ?result, "insert_evaluation_cache");
1020 self.infcx.evaluation_cache.insert(param_env.and(trait_ref), dep_node, result);
1023 /// For various reasons, it's possible for a subobligation
1024 /// to have a *lower* recursion_depth than the obligation used to create it.
1025 /// Projection sub-obligations may be returned from the projection cache,
1026 /// which results in obligations with an 'old' `recursion_depth`.
1027 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1028 /// subobligations without taking in a 'parent' depth, causing the
1029 /// generated subobligations to have a `recursion_depth` of `0`.
1031 /// To ensure that obligation_depth never decreases, we force all subobligations
1032 /// to have at least the depth of the original obligation.
1033 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1038 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1041 /// Checks that the recursion limit has not been exceeded.
1043 /// The weird return type of this function allows it to be used with the `try` (`?`)
1044 /// operator within certain functions.
1045 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1047 obligation: &Obligation<'tcx, T>,
1048 error_obligation: &Obligation<'tcx, V>,
1049 ) -> Result<(), OverflowError> {
1050 if !self.infcx.tcx.recursion_limit().value_within_limit(obligation.recursion_depth) {
1051 match self.query_mode {
1052 TraitQueryMode::Standard => {
1053 self.infcx().report_overflow_error(error_obligation, true);
1055 TraitQueryMode::Canonical => {
1056 return Err(OverflowError);
1063 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1065 OP: FnOnce(&mut Self) -> R,
1067 let (result, dep_node) =
1068 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1069 self.tcx().dep_graph.read_index(dep_node);
1073 #[instrument(level = "debug", skip(self))]
1076 candidate: SelectionCandidate<'tcx>,
1077 obligation: &TraitObligation<'tcx>,
1078 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1079 let tcx = self.tcx();
1080 // Respect const trait obligations
1081 if self.is_trait_predicate_const(obligation.predicate.skip_binder()) {
1082 if Some(obligation.predicate.skip_binder().trait_ref.def_id)
1083 != tcx.lang_items().sized_trait()
1084 // const Sized bounds are skipped
1088 ImplCandidate(def_id)
1089 if tcx.impl_constness(def_id) == hir::Constness::Const => {}
1091 ParamCandidate(ty::ConstnessAnd {
1092 constness: ty::BoundConstness::ConstIfConst,
1096 AutoImplCandidate(..) => {}
1097 // generator, this will raise error in other places
1098 // or ignore error with const_async_blocks feature
1099 GeneratorCandidate => {}
1101 // reject all other types of candidates
1102 return Err(Unimplemented);
1107 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
1108 if let ImplCandidate(def_id) = candidate {
1109 match tcx.impl_polarity(def_id) {
1110 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
1111 return Err(Unimplemented);
1113 ty::ImplPolarity::Reservation => {
1114 if let Some(intercrate_ambiguity_clauses) =
1115 &mut self.intercrate_ambiguity_causes
1117 let attrs = tcx.get_attrs(def_id);
1118 let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
1119 let value = attr.and_then(|a| a.value_str());
1120 if let Some(value) = value {
1123 reservation impl ambiguity on {:?}",
1126 intercrate_ambiguity_clauses.push(
1127 IntercrateAmbiguityCause::ReservationImpl {
1128 message: value.to_string(),
1141 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1142 debug!("is_knowable(intercrate={:?})", self.intercrate);
1144 if !self.intercrate {
1148 let obligation = &stack.obligation;
1149 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1151 // Okay to skip binder because of the nature of the
1152 // trait-ref-is-knowable check, which does not care about
1154 let trait_ref = predicate.skip_binder().trait_ref;
1156 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1159 /// Returns `true` if the global caches can be used.
1160 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1161 // If there are any inference variables in the `ParamEnv`, then we
1162 // always use a cache local to this particular scope. Otherwise, we
1163 // switch to a global cache.
1164 if param_env.needs_infer() {
1168 // Avoid using the master cache during coherence and just rely
1169 // on the local cache. This effectively disables caching
1170 // during coherence. It is really just a simplification to
1171 // avoid us having to fear that coherence results "pollute"
1172 // the master cache. Since coherence executes pretty quickly,
1173 // it's not worth going to more trouble to increase the
1174 // hit-rate, I don't think.
1175 if self.intercrate {
1179 // Otherwise, we can use the global cache.
1183 fn check_candidate_cache(
1185 param_env: ty::ParamEnv<'tcx>,
1186 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1187 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1188 let tcx = self.tcx();
1189 let pred = &cache_fresh_trait_pred.skip_binder();
1190 let trait_ref = pred.trait_ref;
1191 if self.can_use_global_caches(param_env) {
1192 if let Some(res) = tcx
1194 .get(¶m_env.and(trait_ref).with_constness(pred.constness), tcx)
1201 .get(¶m_env.and(trait_ref).with_constness(pred.constness), tcx)
1204 /// Determines whether can we safely cache the result
1205 /// of selecting an obligation. This is almost always `true`,
1206 /// except when dealing with certain `ParamCandidate`s.
1208 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1209 /// since it was usually produced directly from a `DefId`. However,
1210 /// certain cases (currently only librustdoc's blanket impl finder),
1211 /// a `ParamEnv` may be explicitly constructed with inference types.
1212 /// When this is the case, we do *not* want to cache the resulting selection
1213 /// candidate. This is due to the fact that it might not always be possible
1214 /// to equate the obligation's trait ref and the candidate's trait ref,
1215 /// if more constraints end up getting added to an inference variable.
1217 /// Because of this, we always want to re-run the full selection
1218 /// process for our obligation the next time we see it, since
1219 /// we might end up picking a different `SelectionCandidate` (or none at all).
1220 fn can_cache_candidate(
1222 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1225 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1230 fn insert_candidate_cache(
1232 param_env: ty::ParamEnv<'tcx>,
1233 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1234 dep_node: DepNodeIndex,
1235 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1237 let tcx = self.tcx();
1238 let pred = cache_fresh_trait_pred.skip_binder();
1239 let trait_ref = pred.trait_ref;
1241 if !self.can_cache_candidate(&candidate) {
1242 debug!(?trait_ref, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1246 if self.can_use_global_caches(param_env) {
1247 if let Err(Overflow) = candidate {
1248 // Don't cache overflow globally; we only produce this in certain modes.
1249 } else if !trait_ref.needs_infer() {
1250 if !candidate.needs_infer() {
1251 debug!(?trait_ref, ?candidate, "insert_candidate_cache global");
1252 // This may overwrite the cache with the same value.
1253 tcx.selection_cache.insert(
1254 param_env.and(trait_ref).with_constness(pred.constness),
1263 debug!(?trait_ref, ?candidate, "insert_candidate_cache local");
1264 self.infcx.selection_cache.insert(
1265 param_env.and(trait_ref).with_constness(pred.constness),
1271 /// Matches a predicate against the bounds of its self type.
1273 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1274 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1275 /// `Baz` bound. We return indexes into the list returned by
1276 /// `tcx.item_bounds` for any applicable bounds.
1277 fn match_projection_obligation_against_definition_bounds(
1279 obligation: &TraitObligation<'tcx>,
1280 ) -> smallvec::SmallVec<[usize; 2]> {
1281 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1282 let placeholder_trait_predicate =
1283 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1285 ?placeholder_trait_predicate,
1286 "match_projection_obligation_against_definition_bounds"
1289 let tcx = self.infcx.tcx;
1290 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1291 ty::Projection(ref data) => (data.item_def_id, data.substs),
1292 ty::Opaque(def_id, substs) => (def_id, substs),
1295 obligation.cause.span,
1296 "match_projection_obligation_against_definition_bounds() called \
1297 but self-ty is not a projection: {:?}",
1298 placeholder_trait_predicate.trait_ref.self_ty()
1302 let bounds = tcx.item_bounds(def_id).subst(tcx, substs);
1304 // The bounds returned by `item_bounds` may contain duplicates after
1305 // normalization, so try to deduplicate when possible to avoid
1306 // unnecessary ambiguity.
1307 let mut distinct_normalized_bounds = FxHashSet::default();
1309 let matching_bounds = bounds
1312 .filter_map(|(idx, bound)| {
1313 let bound_predicate = bound.kind();
1314 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1315 let bound = bound_predicate.rebind(pred.trait_ref);
1316 if self.infcx.probe(|_| {
1317 match self.match_normalize_trait_ref(
1320 placeholder_trait_predicate.trait_ref,
1323 Ok(Some(normalized_trait))
1324 if distinct_normalized_bounds.insert(normalized_trait) =>
1338 debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds");
1342 /// Equates the trait in `obligation` with trait bound. If the two traits
1343 /// can be equated and the normalized trait bound doesn't contain inference
1344 /// variables or placeholders, the normalized bound is returned.
1345 fn match_normalize_trait_ref(
1347 obligation: &TraitObligation<'tcx>,
1348 trait_bound: ty::PolyTraitRef<'tcx>,
1349 placeholder_trait_ref: ty::TraitRef<'tcx>,
1350 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1351 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1352 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1353 // Avoid unnecessary normalization
1357 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1358 project::normalize_with_depth(
1360 obligation.param_env,
1361 obligation.cause.clone(),
1362 obligation.recursion_depth + 1,
1367 .at(&obligation.cause, obligation.param_env)
1368 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1369 .map(|InferOk { obligations: _, value: () }| {
1370 // This method is called within a probe, so we can't have
1371 // inference variables and placeholders escape.
1372 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1381 fn evaluate_where_clause<'o>(
1383 stack: &TraitObligationStack<'o, 'tcx>,
1384 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1385 ) -> Result<EvaluationResult, OverflowError> {
1386 self.evaluation_probe(|this| {
1387 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1388 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1389 Err(()) => Ok(EvaluatedToErr),
1394 pub(super) fn match_projection_projections(
1396 obligation: &ProjectionTyObligation<'tcx>,
1397 env_predicate: PolyProjectionPredicate<'tcx>,
1398 potentially_unnormalized_candidates: bool,
1400 let mut nested_obligations = Vec::new();
1401 let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars(
1402 obligation.cause.span,
1403 LateBoundRegionConversionTime::HigherRankedType,
1406 let infer_projection = if potentially_unnormalized_candidates {
1407 ensure_sufficient_stack(|| {
1408 project::normalize_with_depth_to(
1410 obligation.param_env,
1411 obligation.cause.clone(),
1412 obligation.recursion_depth + 1,
1413 infer_predicate.projection_ty,
1414 &mut nested_obligations,
1418 infer_predicate.projection_ty
1422 .at(&obligation.cause, obligation.param_env)
1423 .sup(obligation.predicate, infer_projection)
1424 .map_or(false, |InferOk { obligations, value: () }| {
1425 self.evaluate_predicates_recursively(
1426 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1427 nested_obligations.into_iter().chain(obligations),
1429 .map_or(false, |res| res.may_apply())
1433 ///////////////////////////////////////////////////////////////////////////
1436 // Winnowing is the process of attempting to resolve ambiguity by
1437 // probing further. During the winnowing process, we unify all
1438 // type variables and then we also attempt to evaluate recursive
1439 // bounds to see if they are satisfied.
1441 /// Returns `true` if `victim` should be dropped in favor of
1442 /// `other`. Generally speaking we will drop duplicate
1443 /// candidates and prefer where-clause candidates.
1445 /// See the comment for "SelectionCandidate" for more details.
1446 fn candidate_should_be_dropped_in_favor_of(
1448 victim: &EvaluatedCandidate<'tcx>,
1449 other: &EvaluatedCandidate<'tcx>,
1452 if victim.candidate == other.candidate {
1456 // Check if a bound would previously have been removed when normalizing
1457 // the param_env so that it can be given the lowest priority. See
1458 // #50825 for the motivation for this.
1460 |cand: &ty::PolyTraitRef<'_>| cand.is_known_global() && !cand.has_late_bound_regions();
1462 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1463 // and `DiscriminantKindCandidate` to anything else.
1465 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1466 // lifetime of a variable.
1467 match (&other.candidate, &victim.candidate) {
1468 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1470 "default implementations shouldn't be recorded \
1471 when there are other valid candidates"
1477 BuiltinCandidate { has_nested: false }
1478 | DiscriminantKindCandidate
1484 BuiltinCandidate { has_nested: false }
1485 | DiscriminantKindCandidate
1489 (ParamCandidate(other), ParamCandidate(victim)) => {
1490 let same_except_bound_vars = other.value.skip_binder()
1491 == victim.value.skip_binder()
1492 && other.constness == victim.constness
1493 && !other.value.skip_binder().has_escaping_bound_vars();
1494 if same_except_bound_vars {
1495 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1496 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1497 // or the current one if tied (they should both evaluate to the same answer). This is
1498 // probably best characterized as a "hack", since we might prefer to just do our
1499 // best to *not* create essentially duplicate candidates in the first place.
1500 other.value.bound_vars().len() <= victim.value.bound_vars().len()
1501 } else if other.value == victim.value
1502 && victim.constness == ty::BoundConstness::NotConst
1504 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1511 // Global bounds from the where clause should be ignored
1512 // here (see issue #50825). Otherwise, we have a where
1513 // clause so don't go around looking for impls.
1514 // Arbitrarily give param candidates priority
1515 // over projection and object candidates.
1517 ParamCandidate(ref cand),
1520 | GeneratorCandidate
1521 | FnPointerCandidate
1522 | BuiltinObjectCandidate
1523 | BuiltinUnsizeCandidate
1524 | TraitUpcastingUnsizeCandidate(_)
1525 | BuiltinCandidate { .. }
1526 | TraitAliasCandidate(..)
1527 | ObjectCandidate(_)
1528 | ProjectionCandidate(_),
1529 ) => !is_global(&cand.value),
1530 (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1531 // Prefer these to a global where-clause bound
1532 // (see issue #50825).
1533 is_global(&cand.value)
1538 | GeneratorCandidate
1539 | FnPointerCandidate
1540 | BuiltinObjectCandidate
1541 | BuiltinUnsizeCandidate
1542 | TraitUpcastingUnsizeCandidate(_)
1543 | BuiltinCandidate { has_nested: true }
1544 | TraitAliasCandidate(..),
1545 ParamCandidate(ref cand),
1547 // Prefer these to a global where-clause bound
1548 // (see issue #50825).
1549 is_global(&cand.value) && other.evaluation.must_apply_modulo_regions()
1552 (ProjectionCandidate(i), ProjectionCandidate(j))
1553 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1554 // Arbitrarily pick the lower numbered candidate for backwards
1555 // compatibility reasons. Don't let this affect inference.
1556 i < j && !needs_infer
1558 (ObjectCandidate(_), ProjectionCandidate(_))
1559 | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1560 bug!("Have both object and projection candidate")
1563 // Arbitrarily give projection and object candidates priority.
1565 ObjectCandidate(_) | ProjectionCandidate(_),
1568 | GeneratorCandidate
1569 | FnPointerCandidate
1570 | BuiltinObjectCandidate
1571 | BuiltinUnsizeCandidate
1572 | TraitUpcastingUnsizeCandidate(_)
1573 | BuiltinCandidate { .. }
1574 | TraitAliasCandidate(..),
1580 | GeneratorCandidate
1581 | FnPointerCandidate
1582 | BuiltinObjectCandidate
1583 | BuiltinUnsizeCandidate
1584 | TraitUpcastingUnsizeCandidate(_)
1585 | BuiltinCandidate { .. }
1586 | TraitAliasCandidate(..),
1587 ObjectCandidate(_) | ProjectionCandidate(_),
1590 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1591 // See if we can toss out `victim` based on specialization.
1592 // This requires us to know *for sure* that the `other` impl applies
1593 // i.e., `EvaluatedToOk`.
1595 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1596 // to me but is required for `std` to compile, so I didn't change it
1598 let tcx = self.tcx();
1599 if other.evaluation.must_apply_modulo_regions() {
1600 if tcx.specializes((other_def, victim_def)) {
1605 if other.evaluation.must_apply_considering_regions() {
1606 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1607 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1608 // Subtle: If the predicate we are evaluating has inference
1609 // variables, do *not* allow discarding candidates due to
1610 // marker trait impls.
1612 // Without this restriction, we could end up accidentally
1613 // constrainting inference variables based on an arbitrarily
1614 // chosen trait impl.
1616 // Imagine we have the following code:
1619 // #[marker] trait MyTrait {}
1620 // impl MyTrait for u8 {}
1621 // impl MyTrait for bool {}
1624 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1626 // During selection, we will end up with one candidate for each
1627 // impl of `MyTrait`. If we were to discard one impl in favor
1628 // of the other, we would be left with one candidate, causing
1629 // us to "successfully" select the predicate, unifying
1630 // _#0t with (for example) `u8`.
1632 // However, we have no reason to believe that this unification
1633 // is correct - we've essentially just picked an arbitrary
1634 // *possibility* for _#0t, and required that this be the *only*
1637 // Eventually, we will either:
1638 // 1) Unify all inference variables in the predicate through
1639 // some other means (e.g. type-checking of a function). We will
1640 // then be in a position to drop marker trait candidates
1641 // without constraining inference variables (since there are
1642 // none left to constrin)
1643 // 2) Be left with some unconstrained inference variables. We
1644 // will then correctly report an inference error, since the
1645 // existence of multiple marker trait impls tells us nothing
1646 // about which one should actually apply.
1657 // Everything else is ambiguous
1661 | GeneratorCandidate
1662 | FnPointerCandidate
1663 | BuiltinObjectCandidate
1664 | BuiltinUnsizeCandidate
1665 | TraitUpcastingUnsizeCandidate(_)
1666 | BuiltinCandidate { has_nested: true }
1667 | TraitAliasCandidate(..),
1670 | GeneratorCandidate
1671 | FnPointerCandidate
1672 | BuiltinObjectCandidate
1673 | BuiltinUnsizeCandidate
1674 | TraitUpcastingUnsizeCandidate(_)
1675 | BuiltinCandidate { has_nested: true }
1676 | TraitAliasCandidate(..),
1681 fn sized_conditions(
1683 obligation: &TraitObligation<'tcx>,
1684 ) -> BuiltinImplConditions<'tcx> {
1685 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1687 // NOTE: binder moved to (*)
1688 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1690 match self_ty.kind() {
1691 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1702 | ty::GeneratorWitness(..)
1707 // safe for everything
1708 Where(ty::Binder::dummy(Vec::new()))
1711 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1713 ty::Tuple(tys) => Where(
1716 .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()),
1719 ty::Adt(def, substs) => {
1720 let sized_crit = def.sized_constraint(self.tcx());
1721 // (*) binder moved here
1723 obligation.predicate.rebind({
1724 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1729 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1730 ty::Infer(ty::TyVar(_)) => Ambiguous,
1734 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1735 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1740 fn copy_clone_conditions(
1742 obligation: &TraitObligation<'tcx>,
1743 ) -> BuiltinImplConditions<'tcx> {
1744 // NOTE: binder moved to (*)
1745 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1747 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1749 match *self_ty.kind() {
1750 ty::Infer(ty::IntVar(_))
1751 | ty::Infer(ty::FloatVar(_))
1754 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1763 | ty::Ref(_, _, hir::Mutability::Not) => {
1764 // Implementations provided in libcore
1772 | ty::GeneratorWitness(..)
1774 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1776 ty::Array(element_ty, _) => {
1777 // (*) binder moved here
1778 Where(obligation.predicate.rebind(vec![element_ty]))
1782 // (*) binder moved here
1783 Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect()))
1786 ty::Closure(_, substs) => {
1787 // (*) binder moved here
1788 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1789 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1790 // Not yet resolved.
1793 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1797 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1798 // Fallback to whatever user-defined impls exist in this case.
1802 ty::Infer(ty::TyVar(_)) => {
1803 // Unbound type variable. Might or might not have
1804 // applicable impls and so forth, depending on what
1805 // those type variables wind up being bound to.
1811 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1812 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1817 /// For default impls, we need to break apart a type into its
1818 /// "constituent types" -- meaning, the types that it contains.
1820 /// Here are some (simple) examples:
1823 /// (i32, u32) -> [i32, u32]
1824 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1825 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1826 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1828 fn constituent_types_for_ty(
1830 t: ty::Binder<'tcx, Ty<'tcx>>,
1831 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1832 match *t.skip_binder().kind() {
1841 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1843 | ty::Char => ty::Binder::dummy(Vec::new()),
1849 | ty::Projection(..)
1851 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1852 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1855 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1856 t.rebind(vec![element_ty])
1859 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
1861 ty::Tuple(ref tys) => {
1862 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1863 t.rebind(tys.iter().map(|k| k.expect_ty()).collect())
1866 ty::Closure(_, ref substs) => {
1867 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1871 ty::Generator(_, ref substs, _) => {
1872 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
1873 let witness = substs.as_generator().witness();
1874 t.rebind(vec![ty].into_iter().chain(iter::once(witness)).collect())
1877 ty::GeneratorWitness(types) => {
1878 debug_assert!(!types.has_escaping_bound_vars());
1879 types.map_bound(|types| types.to_vec())
1882 // For `PhantomData<T>`, we pass `T`.
1883 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
1885 ty::Adt(def, substs) => {
1886 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
1889 ty::Opaque(def_id, substs) => {
1890 // We can resolve the `impl Trait` to its concrete type,
1891 // which enforces a DAG between the functions requiring
1892 // the auto trait bounds in question.
1893 t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
1898 fn collect_predicates_for_types(
1900 param_env: ty::ParamEnv<'tcx>,
1901 cause: ObligationCause<'tcx>,
1902 recursion_depth: usize,
1903 trait_def_id: DefId,
1904 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
1905 ) -> Vec<PredicateObligation<'tcx>> {
1906 // Because the types were potentially derived from
1907 // higher-ranked obligations they may reference late-bound
1908 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
1909 // yield a type like `for<'a> &'a i32`. In general, we
1910 // maintain the invariant that we never manipulate bound
1911 // regions, so we have to process these bound regions somehow.
1913 // The strategy is to:
1915 // 1. Instantiate those regions to placeholder regions (e.g.,
1916 // `for<'a> &'a i32` becomes `&0 i32`.
1917 // 2. Produce something like `&'0 i32 : Copy`
1918 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
1922 .skip_binder() // binder moved -\
1925 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(ty); // <----/
1927 self.infcx.commit_unconditionally(|_| {
1928 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
1929 let Normalized { value: normalized_ty, mut obligations } =
1930 ensure_sufficient_stack(|| {
1931 project::normalize_with_depth(
1939 let placeholder_obligation = predicate_for_trait_def(
1948 obligations.push(placeholder_obligation);
1955 ///////////////////////////////////////////////////////////////////////////
1958 // Matching is a common path used for both evaluation and
1959 // confirmation. It basically unifies types that appear in impls
1960 // and traits. This does affect the surrounding environment;
1961 // therefore, when used during evaluation, match routines must be
1962 // run inside of a `probe()` so that their side-effects are
1968 obligation: &TraitObligation<'tcx>,
1969 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
1970 match self.match_impl(impl_def_id, obligation) {
1971 Ok(substs) => substs,
1974 "Impl {:?} was matchable against {:?} but now is not",
1982 #[tracing::instrument(level = "debug", skip(self))]
1986 obligation: &TraitObligation<'tcx>,
1987 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
1988 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
1990 // Before we create the substitutions and everything, first
1991 // consider a "quick reject". This avoids creating more types
1992 // and so forth that we need to.
1993 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
1997 let placeholder_obligation =
1998 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
1999 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2001 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2003 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2005 debug!(?impl_trait_ref);
2007 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2008 ensure_sufficient_stack(|| {
2009 project::normalize_with_depth(
2011 obligation.param_env,
2012 obligation.cause.clone(),
2013 obligation.recursion_depth + 1,
2018 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2020 let cause = ObligationCause::new(
2021 obligation.cause.span,
2022 obligation.cause.body_id,
2023 ObligationCauseCode::MatchImpl(Lrc::new(obligation.cause.code.clone()), impl_def_id),
2026 let InferOk { obligations, .. } = self
2028 .at(&cause, obligation.param_env)
2029 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2030 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2031 nested_obligations.extend(obligations);
2034 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2036 debug!("match_impl: reservation impls only apply in intercrate mode");
2040 debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2041 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2044 fn fast_reject_trait_refs(
2046 obligation: &TraitObligation<'_>,
2047 impl_trait_ref: &ty::TraitRef<'_>,
2049 // We can avoid creating type variables and doing the full
2050 // substitution if we find that any of the input types, when
2051 // simplified, do not match.
2053 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
2054 |(obligation_arg, impl_arg)| {
2055 match (obligation_arg.unpack(), impl_arg.unpack()) {
2056 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
2057 let simplified_obligation_ty =
2058 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2059 let simplified_impl_ty =
2060 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2062 simplified_obligation_ty.is_some()
2063 && simplified_impl_ty.is_some()
2064 && simplified_obligation_ty != simplified_impl_ty
2066 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
2067 // Lifetimes can never cause a rejection.
2070 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
2071 // Conservatively ignore consts (i.e. assume they might
2072 // unify later) until we have `fast_reject` support for
2073 // them (if we'll ever need it, even).
2076 _ => unreachable!(),
2082 /// Normalize `where_clause_trait_ref` and try to match it against
2083 /// `obligation`. If successful, return any predicates that
2084 /// result from the normalization.
2085 fn match_where_clause_trait_ref(
2087 obligation: &TraitObligation<'tcx>,
2088 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2089 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2090 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2093 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2094 /// obligation is satisfied.
2095 fn match_poly_trait_ref(
2097 obligation: &TraitObligation<'tcx>,
2098 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2099 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2100 debug!(?obligation, ?poly_trait_ref, "match_poly_trait_ref");
2103 .at(&obligation.cause, obligation.param_env)
2104 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2105 .map(|InferOk { obligations, .. }| obligations)
2109 ///////////////////////////////////////////////////////////////////////////
2112 fn match_fresh_trait_refs(
2114 previous: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2115 current: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2116 param_env: ty::ParamEnv<'tcx>,
2118 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2119 matcher.relate(previous, current).is_ok()
2124 previous_stack: TraitObligationStackList<'o, 'tcx>,
2125 obligation: &'o TraitObligation<'tcx>,
2126 ) -> TraitObligationStack<'o, 'tcx> {
2127 let fresh_trait_ref = obligation
2129 .to_poly_trait_ref()
2130 .fold_with(&mut self.freshener)
2131 .with_constness(obligation.predicate.skip_binder().constness);
2133 let dfn = previous_stack.cache.next_dfn();
2134 let depth = previous_stack.depth() + 1;
2135 TraitObligationStack {
2138 reached_depth: Cell::new(depth),
2139 previous: previous_stack,
2145 fn closure_trait_ref_unnormalized(
2147 obligation: &TraitObligation<'tcx>,
2148 substs: SubstsRef<'tcx>,
2149 ) -> ty::PolyTraitRef<'tcx> {
2150 debug!(?obligation, ?substs, "closure_trait_ref_unnormalized");
2151 let closure_sig = substs.as_closure().sig();
2153 debug!(?closure_sig);
2155 // (1) Feels icky to skip the binder here, but OTOH we know
2156 // that the self-type is an unboxed closure type and hence is
2157 // in fact unparameterized (or at least does not reference any
2158 // regions bound in the obligation). Still probably some
2159 // refactoring could make this nicer.
2160 closure_trait_ref_and_return_type(
2162 obligation.predicate.def_id(),
2163 obligation.predicate.skip_binder().self_ty(), // (1)
2165 util::TupleArgumentsFlag::No,
2167 .map_bound(|(trait_ref, _)| trait_ref)
2170 fn generator_trait_ref_unnormalized(
2172 obligation: &TraitObligation<'tcx>,
2173 substs: SubstsRef<'tcx>,
2174 ) -> ty::PolyTraitRef<'tcx> {
2175 let gen_sig = substs.as_generator().poly_sig();
2177 // (1) Feels icky to skip the binder here, but OTOH we know
2178 // that the self-type is an generator type and hence is
2179 // in fact unparameterized (or at least does not reference any
2180 // regions bound in the obligation). Still probably some
2181 // refactoring could make this nicer.
2183 super::util::generator_trait_ref_and_outputs(
2185 obligation.predicate.def_id(),
2186 obligation.predicate.skip_binder().self_ty(), // (1)
2189 .map_bound(|(trait_ref, ..)| trait_ref)
2192 /// Returns the obligations that are implied by instantiating an
2193 /// impl or trait. The obligations are substituted and fully
2194 /// normalized. This is used when confirming an impl or default
2196 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2197 fn impl_or_trait_obligations(
2199 cause: ObligationCause<'tcx>,
2200 recursion_depth: usize,
2201 param_env: ty::ParamEnv<'tcx>,
2202 def_id: DefId, // of impl or trait
2203 substs: SubstsRef<'tcx>, // for impl or trait
2204 ) -> Vec<PredicateObligation<'tcx>> {
2205 let tcx = self.tcx();
2207 // To allow for one-pass evaluation of the nested obligation,
2208 // each predicate must be preceded by the obligations required
2210 // for example, if we have:
2211 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2212 // the impl will have the following predicates:
2213 // <V as Iterator>::Item = U,
2214 // U: Iterator, U: Sized,
2215 // V: Iterator, V: Sized,
2216 // <U as Iterator>::Item: Copy
2217 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2218 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2219 // `$1: Copy`, so we must ensure the obligations are emitted in
2221 let predicates = tcx.predicates_of(def_id);
2222 debug!(?predicates);
2223 assert_eq!(predicates.parent, None);
2224 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2225 for (predicate, _) in predicates.predicates {
2227 let predicate = normalize_with_depth_to(
2232 predicate.subst(tcx, substs),
2235 obligations.push(Obligation {
2236 cause: cause.clone(),
2243 // We are performing deduplication here to avoid exponential blowups
2244 // (#38528) from happening, but the real cause of the duplication is
2245 // unknown. What we know is that the deduplication avoids exponential
2246 // amount of predicates being propagated when processing deeply nested
2249 // This code is hot enough that it's worth avoiding the allocation
2250 // required for the FxHashSet when possible. Special-casing lengths 0,
2251 // 1 and 2 covers roughly 75-80% of the cases.
2252 if obligations.len() <= 1 {
2253 // No possibility of duplicates.
2254 } else if obligations.len() == 2 {
2255 // Only two elements. Drop the second if they are equal.
2256 if obligations[0] == obligations[1] {
2257 obligations.truncate(1);
2260 // Three or more elements. Use a general deduplication process.
2261 let mut seen = FxHashSet::default();
2262 obligations.retain(|i| seen.insert(i.clone()));
2269 trait TraitObligationExt<'tcx> {
2272 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2273 ) -> ObligationCause<'tcx>;
2276 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2279 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2280 ) -> ObligationCause<'tcx> {
2282 * Creates a cause for obligations that are derived from
2283 * `obligation` by a recursive search (e.g., for a builtin
2284 * bound, or eventually a `auto trait Foo`). If `obligation`
2285 * is itself a derived obligation, this is just a clone, but
2286 * otherwise we create a "derived obligation" cause so as to
2287 * keep track of the original root obligation for error
2291 let obligation = self;
2293 // NOTE(flaper87): As of now, it keeps track of the whole error
2294 // chain. Ideally, we should have a way to configure this either
2295 // by using -Z verbose or just a CLI argument.
2296 let derived_cause = DerivedObligationCause {
2297 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2298 parent_code: Lrc::new(obligation.cause.code.clone()),
2300 let derived_code = variant(derived_cause);
2301 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2305 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2306 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2307 TraitObligationStackList::with(self)
2310 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2314 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2318 /// Indicates that attempting to evaluate this stack entry
2319 /// required accessing something from the stack at depth `reached_depth`.
2320 fn update_reached_depth(&self, reached_depth: usize) {
2322 self.depth >= reached_depth,
2323 "invoked `update_reached_depth` with something under this stack: \
2324 self.depth={} reached_depth={}",
2328 debug!(reached_depth, "update_reached_depth");
2330 while reached_depth < p.depth {
2331 debug!(?p.fresh_trait_ref, "update_reached_depth: marking as cycle participant");
2332 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2333 p = p.previous.head.unwrap();
2338 /// The "provisional evaluation cache" is used to store intermediate cache results
2339 /// when solving auto traits. Auto traits are unusual in that they can support
2340 /// cycles. So, for example, a "proof tree" like this would be ok:
2342 /// - `Foo<T>: Send` :-
2343 /// - `Bar<T>: Send` :-
2344 /// - `Foo<T>: Send` -- cycle, but ok
2345 /// - `Baz<T>: Send`
2347 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2348 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2349 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2350 /// they are coinductive) it is considered ok.
2352 /// However, there is a complication: at the point where we have
2353 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2354 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2355 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2356 /// find out this assumption is wrong? Specifically, we could
2357 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2358 /// `Bar<T>: Send` didn't turn out to be true.
2360 /// In Issue #60010, we found a bug in rustc where it would cache
2361 /// these intermediate results. This was fixed in #60444 by disabling
2362 /// *all* caching for things involved in a cycle -- in our example,
2363 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2364 /// to large slowdowns.
2366 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2367 /// first requires proving `Bar<T>: Send` (which is true:
2369 /// - `Foo<T>: Send` :-
2370 /// - `Bar<T>: Send` :-
2371 /// - `Foo<T>: Send` -- cycle, but ok
2372 /// - `Baz<T>: Send`
2373 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2374 /// - `*const T: Send` -- but what if we later encounter an error?
2376 /// The *provisional evaluation cache* resolves this issue. It stores
2377 /// cache results that we've proven but which were involved in a cycle
2378 /// in some way. We track the minimal stack depth (i.e., the
2379 /// farthest from the top of the stack) that we are dependent on.
2380 /// The idea is that the cache results within are all valid -- so long as
2381 /// none of the nodes in between the current node and the node at that minimum
2382 /// depth result in an error (in which case the cached results are just thrown away).
2384 /// During evaluation, we consult this provisional cache and rely on
2385 /// it. Accessing a cached value is considered equivalent to accessing
2386 /// a result at `reached_depth`, so it marks the *current* solution as
2387 /// provisional as well. If an error is encountered, we toss out any
2388 /// provisional results added from the subtree that encountered the
2389 /// error. When we pop the node at `reached_depth` from the stack, we
2390 /// can commit all the things that remain in the provisional cache.
2391 struct ProvisionalEvaluationCache<'tcx> {
2392 /// next "depth first number" to issue -- just a counter
2395 /// Map from cache key to the provisionally evaluated thing.
2396 /// The cache entries contain the result but also the DFN in which they
2397 /// were added. The DFN is used to clear out values on failure.
2399 /// Imagine we have a stack like:
2401 /// - `A B C` and we add a cache for the result of C (DFN 2)
2402 /// - Then we have a stack `A B D` where `D` has DFN 3
2403 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2404 /// - `E` generates various cache entries which have cyclic dependices on `B`
2405 /// - `A B D E F` and so forth
2406 /// - the DFN of `F` for example would be 5
2407 /// - then we determine that `E` is in error -- we will then clear
2408 /// all cache values whose DFN is >= 4 -- in this case, that
2409 /// means the cached value for `F`.
2410 map: RefCell<FxHashMap<ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, ProvisionalEvaluation>>,
2413 /// A cache value for the provisional cache: contains the depth-first
2414 /// number (DFN) and result.
2415 #[derive(Copy, Clone, Debug)]
2416 struct ProvisionalEvaluation {
2418 reached_depth: usize,
2419 result: EvaluationResult,
2422 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2423 fn default() -> Self {
2424 Self { dfn: Cell::new(0), map: Default::default() }
2428 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2429 /// Get the next DFN in sequence (basically a counter).
2430 fn next_dfn(&self) -> usize {
2431 let result = self.dfn.get();
2432 self.dfn.set(result + 1);
2436 /// Check the provisional cache for any result for
2437 /// `fresh_trait_ref`. If there is a hit, then you must consider
2438 /// it an access to the stack slots at depth
2439 /// `reached_depth` (from the returned value).
2442 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2443 ) -> Option<ProvisionalEvaluation> {
2446 "get_provisional = {:#?}",
2447 self.map.borrow().get(&fresh_trait_ref),
2449 Some(*self.map.borrow().get(&fresh_trait_ref)?)
2452 /// Insert a provisional result into the cache. The result came
2453 /// from the node with the given DFN. It accessed a minimum depth
2454 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
2455 /// and resulted in `result`.
2456 fn insert_provisional(
2459 reached_depth: usize,
2460 fresh_trait_ref: ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>,
2461 result: EvaluationResult,
2463 debug!(?from_dfn, ?fresh_trait_ref, ?result, "insert_provisional");
2465 let mut map = self.map.borrow_mut();
2467 // Subtle: when we complete working on the DFN `from_dfn`, anything
2468 // that remains in the provisional cache must be dependent on some older
2469 // stack entry than `from_dfn`. We have to update their depth with our transitive
2470 // depth in that case or else it would be referring to some popped note.
2473 // A (reached depth 0)
2475 // B // depth 1 -- reached depth = 0
2476 // C // depth 2 -- reached depth = 1 (should be 0)
2479 // D (reached depth 1)
2480 // C (cache -- reached depth = 2)
2481 for (_k, v) in &mut *map {
2482 if v.from_dfn >= from_dfn {
2483 v.reached_depth = reached_depth.min(v.reached_depth);
2487 map.insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, reached_depth, result });
2490 /// Invoked when the node with dfn `dfn` does not get a successful
2491 /// result. This will clear out any provisional cache entries
2492 /// that were added since `dfn` was created. This is because the
2493 /// provisional entries are things which must assume that the
2494 /// things on the stack at the time of their creation succeeded --
2495 /// since the failing node is presently at the top of the stack,
2496 /// these provisional entries must either depend on it or some
2498 fn on_failure(&self, dfn: usize) {
2499 debug!(?dfn, "on_failure");
2500 self.map.borrow_mut().retain(|key, eval| {
2501 if !eval.from_dfn >= dfn {
2502 debug!("on_failure: removing {:?}", key);
2510 /// Invoked when the node at depth `depth` completed without
2511 /// depending on anything higher in the stack (if that completion
2512 /// was a failure, then `on_failure` should have been invoked
2513 /// already). The callback `op` will be invoked for each
2514 /// provisional entry that we can now confirm.
2516 /// Note that we may still have provisional cache items remaining
2517 /// in the cache when this is done. For example, if there is a
2520 /// * A depends on...
2521 /// * B depends on A
2522 /// * C depends on...
2523 /// * D depends on C
2526 /// Then as we complete the C node we will have a provisional cache
2527 /// with results for A, B, C, and D. This method would clear out
2528 /// the C and D results, but leave A and B provisional.
2530 /// This is determined based on the DFN: we remove any provisional
2531 /// results created since `dfn` started (e.g., in our example, dfn
2532 /// would be 2, representing the C node, and hence we would
2533 /// remove the result for D, which has DFN 3, but not the results for
2534 /// A and B, which have DFNs 0 and 1 respectively).
2538 mut op: impl FnMut(ty::ConstnessAnd<ty::PolyTraitRef<'tcx>>, EvaluationResult),
2540 debug!(?dfn, "on_completion");
2542 for (fresh_trait_ref, eval) in
2543 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2545 debug!(?fresh_trait_ref, ?eval, "on_completion");
2547 op(fresh_trait_ref, eval.result);
2552 #[derive(Copy, Clone)]
2553 struct TraitObligationStackList<'o, 'tcx> {
2554 cache: &'o ProvisionalEvaluationCache<'tcx>,
2555 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2558 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2559 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2560 TraitObligationStackList { cache, head: None }
2563 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2564 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2567 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2571 fn depth(&self) -> usize {
2572 if let Some(head) = self.head { head.depth } else { 0 }
2576 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2577 type Item = &'o TraitObligationStack<'o, 'tcx>;
2579 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2586 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2587 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2588 write!(f, "TraitObligationStack({:?})", self.obligation)