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 crate::traits::project::ProjectionCacheKeyExt;
29 use crate::traits::ProjectionCacheKey;
30 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
31 use rustc_data_structures::stack::ensure_sufficient_stack;
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::{self, SimplifyParams, StripReferences};
40 use rustc_middle::ty::fold::BottomUpFolder;
41 use rustc_middle::ty::print::with_no_trimmed_paths;
42 use rustc_middle::ty::relate::TypeRelation;
43 use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef};
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 /// The mode that trait queries run in, which informs our error handling
133 /// policy. In essence, canonicalized queries need their errors propagated
134 /// rather than immediately reported because we do not have accurate spans.
135 query_mode: TraitQueryMode,
138 // A stack that walks back up the stack frame.
139 struct TraitObligationStack<'prev, 'tcx> {
140 obligation: &'prev TraitObligation<'tcx>,
142 /// The trait predicate from `obligation` but "freshened" with the
143 /// selection-context's freshener. Used to check for recursion.
144 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
146 /// Starts out equal to `depth` -- if, during evaluation, we
147 /// encounter a cycle, then we will set this flag to the minimum
148 /// depth of that cycle for all participants in the cycle. These
149 /// participants will then forego caching their results. This is
150 /// not the most efficient solution, but it addresses #60010. The
151 /// problem we are trying to prevent:
153 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
154 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
155 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
157 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
158 /// is `EvaluatedToOk`; this is because they were only considered
159 /// ok on the premise that if `A: AutoTrait` held, but we indeed
160 /// encountered a problem (later on) with `A: AutoTrait. So we
161 /// currently set a flag on the stack node for `B: AutoTrait` (as
162 /// well as the second instance of `A: AutoTrait`) to suppress
165 /// This is a simple, targeted fix. A more-performant fix requires
166 /// deeper changes, but would permit more caching: we could
167 /// basically defer caching until we have fully evaluated the
168 /// tree, and then cache the entire tree at once. In any case, the
169 /// performance impact here shouldn't be so horrible: every time
170 /// this is hit, we do cache at least one trait, so we only
171 /// evaluate each member of a cycle up to N times, where N is the
172 /// length of the cycle. This means the performance impact is
173 /// bounded and we shouldn't have any terrible worst-cases.
174 reached_depth: Cell<usize>,
176 previous: TraitObligationStackList<'prev, 'tcx>,
178 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
181 /// The depth-first number of this node in the search graph -- a
182 /// pre-order index. Basically, a freshly incremented counter.
186 struct SelectionCandidateSet<'tcx> {
187 // A list of candidates that definitely apply to the current
188 // obligation (meaning: types unify).
189 vec: Vec<SelectionCandidate<'tcx>>,
191 // If `true`, then there were candidates that might or might
192 // not have applied, but we couldn't tell. This occurs when some
193 // of the input types are type variables, in which case there are
194 // various "builtin" rules that might or might not trigger.
198 #[derive(PartialEq, Eq, Debug, Clone)]
199 struct EvaluatedCandidate<'tcx> {
200 candidate: SelectionCandidate<'tcx>,
201 evaluation: EvaluationResult,
204 /// When does the builtin impl for `T: Trait` apply?
206 enum BuiltinImplConditions<'tcx> {
207 /// The impl is conditional on `T1, T2, ...: Trait`.
208 Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
209 /// There is no built-in impl. There may be some other
210 /// candidate (a where-clause or user-defined impl).
212 /// It is unknown whether there is an impl.
216 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
217 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
220 freshener: infcx.freshener_keep_static(),
222 intercrate_ambiguity_causes: None,
223 allow_negative_impls: false,
224 query_mode: TraitQueryMode::Standard,
228 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
231 freshener: infcx.freshener_keep_static(),
233 intercrate_ambiguity_causes: None,
234 allow_negative_impls: false,
235 query_mode: TraitQueryMode::Standard,
239 pub fn with_negative(
240 infcx: &'cx InferCtxt<'cx, 'tcx>,
241 allow_negative_impls: bool,
242 ) -> SelectionContext<'cx, 'tcx> {
243 debug!(?allow_negative_impls, "with_negative");
246 freshener: infcx.freshener_keep_static(),
248 intercrate_ambiguity_causes: None,
249 allow_negative_impls,
250 query_mode: TraitQueryMode::Standard,
254 pub fn with_query_mode(
255 infcx: &'cx InferCtxt<'cx, 'tcx>,
256 query_mode: TraitQueryMode,
257 ) -> SelectionContext<'cx, 'tcx> {
258 debug!(?query_mode, "with_query_mode");
261 freshener: infcx.freshener_keep_static(),
263 intercrate_ambiguity_causes: None,
264 allow_negative_impls: false,
269 /// Enables tracking of intercrate ambiguity causes. These are
270 /// used in coherence to give improved diagnostics. We don't do
271 /// this until we detect a coherence error because it can lead to
272 /// false overflow results (#47139) and because it costs
273 /// computation time.
274 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
275 assert!(self.intercrate);
276 assert!(self.intercrate_ambiguity_causes.is_none());
277 self.intercrate_ambiguity_causes = Some(vec![]);
278 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
281 /// Gets the intercrate ambiguity causes collected since tracking
282 /// was enabled and disables tracking at the same time. If
283 /// tracking is not enabled, just returns an empty vector.
284 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
285 assert!(self.intercrate);
286 self.intercrate_ambiguity_causes.take().unwrap_or_default()
289 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
293 pub fn tcx(&self) -> TyCtxt<'tcx> {
297 pub fn is_intercrate(&self) -> bool {
301 ///////////////////////////////////////////////////////////////////////////
304 // The selection phase tries to identify *how* an obligation will
305 // be resolved. For example, it will identify which impl or
306 // parameter bound is to be used. The process can be inconclusive
307 // if the self type in the obligation is not fully inferred. Selection
308 // can result in an error in one of two ways:
310 // 1. If no applicable impl or parameter bound can be found.
311 // 2. If the output type parameters in the obligation do not match
312 // those specified by the impl/bound. For example, if the obligation
313 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
314 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
316 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
317 /// type environment by performing unification.
318 #[instrument(level = "debug", skip(self))]
321 obligation: &TraitObligation<'tcx>,
322 ) -> SelectionResult<'tcx, Selection<'tcx>> {
323 let candidate = match self.select_from_obligation(obligation) {
324 Err(SelectionError::Overflow) => {
325 // In standard mode, overflow must have been caught and reported
327 assert!(self.query_mode == TraitQueryMode::Canonical);
328 return Err(SelectionError::Overflow);
330 Err(SelectionError::Ambiguous(_)) => {
339 Ok(Some(candidate)) => candidate,
342 match self.confirm_candidate(obligation, candidate) {
343 Err(SelectionError::Overflow) => {
344 assert!(self.query_mode == TraitQueryMode::Canonical);
345 Err(SelectionError::Overflow)
349 debug!(?candidate, "confirmed");
355 crate fn select_from_obligation(
357 obligation: &TraitObligation<'tcx>,
358 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
359 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
361 let pec = &ProvisionalEvaluationCache::default();
362 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
364 self.candidate_from_obligation(&stack)
367 ///////////////////////////////////////////////////////////////////////////
370 // Tests whether an obligation can be selected or whether an impl
371 // can be applied to particular types. It skips the "confirmation"
372 // step and hence completely ignores output type parameters.
374 // The result is "true" if the obligation *may* hold and "false" if
375 // we can be sure it does not.
377 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
378 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
379 debug!(?obligation, "predicate_may_hold_fatal");
381 // This fatal query is a stopgap that should only be used in standard mode,
382 // where we do not expect overflow to be propagated.
383 assert!(self.query_mode == TraitQueryMode::Standard);
385 self.evaluate_root_obligation(obligation)
386 .expect("Overflow should be caught earlier in standard query mode")
390 /// Evaluates whether the obligation `obligation` can be satisfied
391 /// and returns an `EvaluationResult`. This is meant for the
393 pub fn evaluate_root_obligation(
395 obligation: &PredicateObligation<'tcx>,
396 ) -> Result<EvaluationResult, OverflowError> {
397 self.evaluation_probe(|this| {
398 this.evaluate_predicate_recursively(
399 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
407 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
408 ) -> Result<EvaluationResult, OverflowError> {
409 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
410 let result = op(self)?;
412 match self.infcx.leak_check(true, snapshot) {
414 Err(_) => return Ok(EvaluatedToErr),
417 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
419 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
424 /// Evaluates the predicates in `predicates` recursively. Note that
425 /// this applies projections in the predicates, and therefore
426 /// is run within an inference probe.
427 #[instrument(skip(self, stack), level = "debug")]
428 fn evaluate_predicates_recursively<'o, I>(
430 stack: TraitObligationStackList<'o, 'tcx>,
432 ) -> Result<EvaluationResult, OverflowError>
434 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
436 let mut result = EvaluatedToOk;
437 for obligation in predicates {
438 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
439 if let EvaluatedToErr = eval {
440 // fast-path - EvaluatedToErr is the top of the lattice,
441 // so we don't need to look on the other predicates.
442 return Ok(EvaluatedToErr);
444 result = cmp::max(result, eval);
452 skip(self, previous_stack),
453 fields(previous_stack = ?previous_stack.head())
455 fn evaluate_predicate_recursively<'o>(
457 previous_stack: TraitObligationStackList<'o, 'tcx>,
458 obligation: PredicateObligation<'tcx>,
459 ) -> Result<EvaluationResult, OverflowError> {
460 // `previous_stack` stores a `TraitObligation`, while `obligation` is
461 // a `PredicateObligation`. These are distinct types, so we can't
462 // use any `Option` combinator method that would force them to be
464 match previous_stack.head() {
465 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
466 None => self.check_recursion_limit(&obligation, &obligation)?,
469 let result = ensure_sufficient_stack(|| {
470 let bound_predicate = obligation.predicate.kind();
471 match bound_predicate.skip_binder() {
472 ty::PredicateKind::Trait(t) => {
473 let t = bound_predicate.rebind(t);
474 debug_assert!(!t.has_escaping_bound_vars());
475 let obligation = obligation.with(t);
476 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
479 ty::PredicateKind::Subtype(p) => {
480 let p = bound_predicate.rebind(p);
481 // Does this code ever run?
482 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
483 Some(Ok(InferOk { mut obligations, .. })) => {
484 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
485 self.evaluate_predicates_recursively(
487 obligations.into_iter(),
490 Some(Err(_)) => Ok(EvaluatedToErr),
491 None => Ok(EvaluatedToAmbig),
495 ty::PredicateKind::Coerce(p) => {
496 let p = bound_predicate.rebind(p);
497 // Does this code ever run?
498 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
499 Some(Ok(InferOk { mut obligations, .. })) => {
500 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
501 self.evaluate_predicates_recursively(
503 obligations.into_iter(),
506 Some(Err(_)) => Ok(EvaluatedToErr),
507 None => Ok(EvaluatedToAmbig),
511 ty::PredicateKind::WellFormed(arg) => match wf::obligations(
513 obligation.param_env,
514 obligation.cause.body_id,
515 obligation.recursion_depth + 1,
517 obligation.cause.span,
519 Some(mut obligations) => {
520 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
521 self.evaluate_predicates_recursively(previous_stack, obligations)
523 None => Ok(EvaluatedToAmbig),
526 ty::PredicateKind::TypeOutlives(pred) => {
527 // A global type with no late-bound regions can only
528 // contain the "'static" lifetime (any other lifetime
529 // would either be late-bound or local), so it is guaranteed
530 // to outlive any other lifetime
531 if pred.0.is_global() && !pred.0.has_late_bound_regions() {
534 Ok(EvaluatedToOkModuloRegions)
538 ty::PredicateKind::RegionOutlives(..) => {
539 // We do not consider region relationships when evaluating trait matches.
540 Ok(EvaluatedToOkModuloRegions)
543 ty::PredicateKind::ObjectSafe(trait_def_id) => {
544 if self.tcx().is_object_safe(trait_def_id) {
551 ty::PredicateKind::Projection(data) => {
552 let data = bound_predicate.rebind(data);
553 let project_obligation = obligation.with(data);
554 match project::poly_project_and_unify_type(self, &project_obligation) {
555 Ok(Ok(Some(mut subobligations))) => {
557 // If we've previously marked this projection as 'complete', thne
558 // use the final cached result (either `EvaluatedToOk` or
559 // `EvaluatedToOkModuloRegions`), and skip re-evaluating the
562 ProjectionCacheKey::from_poly_projection_predicate(self, data)
564 if let Some(cached_res) = self
571 break 'compute_res Ok(cached_res);
576 subobligations.iter_mut(),
577 obligation.recursion_depth,
579 let res = self.evaluate_predicates_recursively(
583 if let Ok(res) = res {
584 if res == EvaluatedToOk || res == EvaluatedToOkModuloRegions {
586 ProjectionCacheKey::from_poly_projection_predicate(
590 // If the result is something that we can cache, then mark this
591 // entry as 'complete'. This will allow us to skip evaluating the
592 // suboligations at all the next time we evaluate the projection
605 Ok(Ok(None)) => Ok(EvaluatedToAmbig),
606 Ok(Err(project::InProgress)) => Ok(EvaluatedToRecur),
607 Err(_) => Ok(EvaluatedToErr),
611 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
612 match self.infcx.closure_kind(closure_substs) {
613 Some(closure_kind) => {
614 if closure_kind.extends(kind) {
620 None => Ok(EvaluatedToAmbig),
624 ty::PredicateKind::ConstEvaluatable(uv) => {
625 match const_evaluatable::is_const_evaluatable(
628 obligation.param_env,
629 obligation.cause.span,
631 Ok(()) => Ok(EvaluatedToOk),
632 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
633 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
634 Err(_) => Ok(EvaluatedToErr),
638 ty::PredicateKind::ConstEquate(c1, c2) => {
639 debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
641 if self.tcx().features().generic_const_exprs {
642 // FIXME: we probably should only try to unify abstract constants
643 // if the constants depend on generic parameters.
645 // Let's just see where this breaks :shrug:
646 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
649 if self.infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
650 return Ok(EvaluatedToOk);
655 let evaluate = |c: &'tcx ty::Const<'tcx>| {
656 if let ty::ConstKind::Unevaluated(unevaluated) = c.val {
659 obligation.param_env,
661 Some(obligation.cause.span),
663 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty))
669 match (evaluate(c1), evaluate(c2)) {
670 (Ok(c1), Ok(c2)) => {
673 .at(&obligation.cause, obligation.param_env)
676 Ok(_) => Ok(EvaluatedToOk),
677 Err(_) => Ok(EvaluatedToErr),
680 (Err(ErrorHandled::Reported(ErrorReported)), _)
681 | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
682 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
684 obligation.cause.span(self.tcx()),
685 "ConstEquate: const_eval_resolve returned an unexpected error"
688 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
689 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
692 // Two different constants using generic parameters ~> error.
698 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
699 bug!("TypeWellFormedFromEnv is only used for chalk")
701 ty::PredicateKind::OpaqueType(a, b) => {
702 match self.infcx().handle_opaque_type(
706 obligation.param_env,
709 self.evaluate_predicates_recursively(previous_stack, res.obligations)
711 Err(_) => Ok(EvaluatedToErr),
717 debug!("finished: {:?} from {:?}", result, obligation);
722 #[instrument(skip(self, previous_stack), level = "debug")]
723 fn evaluate_trait_predicate_recursively<'o>(
725 previous_stack: TraitObligationStackList<'o, 'tcx>,
726 mut obligation: TraitObligation<'tcx>,
727 ) -> Result<EvaluationResult, OverflowError> {
729 && obligation.is_global()
730 && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst())
732 // If a param env has no global bounds, global obligations do not
733 // depend on its particular value in order to work, so we can clear
734 // out the param env and get better caching.
736 obligation.param_env = obligation.param_env.without_caller_bounds();
739 let stack = self.push_stack(previous_stack, &obligation);
740 let mut fresh_trait_pred = stack.fresh_trait_pred;
741 let mut param_env = obligation.param_env;
743 fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| {
744 pred.remap_constness(self.tcx(), &mut param_env);
748 debug!(?fresh_trait_pred);
750 if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
751 debug!(?result, "CACHE HIT");
755 if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
756 debug!(?result, "PROVISIONAL CACHE HIT");
757 stack.update_reached_depth(result.reached_depth);
758 return Ok(result.result);
761 // Check if this is a match for something already on the
762 // stack. If so, we don't want to insert the result into the
763 // main cache (it is cycle dependent) nor the provisional
764 // cache (which is meant for things that have completed but
765 // for a "backedge" -- this result *is* the backedge).
766 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
767 return Ok(cycle_result);
770 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
771 let result = result?;
773 if !result.must_apply_modulo_regions() {
774 stack.cache().on_failure(stack.dfn);
777 let reached_depth = stack.reached_depth.get();
778 if reached_depth >= stack.depth {
779 debug!(?result, "CACHE MISS");
780 self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
782 stack.cache().on_completion(
784 |fresh_trait_pred, provisional_result, provisional_dep_node| {
785 // Create a new `DepNode` that has dependencies on:
786 // * The `DepNode` for the original evaluation that resulted in a provisional cache
787 // entry being crated
788 // * The `DepNode` for the *current* evaluation, which resulted in us completing
789 // provisional caches entries and inserting them into the evaluation cache
791 // This ensures that when a query reads this entry from the evaluation cache,
792 // it will end up (transitively) dependening on all of the incr-comp dependencies
793 // created during the evaluation of this trait. For example, evaluating a trait
794 // will usually require us to invoke `type_of(field_def_id)` to determine the
795 // constituent types, and we want any queries reading from this evaluation
796 // cache entry to end up with a transitive `type_of(field_def_id`)` dependency.
798 // By using `in_task`, we're also creating an edge from the *current* query
799 // to the newly-created `combined_dep_node`. This is probably redundant,
800 // but it's better to add too many dep graph edges than to add too few
802 let ((), combined_dep_node) = self.in_task(|this| {
803 this.tcx().dep_graph.read_index(provisional_dep_node);
804 this.tcx().dep_graph.read_index(dep_node);
806 self.insert_evaluation_cache(
810 provisional_result.max(result),
815 debug!(?result, "PROVISIONAL");
817 "caching provisionally because {:?} \
818 is a cycle participant (at depth {}, reached depth {})",
819 fresh_trait_pred, stack.depth, reached_depth,
822 stack.cache().insert_provisional(
834 /// If there is any previous entry on the stack that precisely
835 /// matches this obligation, then we can assume that the
836 /// obligation is satisfied for now (still all other conditions
837 /// must be met of course). One obvious case this comes up is
838 /// marker traits like `Send`. Think of a linked list:
840 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
842 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
843 /// `Option<Box<List<T>>>` is `Send`, and in turn
844 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
847 /// Note that we do this comparison using the `fresh_trait_ref`
848 /// fields. Because these have all been freshened using
849 /// `self.freshener`, we can be sure that (a) this will not
850 /// affect the inferencer state and (b) that if we see two
851 /// fresh regions with the same index, they refer to the same
852 /// unbound type variable.
853 fn check_evaluation_cycle(
855 stack: &TraitObligationStack<'_, 'tcx>,
856 ) -> Option<EvaluationResult> {
857 if let Some(cycle_depth) = stack
859 .skip(1) // Skip top-most frame.
861 stack.obligation.param_env == prev.obligation.param_env
862 && stack.fresh_trait_pred == prev.fresh_trait_pred
864 .map(|stack| stack.depth)
866 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
868 // If we have a stack like `A B C D E A`, where the top of
869 // the stack is the final `A`, then this will iterate over
870 // `A, E, D, C, B` -- i.e., all the participants apart
871 // from the cycle head. We mark them as participating in a
872 // cycle. This suppresses caching for those nodes. See
873 // `in_cycle` field for more details.
874 stack.update_reached_depth(cycle_depth);
876 // Subtle: when checking for a coinductive cycle, we do
877 // not compare using the "freshened trait refs" (which
878 // have erased regions) but rather the fully explicit
879 // trait refs. This is important because it's only a cycle
880 // if the regions match exactly.
881 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
882 let tcx = self.tcx();
883 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
884 if self.coinductive_match(cycle) {
885 debug!("evaluate_stack --> recursive, coinductive");
888 debug!("evaluate_stack --> recursive, inductive");
889 Some(EvaluatedToRecur)
896 fn evaluate_stack<'o>(
898 stack: &TraitObligationStack<'o, 'tcx>,
899 ) -> Result<EvaluationResult, OverflowError> {
900 // In intercrate mode, whenever any of the generics are unbound,
901 // there can always be an impl. Even if there are no impls in
902 // this crate, perhaps the type would be unified with
903 // something from another crate that does provide an impl.
905 // In intra mode, we must still be conservative. The reason is
906 // that we want to avoid cycles. Imagine an impl like:
908 // impl<T:Eq> Eq for Vec<T>
910 // and a trait reference like `$0 : Eq` where `$0` is an
911 // unbound variable. When we evaluate this trait-reference, we
912 // will unify `$0` with `Vec<$1>` (for some fresh variable
913 // `$1`), on the condition that `$1 : Eq`. We will then wind
914 // up with many candidates (since that are other `Eq` impls
915 // that apply) and try to winnow things down. This results in
916 // a recursive evaluation that `$1 : Eq` -- as you can
917 // imagine, this is just where we started. To avoid that, we
918 // check for unbound variables and return an ambiguous (hence possible)
919 // match if we've seen this trait before.
921 // This suffices to allow chains like `FnMut` implemented in
922 // terms of `Fn` etc, but we could probably make this more
924 let unbound_input_types =
925 stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh());
927 if stack.obligation.polarity() != ty::ImplPolarity::Negative {
928 // This check was an imperfect workaround for a bug in the old
929 // intercrate mode; it should be removed when that goes away.
930 if unbound_input_types && self.intercrate {
931 debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
932 // Heuristics: show the diagnostics when there are no candidates in crate.
933 if self.intercrate_ambiguity_causes.is_some() {
934 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
935 if let Ok(candidate_set) = self.assemble_candidates(stack) {
936 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
937 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
938 let self_ty = trait_ref.self_ty();
939 let cause = with_no_trimmed_paths(|| {
940 IntercrateAmbiguityCause::DownstreamCrate {
941 trait_desc: trait_ref.print_only_trait_path().to_string(),
942 self_desc: if self_ty.has_concrete_skeleton() {
943 Some(self_ty.to_string())
950 debug!(?cause, "evaluate_stack: pushing cause");
951 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
955 return Ok(EvaluatedToAmbig);
959 if unbound_input_types
960 && stack.iter().skip(1).any(|prev| {
961 stack.obligation.param_env == prev.obligation.param_env
962 && self.match_fresh_trait_refs(
963 stack.fresh_trait_pred,
964 prev.fresh_trait_pred,
965 prev.obligation.param_env,
969 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
970 return Ok(EvaluatedToUnknown);
973 match self.candidate_from_obligation(stack) {
974 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
975 Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig),
976 Ok(None) => Ok(EvaluatedToAmbig),
977 Err(Overflow) => Err(OverflowError::Canonical),
978 Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
979 Err(..) => Ok(EvaluatedToErr),
983 /// For defaulted traits, we use a co-inductive strategy to solve, so
984 /// that recursion is ok. This routine returns `true` if the top of the
985 /// stack (`cycle[0]`):
987 /// - is a defaulted trait,
988 /// - it also appears in the backtrace at some position `X`,
989 /// - all the predicates at positions `X..` between `X` and the top are
990 /// also defaulted traits.
991 pub fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
993 I: Iterator<Item = ty::Predicate<'tcx>>,
995 cycle.all(|predicate| self.coinductive_predicate(predicate))
998 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
999 let result = match predicate.kind().skip_binder() {
1000 ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1003 debug!(?predicate, ?result, "coinductive_predicate");
1007 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
1008 /// obligations are met. Returns whether `candidate` remains viable after this further
1013 fields(depth = stack.obligation.recursion_depth)
1015 fn evaluate_candidate<'o>(
1017 stack: &TraitObligationStack<'o, 'tcx>,
1018 candidate: &SelectionCandidate<'tcx>,
1019 ) -> Result<EvaluationResult, OverflowError> {
1020 let mut result = self.evaluation_probe(|this| {
1021 let candidate = (*candidate).clone();
1022 match this.confirm_candidate(stack.obligation, candidate) {
1025 this.evaluate_predicates_recursively(
1027 selection.nested_obligations().into_iter(),
1030 Err(..) => Ok(EvaluatedToErr),
1034 // If we erased any lifetimes, then we want to use
1035 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
1036 // as your final result. The result will be cached using
1037 // the freshened trait predicate as a key, so we need
1038 // our result to be correct by *any* choice of original lifetimes,
1039 // not just the lifetime choice for this particular (non-erased)
1042 if stack.fresh_trait_pred.has_erased_regions() {
1043 result = result.max(EvaluatedToOkModuloRegions);
1050 fn check_evaluation_cache(
1052 param_env: ty::ParamEnv<'tcx>,
1053 trait_pred: ty::PolyTraitPredicate<'tcx>,
1054 ) -> Option<EvaluationResult> {
1055 // Neither the global nor local cache is aware of intercrate
1056 // mode, so don't do any caching. In particular, we might
1057 // re-use the same `InferCtxt` with both an intercrate
1058 // and non-intercrate `SelectionContext`
1059 if self.intercrate {
1063 let tcx = self.tcx();
1064 if self.can_use_global_caches(param_env) {
1065 if let Some(res) = tcx.evaluation_cache.get(¶m_env.and(trait_pred), tcx) {
1069 self.infcx.evaluation_cache.get(¶m_env.and(trait_pred), tcx)
1072 fn insert_evaluation_cache(
1074 param_env: ty::ParamEnv<'tcx>,
1075 trait_pred: ty::PolyTraitPredicate<'tcx>,
1076 dep_node: DepNodeIndex,
1077 result: EvaluationResult,
1079 // Avoid caching results that depend on more than just the trait-ref
1080 // - the stack can create recursion.
1081 if result.is_stack_dependent() {
1085 // Neither the global nor local cache is aware of intercrate
1086 // mode, so don't do any caching. In particular, we might
1087 // re-use the same `InferCtxt` with both an intercrate
1088 // and non-intercrate `SelectionContext`
1089 if self.intercrate {
1093 if self.can_use_global_caches(param_env) {
1094 if !trait_pred.needs_infer() {
1095 debug!(?trait_pred, ?result, "insert_evaluation_cache global");
1096 // This may overwrite the cache with the same value
1097 // FIXME: Due to #50507 this overwrites the different values
1098 // This should be changed to use HashMapExt::insert_same
1099 // when that is fixed
1100 self.tcx().evaluation_cache.insert(param_env.and(trait_pred), dep_node, result);
1105 debug!(?trait_pred, ?result, "insert_evaluation_cache");
1106 self.infcx.evaluation_cache.insert(param_env.and(trait_pred), dep_node, result);
1109 /// For various reasons, it's possible for a subobligation
1110 /// to have a *lower* recursion_depth than the obligation used to create it.
1111 /// Projection sub-obligations may be returned from the projection cache,
1112 /// which results in obligations with an 'old' `recursion_depth`.
1113 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1114 /// subobligations without taking in a 'parent' depth, causing the
1115 /// generated subobligations to have a `recursion_depth` of `0`.
1117 /// To ensure that obligation_depth never decreases, we force all subobligations
1118 /// to have at least the depth of the original obligation.
1119 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1124 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1127 fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
1130 error_obligation: &Obligation<'tcx, T>,
1131 ) -> Result<(), OverflowError> {
1132 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1133 match self.query_mode {
1134 TraitQueryMode::Standard => {
1135 if self.infcx.is_tainted_by_errors() {
1136 return Err(OverflowError::ErrorReporting);
1138 self.infcx.report_overflow_error(error_obligation, true);
1140 TraitQueryMode::Canonical => {
1141 return Err(OverflowError::Canonical);
1148 /// Checks that the recursion limit has not been exceeded.
1150 /// The weird return type of this function allows it to be used with the `try` (`?`)
1151 /// operator within certain functions.
1153 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1155 obligation: &Obligation<'tcx, T>,
1156 error_obligation: &Obligation<'tcx, V>,
1157 ) -> Result<(), OverflowError> {
1158 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1161 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1163 OP: FnOnce(&mut Self) -> R,
1165 let (result, dep_node) =
1166 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
1167 self.tcx().dep_graph.read_index(dep_node);
1171 /// filter_impls filters constant trait obligations and candidates that have a positive impl
1172 /// for a negative goal and a negative impl for a positive goal
1173 #[instrument(level = "debug", skip(self))]
1176 candidates: Vec<SelectionCandidate<'tcx>>,
1177 obligation: &TraitObligation<'tcx>,
1178 ) -> Vec<SelectionCandidate<'tcx>> {
1179 let tcx = self.tcx();
1180 let mut result = Vec::with_capacity(candidates.len());
1182 for candidate in candidates {
1183 // Respect const trait obligations
1184 if obligation.is_const() {
1187 ImplCandidate(def_id)
1188 if tcx.impl_constness(def_id) == hir::Constness::Const => {}
1190 ParamCandidate(trait_pred) if trait_pred.is_const_if_const() => {}
1192 AutoImplCandidate(..) => {}
1193 // generator, this will raise error in other places
1194 // or ignore error with const_async_blocks feature
1195 GeneratorCandidate => {}
1196 // FnDef where the function is const
1197 FnPointerCandidate { is_const: true } => {}
1198 ConstDropCandidate(_) => {}
1200 // reject all other types of candidates
1206 if let ImplCandidate(def_id) = candidate {
1207 if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id)
1208 || obligation.polarity() == tcx.impl_polarity(def_id)
1209 || self.allow_negative_impls
1211 result.push(candidate);
1214 result.push(candidate);
1221 /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1222 #[instrument(level = "debug", skip(self))]
1223 fn filter_reservation_impls(
1225 candidate: SelectionCandidate<'tcx>,
1226 obligation: &TraitObligation<'tcx>,
1227 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1228 let tcx = self.tcx();
1229 // Treat reservation impls as ambiguity.
1230 if let ImplCandidate(def_id) = candidate {
1231 if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
1232 if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1233 let attrs = tcx.get_attrs(def_id);
1234 let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
1235 let value = attr.and_then(|a| a.value_str());
1236 if let Some(value) = value {
1238 "filter_reservation_impls: \
1239 reservation impl ambiguity on {:?}",
1242 intercrate_ambiguity_clauses.push(
1243 IntercrateAmbiguityCause::ReservationImpl {
1244 message: value.to_string(),
1255 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1256 debug!("is_knowable(intercrate={:?})", self.intercrate);
1258 if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative {
1262 let obligation = &stack.obligation;
1263 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1265 // Okay to skip binder because of the nature of the
1266 // trait-ref-is-knowable check, which does not care about
1268 let trait_ref = predicate.skip_binder().trait_ref;
1270 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1273 /// Returns `true` if the global caches can be used.
1274 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1275 // If there are any inference variables in the `ParamEnv`, then we
1276 // always use a cache local to this particular scope. Otherwise, we
1277 // switch to a global cache.
1278 if param_env.needs_infer() {
1282 // Avoid using the master cache during coherence and just rely
1283 // on the local cache. This effectively disables caching
1284 // during coherence. It is really just a simplification to
1285 // avoid us having to fear that coherence results "pollute"
1286 // the master cache. Since coherence executes pretty quickly,
1287 // it's not worth going to more trouble to increase the
1288 // hit-rate, I don't think.
1289 if self.intercrate {
1293 // Otherwise, we can use the global cache.
1297 fn check_candidate_cache(
1299 mut param_env: ty::ParamEnv<'tcx>,
1300 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1301 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1302 // Neither the global nor local cache is aware of intercrate
1303 // mode, so don't do any caching. In particular, we might
1304 // re-use the same `InferCtxt` with both an intercrate
1305 // and non-intercrate `SelectionContext`
1306 if self.intercrate {
1309 let tcx = self.tcx();
1310 let mut pred = cache_fresh_trait_pred.skip_binder();
1311 pred.remap_constness(tcx, &mut param_env);
1313 if self.can_use_global_caches(param_env) {
1314 if let Some(res) = tcx.selection_cache.get(¶m_env.and(pred), tcx) {
1318 self.infcx.selection_cache.get(¶m_env.and(pred), tcx)
1321 /// Determines whether can we safely cache the result
1322 /// of selecting an obligation. This is almost always `true`,
1323 /// except when dealing with certain `ParamCandidate`s.
1325 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1326 /// since it was usually produced directly from a `DefId`. However,
1327 /// certain cases (currently only librustdoc's blanket impl finder),
1328 /// a `ParamEnv` may be explicitly constructed with inference types.
1329 /// When this is the case, we do *not* want to cache the resulting selection
1330 /// candidate. This is due to the fact that it might not always be possible
1331 /// to equate the obligation's trait ref and the candidate's trait ref,
1332 /// if more constraints end up getting added to an inference variable.
1334 /// Because of this, we always want to re-run the full selection
1335 /// process for our obligation the next time we see it, since
1336 /// we might end up picking a different `SelectionCandidate` (or none at all).
1337 fn can_cache_candidate(
1339 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1341 // Neither the global nor local cache is aware of intercrate
1342 // mode, so don't do any caching. In particular, we might
1343 // re-use the same `InferCtxt` with both an intercrate
1344 // and non-intercrate `SelectionContext`
1345 if self.intercrate {
1349 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
1354 #[instrument(skip(self, param_env, cache_fresh_trait_pred, dep_node), level = "debug")]
1355 fn insert_candidate_cache(
1357 mut param_env: ty::ParamEnv<'tcx>,
1358 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1359 dep_node: DepNodeIndex,
1360 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1362 let tcx = self.tcx();
1363 let mut pred = cache_fresh_trait_pred.skip_binder();
1365 pred.remap_constness(tcx, &mut param_env);
1367 if !self.can_cache_candidate(&candidate) {
1368 debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1372 if self.can_use_global_caches(param_env) {
1373 if let Err(Overflow) = candidate {
1374 // Don't cache overflow globally; we only produce this in certain modes.
1375 } else if !pred.needs_infer() {
1376 if !candidate.needs_infer() {
1377 debug!(?pred, ?candidate, "insert_candidate_cache global");
1378 // This may overwrite the cache with the same value.
1379 tcx.selection_cache.insert(param_env.and(pred), dep_node, candidate);
1385 debug!(?pred, ?candidate, "insert_candidate_cache local");
1386 self.infcx.selection_cache.insert(param_env.and(pred), dep_node, candidate);
1389 /// Matches a predicate against the bounds of its self type.
1391 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1392 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1393 /// `Baz` bound. We return indexes into the list returned by
1394 /// `tcx.item_bounds` for any applicable bounds.
1395 #[instrument(level = "debug", skip(self))]
1396 fn match_projection_obligation_against_definition_bounds(
1398 obligation: &TraitObligation<'tcx>,
1399 ) -> smallvec::SmallVec<[usize; 2]> {
1400 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
1401 let placeholder_trait_predicate =
1402 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
1403 debug!(?placeholder_trait_predicate);
1405 let tcx = self.infcx.tcx;
1406 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1407 ty::Projection(ref data) => (data.item_def_id, data.substs),
1408 ty::Opaque(def_id, substs) => (def_id, substs),
1411 obligation.cause.span,
1412 "match_projection_obligation_against_definition_bounds() called \
1413 but self-ty is not a projection: {:?}",
1414 placeholder_trait_predicate.trait_ref.self_ty()
1418 let bounds = tcx.item_bounds(def_id).subst(tcx, substs);
1420 // The bounds returned by `item_bounds` may contain duplicates after
1421 // normalization, so try to deduplicate when possible to avoid
1422 // unnecessary ambiguity.
1423 let mut distinct_normalized_bounds = FxHashSet::default();
1425 let matching_bounds = bounds
1428 .filter_map(|(idx, bound)| {
1429 let bound_predicate = bound.kind();
1430 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
1431 let bound = bound_predicate.rebind(pred.trait_ref);
1432 if self.infcx.probe(|_| {
1433 match self.match_normalize_trait_ref(
1436 placeholder_trait_predicate.trait_ref,
1439 Ok(Some(normalized_trait))
1440 if distinct_normalized_bounds.insert(normalized_trait) =>
1454 debug!(?matching_bounds);
1458 /// Equates the trait in `obligation` with trait bound. If the two traits
1459 /// can be equated and the normalized trait bound doesn't contain inference
1460 /// variables or placeholders, the normalized bound is returned.
1461 fn match_normalize_trait_ref(
1463 obligation: &TraitObligation<'tcx>,
1464 trait_bound: ty::PolyTraitRef<'tcx>,
1465 placeholder_trait_ref: ty::TraitRef<'tcx>,
1466 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
1467 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1468 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1469 // Avoid unnecessary normalization
1473 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1474 project::normalize_with_depth(
1476 obligation.param_env,
1477 obligation.cause.clone(),
1478 obligation.recursion_depth + 1,
1483 .at(&obligation.cause, obligation.param_env)
1484 .define_opaque_types(false)
1485 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1486 .map(|InferOk { obligations: _, value: () }| {
1487 // This method is called within a probe, so we can't have
1488 // inference variables and placeholders escape.
1489 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1498 fn evaluate_where_clause<'o>(
1500 stack: &TraitObligationStack<'o, 'tcx>,
1501 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1502 ) -> Result<EvaluationResult, OverflowError> {
1503 self.evaluation_probe(|this| {
1504 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1505 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1506 Err(()) => Ok(EvaluatedToErr),
1511 pub(super) fn match_projection_projections(
1513 obligation: &ProjectionTyObligation<'tcx>,
1514 env_predicate: PolyProjectionPredicate<'tcx>,
1515 potentially_unnormalized_candidates: bool,
1517 let mut nested_obligations = Vec::new();
1518 let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars(
1519 obligation.cause.span,
1520 LateBoundRegionConversionTime::HigherRankedType,
1523 let infer_projection = if potentially_unnormalized_candidates {
1524 ensure_sufficient_stack(|| {
1525 project::normalize_with_depth_to(
1527 obligation.param_env,
1528 obligation.cause.clone(),
1529 obligation.recursion_depth + 1,
1530 infer_predicate.projection_ty,
1531 &mut nested_obligations,
1535 infer_predicate.projection_ty
1539 .at(&obligation.cause, obligation.param_env)
1540 .define_opaque_types(false)
1541 .sup(obligation.predicate, infer_projection)
1542 .map_or(false, |InferOk { obligations, value: () }| {
1543 self.evaluate_predicates_recursively(
1544 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1545 nested_obligations.into_iter().chain(obligations),
1547 .map_or(false, |res| res.may_apply())
1551 ///////////////////////////////////////////////////////////////////////////
1554 // Winnowing is the process of attempting to resolve ambiguity by
1555 // probing further. During the winnowing process, we unify all
1556 // type variables and then we also attempt to evaluate recursive
1557 // bounds to see if they are satisfied.
1559 /// Returns `true` if `victim` should be dropped in favor of
1560 /// `other`. Generally speaking we will drop duplicate
1561 /// candidates and prefer where-clause candidates.
1563 /// See the comment for "SelectionCandidate" for more details.
1564 fn candidate_should_be_dropped_in_favor_of(
1566 sized_predicate: bool,
1567 victim: &EvaluatedCandidate<'tcx>,
1568 other: &EvaluatedCandidate<'tcx>,
1571 if victim.candidate == other.candidate {
1575 // Check if a bound would previously have been removed when normalizing
1576 // the param_env so that it can be given the lowest priority. See
1577 // #50825 for the motivation for this.
1578 let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| {
1579 cand.is_global() && !cand.has_late_bound_regions()
1582 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1583 // `DiscriminantKindCandidate`, and `ConstDropCandidate` to anything else.
1585 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1586 // lifetime of a variable.
1587 match (&other.candidate, &victim.candidate) {
1588 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1590 "default implementations shouldn't be recorded \
1591 when there are other valid candidates"
1597 BuiltinCandidate { has_nested: false }
1598 | DiscriminantKindCandidate
1600 | ConstDropCandidate(_),
1605 BuiltinCandidate { has_nested: false }
1606 | DiscriminantKindCandidate
1608 | ConstDropCandidate(_),
1611 (ParamCandidate(other), ParamCandidate(victim)) => {
1612 let same_except_bound_vars = other.skip_binder().trait_ref
1613 == victim.skip_binder().trait_ref
1614 && other.skip_binder().constness == victim.skip_binder().constness
1615 && other.skip_binder().polarity == victim.skip_binder().polarity
1616 && !other.skip_binder().trait_ref.has_escaping_bound_vars();
1617 if same_except_bound_vars {
1618 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1619 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1620 // or the current one if tied (they should both evaluate to the same answer). This is
1621 // probably best characterized as a "hack", since we might prefer to just do our
1622 // best to *not* create essentially duplicate candidates in the first place.
1623 other.bound_vars().len() <= victim.bound_vars().len()
1624 } else if other.skip_binder().trait_ref == victim.skip_binder().trait_ref
1625 && victim.skip_binder().constness == ty::BoundConstness::NotConst
1626 && other.skip_binder().polarity == victim.skip_binder().polarity
1628 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1635 // Drop otherwise equivalent non-const fn pointer candidates
1636 (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
1638 // If obligation is a sized predicate or the where-clause bound is
1639 // global, prefer the projection or object candidate. See issue
1640 // #50825 and #89352.
1641 (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1642 sized_predicate || is_global(cand)
1644 (ParamCandidate(ref cand), ObjectCandidate(_) | ProjectionCandidate(_)) => {
1645 !(sized_predicate || is_global(cand))
1648 // Global bounds from the where clause should be ignored
1649 // here (see issue #50825). Otherwise, we have a where
1650 // clause so don't go around looking for impls.
1651 // Arbitrarily give param candidates priority
1652 // over projection and object candidates.
1654 ParamCandidate(ref cand),
1657 | GeneratorCandidate
1658 | FnPointerCandidate { .. }
1659 | BuiltinObjectCandidate
1660 | BuiltinUnsizeCandidate
1661 | TraitUpcastingUnsizeCandidate(_)
1662 | BuiltinCandidate { .. }
1663 | TraitAliasCandidate(..),
1664 ) => !is_global(cand),
1668 | GeneratorCandidate
1669 | FnPointerCandidate { .. }
1670 | BuiltinObjectCandidate
1671 | BuiltinUnsizeCandidate
1672 | TraitUpcastingUnsizeCandidate(_)
1673 | BuiltinCandidate { has_nested: true }
1674 | TraitAliasCandidate(..),
1675 ParamCandidate(ref cand),
1677 // Prefer these to a global where-clause bound
1678 // (see issue #50825).
1679 is_global(cand) && other.evaluation.must_apply_modulo_regions()
1682 (ProjectionCandidate(i), ProjectionCandidate(j))
1683 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1684 // Arbitrarily pick the lower numbered candidate for backwards
1685 // compatibility reasons. Don't let this affect inference.
1686 i < j && !needs_infer
1688 (ObjectCandidate(_), ProjectionCandidate(_))
1689 | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1690 bug!("Have both object and projection candidate")
1693 // Arbitrarily give projection and object candidates priority.
1695 ObjectCandidate(_) | ProjectionCandidate(_),
1698 | GeneratorCandidate
1699 | FnPointerCandidate { .. }
1700 | BuiltinObjectCandidate
1701 | BuiltinUnsizeCandidate
1702 | TraitUpcastingUnsizeCandidate(_)
1703 | BuiltinCandidate { .. }
1704 | TraitAliasCandidate(..),
1710 | GeneratorCandidate
1711 | FnPointerCandidate { .. }
1712 | BuiltinObjectCandidate
1713 | BuiltinUnsizeCandidate
1714 | TraitUpcastingUnsizeCandidate(_)
1715 | BuiltinCandidate { .. }
1716 | TraitAliasCandidate(..),
1717 ObjectCandidate(_) | ProjectionCandidate(_),
1720 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
1721 // See if we can toss out `victim` based on specialization.
1722 // This requires us to know *for sure* that the `other` impl applies
1723 // i.e., `EvaluatedToOk`.
1725 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1726 // to me but is required for `std` to compile, so I didn't change it
1728 let tcx = self.tcx();
1729 if other.evaluation.must_apply_modulo_regions() {
1730 if tcx.specializes((other_def, victim_def)) {
1735 if other.evaluation.must_apply_considering_regions() {
1736 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
1737 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1738 // Subtle: If the predicate we are evaluating has inference
1739 // variables, do *not* allow discarding candidates due to
1740 // marker trait impls.
1742 // Without this restriction, we could end up accidentally
1743 // constrainting inference variables based on an arbitrarily
1744 // chosen trait impl.
1746 // Imagine we have the following code:
1749 // #[marker] trait MyTrait {}
1750 // impl MyTrait for u8 {}
1751 // impl MyTrait for bool {}
1754 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1756 // During selection, we will end up with one candidate for each
1757 // impl of `MyTrait`. If we were to discard one impl in favor
1758 // of the other, we would be left with one candidate, causing
1759 // us to "successfully" select the predicate, unifying
1760 // _#0t with (for example) `u8`.
1762 // However, we have no reason to believe that this unification
1763 // is correct - we've essentially just picked an arbitrary
1764 // *possibility* for _#0t, and required that this be the *only*
1767 // Eventually, we will either:
1768 // 1) Unify all inference variables in the predicate through
1769 // some other means (e.g. type-checking of a function). We will
1770 // then be in a position to drop marker trait candidates
1771 // without constraining inference variables (since there are
1772 // none left to constrin)
1773 // 2) Be left with some unconstrained inference variables. We
1774 // will then correctly report an inference error, since the
1775 // existence of multiple marker trait impls tells us nothing
1776 // about which one should actually apply.
1787 // Everything else is ambiguous
1791 | GeneratorCandidate
1792 | FnPointerCandidate { .. }
1793 | BuiltinObjectCandidate
1794 | BuiltinUnsizeCandidate
1795 | TraitUpcastingUnsizeCandidate(_)
1796 | BuiltinCandidate { has_nested: true }
1797 | TraitAliasCandidate(..),
1800 | GeneratorCandidate
1801 | FnPointerCandidate { .. }
1802 | BuiltinObjectCandidate
1803 | BuiltinUnsizeCandidate
1804 | TraitUpcastingUnsizeCandidate(_)
1805 | BuiltinCandidate { has_nested: true }
1806 | TraitAliasCandidate(..),
1811 fn sized_conditions(
1813 obligation: &TraitObligation<'tcx>,
1814 ) -> BuiltinImplConditions<'tcx> {
1815 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1817 // NOTE: binder moved to (*)
1818 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1820 match self_ty.kind() {
1821 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1832 | ty::GeneratorWitness(..)
1837 // safe for everything
1838 Where(ty::Binder::dummy(Vec::new()))
1841 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1843 ty::Tuple(tys) => Where(
1846 .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()),
1849 ty::Adt(def, substs) => {
1850 let sized_crit = def.sized_constraint(self.tcx());
1851 // (*) binder moved here
1853 obligation.predicate.rebind({
1854 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1859 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1860 ty::Infer(ty::TyVar(_)) => Ambiguous,
1864 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1865 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1870 fn copy_clone_conditions(
1872 obligation: &TraitObligation<'tcx>,
1873 ) -> BuiltinImplConditions<'tcx> {
1874 // NOTE: binder moved to (*)
1875 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1877 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1879 match *self_ty.kind() {
1880 ty::Infer(ty::IntVar(_))
1881 | ty::Infer(ty::FloatVar(_))
1884 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
1893 | ty::Ref(_, _, hir::Mutability::Not)
1894 | ty::Array(..) => {
1895 // Implementations provided in libcore
1903 | ty::GeneratorWitness(..)
1905 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1908 // (*) binder moved here
1909 Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect()))
1912 ty::Closure(_, substs) => {
1913 // (*) binder moved here
1914 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1915 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1916 // Not yet resolved.
1919 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1923 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1924 // Fallback to whatever user-defined impls exist in this case.
1928 ty::Infer(ty::TyVar(_)) => {
1929 // Unbound type variable. Might or might not have
1930 // applicable impls and so forth, depending on what
1931 // those type variables wind up being bound to.
1937 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1938 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1943 /// For default impls, we need to break apart a type into its
1944 /// "constituent types" -- meaning, the types that it contains.
1946 /// Here are some (simple) examples:
1949 /// (i32, u32) -> [i32, u32]
1950 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1951 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1952 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1954 fn constituent_types_for_ty(
1956 t: ty::Binder<'tcx, Ty<'tcx>>,
1957 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
1958 match *t.skip_binder().kind() {
1967 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1969 | ty::Char => ty::Binder::dummy(Vec::new()),
1975 | ty::Projection(..)
1977 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1978 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1981 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
1982 t.rebind(vec![element_ty])
1985 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
1987 ty::Tuple(ref tys) => {
1988 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1989 t.rebind(tys.iter().map(|k| k.expect_ty()).collect())
1992 ty::Closure(_, ref substs) => {
1993 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1997 ty::Generator(_, ref substs, _) => {
1998 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
1999 let witness = substs.as_generator().witness();
2000 t.rebind([ty].into_iter().chain(iter::once(witness)).collect())
2003 ty::GeneratorWitness(types) => {
2004 debug_assert!(!types.has_escaping_bound_vars());
2005 types.map_bound(|types| types.to_vec())
2008 // For `PhantomData<T>`, we pass `T`.
2009 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
2011 ty::Adt(def, substs) => {
2012 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
2015 ty::Opaque(def_id, substs) => {
2016 // We can resolve the `impl Trait` to its concrete type,
2017 // which enforces a DAG between the functions requiring
2018 // the auto trait bounds in question.
2019 t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
2024 fn collect_predicates_for_types(
2026 param_env: ty::ParamEnv<'tcx>,
2027 cause: ObligationCause<'tcx>,
2028 recursion_depth: usize,
2029 trait_def_id: DefId,
2030 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
2031 ) -> Vec<PredicateObligation<'tcx>> {
2032 // Because the types were potentially derived from
2033 // higher-ranked obligations they may reference late-bound
2034 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2035 // yield a type like `for<'a> &'a i32`. In general, we
2036 // maintain the invariant that we never manipulate bound
2037 // regions, so we have to process these bound regions somehow.
2039 // The strategy is to:
2041 // 1. Instantiate those regions to placeholder regions (e.g.,
2042 // `for<'a> &'a i32` becomes `&0 i32`.
2043 // 2. Produce something like `&'0 i32 : Copy`
2044 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2048 .skip_binder() // binder moved -\
2051 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(ty); // <----/
2053 self.infcx.commit_unconditionally(|_| {
2054 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
2055 let Normalized { value: normalized_ty, mut obligations } =
2056 ensure_sufficient_stack(|| {
2057 project::normalize_with_depth(
2065 let placeholder_obligation = predicate_for_trait_def(
2074 obligations.push(placeholder_obligation);
2081 ///////////////////////////////////////////////////////////////////////////
2084 // Matching is a common path used for both evaluation and
2085 // confirmation. It basically unifies types that appear in impls
2086 // and traits. This does affect the surrounding environment;
2087 // therefore, when used during evaluation, match routines must be
2088 // run inside of a `probe()` so that their side-effects are
2094 obligation: &TraitObligation<'tcx>,
2095 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
2096 match self.match_impl(impl_def_id, obligation) {
2097 Ok(substs) => substs,
2099 self.infcx.tcx.sess.delay_span_bug(
2100 obligation.cause.span,
2102 "Impl {:?} was matchable against {:?} but now is not",
2103 impl_def_id, obligation
2106 let value = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2107 let err = self.tcx().ty_error();
2108 let value = value.fold_with(&mut BottomUpFolder {
2114 Normalized { value, obligations: vec![] }
2119 #[tracing::instrument(level = "debug", skip(self))]
2123 obligation: &TraitObligation<'tcx>,
2124 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2125 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2127 // Before we create the substitutions and everything, first
2128 // consider a "quick reject". This avoids creating more types
2129 // and so forth that we need to.
2130 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2134 let placeholder_obligation =
2135 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
2136 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2138 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2140 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2142 debug!(?impl_trait_ref);
2144 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2145 ensure_sufficient_stack(|| {
2146 project::normalize_with_depth(
2148 obligation.param_env,
2149 obligation.cause.clone(),
2150 obligation.recursion_depth + 1,
2155 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2157 let cause = ObligationCause::new(
2158 obligation.cause.span,
2159 obligation.cause.body_id,
2160 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2163 let InferOk { obligations, .. } = self
2165 .at(&cause, obligation.param_env)
2166 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
2167 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2168 nested_obligations.extend(obligations);
2171 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2173 debug!("match_impl: reservation impls only apply in intercrate mode");
2177 debug!(?impl_substs, ?nested_obligations, "match_impl: success");
2178 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2181 fn fast_reject_trait_refs(
2183 obligation: &TraitObligation<'_>,
2184 impl_trait_ref: &ty::TraitRef<'_>,
2186 // We can avoid creating type variables and doing the full
2187 // substitution if we find that any of the input types, when
2188 // simplified, do not match.
2190 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
2191 |(obligation_arg, impl_arg)| {
2192 match (obligation_arg.unpack(), impl_arg.unpack()) {
2193 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
2194 // Note, we simplify parameters for the obligation but not the
2195 // impl so that we do not reject a blanket impl but do reject
2196 // more concrete impls if we're searching for `T: Trait`.
2197 let simplified_obligation_ty = fast_reject::simplify_type(
2200 SimplifyParams::Yes,
2201 StripReferences::No,
2203 let simplified_impl_ty = fast_reject::simplify_type(
2207 StripReferences::No,
2210 simplified_obligation_ty.is_some()
2211 && simplified_impl_ty.is_some()
2212 && simplified_obligation_ty != simplified_impl_ty
2214 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
2215 // Lifetimes can never cause a rejection.
2218 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
2219 // Conservatively ignore consts (i.e. assume they might
2220 // unify later) until we have `fast_reject` support for
2221 // them (if we'll ever need it, even).
2224 _ => unreachable!(),
2230 /// Normalize `where_clause_trait_ref` and try to match it against
2231 /// `obligation`. If successful, return any predicates that
2232 /// result from the normalization.
2233 fn match_where_clause_trait_ref(
2235 obligation: &TraitObligation<'tcx>,
2236 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2237 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2238 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2241 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2242 /// obligation is satisfied.
2243 #[instrument(skip(self), level = "debug")]
2244 fn match_poly_trait_ref(
2246 obligation: &TraitObligation<'tcx>,
2247 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2248 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2250 .at(&obligation.cause, obligation.param_env)
2251 // We don't want predicates for opaque types to just match all other types,
2252 // if there is an obligation on the opaque type, then that obligation must be met
2253 // opaquely. Otherwise we'd match any obligation to the opaque type and then error
2255 .define_opaque_types(false)
2256 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2257 .map(|InferOk { obligations, .. }| obligations)
2261 ///////////////////////////////////////////////////////////////////////////
2264 fn match_fresh_trait_refs(
2266 previous: ty::PolyTraitPredicate<'tcx>,
2267 current: ty::PolyTraitPredicate<'tcx>,
2268 param_env: ty::ParamEnv<'tcx>,
2270 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2271 matcher.relate(previous, current).is_ok()
2276 previous_stack: TraitObligationStackList<'o, 'tcx>,
2277 obligation: &'o TraitObligation<'tcx>,
2278 ) -> TraitObligationStack<'o, 'tcx> {
2279 let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
2281 let dfn = previous_stack.cache.next_dfn();
2282 let depth = previous_stack.depth() + 1;
2283 TraitObligationStack {
2286 reached_depth: Cell::new(depth),
2287 previous: previous_stack,
2293 #[instrument(skip(self), level = "debug")]
2294 fn closure_trait_ref_unnormalized(
2296 obligation: &TraitObligation<'tcx>,
2297 substs: SubstsRef<'tcx>,
2298 ) -> ty::PolyTraitRef<'tcx> {
2299 let closure_sig = substs.as_closure().sig();
2301 debug!(?closure_sig);
2303 // (1) Feels icky to skip the binder here, but OTOH we know
2304 // that the self-type is an unboxed closure type and hence is
2305 // in fact unparameterized (or at least does not reference any
2306 // regions bound in the obligation). Still probably some
2307 // refactoring could make this nicer.
2308 closure_trait_ref_and_return_type(
2310 obligation.predicate.def_id(),
2311 obligation.predicate.skip_binder().self_ty(), // (1)
2313 util::TupleArgumentsFlag::No,
2315 .map_bound(|(trait_ref, _)| trait_ref)
2318 fn generator_trait_ref_unnormalized(
2320 obligation: &TraitObligation<'tcx>,
2321 substs: SubstsRef<'tcx>,
2322 ) -> ty::PolyTraitRef<'tcx> {
2323 let gen_sig = substs.as_generator().poly_sig();
2325 // (1) Feels icky to skip the binder here, but OTOH we know
2326 // that the self-type is an generator type and hence is
2327 // in fact unparameterized (or at least does not reference any
2328 // regions bound in the obligation). Still probably some
2329 // refactoring could make this nicer.
2331 super::util::generator_trait_ref_and_outputs(
2333 obligation.predicate.def_id(),
2334 obligation.predicate.skip_binder().self_ty(), // (1)
2337 .map_bound(|(trait_ref, ..)| trait_ref)
2340 /// Returns the obligations that are implied by instantiating an
2341 /// impl or trait. The obligations are substituted and fully
2342 /// normalized. This is used when confirming an impl or default
2344 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2345 fn impl_or_trait_obligations(
2347 cause: ObligationCause<'tcx>,
2348 recursion_depth: usize,
2349 param_env: ty::ParamEnv<'tcx>,
2350 def_id: DefId, // of impl or trait
2351 substs: SubstsRef<'tcx>, // for impl or trait
2352 ) -> Vec<PredicateObligation<'tcx>> {
2353 let tcx = self.tcx();
2355 // To allow for one-pass evaluation of the nested obligation,
2356 // each predicate must be preceded by the obligations required
2358 // for example, if we have:
2359 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2360 // the impl will have the following predicates:
2361 // <V as Iterator>::Item = U,
2362 // U: Iterator, U: Sized,
2363 // V: Iterator, V: Sized,
2364 // <U as Iterator>::Item: Copy
2365 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2366 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2367 // `$1: Copy`, so we must ensure the obligations are emitted in
2369 let predicates = tcx.predicates_of(def_id);
2370 debug!(?predicates);
2371 assert_eq!(predicates.parent, None);
2372 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2373 for (predicate, _) in predicates.predicates {
2375 let predicate = normalize_with_depth_to(
2380 predicate.subst(tcx, substs),
2383 obligations.push(Obligation {
2384 cause: cause.clone(),
2391 // We are performing deduplication here to avoid exponential blowups
2392 // (#38528) from happening, but the real cause of the duplication is
2393 // unknown. What we know is that the deduplication avoids exponential
2394 // amount of predicates being propagated when processing deeply nested
2397 // This code is hot enough that it's worth avoiding the allocation
2398 // required for the FxHashSet when possible. Special-casing lengths 0,
2399 // 1 and 2 covers roughly 75-80% of the cases.
2400 if obligations.len() <= 1 {
2401 // No possibility of duplicates.
2402 } else if obligations.len() == 2 {
2403 // Only two elements. Drop the second if they are equal.
2404 if obligations[0] == obligations[1] {
2405 obligations.truncate(1);
2408 // Three or more elements. Use a general deduplication process.
2409 let mut seen = FxHashSet::default();
2410 obligations.retain(|i| seen.insert(i.clone()));
2417 trait TraitObligationExt<'tcx> {
2420 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2421 ) -> ObligationCause<'tcx>;
2424 impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
2427 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2428 ) -> ObligationCause<'tcx> {
2430 * Creates a cause for obligations that are derived from
2431 * `obligation` by a recursive search (e.g., for a builtin
2432 * bound, or eventually a `auto trait Foo`). If `obligation`
2433 * is itself a derived obligation, this is just a clone, but
2434 * otherwise we create a "derived obligation" cause so as to
2435 * keep track of the original root obligation for error
2439 let obligation = self;
2441 // NOTE(flaper87): As of now, it keeps track of the whole error
2442 // chain. Ideally, we should have a way to configure this either
2443 // by using -Z verbose or just a CLI argument.
2444 let derived_cause = DerivedObligationCause {
2445 parent_trait_pred: obligation.predicate,
2446 parent_code: obligation.cause.clone_code(),
2448 let derived_code = variant(derived_cause);
2449 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2453 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2454 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2455 TraitObligationStackList::with(self)
2458 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2462 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2466 /// Indicates that attempting to evaluate this stack entry
2467 /// required accessing something from the stack at depth `reached_depth`.
2468 fn update_reached_depth(&self, reached_depth: usize) {
2470 self.depth >= reached_depth,
2471 "invoked `update_reached_depth` with something under this stack: \
2472 self.depth={} reached_depth={}",
2476 debug!(reached_depth, "update_reached_depth");
2478 while reached_depth < p.depth {
2479 debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
2480 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2481 p = p.previous.head.unwrap();
2486 /// The "provisional evaluation cache" is used to store intermediate cache results
2487 /// when solving auto traits. Auto traits are unusual in that they can support
2488 /// cycles. So, for example, a "proof tree" like this would be ok:
2490 /// - `Foo<T>: Send` :-
2491 /// - `Bar<T>: Send` :-
2492 /// - `Foo<T>: Send` -- cycle, but ok
2493 /// - `Baz<T>: Send`
2495 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2496 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2497 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2498 /// they are coinductive) it is considered ok.
2500 /// However, there is a complication: at the point where we have
2501 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2502 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2503 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2504 /// find out this assumption is wrong? Specifically, we could
2505 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2506 /// `Bar<T>: Send` didn't turn out to be true.
2508 /// In Issue #60010, we found a bug in rustc where it would cache
2509 /// these intermediate results. This was fixed in #60444 by disabling
2510 /// *all* caching for things involved in a cycle -- in our example,
2511 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2512 /// to large slowdowns.
2514 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2515 /// first requires proving `Bar<T>: Send` (which is true:
2517 /// - `Foo<T>: Send` :-
2518 /// - `Bar<T>: Send` :-
2519 /// - `Foo<T>: Send` -- cycle, but ok
2520 /// - `Baz<T>: Send`
2521 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2522 /// - `*const T: Send` -- but what if we later encounter an error?
2524 /// The *provisional evaluation cache* resolves this issue. It stores
2525 /// cache results that we've proven but which were involved in a cycle
2526 /// in some way. We track the minimal stack depth (i.e., the
2527 /// farthest from the top of the stack) that we are dependent on.
2528 /// The idea is that the cache results within are all valid -- so long as
2529 /// none of the nodes in between the current node and the node at that minimum
2530 /// depth result in an error (in which case the cached results are just thrown away).
2532 /// During evaluation, we consult this provisional cache and rely on
2533 /// it. Accessing a cached value is considered equivalent to accessing
2534 /// a result at `reached_depth`, so it marks the *current* solution as
2535 /// provisional as well. If an error is encountered, we toss out any
2536 /// provisional results added from the subtree that encountered the
2537 /// error. When we pop the node at `reached_depth` from the stack, we
2538 /// can commit all the things that remain in the provisional cache.
2539 struct ProvisionalEvaluationCache<'tcx> {
2540 /// next "depth first number" to issue -- just a counter
2543 /// Map from cache key to the provisionally evaluated thing.
2544 /// The cache entries contain the result but also the DFN in which they
2545 /// were added. The DFN is used to clear out values on failure.
2547 /// Imagine we have a stack like:
2549 /// - `A B C` and we add a cache for the result of C (DFN 2)
2550 /// - Then we have a stack `A B D` where `D` has DFN 3
2551 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2552 /// - `E` generates various cache entries which have cyclic dependices on `B`
2553 /// - `A B D E F` and so forth
2554 /// - the DFN of `F` for example would be 5
2555 /// - then we determine that `E` is in error -- we will then clear
2556 /// all cache values whose DFN is >= 4 -- in this case, that
2557 /// means the cached value for `F`.
2558 map: RefCell<FxHashMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
2561 /// A cache value for the provisional cache: contains the depth-first
2562 /// number (DFN) and result.
2563 #[derive(Copy, Clone, Debug)]
2564 struct ProvisionalEvaluation {
2566 reached_depth: usize,
2567 result: EvaluationResult,
2568 /// The `DepNodeIndex` created for the `evaluate_stack` call for this provisional
2569 /// evaluation. When we create an entry in the evaluation cache using this provisional
2570 /// cache entry (see `on_completion`), we use this `dep_node` to ensure that future reads from
2571 /// the cache will have all of the necessary incr comp dependencies tracked.
2572 dep_node: DepNodeIndex,
2575 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2576 fn default() -> Self {
2577 Self { dfn: Cell::new(0), map: Default::default() }
2581 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2582 /// Get the next DFN in sequence (basically a counter).
2583 fn next_dfn(&self) -> usize {
2584 let result = self.dfn.get();
2585 self.dfn.set(result + 1);
2589 /// Check the provisional cache for any result for
2590 /// `fresh_trait_ref`. If there is a hit, then you must consider
2591 /// it an access to the stack slots at depth
2592 /// `reached_depth` (from the returned value).
2595 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2596 ) -> Option<ProvisionalEvaluation> {
2599 "get_provisional = {:#?}",
2600 self.map.borrow().get(&fresh_trait_pred),
2602 Some(*self.map.borrow().get(&fresh_trait_pred)?)
2605 /// Insert a provisional result into the cache. The result came
2606 /// from the node with the given DFN. It accessed a minimum depth
2607 /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
2608 /// and resulted in `result`.
2609 fn insert_provisional(
2612 reached_depth: usize,
2613 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
2614 result: EvaluationResult,
2615 dep_node: DepNodeIndex,
2617 debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
2619 let mut map = self.map.borrow_mut();
2621 // Subtle: when we complete working on the DFN `from_dfn`, anything
2622 // that remains in the provisional cache must be dependent on some older
2623 // stack entry than `from_dfn`. We have to update their depth with our transitive
2624 // depth in that case or else it would be referring to some popped note.
2627 // A (reached depth 0)
2629 // B // depth 1 -- reached depth = 0
2630 // C // depth 2 -- reached depth = 1 (should be 0)
2633 // D (reached depth 1)
2634 // C (cache -- reached depth = 2)
2635 for (_k, v) in &mut *map {
2636 if v.from_dfn >= from_dfn {
2637 v.reached_depth = reached_depth.min(v.reached_depth);
2643 ProvisionalEvaluation { from_dfn, reached_depth, result, dep_node },
2647 /// Invoked when the node with dfn `dfn` does not get a successful
2648 /// result. This will clear out any provisional cache entries
2649 /// that were added since `dfn` was created. This is because the
2650 /// provisional entries are things which must assume that the
2651 /// things on the stack at the time of their creation succeeded --
2652 /// since the failing node is presently at the top of the stack,
2653 /// these provisional entries must either depend on it or some
2655 fn on_failure(&self, dfn: usize) {
2656 debug!(?dfn, "on_failure");
2657 self.map.borrow_mut().retain(|key, eval| {
2658 if !eval.from_dfn >= dfn {
2659 debug!("on_failure: removing {:?}", key);
2667 /// Invoked when the node at depth `depth` completed without
2668 /// depending on anything higher in the stack (if that completion
2669 /// was a failure, then `on_failure` should have been invoked
2670 /// already). The callback `op` will be invoked for each
2671 /// provisional entry that we can now confirm.
2673 /// Note that we may still have provisional cache items remaining
2674 /// in the cache when this is done. For example, if there is a
2677 /// * A depends on...
2678 /// * B depends on A
2679 /// * C depends on...
2680 /// * D depends on C
2683 /// Then as we complete the C node we will have a provisional cache
2684 /// with results for A, B, C, and D. This method would clear out
2685 /// the C and D results, but leave A and B provisional.
2687 /// This is determined based on the DFN: we remove any provisional
2688 /// results created since `dfn` started (e.g., in our example, dfn
2689 /// would be 2, representing the C node, and hence we would
2690 /// remove the result for D, which has DFN 3, but not the results for
2691 /// A and B, which have DFNs 0 and 1 respectively).
2695 mut op: impl FnMut(ty::PolyTraitPredicate<'tcx>, EvaluationResult, DepNodeIndex),
2697 debug!(?dfn, "on_completion");
2699 for (fresh_trait_pred, eval) in
2700 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2702 debug!(?fresh_trait_pred, ?eval, "on_completion");
2704 op(fresh_trait_pred, eval.result, eval.dep_node);
2709 #[derive(Copy, Clone)]
2710 struct TraitObligationStackList<'o, 'tcx> {
2711 cache: &'o ProvisionalEvaluationCache<'tcx>,
2712 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2715 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2716 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2717 TraitObligationStackList { cache, head: None }
2720 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2721 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2724 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2728 fn depth(&self) -> usize {
2729 if let Some(head) = self.head { head.depth } else { 0 }
2733 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2734 type Item = &'o TraitObligationStack<'o, 'tcx>;
2736 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2743 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2744 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2745 write!(f, "TraitObligationStack({:?})", self.obligation)