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_hir
::Constness
;
36 use rustc_infer
::infer
::LateBoundRegionConversionTime
;
37 use rustc_middle
::dep_graph
::{DepKind, DepNodeIndex}
;
38 use rustc_middle
::mir
::abstract_const
::NotConstEvaluatable
;
39 use rustc_middle
::mir
::interpret
::ErrorHandled
;
40 use rustc_middle
::ty
::fast_reject
;
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, WithConstness}
;
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 ref from `obligation` but "freshened" with the
143 /// selection-context's freshener. Used to check for recursion.
144 fresh_trait_ref
: ty
::PolyTraitRef
<'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?
205 enum BuiltinImplConditions
<'tcx
> {
206 /// The impl is conditional on `T1, T2, ...: Trait`.
207 Where(ty
::Binder
<'tcx
, Vec
<Ty
<'tcx
>>>),
208 /// There is no built-in impl. There may be some other
209 /// candidate (a where-clause or user-defined impl).
211 /// It is unknown whether there is an impl.
215 impl<'cx
, 'tcx
> SelectionContext
<'cx
, 'tcx
> {
216 pub fn new(infcx
: &'cx InferCtxt
<'cx
, 'tcx
>) -> SelectionContext
<'cx
, 'tcx
> {
219 freshener
: infcx
.freshener_keep_static(),
221 intercrate_ambiguity_causes
: None
,
222 allow_negative_impls
: false,
223 query_mode
: TraitQueryMode
::Standard
,
227 pub fn intercrate(infcx
: &'cx InferCtxt
<'cx
, 'tcx
>) -> SelectionContext
<'cx
, 'tcx
> {
230 freshener
: infcx
.freshener_keep_static(),
232 intercrate_ambiguity_causes
: None
,
233 allow_negative_impls
: false,
234 query_mode
: TraitQueryMode
::Standard
,
238 pub fn with_negative(
239 infcx
: &'cx InferCtxt
<'cx
, 'tcx
>,
240 allow_negative_impls
: bool
,
241 ) -> SelectionContext
<'cx
, 'tcx
> {
242 debug
!(?allow_negative_impls
, "with_negative");
245 freshener
: infcx
.freshener_keep_static(),
247 intercrate_ambiguity_causes
: None
,
248 allow_negative_impls
,
249 query_mode
: TraitQueryMode
::Standard
,
253 pub fn with_query_mode(
254 infcx
: &'cx InferCtxt
<'cx
, 'tcx
>,
255 query_mode
: TraitQueryMode
,
256 ) -> SelectionContext
<'cx
, 'tcx
> {
257 debug
!(?query_mode
, "with_query_mode");
260 freshener
: infcx
.freshener_keep_static(),
262 intercrate_ambiguity_causes
: None
,
263 allow_negative_impls
: false,
268 /// Enables tracking of intercrate ambiguity causes. These are
269 /// used in coherence to give improved diagnostics. We don't do
270 /// this until we detect a coherence error because it can lead to
271 /// false overflow results (#47139) and because it costs
272 /// computation time.
273 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
274 assert
!(self.intercrate
);
275 assert
!(self.intercrate_ambiguity_causes
.is_none());
276 self.intercrate_ambiguity_causes
= Some(vec
![]);
277 debug
!("selcx: enable_tracking_intercrate_ambiguity_causes");
280 /// Gets the intercrate ambiguity causes collected since tracking
281 /// was enabled and disables tracking at the same time. If
282 /// tracking is not enabled, just returns an empty vector.
283 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec
<IntercrateAmbiguityCause
> {
284 assert
!(self.intercrate
);
285 self.intercrate_ambiguity_causes
.take().unwrap_or_default()
288 pub fn infcx(&self) -> &'cx InferCtxt
<'cx
, 'tcx
> {
292 pub fn tcx(&self) -> TyCtxt
<'tcx
> {
296 ///////////////////////////////////////////////////////////////////////////
299 // The selection phase tries to identify *how* an obligation will
300 // be resolved. For example, it will identify which impl or
301 // parameter bound is to be used. The process can be inconclusive
302 // if the self type in the obligation is not fully inferred. Selection
303 // can result in an error in one of two ways:
305 // 1. If no applicable impl or parameter bound can be found.
306 // 2. If the output type parameters in the obligation do not match
307 // those specified by the impl/bound. For example, if the obligation
308 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
309 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
311 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
312 /// type environment by performing unification.
313 #[instrument(level = "debug", skip(self))]
316 obligation
: &TraitObligation
<'tcx
>,
317 ) -> SelectionResult
<'tcx
, Selection
<'tcx
>> {
318 debug_assert
!(!obligation
.predicate
.has_escaping_bound_vars());
320 let pec
= &ProvisionalEvaluationCache
::default();
321 let stack
= self.push_stack(TraitObligationStackList
::empty(pec
), obligation
);
323 let candidate
= match self.candidate_from_obligation(&stack
) {
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
);
336 Ok(Some(candidate
)) => candidate
,
339 match self.confirm_candidate(obligation
, candidate
) {
340 Err(SelectionError
::Overflow
) => {
341 assert
!(self.query_mode
== TraitQueryMode
::Canonical
);
342 Err(SelectionError
::Overflow
)
352 ///////////////////////////////////////////////////////////////////////////
355 // Tests whether an obligation can be selected or whether an impl
356 // can be applied to particular types. It skips the "confirmation"
357 // step and hence completely ignores output type parameters.
359 // The result is "true" if the obligation *may* hold and "false" if
360 // we can be sure it does not.
362 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
363 pub fn predicate_may_hold_fatal(&mut self, obligation
: &PredicateObligation
<'tcx
>) -> bool
{
364 debug
!(?obligation
, "predicate_may_hold_fatal");
366 // This fatal query is a stopgap that should only be used in standard mode,
367 // where we do not expect overflow to be propagated.
368 assert
!(self.query_mode
== TraitQueryMode
::Standard
);
370 self.evaluate_root_obligation(obligation
)
371 .expect("Overflow should be caught earlier in standard query mode")
375 /// Evaluates whether the obligation `obligation` can be satisfied
376 /// and returns an `EvaluationResult`. This is meant for the
378 pub fn evaluate_root_obligation(
380 obligation
: &PredicateObligation
<'tcx
>,
381 ) -> Result
<EvaluationResult
, OverflowError
> {
382 self.evaluation_probe(|this
| {
383 this
.evaluate_predicate_recursively(
384 TraitObligationStackList
::empty(&ProvisionalEvaluationCache
::default()),
392 op
: impl FnOnce(&mut Self) -> Result
<EvaluationResult
, OverflowError
>,
393 ) -> Result
<EvaluationResult
, OverflowError
> {
394 self.infcx
.probe(|snapshot
| -> Result
<EvaluationResult
, OverflowError
> {
395 let result
= op(self)?
;
397 match self.infcx
.leak_check(true, snapshot
) {
399 Err(_
) => return Ok(EvaluatedToErr
),
402 match self.infcx
.region_constraints_added_in_snapshot(snapshot
) {
404 Some(_
) => Ok(result
.max(EvaluatedToOkModuloRegions
)),
409 /// Evaluates the predicates in `predicates` recursively. Note that
410 /// this applies projections in the predicates, and therefore
411 /// is run within an inference probe.
412 fn evaluate_predicates_recursively
<'o
, I
>(
414 stack
: TraitObligationStackList
<'o
, 'tcx
>,
416 ) -> Result
<EvaluationResult
, OverflowError
>
418 I
: IntoIterator
<Item
= PredicateObligation
<'tcx
>> + std
::fmt
::Debug
,
420 let mut result
= EvaluatedToOk
;
421 debug
!(?predicates
, "evaluate_predicates_recursively");
422 for obligation
in predicates
{
423 let eval
= self.evaluate_predicate_recursively(stack
, obligation
.clone())?
;
424 if let EvaluatedToErr
= eval
{
425 // fast-path - EvaluatedToErr is the top of the lattice,
426 // so we don't need to look on the other predicates.
427 return Ok(EvaluatedToErr
);
429 result
= cmp
::max(result
, eval
);
437 skip(self, previous_stack
),
438 fields(previous_stack
= ?previous_stack
.head())
440 fn evaluate_predicate_recursively
<'o
>(
442 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
443 obligation
: PredicateObligation
<'tcx
>,
444 ) -> Result
<EvaluationResult
, OverflowError
> {
445 // `previous_stack` stores a `TraitObligation`, while `obligation` is
446 // a `PredicateObligation`. These are distinct types, so we can't
447 // use any `Option` combinator method that would force them to be
449 match previous_stack
.head() {
450 Some(h
) => self.check_recursion_limit(&obligation
, h
.obligation
)?
,
451 None
=> self.check_recursion_limit(&obligation
, &obligation
)?
,
454 let result
= ensure_sufficient_stack(|| {
455 let bound_predicate
= obligation
.predicate
.kind();
456 match bound_predicate
.skip_binder() {
457 ty
::PredicateKind
::Trait(t
, _
) => {
458 let t
= bound_predicate
.rebind(t
);
459 debug_assert
!(!t
.has_escaping_bound_vars());
460 let obligation
= obligation
.with(t
);
461 self.evaluate_trait_predicate_recursively(previous_stack
, obligation
)
464 ty
::PredicateKind
::Subtype(p
) => {
465 let p
= bound_predicate
.rebind(p
);
466 // Does this code ever run?
467 match self.infcx
.subtype_predicate(&obligation
.cause
, obligation
.param_env
, p
) {
468 Some(Ok(InferOk { mut obligations, .. }
)) => {
469 self.add_depth(obligations
.iter_mut(), obligation
.recursion_depth
);
470 self.evaluate_predicates_recursively(
472 obligations
.into_iter(),
475 Some(Err(_
)) => Ok(EvaluatedToErr
),
476 None
=> Ok(EvaluatedToAmbig
),
480 ty
::PredicateKind
::WellFormed(arg
) => match wf
::obligations(
482 obligation
.param_env
,
483 obligation
.cause
.body_id
,
484 obligation
.recursion_depth
+ 1,
486 obligation
.cause
.span
,
488 Some(mut obligations
) => {
489 self.add_depth(obligations
.iter_mut(), obligation
.recursion_depth
);
490 self.evaluate_predicates_recursively(previous_stack
, obligations
)
492 None
=> Ok(EvaluatedToAmbig
),
495 ty
::PredicateKind
::TypeOutlives(pred
) => {
496 if pred
.0.is_global
() {
499 Ok(EvaluatedToOkModuloRegions
)
503 ty
::PredicateKind
::RegionOutlives(..) => {
504 // We do not consider region relationships when evaluating trait matches.
505 Ok(EvaluatedToOkModuloRegions
)
508 ty
::PredicateKind
::ObjectSafe(trait_def_id
) => {
509 if self.tcx().is_object_safe(trait_def_id
) {
516 ty
::PredicateKind
::Projection(data
) => {
517 let data
= bound_predicate
.rebind(data
);
518 let project_obligation
= obligation
.with(data
);
519 match project
::poly_project_and_unify_type(self, &project_obligation
) {
520 Ok(Ok(Some(mut subobligations
))) => {
521 self.add_depth(subobligations
.iter_mut(), obligation
.recursion_depth
);
523 .evaluate_predicates_recursively(previous_stack
, subobligations
);
525 ProjectionCacheKey
::from_poly_projection_predicate(self, data
)
527 self.infcx
.inner
.borrow_mut().projection_cache().complete(key
);
531 Ok(Ok(None
)) => Ok(EvaluatedToAmbig
),
532 Ok(Err(project
::InProgress
)) => Ok(EvaluatedToRecur
),
533 Err(_
) => Ok(EvaluatedToErr
),
537 ty
::PredicateKind
::ClosureKind(_
, closure_substs
, kind
) => {
538 match self.infcx
.closure_kind(closure_substs
) {
539 Some(closure_kind
) => {
540 if closure_kind
.extends(kind
) {
546 None
=> Ok(EvaluatedToAmbig
),
550 ty
::PredicateKind
::ConstEvaluatable(def_id
, substs
) => {
551 match const_evaluatable
::is_const_evaluatable(
555 obligation
.param_env
,
556 obligation
.cause
.span
,
558 Ok(()) => Ok(EvaluatedToOk
),
559 Err(NotConstEvaluatable
::MentionsInfer
) => Ok(EvaluatedToAmbig
),
560 Err(NotConstEvaluatable
::MentionsParam
) => Ok(EvaluatedToErr
),
561 Err(_
) => Ok(EvaluatedToErr
),
565 ty
::PredicateKind
::ConstEquate(c1
, c2
) => {
566 debug
!(?c1
, ?c2
, "evaluate_predicate_recursively: equating consts");
568 if self.tcx().features().const_evaluatable_checked
{
569 // FIXME: we probably should only try to unify abstract constants
570 // if the constants depend on generic parameters.
572 // Let's just see where this breaks :shrug:
573 if let (ty
::ConstKind
::Unevaluated(a
), ty
::ConstKind
::Unevaluated(b
)) =
578 .try_unify_abstract_consts(((a
.def
, a
.substs
), (b
.def
, b
.substs
)))
580 return Ok(EvaluatedToOk
);
585 let evaluate
= |c
: &'tcx ty
::Const
<'tcx
>| {
586 if let ty
::ConstKind
::Unevaluated(unevaluated
) = c
.val
{
589 obligation
.param_env
,
591 Some(obligation
.cause
.span
),
593 .map(|val
| ty
::Const
::from_value(self.tcx(), val
, c
.ty
))
599 match (evaluate(c1
), evaluate(c2
)) {
600 (Ok(c1
), Ok(c2
)) => {
603 .at(&obligation
.cause
, obligation
.param_env
)
606 Ok(_
) => Ok(EvaluatedToOk
),
607 Err(_
) => Ok(EvaluatedToErr
),
610 (Err(ErrorHandled
::Reported(ErrorReported
)), _
)
611 | (_
, Err(ErrorHandled
::Reported(ErrorReported
))) => Ok(EvaluatedToErr
),
612 (Err(ErrorHandled
::Linted
), _
) | (_
, Err(ErrorHandled
::Linted
)) => {
614 obligation
.cause
.span(self.tcx()),
615 "ConstEquate: const_eval_resolve returned an unexpected error"
618 (Err(ErrorHandled
::TooGeneric
), _
) | (_
, Err(ErrorHandled
::TooGeneric
)) => {
619 if c1
.has_infer_types_or_consts() || c2
.has_infer_types_or_consts() {
622 // Two different constants using generic parameters ~> error.
628 ty
::PredicateKind
::TypeWellFormedFromEnv(..) => {
629 bug
!("TypeWellFormedFromEnv is only used for chalk")
639 fn evaluate_trait_predicate_recursively
<'o
>(
641 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
642 mut obligation
: TraitObligation
<'tcx
>,
643 ) -> Result
<EvaluationResult
, OverflowError
> {
644 debug
!(?obligation
, "evaluate_trait_predicate_recursively");
647 && obligation
.is_global()
648 && obligation
.param_env
.caller_bounds().iter().all(|bound
| bound
.needs_subst())
650 // If a param env has no global bounds, global obligations do not
651 // depend on its particular value in order to work, so we can clear
652 // out the param env and get better caching.
653 debug
!("evaluate_trait_predicate_recursively - in global");
654 obligation
.param_env
= obligation
.param_env
.without_caller_bounds();
657 let stack
= self.push_stack(previous_stack
, &obligation
);
658 let fresh_trait_ref
= stack
.fresh_trait_ref
;
660 debug
!(?fresh_trait_ref
);
662 if let Some(result
) = self.check_evaluation_cache(obligation
.param_env
, fresh_trait_ref
) {
663 debug
!(?result
, "CACHE HIT");
667 if let Some(result
) = stack
.cache().get_provisional(fresh_trait_ref
) {
668 debug
!(?result
, "PROVISIONAL CACHE HIT");
669 stack
.update_reached_depth(result
.reached_depth
);
670 return Ok(result
.result
);
673 // Check if this is a match for something already on the
674 // stack. If so, we don't want to insert the result into the
675 // main cache (it is cycle dependent) nor the provisional
676 // cache (which is meant for things that have completed but
677 // for a "backedge" -- this result *is* the backedge).
678 if let Some(cycle_result
) = self.check_evaluation_cycle(&stack
) {
679 return Ok(cycle_result
);
682 let (result
, dep_node
) = self.in_task(|this
| this
.evaluate_stack(&stack
));
683 let result
= result?
;
685 if !result
.must_apply_modulo_regions() {
686 stack
.cache().on_failure(stack
.dfn
);
689 let reached_depth
= stack
.reached_depth
.get();
690 if reached_depth
>= stack
.depth
{
691 debug
!(?result
, "CACHE MISS");
692 self.insert_evaluation_cache(obligation
.param_env
, fresh_trait_ref
, dep_node
, result
);
694 stack
.cache().on_completion(stack
.dfn
, |fresh_trait_ref
, provisional_result
| {
695 self.insert_evaluation_cache(
696 obligation
.param_env
,
699 provisional_result
.max(result
),
703 debug
!(?result
, "PROVISIONAL");
705 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
706 is a cycle participant (at depth {}, reached depth {})",
707 fresh_trait_ref
, stack
.depth
, reached_depth
,
710 stack
.cache().insert_provisional(stack
.dfn
, reached_depth
, fresh_trait_ref
, result
);
716 /// If there is any previous entry on the stack that precisely
717 /// matches this obligation, then we can assume that the
718 /// obligation is satisfied for now (still all other conditions
719 /// must be met of course). One obvious case this comes up is
720 /// marker traits like `Send`. Think of a linked list:
722 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
724 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
725 /// `Option<Box<List<T>>>` is `Send`, and in turn
726 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
729 /// Note that we do this comparison using the `fresh_trait_ref`
730 /// fields. Because these have all been freshened using
731 /// `self.freshener`, we can be sure that (a) this will not
732 /// affect the inferencer state and (b) that if we see two
733 /// fresh regions with the same index, they refer to the same
734 /// unbound type variable.
735 fn check_evaluation_cycle(
737 stack
: &TraitObligationStack
<'_
, 'tcx
>,
738 ) -> Option
<EvaluationResult
> {
739 if let Some(cycle_depth
) = stack
741 .skip(1) // Skip top-most frame.
743 stack
.obligation
.param_env
== prev
.obligation
.param_env
744 && stack
.fresh_trait_ref
== prev
.fresh_trait_ref
746 .map(|stack
| stack
.depth
)
748 debug
!("evaluate_stack --> recursive at depth {}", cycle_depth
);
750 // If we have a stack like `A B C D E A`, where the top of
751 // the stack is the final `A`, then this will iterate over
752 // `A, E, D, C, B` -- i.e., all the participants apart
753 // from the cycle head. We mark them as participating in a
754 // cycle. This suppresses caching for those nodes. See
755 // `in_cycle` field for more details.
756 stack
.update_reached_depth(cycle_depth
);
758 // Subtle: when checking for a coinductive cycle, we do
759 // not compare using the "freshened trait refs" (which
760 // have erased regions) but rather the fully explicit
761 // trait refs. This is important because it's only a cycle
762 // if the regions match exactly.
763 let cycle
= stack
.iter().skip(1).take_while(|s
| s
.depth
>= cycle_depth
);
764 let tcx
= self.tcx();
766 cycle
.map(|stack
| stack
.obligation
.predicate
.without_const().to_predicate(tcx
));
767 if self.coinductive_match(cycle
) {
768 debug
!("evaluate_stack --> recursive, coinductive");
771 debug
!("evaluate_stack --> recursive, inductive");
772 Some(EvaluatedToRecur
)
779 fn evaluate_stack
<'o
>(
781 stack
: &TraitObligationStack
<'o
, 'tcx
>,
782 ) -> Result
<EvaluationResult
, OverflowError
> {
783 // In intercrate mode, whenever any of the generics are unbound,
784 // there can always be an impl. Even if there are no impls in
785 // this crate, perhaps the type would be unified with
786 // something from another crate that does provide an impl.
788 // In intra mode, we must still be conservative. The reason is
789 // that we want to avoid cycles. Imagine an impl like:
791 // impl<T:Eq> Eq for Vec<T>
793 // and a trait reference like `$0 : Eq` where `$0` is an
794 // unbound variable. When we evaluate this trait-reference, we
795 // will unify `$0` with `Vec<$1>` (for some fresh variable
796 // `$1`), on the condition that `$1 : Eq`. We will then wind
797 // up with many candidates (since that are other `Eq` impls
798 // that apply) and try to winnow things down. This results in
799 // a recursive evaluation that `$1 : Eq` -- as you can
800 // imagine, this is just where we started. To avoid that, we
801 // check for unbound variables and return an ambiguous (hence possible)
802 // match if we've seen this trait before.
804 // This suffices to allow chains like `FnMut` implemented in
805 // terms of `Fn` etc, but we could probably make this more
807 let unbound_input_types
=
808 stack
.fresh_trait_ref
.skip_binder().substs
.types().any(|ty
| ty
.is_fresh());
809 // This check was an imperfect workaround for a bug in the old
810 // intercrate mode; it should be removed when that goes away.
811 if unbound_input_types
&& self.intercrate
{
812 debug
!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
813 // Heuristics: show the diagnostics when there are no candidates in crate.
814 if self.intercrate_ambiguity_causes
.is_some() {
815 debug
!("evaluate_stack: intercrate_ambiguity_causes is some");
816 if let Ok(candidate_set
) = self.assemble_candidates(stack
) {
817 if !candidate_set
.ambiguous
&& candidate_set
.vec
.is_empty() {
818 let trait_ref
= stack
.obligation
.predicate
.skip_binder().trait_ref
;
819 let self_ty
= trait_ref
.self_ty();
821 with_no_trimmed_paths(|| IntercrateAmbiguityCause
::DownstreamCrate
{
822 trait_desc
: trait_ref
.print_only_trait_path().to_string(),
823 self_desc
: if self_ty
.has_concrete_skeleton() {
824 Some(self_ty
.to_string())
830 debug
!(?cause
, "evaluate_stack: pushing cause");
831 self.intercrate_ambiguity_causes
.as_mut().unwrap().push(cause
);
835 return Ok(EvaluatedToAmbig
);
837 if unbound_input_types
838 && stack
.iter().skip(1).any(|prev
| {
839 stack
.obligation
.param_env
== prev
.obligation
.param_env
840 && self.match_fresh_trait_refs(
841 stack
.fresh_trait_ref
,
842 prev
.fresh_trait_ref
,
843 prev
.obligation
.param_env
,
847 debug
!("evaluate_stack --> unbound argument, recursive --> giving up",);
848 return Ok(EvaluatedToUnknown
);
851 match self.candidate_from_obligation(stack
) {
852 Ok(Some(c
)) => self.evaluate_candidate(stack
, &c
),
853 Ok(None
) => Ok(EvaluatedToAmbig
),
854 Err(Overflow
) => Err(OverflowError
),
855 Err(..) => Ok(EvaluatedToErr
),
859 /// For defaulted traits, we use a co-inductive strategy to solve, so
860 /// that recursion is ok. This routine returns `true` if the top of the
861 /// stack (`cycle[0]`):
863 /// - is a defaulted trait,
864 /// - it also appears in the backtrace at some position `X`,
865 /// - all the predicates at positions `X..` between `X` and the top are
866 /// also defaulted traits.
867 pub fn coinductive_match
<I
>(&mut self, mut cycle
: I
) -> bool
869 I
: Iterator
<Item
= ty
::Predicate
<'tcx
>>,
871 cycle
.all(|predicate
| self.coinductive_predicate(predicate
))
874 fn coinductive_predicate(&self, predicate
: ty
::Predicate
<'tcx
>) -> bool
{
875 let result
= match predicate
.kind().skip_binder() {
876 ty
::PredicateKind
::Trait(ref data
, _
) => self.tcx().trait_is_auto(data
.def_id()),
879 debug
!(?predicate
, ?result
, "coinductive_predicate");
883 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
884 /// obligations are met. Returns whether `candidate` remains viable after this further
889 fields(depth
= stack
.obligation
.recursion_depth
)
891 fn evaluate_candidate
<'o
>(
893 stack
: &TraitObligationStack
<'o
, 'tcx
>,
894 candidate
: &SelectionCandidate
<'tcx
>,
895 ) -> Result
<EvaluationResult
, OverflowError
> {
896 let mut result
= self.evaluation_probe(|this
| {
897 let candidate
= (*candidate
).clone();
898 match this
.confirm_candidate(stack
.obligation
, candidate
) {
901 this
.evaluate_predicates_recursively(
903 selection
.nested_obligations().into_iter(),
906 Err(..) => Ok(EvaluatedToErr
),
910 // If we erased any lifetimes, then we want to use
911 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
912 // as your final result. The result will be cached using
913 // the freshened trait predicate as a key, so we need
914 // our result to be correct by *any* choice of original lifetimes,
915 // not just the lifetime choice for this particular (non-erased)
918 if stack
.fresh_trait_ref
.has_erased_regions() {
919 result
= result
.max(EvaluatedToOkModuloRegions
);
926 fn check_evaluation_cache(
928 param_env
: ty
::ParamEnv
<'tcx
>,
929 trait_ref
: ty
::PolyTraitRef
<'tcx
>,
930 ) -> Option
<EvaluationResult
> {
931 let tcx
= self.tcx();
932 if self.can_use_global_caches(param_env
) {
933 if let Some(res
) = tcx
.evaluation_cache
.get(¶m_env
.and(trait_ref
), tcx
) {
937 self.infcx
.evaluation_cache
.get(¶m_env
.and(trait_ref
), tcx
)
940 fn insert_evaluation_cache(
942 param_env
: ty
::ParamEnv
<'tcx
>,
943 trait_ref
: ty
::PolyTraitRef
<'tcx
>,
944 dep_node
: DepNodeIndex
,
945 result
: EvaluationResult
,
947 // Avoid caching results that depend on more than just the trait-ref
948 // - the stack can create recursion.
949 if result
.is_stack_dependent() {
953 if self.can_use_global_caches(param_env
) {
954 if !trait_ref
.needs_infer() {
955 debug
!(?trait_ref
, ?result
, "insert_evaluation_cache global");
956 // This may overwrite the cache with the same value
957 // FIXME: Due to #50507 this overwrites the different values
958 // This should be changed to use HashMapExt::insert_same
959 // when that is fixed
960 self.tcx().evaluation_cache
.insert(param_env
.and(trait_ref
), dep_node
, result
);
965 debug
!(?trait_ref
, ?result
, "insert_evaluation_cache");
966 self.infcx
.evaluation_cache
.insert(param_env
.and(trait_ref
), dep_node
, result
);
969 /// For various reasons, it's possible for a subobligation
970 /// to have a *lower* recursion_depth than the obligation used to create it.
971 /// Projection sub-obligations may be returned from the projection cache,
972 /// which results in obligations with an 'old' `recursion_depth`.
973 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
974 /// subobligations without taking in a 'parent' depth, causing the
975 /// generated subobligations to have a `recursion_depth` of `0`.
977 /// To ensure that obligation_depth never decreases, we force all subobligations
978 /// to have at least the depth of the original obligation.
979 fn add_depth
<T
: 'cx
, I
: Iterator
<Item
= &'cx
mut Obligation
<'tcx
, T
>>>(
984 it
.for_each(|o
| o
.recursion_depth
= cmp
::max(min_depth
, o
.recursion_depth
) + 1);
987 /// Checks that the recursion limit has not been exceeded.
989 /// The weird return type of this function allows it to be used with the `try` (`?`)
990 /// operator within certain functions.
991 fn check_recursion_limit
<T
: Display
+ TypeFoldable
<'tcx
>, V
: Display
+ TypeFoldable
<'tcx
>>(
993 obligation
: &Obligation
<'tcx
, T
>,
994 error_obligation
: &Obligation
<'tcx
, V
>,
995 ) -> Result
<(), OverflowError
> {
996 if !self.infcx
.tcx
.recursion_limit().value_within_limit(obligation
.recursion_depth
) {
997 match self.query_mode
{
998 TraitQueryMode
::Standard
=> {
999 self.infcx().report_overflow_error(error_obligation
, true);
1001 TraitQueryMode
::Canonical
=> {
1002 return Err(OverflowError
);
1009 fn in_task
<OP
, R
>(&mut self, op
: OP
) -> (R
, DepNodeIndex
)
1011 OP
: FnOnce(&mut Self) -> R
,
1013 let (result
, dep_node
) =
1014 self.tcx().dep_graph
.with_anon_task(self.tcx(), DepKind
::TraitSelect
, || op(self));
1015 self.tcx().dep_graph
.read_index(dep_node
);
1019 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
1020 fn filter_negative_and_reservation_impls(
1022 candidate
: SelectionCandidate
<'tcx
>,
1023 ) -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>> {
1024 if let ImplCandidate(def_id
) = candidate
{
1025 let tcx
= self.tcx();
1026 match tcx
.impl_polarity(def_id
) {
1027 ty
::ImplPolarity
::Negative
if !self.allow_negative_impls
=> {
1028 return Err(Unimplemented
);
1030 ty
::ImplPolarity
::Reservation
=> {
1031 if let Some(intercrate_ambiguity_clauses
) =
1032 &mut self.intercrate_ambiguity_causes
1034 let attrs
= tcx
.get_attrs(def_id
);
1035 let attr
= tcx
.sess
.find_by_name(&attrs
, sym
::rustc_reservation_impl
);
1036 let value
= attr
.and_then(|a
| a
.value_str());
1037 if let Some(value
) = value
{
1039 "filter_negative_and_reservation_impls: \
1040 reservation impl ambiguity on {:?}",
1043 intercrate_ambiguity_clauses
.push(
1044 IntercrateAmbiguityCause
::ReservationImpl
{
1045 message
: value
.to_string(),
1058 fn is_knowable
<'o
>(&mut self, stack
: &TraitObligationStack
<'o
, 'tcx
>) -> Option
<Conflict
> {
1059 debug
!("is_knowable(intercrate={:?})", self.intercrate
);
1061 if !self.intercrate
{
1065 let obligation
= &stack
.obligation
;
1066 let predicate
= self.infcx().resolve_vars_if_possible(obligation
.predicate
);
1068 // Okay to skip binder because of the nature of the
1069 // trait-ref-is-knowable check, which does not care about
1071 let trait_ref
= predicate
.skip_binder().trait_ref
;
1073 coherence
::trait_ref_is_knowable(self.tcx(), trait_ref
)
1076 /// Returns `true` if the global caches can be used.
1077 fn can_use_global_caches(&self, param_env
: ty
::ParamEnv
<'tcx
>) -> bool
{
1078 // If there are any inference variables in the `ParamEnv`, then we
1079 // always use a cache local to this particular scope. Otherwise, we
1080 // switch to a global cache.
1081 if param_env
.needs_infer() {
1085 // Avoid using the master cache during coherence and just rely
1086 // on the local cache. This effectively disables caching
1087 // during coherence. It is really just a simplification to
1088 // avoid us having to fear that coherence results "pollute"
1089 // the master cache. Since coherence executes pretty quickly,
1090 // it's not worth going to more trouble to increase the
1091 // hit-rate, I don't think.
1092 if self.intercrate
{
1096 // Otherwise, we can use the global cache.
1100 fn check_candidate_cache(
1102 param_env
: ty
::ParamEnv
<'tcx
>,
1103 cache_fresh_trait_pred
: ty
::PolyTraitPredicate
<'tcx
>,
1104 ) -> Option
<SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>> {
1105 let tcx
= self.tcx();
1106 let trait_ref
= &cache_fresh_trait_pred
.skip_binder().trait_ref
;
1107 if self.can_use_global_caches(param_env
) {
1108 if let Some(res
) = tcx
.selection_cache
.get(¶m_env
.and(*trait_ref
), tcx
) {
1112 self.infcx
.selection_cache
.get(¶m_env
.and(*trait_ref
), tcx
)
1115 /// Determines whether can we safely cache the result
1116 /// of selecting an obligation. This is almost always `true`,
1117 /// except when dealing with certain `ParamCandidate`s.
1119 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1120 /// since it was usually produced directly from a `DefId`. However,
1121 /// certain cases (currently only librustdoc's blanket impl finder),
1122 /// a `ParamEnv` may be explicitly constructed with inference types.
1123 /// When this is the case, we do *not* want to cache the resulting selection
1124 /// candidate. This is due to the fact that it might not always be possible
1125 /// to equate the obligation's trait ref and the candidate's trait ref,
1126 /// if more constraints end up getting added to an inference variable.
1128 /// Because of this, we always want to re-run the full selection
1129 /// process for our obligation the next time we see it, since
1130 /// we might end up picking a different `SelectionCandidate` (or none at all).
1131 fn can_cache_candidate(
1133 result
: &SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>,
1136 Ok(Some(SelectionCandidate
::ParamCandidate(trait_ref
))) => !trait_ref
.needs_infer(),
1141 fn insert_candidate_cache(
1143 param_env
: ty
::ParamEnv
<'tcx
>,
1144 cache_fresh_trait_pred
: ty
::PolyTraitPredicate
<'tcx
>,
1145 dep_node
: DepNodeIndex
,
1146 candidate
: SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>,
1148 let tcx
= self.tcx();
1149 let trait_ref
= cache_fresh_trait_pred
.skip_binder().trait_ref
;
1151 if !self.can_cache_candidate(&candidate
) {
1152 debug
!(?trait_ref
, ?candidate
, "insert_candidate_cache - candidate is not cacheable");
1156 if self.can_use_global_caches(param_env
) {
1157 if let Err(Overflow
) = candidate
{
1158 // Don't cache overflow globally; we only produce this in certain modes.
1159 } else if !trait_ref
.needs_infer() {
1160 if !candidate
.needs_infer() {
1161 debug
!(?trait_ref
, ?candidate
, "insert_candidate_cache global");
1162 // This may overwrite the cache with the same value.
1163 tcx
.selection_cache
.insert(param_env
.and(trait_ref
), dep_node
, candidate
);
1169 debug
!(?trait_ref
, ?candidate
, "insert_candidate_cache local");
1170 self.infcx
.selection_cache
.insert(param_env
.and(trait_ref
), dep_node
, candidate
);
1173 /// Matches a predicate against the bounds of its self type.
1175 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1176 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1177 /// `Baz` bound. We return indexes into the list returned by
1178 /// `tcx.item_bounds` for any applicable bounds.
1179 fn match_projection_obligation_against_definition_bounds(
1181 obligation
: &TraitObligation
<'tcx
>,
1182 ) -> smallvec
::SmallVec
<[usize; 2]> {
1183 let poly_trait_predicate
= self.infcx().resolve_vars_if_possible(obligation
.predicate
);
1184 let placeholder_trait_predicate
=
1185 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate
);
1187 ?placeholder_trait_predicate
,
1188 "match_projection_obligation_against_definition_bounds"
1191 let tcx
= self.infcx
.tcx
;
1192 let (def_id
, substs
) = match *placeholder_trait_predicate
.trait_ref
.self_ty().kind() {
1193 ty
::Projection(ref data
) => (data
.item_def_id
, data
.substs
),
1194 ty
::Opaque(def_id
, substs
) => (def_id
, substs
),
1197 obligation
.cause
.span
,
1198 "match_projection_obligation_against_definition_bounds() called \
1199 but self-ty is not a projection: {:?}",
1200 placeholder_trait_predicate
.trait_ref
.self_ty()
1204 let bounds
= tcx
.item_bounds(def_id
).subst(tcx
, substs
);
1206 // The bounds returned by `item_bounds` may contain duplicates after
1207 // normalization, so try to deduplicate when possible to avoid
1208 // unnecessary ambiguity.
1209 let mut distinct_normalized_bounds
= FxHashSet
::default();
1211 let matching_bounds
= bounds
1214 .filter_map(|(idx
, bound
)| {
1215 let bound_predicate
= bound
.kind();
1216 if let ty
::PredicateKind
::Trait(pred
, _
) = bound_predicate
.skip_binder() {
1217 let bound
= bound_predicate
.rebind(pred
.trait_ref
);
1218 if self.infcx
.probe(|_
| {
1219 match self.match_normalize_trait_ref(
1222 placeholder_trait_predicate
.trait_ref
,
1225 Ok(Some(normalized_trait
))
1226 if distinct_normalized_bounds
.insert(normalized_trait
) =>
1240 debug
!(?matching_bounds
, "match_projection_obligation_against_definition_bounds");
1244 /// Equates the trait in `obligation` with trait bound. If the two traits
1245 /// can be equated and the normalized trait bound doesn't contain inference
1246 /// variables or placeholders, the normalized bound is returned.
1247 fn match_normalize_trait_ref(
1249 obligation
: &TraitObligation
<'tcx
>,
1250 trait_bound
: ty
::PolyTraitRef
<'tcx
>,
1251 placeholder_trait_ref
: ty
::TraitRef
<'tcx
>,
1252 ) -> Result
<Option
<ty
::PolyTraitRef
<'tcx
>>, ()> {
1253 debug_assert
!(!placeholder_trait_ref
.has_escaping_bound_vars());
1254 if placeholder_trait_ref
.def_id
!= trait_bound
.def_id() {
1255 // Avoid unnecessary normalization
1259 let Normalized { value: trait_bound, obligations: _ }
= ensure_sufficient_stack(|| {
1260 project
::normalize_with_depth(
1262 obligation
.param_env
,
1263 obligation
.cause
.clone(),
1264 obligation
.recursion_depth
+ 1,
1269 .at(&obligation
.cause
, obligation
.param_env
)
1270 .sup(ty
::Binder
::dummy(placeholder_trait_ref
), trait_bound
)
1271 .map(|InferOk { obligations: _, value: () }
| {
1272 // This method is called within a probe, so we can't have
1273 // inference variables and placeholders escape.
1274 if !trait_bound
.needs_infer() && !trait_bound
.has_placeholders() {
1283 fn evaluate_where_clause
<'o
>(
1285 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1286 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
1287 ) -> Result
<EvaluationResult
, OverflowError
> {
1288 self.evaluation_probe(|this
| {
1289 match this
.match_where_clause_trait_ref(stack
.obligation
, where_clause_trait_ref
) {
1290 Ok(obligations
) => this
.evaluate_predicates_recursively(stack
.list(), obligations
),
1291 Err(()) => Ok(EvaluatedToErr
),
1296 pub(super) fn match_projection_projections(
1298 obligation
: &ProjectionTyObligation
<'tcx
>,
1299 env_predicate
: PolyProjectionPredicate
<'tcx
>,
1300 potentially_unnormalized_candidates
: bool
,
1302 let mut nested_obligations
= Vec
::new();
1303 let (infer_predicate
, _
) = self.infcx
.replace_bound_vars_with_fresh_vars(
1304 obligation
.cause
.span
,
1305 LateBoundRegionConversionTime
::HigherRankedType
,
1308 let infer_projection
= if potentially_unnormalized_candidates
{
1309 ensure_sufficient_stack(|| {
1310 project
::normalize_with_depth_to(
1312 obligation
.param_env
,
1313 obligation
.cause
.clone(),
1314 obligation
.recursion_depth
+ 1,
1315 infer_predicate
.projection_ty
,
1316 &mut nested_obligations
,
1320 infer_predicate
.projection_ty
1324 .at(&obligation
.cause
, obligation
.param_env
)
1325 .sup(obligation
.predicate
, infer_projection
)
1326 .map_or(false, |InferOk { obligations, value: () }
| {
1327 self.evaluate_predicates_recursively(
1328 TraitObligationStackList
::empty(&ProvisionalEvaluationCache
::default()),
1329 nested_obligations
.into_iter().chain(obligations
),
1331 .map_or(false, |res
| res
.may_apply())
1335 ///////////////////////////////////////////////////////////////////////////
1338 // Winnowing is the process of attempting to resolve ambiguity by
1339 // probing further. During the winnowing process, we unify all
1340 // type variables and then we also attempt to evaluate recursive
1341 // bounds to see if they are satisfied.
1343 /// Returns `true` if `victim` should be dropped in favor of
1344 /// `other`. Generally speaking we will drop duplicate
1345 /// candidates and prefer where-clause candidates.
1347 /// See the comment for "SelectionCandidate" for more details.
1348 fn candidate_should_be_dropped_in_favor_of(
1350 victim
: &EvaluatedCandidate
<'tcx
>,
1351 other
: &EvaluatedCandidate
<'tcx
>,
1354 if victim
.candidate
== other
.candidate
{
1358 // Check if a bound would previously have been removed when normalizing
1359 // the param_env so that it can be given the lowest priority. See
1360 // #50825 for the motivation for this.
1362 |cand
: &ty
::PolyTraitRef
<'_
>| cand
.is_global() && !cand
.has_late_bound_regions();
1364 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1365 // and `DiscriminantKindCandidate` to anything else.
1367 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1368 // lifetime of a variable.
1369 match (&other
.candidate
, &victim
.candidate
) {
1370 (_
, AutoImplCandidate(..)) | (AutoImplCandidate(..), _
) => {
1372 "default implementations shouldn't be recorded \
1373 when there are other valid candidates"
1379 BuiltinCandidate { has_nested: false }
1380 | DiscriminantKindCandidate
1386 BuiltinCandidate { has_nested: false }
1387 | DiscriminantKindCandidate
1391 (ParamCandidate(other
), ParamCandidate(victim
)) => {
1392 let value_same_except_bound_vars
= other
.value
.skip_binder()
1393 == victim
.value
.skip_binder()
1394 && !other
.value
.skip_binder().has_escaping_bound_vars();
1395 if value_same_except_bound_vars
{
1396 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1397 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1398 // or the current one if tied (they should both evaluate to the same answer). This is
1399 // probably best characterized as a "hack", since we might prefer to just do our
1400 // best to *not* create essentially duplicate candidates in the first place.
1401 other
.value
.bound_vars().len() <= victim
.value
.bound_vars().len()
1402 } else if other
.value
== victim
.value
&& victim
.constness
== Constness
::NotConst
{
1403 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1410 // Global bounds from the where clause should be ignored
1411 // here (see issue #50825). Otherwise, we have a where
1412 // clause so don't go around looking for impls.
1413 // Arbitrarily give param candidates priority
1414 // over projection and object candidates.
1416 ParamCandidate(ref cand
),
1419 | GeneratorCandidate
1420 | FnPointerCandidate
1421 | BuiltinObjectCandidate
1422 | BuiltinUnsizeCandidate
1423 | BuiltinCandidate { .. }
1424 | TraitAliasCandidate(..)
1425 | ObjectCandidate(_
)
1426 | ProjectionCandidate(_
),
1427 ) => !is_global(&cand
.value
),
1428 (ObjectCandidate(_
) | ProjectionCandidate(_
), ParamCandidate(ref cand
)) => {
1429 // Prefer these to a global where-clause bound
1430 // (see issue #50825).
1431 is_global(&cand
.value
)
1436 | GeneratorCandidate
1437 | FnPointerCandidate
1438 | BuiltinObjectCandidate
1439 | BuiltinUnsizeCandidate
1440 | BuiltinCandidate { has_nested: true }
1441 | TraitAliasCandidate(..),
1442 ParamCandidate(ref cand
),
1444 // Prefer these to a global where-clause bound
1445 // (see issue #50825).
1446 is_global(&cand
.value
) && other
.evaluation
.must_apply_modulo_regions()
1449 (ProjectionCandidate(i
), ProjectionCandidate(j
))
1450 | (ObjectCandidate(i
), ObjectCandidate(j
)) => {
1451 // Arbitrarily pick the lower numbered candidate for backwards
1452 // compatibility reasons. Don't let this affect inference.
1453 i
< j
&& !needs_infer
1455 (ObjectCandidate(_
), ProjectionCandidate(_
))
1456 | (ProjectionCandidate(_
), ObjectCandidate(_
)) => {
1457 bug
!("Have both object and projection candidate")
1460 // Arbitrarily give projection and object candidates priority.
1462 ObjectCandidate(_
) | ProjectionCandidate(_
),
1465 | GeneratorCandidate
1466 | FnPointerCandidate
1467 | BuiltinObjectCandidate
1468 | BuiltinUnsizeCandidate
1469 | BuiltinCandidate { .. }
1470 | TraitAliasCandidate(..),
1476 | GeneratorCandidate
1477 | FnPointerCandidate
1478 | BuiltinObjectCandidate
1479 | BuiltinUnsizeCandidate
1480 | BuiltinCandidate { .. }
1481 | TraitAliasCandidate(..),
1482 ObjectCandidate(_
) | ProjectionCandidate(_
),
1485 (&ImplCandidate(other_def
), &ImplCandidate(victim_def
)) => {
1486 // See if we can toss out `victim` based on specialization.
1487 // This requires us to know *for sure* that the `other` impl applies
1488 // i.e., `EvaluatedToOk`.
1489 if other
.evaluation
.must_apply_modulo_regions() {
1490 let tcx
= self.tcx();
1491 if tcx
.specializes((other_def
, victim_def
)) {
1494 return match tcx
.impls_are_allowed_to_overlap(other_def
, victim_def
) {
1495 Some(ty
::ImplOverlapKind
::Permitted { marker: true }
) => {
1496 // Subtle: If the predicate we are evaluating has inference
1497 // variables, do *not* allow discarding candidates due to
1498 // marker trait impls.
1500 // Without this restriction, we could end up accidentally
1501 // constrainting inference variables based on an arbitrarily
1502 // chosen trait impl.
1504 // Imagine we have the following code:
1507 // #[marker] trait MyTrait {}
1508 // impl MyTrait for u8 {}
1509 // impl MyTrait for bool {}
1512 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1514 // During selection, we will end up with one candidate for each
1515 // impl of `MyTrait`. If we were to discard one impl in favor
1516 // of the other, we would be left with one candidate, causing
1517 // us to "successfully" select the predicate, unifying
1518 // _#0t with (for example) `u8`.
1520 // However, we have no reason to believe that this unification
1521 // is correct - we've essentially just picked an arbitrary
1522 // *possibility* for _#0t, and required that this be the *only*
1525 // Eventually, we will either:
1526 // 1) Unify all inference variables in the predicate through
1527 // some other means (e.g. type-checking of a function). We will
1528 // then be in a position to drop marker trait candidates
1529 // without constraining inference variables (since there are
1530 // none left to constrin)
1531 // 2) Be left with some unconstrained inference variables. We
1532 // will then correctly report an inference error, since the
1533 // existence of multiple marker trait impls tells us nothing
1534 // about which one should actually apply.
1545 // Everything else is ambiguous
1549 | GeneratorCandidate
1550 | FnPointerCandidate
1551 | BuiltinObjectCandidate
1552 | BuiltinUnsizeCandidate
1553 | BuiltinCandidate { has_nested: true }
1554 | TraitAliasCandidate(..),
1557 | GeneratorCandidate
1558 | FnPointerCandidate
1559 | BuiltinObjectCandidate
1560 | BuiltinUnsizeCandidate
1561 | BuiltinCandidate { has_nested: true }
1562 | TraitAliasCandidate(..),
1567 fn sized_conditions(
1569 obligation
: &TraitObligation
<'tcx
>,
1570 ) -> BuiltinImplConditions
<'tcx
> {
1571 use self::BuiltinImplConditions
::{Ambiguous, None, Where}
;
1573 // NOTE: binder moved to (*)
1574 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.skip_binder().self_ty());
1576 match self_ty
.kind() {
1577 ty
::Infer(ty
::IntVar(_
) | ty
::FloatVar(_
))
1588 | ty
::GeneratorWitness(..)
1593 // safe for everything
1594 Where(ty
::Binder
::dummy(Vec
::new()))
1597 ty
::Str
| ty
::Slice(_
) | ty
::Dynamic(..) | ty
::Foreign(..) => None
,
1599 ty
::Tuple(tys
) => Where(
1602 .rebind(tys
.last().into_iter().map(|k
| k
.expect_ty()).collect()),
1605 ty
::Adt(def
, substs
) => {
1606 let sized_crit
= def
.sized_constraint(self.tcx());
1607 // (*) binder moved here
1609 obligation
.predicate
.rebind({
1610 sized_crit
.iter().map(|ty
| ty
.subst(self.tcx(), substs
)).collect()
1615 ty
::Projection(_
) | ty
::Param(_
) | ty
::Opaque(..) => None
,
1616 ty
::Infer(ty
::TyVar(_
)) => Ambiguous
,
1620 | ty
::Infer(ty
::FreshTy(_
) | ty
::FreshIntTy(_
) | ty
::FreshFloatTy(_
)) => {
1621 bug
!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty
);
1626 fn copy_clone_conditions(
1628 obligation
: &TraitObligation
<'tcx
>,
1629 ) -> BuiltinImplConditions
<'tcx
> {
1630 // NOTE: binder moved to (*)
1631 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.skip_binder().self_ty());
1633 use self::BuiltinImplConditions
::{Ambiguous, None, Where}
;
1635 match *self_ty
.kind() {
1636 ty
::Infer(ty
::IntVar(_
))
1637 | ty
::Infer(ty
::FloatVar(_
))
1640 | ty
::Error(_
) => Where(ty
::Binder
::dummy(Vec
::new())),
1649 | ty
::Ref(_
, _
, hir
::Mutability
::Not
) => {
1650 // Implementations provided in libcore
1658 | ty
::GeneratorWitness(..)
1660 | ty
::Ref(_
, _
, hir
::Mutability
::Mut
) => None
,
1662 ty
::Array(element_ty
, _
) => {
1663 // (*) binder moved here
1664 Where(obligation
.predicate
.rebind(vec
![element_ty
]))
1668 // (*) binder moved here
1669 Where(obligation
.predicate
.rebind(tys
.iter().map(|k
| k
.expect_ty()).collect()))
1672 ty
::Closure(_
, substs
) => {
1673 // (*) binder moved here
1674 let ty
= self.infcx
.shallow_resolve(substs
.as_closure().tupled_upvars_ty());
1675 if let ty
::Infer(ty
::TyVar(_
)) = ty
.kind() {
1676 // Not yet resolved.
1679 Where(obligation
.predicate
.rebind(substs
.as_closure().upvar_tys().collect()))
1683 ty
::Adt(..) | ty
::Projection(..) | ty
::Param(..) | ty
::Opaque(..) => {
1684 // Fallback to whatever user-defined impls exist in this case.
1688 ty
::Infer(ty
::TyVar(_
)) => {
1689 // Unbound type variable. Might or might not have
1690 // applicable impls and so forth, depending on what
1691 // those type variables wind up being bound to.
1697 | ty
::Infer(ty
::FreshTy(_
) | ty
::FreshIntTy(_
) | ty
::FreshFloatTy(_
)) => {
1698 bug
!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty
);
1703 /// For default impls, we need to break apart a type into its
1704 /// "constituent types" -- meaning, the types that it contains.
1706 /// Here are some (simple) examples:
1709 /// (i32, u32) -> [i32, u32]
1710 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1711 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1712 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1714 fn constituent_types_for_ty(
1716 t
: ty
::Binder
<'tcx
, Ty
<'tcx
>>,
1717 ) -> ty
::Binder
<'tcx
, Vec
<Ty
<'tcx
>>> {
1718 match *t
.skip_binder().kind() {
1727 | ty
::Infer(ty
::IntVar(_
) | ty
::FloatVar(_
))
1729 | ty
::Char
=> ty
::Binder
::dummy(Vec
::new()),
1735 | ty
::Projection(..)
1737 | ty
::Infer(ty
::TyVar(_
) | ty
::FreshTy(_
) | ty
::FreshIntTy(_
) | ty
::FreshFloatTy(_
)) => {
1738 bug
!("asked to assemble constituent types of unexpected type: {:?}", t
);
1741 ty
::RawPtr(ty
::TypeAndMut { ty: element_ty, .. }
) | ty
::Ref(_
, element_ty
, _
) => {
1742 t
.rebind(vec
![element_ty
])
1745 ty
::Array(element_ty
, _
) | ty
::Slice(element_ty
) => t
.rebind(vec
![element_ty
]),
1747 ty
::Tuple(ref tys
) => {
1748 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1749 t
.rebind(tys
.iter().map(|k
| k
.expect_ty()).collect())
1752 ty
::Closure(_
, ref substs
) => {
1753 let ty
= self.infcx
.shallow_resolve(substs
.as_closure().tupled_upvars_ty());
1757 ty
::Generator(_
, ref substs
, _
) => {
1758 let ty
= self.infcx
.shallow_resolve(substs
.as_generator().tupled_upvars_ty());
1759 let witness
= substs
.as_generator().witness();
1760 t
.rebind(vec
![ty
].into_iter().chain(iter
::once(witness
)).collect())
1763 ty
::GeneratorWitness(types
) => {
1764 debug_assert
!(!types
.has_escaping_bound_vars());
1765 types
.map_bound(|types
| types
.to_vec())
1768 // For `PhantomData<T>`, we pass `T`.
1769 ty
::Adt(def
, substs
) if def
.is_phantom_data() => t
.rebind(substs
.types().collect()),
1771 ty
::Adt(def
, substs
) => {
1772 t
.rebind(def
.all_fields().map(|f
| f
.ty(self.tcx(), substs
)).collect())
1775 ty
::Opaque(def_id
, substs
) => {
1776 // We can resolve the `impl Trait` to its concrete type,
1777 // which enforces a DAG between the functions requiring
1778 // the auto trait bounds in question.
1779 t
.rebind(vec
![self.tcx().type_of(def_id
).subst(self.tcx(), substs
)])
1784 fn collect_predicates_for_types(
1786 param_env
: ty
::ParamEnv
<'tcx
>,
1787 cause
: ObligationCause
<'tcx
>,
1788 recursion_depth
: usize,
1789 trait_def_id
: DefId
,
1790 types
: ty
::Binder
<'tcx
, Vec
<Ty
<'tcx
>>>,
1791 ) -> Vec
<PredicateObligation
<'tcx
>> {
1792 // Because the types were potentially derived from
1793 // higher-ranked obligations they may reference late-bound
1794 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
1795 // yield a type like `for<'a> &'a i32`. In general, we
1796 // maintain the invariant that we never manipulate bound
1797 // regions, so we have to process these bound regions somehow.
1799 // The strategy is to:
1801 // 1. Instantiate those regions to placeholder regions (e.g.,
1802 // `for<'a> &'a i32` becomes `&0 i32`.
1803 // 2. Produce something like `&'0 i32 : Copy`
1804 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
1808 .skip_binder() // binder moved -\
1811 let ty
: ty
::Binder
<'tcx
, Ty
<'tcx
>> = types
.rebind(ty
); // <----/
1813 self.infcx
.commit_unconditionally(|_
| {
1814 let placeholder_ty
= self.infcx
.replace_bound_vars_with_placeholders(ty
);
1815 let Normalized { value: normalized_ty, mut obligations }
=
1816 ensure_sufficient_stack(|| {
1817 project
::normalize_with_depth(
1825 let placeholder_obligation
= predicate_for_trait_def(
1834 obligations
.push(placeholder_obligation
);
1841 ///////////////////////////////////////////////////////////////////////////
1844 // Matching is a common path used for both evaluation and
1845 // confirmation. It basically unifies types that appear in impls
1846 // and traits. This does affect the surrounding environment;
1847 // therefore, when used during evaluation, match routines must be
1848 // run inside of a `probe()` so that their side-effects are
1854 obligation
: &TraitObligation
<'tcx
>,
1855 ) -> Normalized
<'tcx
, SubstsRef
<'tcx
>> {
1856 match self.match_impl(impl_def_id
, obligation
) {
1857 Ok(substs
) => substs
,
1860 "Impl {:?} was matchable against {:?} but now is not",
1868 #[tracing::instrument(level = "debug", skip(self))]
1872 obligation
: &TraitObligation
<'tcx
>,
1873 ) -> Result
<Normalized
<'tcx
, SubstsRef
<'tcx
>>, ()> {
1874 let impl_trait_ref
= self.tcx().impl_trait_ref(impl_def_id
).unwrap();
1876 // Before we create the substitutions and everything, first
1877 // consider a "quick reject". This avoids creating more types
1878 // and so forth that we need to.
1879 if self.fast_reject_trait_refs(obligation
, &impl_trait_ref
) {
1883 let placeholder_obligation
=
1884 self.infcx().replace_bound_vars_with_placeholders(obligation
.predicate
);
1885 let placeholder_obligation_trait_ref
= placeholder_obligation
.trait_ref
;
1887 let impl_substs
= self.infcx
.fresh_substs_for_item(obligation
.cause
.span
, impl_def_id
);
1889 let impl_trait_ref
= impl_trait_ref
.subst(self.tcx(), impl_substs
);
1891 debug
!(?impl_trait_ref
);
1893 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations }
=
1894 ensure_sufficient_stack(|| {
1895 project
::normalize_with_depth(
1897 obligation
.param_env
,
1898 obligation
.cause
.clone(),
1899 obligation
.recursion_depth
+ 1,
1904 debug
!(?impl_trait_ref
, ?placeholder_obligation_trait_ref
);
1906 let cause
= ObligationCause
::new(
1907 obligation
.cause
.span
,
1908 obligation
.cause
.body_id
,
1909 ObligationCauseCode
::MatchImpl(Lrc
::new(obligation
.cause
.code
.clone()), impl_def_id
),
1912 let InferOk { obligations, .. }
= self
1914 .at(&cause
, obligation
.param_env
)
1915 .eq(placeholder_obligation_trait_ref
, impl_trait_ref
)
1916 .map_err(|e
| debug
!("match_impl: failed eq_trait_refs due to `{}`", e
))?
;
1917 nested_obligations
.extend(obligations
);
1920 && self.tcx().impl_polarity(impl_def_id
) == ty
::ImplPolarity
::Reservation
1922 debug
!("match_impl: reservation impls only apply in intercrate mode");
1926 debug
!(?impl_substs
, ?nested_obligations
, "match_impl: success");
1927 Ok(Normalized { value: impl_substs, obligations: nested_obligations }
)
1930 fn fast_reject_trait_refs(
1932 obligation
: &TraitObligation
<'_
>,
1933 impl_trait_ref
: &ty
::TraitRef
<'_
>,
1935 // We can avoid creating type variables and doing the full
1936 // substitution if we find that any of the input types, when
1937 // simplified, do not match.
1939 iter
::zip(obligation
.predicate
.skip_binder().trait_ref
.substs
, impl_trait_ref
.substs
).any(
1940 |(obligation_arg
, impl_arg
)| {
1941 match (obligation_arg
.unpack(), impl_arg
.unpack()) {
1942 (GenericArgKind
::Type(obligation_ty
), GenericArgKind
::Type(impl_ty
)) => {
1943 let simplified_obligation_ty
=
1944 fast_reject
::simplify_type(self.tcx(), obligation_ty
, true);
1945 let simplified_impl_ty
=
1946 fast_reject
::simplify_type(self.tcx(), impl_ty
, false);
1948 simplified_obligation_ty
.is_some()
1949 && simplified_impl_ty
.is_some()
1950 && simplified_obligation_ty
!= simplified_impl_ty
1952 (GenericArgKind
::Lifetime(_
), GenericArgKind
::Lifetime(_
)) => {
1953 // Lifetimes can never cause a rejection.
1956 (GenericArgKind
::Const(_
), GenericArgKind
::Const(_
)) => {
1957 // Conservatively ignore consts (i.e. assume they might
1958 // unify later) until we have `fast_reject` support for
1959 // them (if we'll ever need it, even).
1962 _
=> unreachable
!(),
1968 /// Normalize `where_clause_trait_ref` and try to match it against
1969 /// `obligation`. If successful, return any predicates that
1970 /// result from the normalization.
1971 fn match_where_clause_trait_ref(
1973 obligation
: &TraitObligation
<'tcx
>,
1974 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
1975 ) -> Result
<Vec
<PredicateObligation
<'tcx
>>, ()> {
1976 self.match_poly_trait_ref(obligation
, where_clause_trait_ref
)
1979 /// Returns `Ok` if `poly_trait_ref` being true implies that the
1980 /// obligation is satisfied.
1981 fn match_poly_trait_ref(
1983 obligation
: &TraitObligation
<'tcx
>,
1984 poly_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
1985 ) -> Result
<Vec
<PredicateObligation
<'tcx
>>, ()> {
1986 debug
!(?obligation
, ?poly_trait_ref
, "match_poly_trait_ref");
1989 .at(&obligation
.cause
, obligation
.param_env
)
1990 .sup(obligation
.predicate
.to_poly_trait_ref(), poly_trait_ref
)
1991 .map(|InferOk { obligations, .. }
| obligations
)
1995 ///////////////////////////////////////////////////////////////////////////
1998 fn match_fresh_trait_refs(
2000 previous
: ty
::PolyTraitRef
<'tcx
>,
2001 current
: ty
::PolyTraitRef
<'tcx
>,
2002 param_env
: ty
::ParamEnv
<'tcx
>,
2004 let mut matcher
= ty
::_match
::Match
::new(self.tcx(), param_env
);
2005 matcher
.relate(previous
, current
).is_ok()
2010 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
2011 obligation
: &'o TraitObligation
<'tcx
>,
2012 ) -> TraitObligationStack
<'o
, 'tcx
> {
2013 let fresh_trait_ref
=
2014 obligation
.predicate
.to_poly_trait_ref().fold_with(&mut self.freshener
);
2016 let dfn
= previous_stack
.cache
.next_dfn();
2017 let depth
= previous_stack
.depth() + 1;
2018 TraitObligationStack
{
2021 reached_depth
: Cell
::new(depth
),
2022 previous
: previous_stack
,
2028 fn closure_trait_ref_unnormalized(
2030 obligation
: &TraitObligation
<'tcx
>,
2031 substs
: SubstsRef
<'tcx
>,
2032 ) -> ty
::PolyTraitRef
<'tcx
> {
2033 debug
!(?obligation
, ?substs
, "closure_trait_ref_unnormalized");
2034 let closure_sig
= substs
.as_closure().sig();
2036 debug
!(?closure_sig
);
2038 // (1) Feels icky to skip the binder here, but OTOH we know
2039 // that the self-type is an unboxed closure type and hence is
2040 // in fact unparameterized (or at least does not reference any
2041 // regions bound in the obligation). Still probably some
2042 // refactoring could make this nicer.
2043 closure_trait_ref_and_return_type(
2045 obligation
.predicate
.def_id(),
2046 obligation
.predicate
.skip_binder().self_ty(), // (1)
2048 util
::TupleArgumentsFlag
::No
,
2050 .map_bound(|(trait_ref
, _
)| trait_ref
)
2053 fn generator_trait_ref_unnormalized(
2055 obligation
: &TraitObligation
<'tcx
>,
2056 substs
: SubstsRef
<'tcx
>,
2057 ) -> ty
::PolyTraitRef
<'tcx
> {
2058 let gen_sig
= substs
.as_generator().poly_sig();
2060 // (1) Feels icky to skip the binder here, but OTOH we know
2061 // that the self-type is an generator type and hence is
2062 // in fact unparameterized (or at least does not reference any
2063 // regions bound in the obligation). Still probably some
2064 // refactoring could make this nicer.
2066 super::util
::generator_trait_ref_and_outputs(
2068 obligation
.predicate
.def_id(),
2069 obligation
.predicate
.skip_binder().self_ty(), // (1)
2072 .map_bound(|(trait_ref
, ..)| trait_ref
)
2075 /// Returns the obligations that are implied by instantiating an
2076 /// impl or trait. The obligations are substituted and fully
2077 /// normalized. This is used when confirming an impl or default
2079 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2080 fn impl_or_trait_obligations(
2082 cause
: ObligationCause
<'tcx
>,
2083 recursion_depth
: usize,
2084 param_env
: ty
::ParamEnv
<'tcx
>,
2085 def_id
: DefId
, // of impl or trait
2086 substs
: SubstsRef
<'tcx
>, // for impl or trait
2087 ) -> Vec
<PredicateObligation
<'tcx
>> {
2088 let tcx
= self.tcx();
2090 // To allow for one-pass evaluation of the nested obligation,
2091 // each predicate must be preceded by the obligations required
2093 // for example, if we have:
2094 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2095 // the impl will have the following predicates:
2096 // <V as Iterator>::Item = U,
2097 // U: Iterator, U: Sized,
2098 // V: Iterator, V: Sized,
2099 // <U as Iterator>::Item: Copy
2100 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2101 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2102 // `$1: Copy`, so we must ensure the obligations are emitted in
2104 let predicates
= tcx
.predicates_of(def_id
);
2105 debug
!(?predicates
);
2106 assert_eq
!(predicates
.parent
, None
);
2107 let mut obligations
= Vec
::with_capacity(predicates
.predicates
.len());
2108 for (predicate
, _
) in predicates
.predicates
{
2110 let predicate
= normalize_with_depth_to(
2115 predicate
.subst(tcx
, substs
),
2118 obligations
.push(Obligation
{
2119 cause
: cause
.clone(),
2126 // We are performing deduplication here to avoid exponential blowups
2127 // (#38528) from happening, but the real cause of the duplication is
2128 // unknown. What we know is that the deduplication avoids exponential
2129 // amount of predicates being propagated when processing deeply nested
2132 // This code is hot enough that it's worth avoiding the allocation
2133 // required for the FxHashSet when possible. Special-casing lengths 0,
2134 // 1 and 2 covers roughly 75-80% of the cases.
2135 if obligations
.len() <= 1 {
2136 // No possibility of duplicates.
2137 } else if obligations
.len() == 2 {
2138 // Only two elements. Drop the second if they are equal.
2139 if obligations
[0] == obligations
[1] {
2140 obligations
.truncate(1);
2143 // Three or more elements. Use a general deduplication process.
2144 let mut seen
= FxHashSet
::default();
2145 obligations
.retain(|i
| seen
.insert(i
.clone()));
2152 trait TraitObligationExt
<'tcx
> {
2155 variant
: fn(DerivedObligationCause
<'tcx
>) -> ObligationCauseCode
<'tcx
>,
2156 ) -> ObligationCause
<'tcx
>;
2159 impl<'tcx
> TraitObligationExt
<'tcx
> for TraitObligation
<'tcx
> {
2162 variant
: fn(DerivedObligationCause
<'tcx
>) -> ObligationCauseCode
<'tcx
>,
2163 ) -> ObligationCause
<'tcx
> {
2165 * Creates a cause for obligations that are derived from
2166 * `obligation` by a recursive search (e.g., for a builtin
2167 * bound, or eventually a `auto trait Foo`). If `obligation`
2168 * is itself a derived obligation, this is just a clone, but
2169 * otherwise we create a "derived obligation" cause so as to
2170 * keep track of the original root obligation for error
2174 let obligation
= self;
2176 // NOTE(flaper87): As of now, it keeps track of the whole error
2177 // chain. Ideally, we should have a way to configure this either
2178 // by using -Z verbose or just a CLI argument.
2179 let derived_cause
= DerivedObligationCause
{
2180 parent_trait_ref
: obligation
.predicate
.to_poly_trait_ref(),
2181 parent_code
: Lrc
::new(obligation
.cause
.code
.clone()),
2183 let derived_code
= variant(derived_cause
);
2184 ObligationCause
::new(obligation
.cause
.span
, obligation
.cause
.body_id
, derived_code
)
2188 impl<'o
, 'tcx
> TraitObligationStack
<'o
, 'tcx
> {
2189 fn list(&'o
self) -> TraitObligationStackList
<'o
, 'tcx
> {
2190 TraitObligationStackList
::with(self)
2193 fn cache(&self) -> &'o ProvisionalEvaluationCache
<'tcx
> {
2197 fn iter(&'o
self) -> TraitObligationStackList
<'o
, 'tcx
> {
2201 /// Indicates that attempting to evaluate this stack entry
2202 /// required accessing something from the stack at depth `reached_depth`.
2203 fn update_reached_depth(&self, reached_depth
: usize) {
2205 self.depth
>= reached_depth
,
2206 "invoked `update_reached_depth` with something under this stack: \
2207 self.depth={} reached_depth={}",
2211 debug
!(reached_depth
, "update_reached_depth");
2213 while reached_depth
< p
.depth
{
2214 debug
!(?p
.fresh_trait_ref
, "update_reached_depth: marking as cycle participant");
2215 p
.reached_depth
.set(p
.reached_depth
.get().min(reached_depth
));
2216 p
= p
.previous
.head
.unwrap();
2221 /// The "provisional evaluation cache" is used to store intermediate cache results
2222 /// when solving auto traits. Auto traits are unusual in that they can support
2223 /// cycles. So, for example, a "proof tree" like this would be ok:
2225 /// - `Foo<T>: Send` :-
2226 /// - `Bar<T>: Send` :-
2227 /// - `Foo<T>: Send` -- cycle, but ok
2228 /// - `Baz<T>: Send`
2230 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2231 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2232 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2233 /// they are coinductive) it is considered ok.
2235 /// However, there is a complication: at the point where we have
2236 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2237 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2238 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2239 /// find out this assumption is wrong? Specifically, we could
2240 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2241 /// `Bar<T>: Send` didn't turn out to be true.
2243 /// In Issue #60010, we found a bug in rustc where it would cache
2244 /// these intermediate results. This was fixed in #60444 by disabling
2245 /// *all* caching for things involved in a cycle -- in our example,
2246 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2247 /// to large slowdowns.
2249 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2250 /// first requires proving `Bar<T>: Send` (which is true:
2252 /// - `Foo<T>: Send` :-
2253 /// - `Bar<T>: Send` :-
2254 /// - `Foo<T>: Send` -- cycle, but ok
2255 /// - `Baz<T>: Send`
2256 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2257 /// - `*const T: Send` -- but what if we later encounter an error?
2259 /// The *provisional evaluation cache* resolves this issue. It stores
2260 /// cache results that we've proven but which were involved in a cycle
2261 /// in some way. We track the minimal stack depth (i.e., the
2262 /// farthest from the top of the stack) that we are dependent on.
2263 /// The idea is that the cache results within are all valid -- so long as
2264 /// none of the nodes in between the current node and the node at that minimum
2265 /// depth result in an error (in which case the cached results are just thrown away).
2267 /// During evaluation, we consult this provisional cache and rely on
2268 /// it. Accessing a cached value is considered equivalent to accessing
2269 /// a result at `reached_depth`, so it marks the *current* solution as
2270 /// provisional as well. If an error is encountered, we toss out any
2271 /// provisional results added from the subtree that encountered the
2272 /// error. When we pop the node at `reached_depth` from the stack, we
2273 /// can commit all the things that remain in the provisional cache.
2274 struct ProvisionalEvaluationCache
<'tcx
> {
2275 /// next "depth first number" to issue -- just a counter
2278 /// Map from cache key to the provisionally evaluated thing.
2279 /// The cache entries contain the result but also the DFN in which they
2280 /// were added. The DFN is used to clear out values on failure.
2282 /// Imagine we have a stack like:
2284 /// - `A B C` and we add a cache for the result of C (DFN 2)
2285 /// - Then we have a stack `A B D` where `D` has DFN 3
2286 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2287 /// - `E` generates various cache entries which have cyclic dependices on `B`
2288 /// - `A B D E F` and so forth
2289 /// - the DFN of `F` for example would be 5
2290 /// - then we determine that `E` is in error -- we will then clear
2291 /// all cache values whose DFN is >= 4 -- in this case, that
2292 /// means the cached value for `F`.
2293 map
: RefCell
<FxHashMap
<ty
::PolyTraitRef
<'tcx
>, ProvisionalEvaluation
>>,
2296 /// A cache value for the provisional cache: contains the depth-first
2297 /// number (DFN) and result.
2298 #[derive(Copy, Clone, Debug)]
2299 struct ProvisionalEvaluation
{
2301 reached_depth
: usize,
2302 result
: EvaluationResult
,
2305 impl<'tcx
> Default
for ProvisionalEvaluationCache
<'tcx
> {
2306 fn default() -> Self {
2307 Self { dfn: Cell::new(0), map: Default::default() }
2311 impl<'tcx
> ProvisionalEvaluationCache
<'tcx
> {
2312 /// Get the next DFN in sequence (basically a counter).
2313 fn next_dfn(&self) -> usize {
2314 let result
= self.dfn
.get();
2315 self.dfn
.set(result
+ 1);
2319 /// Check the provisional cache for any result for
2320 /// `fresh_trait_ref`. If there is a hit, then you must consider
2321 /// it an access to the stack slots at depth
2322 /// `reached_depth` (from the returned value).
2325 fresh_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
2326 ) -> Option
<ProvisionalEvaluation
> {
2329 "get_provisional = {:#?}",
2330 self.map
.borrow().get(&fresh_trait_ref
),
2332 Some(self.map
.borrow().get(&fresh_trait_ref
)?
.clone())
2335 /// Insert a provisional result into the cache. The result came
2336 /// from the node with the given DFN. It accessed a minimum depth
2337 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
2338 /// and resulted in `result`.
2339 fn insert_provisional(
2342 reached_depth
: usize,
2343 fresh_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
2344 result
: EvaluationResult
,
2346 debug
!(?from_dfn
, ?fresh_trait_ref
, ?result
, "insert_provisional");
2348 let mut map
= self.map
.borrow_mut();
2350 // Subtle: when we complete working on the DFN `from_dfn`, anything
2351 // that remains in the provisional cache must be dependent on some older
2352 // stack entry than `from_dfn`. We have to update their depth with our transitive
2353 // depth in that case or else it would be referring to some popped note.
2356 // A (reached depth 0)
2358 // B // depth 1 -- reached depth = 0
2359 // C // depth 2 -- reached depth = 1 (should be 0)
2362 // D (reached depth 1)
2363 // C (cache -- reached depth = 2)
2364 for (_k
, v
) in &mut *map
{
2365 if v
.from_dfn
>= from_dfn
{
2366 v
.reached_depth
= reached_depth
.min(v
.reached_depth
);
2370 map
.insert(fresh_trait_ref
, ProvisionalEvaluation { from_dfn, reached_depth, result }
);
2373 /// Invoked when the node with dfn `dfn` does not get a successful
2374 /// result. This will clear out any provisional cache entries
2375 /// that were added since `dfn` was created. This is because the
2376 /// provisional entries are things which must assume that the
2377 /// things on the stack at the time of their creation succeeded --
2378 /// since the failing node is presently at the top of the stack,
2379 /// these provisional entries must either depend on it or some
2381 fn on_failure(&self, dfn
: usize) {
2382 debug
!(?dfn
, "on_failure");
2383 self.map
.borrow_mut().retain(|key
, eval
| {
2384 if !eval
.from_dfn
>= dfn
{
2385 debug
!("on_failure: removing {:?}", key
);
2393 /// Invoked when the node at depth `depth` completed without
2394 /// depending on anything higher in the stack (if that completion
2395 /// was a failure, then `on_failure` should have been invoked
2396 /// already). The callback `op` will be invoked for each
2397 /// provisional entry that we can now confirm.
2399 /// Note that we may still have provisional cache items remaining
2400 /// in the cache when this is done. For example, if there is a
2403 /// * A depends on...
2404 /// * B depends on A
2405 /// * C depends on...
2406 /// * D depends on C
2409 /// Then as we complete the C node we will have a provisional cache
2410 /// with results for A, B, C, and D. This method would clear out
2411 /// the C and D results, but leave A and B provisional.
2413 /// This is determined based on the DFN: we remove any provisional
2414 /// results created since `dfn` started (e.g., in our example, dfn
2415 /// would be 2, representing the C node, and hence we would
2416 /// remove the result for D, which has DFN 3, but not the results for
2417 /// A and B, which have DFNs 0 and 1 respectively).
2421 mut op
: impl FnMut(ty
::PolyTraitRef
<'tcx
>, EvaluationResult
),
2423 debug
!(?dfn
, "on_completion");
2425 for (fresh_trait_ref
, eval
) in
2426 self.map
.borrow_mut().drain_filter(|_k
, eval
| eval
.from_dfn
>= dfn
)
2428 debug
!(?fresh_trait_ref
, ?eval
, "on_completion");
2430 op(fresh_trait_ref
, eval
.result
);
2435 #[derive(Copy, Clone)]
2436 struct TraitObligationStackList
<'o
, 'tcx
> {
2437 cache
: &'o ProvisionalEvaluationCache
<'tcx
>,
2438 head
: Option
<&'o TraitObligationStack
<'o
, 'tcx
>>,
2441 impl<'o
, 'tcx
> TraitObligationStackList
<'o
, 'tcx
> {
2442 fn empty(cache
: &'o ProvisionalEvaluationCache
<'tcx
>) -> TraitObligationStackList
<'o
, 'tcx
> {
2443 TraitObligationStackList { cache, head: None }
2446 fn with(r
: &'o TraitObligationStack
<'o
, 'tcx
>) -> TraitObligationStackList
<'o
, 'tcx
> {
2447 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2450 fn head(&self) -> Option
<&'o TraitObligationStack
<'o
, 'tcx
>> {
2454 fn depth(&self) -> usize {
2455 if let Some(head
) = self.head { head.depth }
else { 0 }
2459 impl<'o
, 'tcx
> Iterator
for TraitObligationStackList
<'o
, 'tcx
> {
2460 type Item
= &'o TraitObligationStack
<'o
, 'tcx
>;
2462 fn next(&mut self) -> Option
<&'o TraitObligationStack
<'o
, 'tcx
>> {
2469 impl<'o
, 'tcx
> fmt
::Debug
for TraitObligationStack
<'o
, 'tcx
> {
2470 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2471 write
!(f
, "TraitObligationStack({:?})", self.obligation
)