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, Unimplemented}
;
24 use super::{ObligationCause, PredicateObligation, TraitObligation}
;
26 use crate::infer
::{InferCtxt, InferOk, TypeFreshener}
;
27 use crate::traits
::error_reporting
::InferCtxtExt
;
28 use rustc_data_structures
::fx
::{FxHashMap, FxHashSet}
;
29 use rustc_data_structures
::stack
::ensure_sufficient_stack
;
30 use rustc_data_structures
::sync
::Lrc
;
31 use rustc_errors
::ErrorReported
;
33 use rustc_hir
::def_id
::DefId
;
34 use rustc_infer
::infer
::LateBoundRegionConversionTime
;
35 use rustc_middle
::dep_graph
::{DepKind, DepNodeIndex}
;
36 use rustc_middle
::mir
::interpret
::ErrorHandled
;
37 use rustc_middle
::thir
::abstract_const
::NotConstEvaluatable
;
38 use rustc_middle
::ty
::fast_reject
;
39 use rustc_middle
::ty
::print
::with_no_trimmed_paths
;
40 use rustc_middle
::ty
::relate
::TypeRelation
;
41 use rustc_middle
::ty
::subst
::{GenericArgKind, Subst, SubstsRef}
;
42 use rustc_middle
::ty
::WithConstness
;
43 use rustc_middle
::ty
::{self, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate}
;
44 use rustc_middle
::ty
::{Ty, TyCtxt, TypeFoldable}
;
45 use rustc_span
::symbol
::sym
;
47 use std
::cell
::{Cell, RefCell}
;
49 use std
::fmt
::{self, Display}
;
52 pub use rustc_middle
::traits
::select
::*;
54 mod candidate_assembly
;
57 #[derive(Clone, Debug)]
58 pub enum IntercrateAmbiguityCause
{
59 DownstreamCrate { trait_desc: String, self_desc: Option<String> }
,
60 UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> }
,
61 ReservationImpl { message: String }
,
64 impl IntercrateAmbiguityCause
{
65 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
66 /// See #23980 for details.
67 pub fn add_intercrate_ambiguity_hint(&self, err
: &mut rustc_errors
::DiagnosticBuilder
<'_
>) {
68 err
.note(&self.intercrate_ambiguity_hint());
71 pub fn intercrate_ambiguity_hint(&self) -> String
{
73 IntercrateAmbiguityCause
::DownstreamCrate { trait_desc, self_desc }
=> {
74 let self_desc
= if let Some(ty
) = self_desc
{
75 format
!(" for type `{}`", ty
)
79 format
!("downstream crates may implement trait `{}`{}", trait_desc
, self_desc
)
81 IntercrateAmbiguityCause
::UpstreamCrateUpdate { trait_desc, self_desc }
=> {
82 let self_desc
= if let Some(ty
) = self_desc
{
83 format
!(" for type `{}`", ty
)
88 "upstream crates may add a new impl of trait `{}`{} \
93 IntercrateAmbiguityCause
::ReservationImpl { message }
=> message
.clone(),
98 pub struct SelectionContext
<'cx
, 'tcx
> {
99 infcx
: &'cx InferCtxt
<'cx
, 'tcx
>,
101 /// Freshener used specifically for entries on the obligation
102 /// stack. This ensures that all entries on the stack at one time
103 /// will have the same set of placeholder entries, which is
104 /// important for checking for trait bounds that recursively
105 /// require themselves.
106 freshener
: TypeFreshener
<'cx
, 'tcx
>,
108 /// If `true`, indicates that the evaluation should be conservative
109 /// and consider the possibility of types outside this crate.
110 /// This comes up primarily when resolving ambiguity. Imagine
111 /// there is some trait reference `$0: Bar` where `$0` is an
112 /// inference variable. If `intercrate` is true, then we can never
113 /// say for sure that this reference is not implemented, even if
114 /// there are *no impls at all for `Bar`*, because `$0` could be
115 /// bound to some type that in a downstream crate that implements
116 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
117 /// though, we set this to false, because we are only interested
118 /// in types that the user could actually have written --- in
119 /// other words, we consider `$0: Bar` to be unimplemented if
120 /// there is no type that the user could *actually name* that
121 /// would satisfy it. This avoids crippling inference, basically.
124 intercrate_ambiguity_causes
: Option
<Vec
<IntercrateAmbiguityCause
>>,
126 /// Controls whether or not to filter out negative impls when selecting.
127 /// This is used in librustdoc to distinguish between the lack of an impl
128 /// and a negative impl
129 allow_negative_impls
: bool
,
131 /// Are we in a const context that needs `~const` bounds to be const?
132 is_in_const_context
: bool
,
134 /// The mode that trait queries run in, which informs our error handling
135 /// policy. In essence, canonicalized queries need their errors propagated
136 /// rather than immediately reported because we do not have accurate spans.
137 query_mode
: TraitQueryMode
,
140 // A stack that walks back up the stack frame.
141 struct TraitObligationStack
<'prev
, 'tcx
> {
142 obligation
: &'prev TraitObligation
<'tcx
>,
144 /// The trait ref from `obligation` but "freshened" with the
145 /// selection-context's freshener. Used to check for recursion.
146 fresh_trait_ref
: ty
::ConstnessAnd
<ty
::PolyTraitRef
<'tcx
>>,
148 /// Starts out equal to `depth` -- if, during evaluation, we
149 /// encounter a cycle, then we will set this flag to the minimum
150 /// depth of that cycle for all participants in the cycle. These
151 /// participants will then forego caching their results. This is
152 /// not the most efficient solution, but it addresses #60010. The
153 /// problem we are trying to prevent:
155 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
156 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
157 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
159 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
160 /// is `EvaluatedToOk`; this is because they were only considered
161 /// ok on the premise that if `A: AutoTrait` held, but we indeed
162 /// encountered a problem (later on) with `A: AutoTrait. So we
163 /// currently set a flag on the stack node for `B: AutoTrait` (as
164 /// well as the second instance of `A: AutoTrait`) to suppress
167 /// This is a simple, targeted fix. A more-performant fix requires
168 /// deeper changes, but would permit more caching: we could
169 /// basically defer caching until we have fully evaluated the
170 /// tree, and then cache the entire tree at once. In any case, the
171 /// performance impact here shouldn't be so horrible: every time
172 /// this is hit, we do cache at least one trait, so we only
173 /// evaluate each member of a cycle up to N times, where N is the
174 /// length of the cycle. This means the performance impact is
175 /// bounded and we shouldn't have any terrible worst-cases.
176 reached_depth
: Cell
<usize>,
178 previous
: TraitObligationStackList
<'prev
, 'tcx
>,
180 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
183 /// The depth-first number of this node in the search graph -- a
184 /// pre-order index. Basically, a freshly incremented counter.
188 struct SelectionCandidateSet
<'tcx
> {
189 // A list of candidates that definitely apply to the current
190 // obligation (meaning: types unify).
191 vec
: Vec
<SelectionCandidate
<'tcx
>>,
193 // If `true`, then there were candidates that might or might
194 // not have applied, but we couldn't tell. This occurs when some
195 // of the input types are type variables, in which case there are
196 // various "builtin" rules that might or might not trigger.
200 #[derive(PartialEq, Eq, Debug, Clone)]
201 struct EvaluatedCandidate
<'tcx
> {
202 candidate
: SelectionCandidate
<'tcx
>,
203 evaluation
: EvaluationResult
,
206 /// When does the builtin impl for `T: Trait` apply?
207 enum BuiltinImplConditions
<'tcx
> {
208 /// The impl is conditional on `T1, T2, ...: Trait`.
209 Where(ty
::Binder
<'tcx
, Vec
<Ty
<'tcx
>>>),
210 /// There is no built-in impl. There may be some other
211 /// candidate (a where-clause or user-defined impl).
213 /// It is unknown whether there is an impl.
217 impl<'cx
, 'tcx
> SelectionContext
<'cx
, 'tcx
> {
218 pub fn new(infcx
: &'cx InferCtxt
<'cx
, 'tcx
>) -> SelectionContext
<'cx
, 'tcx
> {
221 freshener
: infcx
.freshener_keep_static(),
223 intercrate_ambiguity_causes
: None
,
224 allow_negative_impls
: false,
225 is_in_const_context
: false,
226 query_mode
: TraitQueryMode
::Standard
,
230 pub fn intercrate(infcx
: &'cx InferCtxt
<'cx
, 'tcx
>) -> SelectionContext
<'cx
, 'tcx
> {
233 freshener
: infcx
.freshener_keep_static(),
235 intercrate_ambiguity_causes
: None
,
236 allow_negative_impls
: false,
237 is_in_const_context
: false,
238 query_mode
: TraitQueryMode
::Standard
,
242 pub fn with_negative(
243 infcx
: &'cx InferCtxt
<'cx
, 'tcx
>,
244 allow_negative_impls
: bool
,
245 ) -> SelectionContext
<'cx
, 'tcx
> {
246 debug
!(?allow_negative_impls
, "with_negative");
249 freshener
: infcx
.freshener_keep_static(),
251 intercrate_ambiguity_causes
: None
,
252 allow_negative_impls
,
253 is_in_const_context
: false,
254 query_mode
: TraitQueryMode
::Standard
,
258 pub fn with_query_mode(
259 infcx
: &'cx InferCtxt
<'cx
, 'tcx
>,
260 query_mode
: TraitQueryMode
,
261 ) -> SelectionContext
<'cx
, 'tcx
> {
262 debug
!(?query_mode
, "with_query_mode");
265 freshener
: infcx
.freshener_keep_static(),
267 intercrate_ambiguity_causes
: None
,
268 allow_negative_impls
: false,
269 is_in_const_context
: false,
274 pub fn with_constness(
275 infcx
: &'cx InferCtxt
<'cx
, 'tcx
>,
276 constness
: hir
::Constness
,
277 ) -> SelectionContext
<'cx
, 'tcx
> {
280 freshener
: infcx
.freshener_keep_static(),
282 intercrate_ambiguity_causes
: None
,
283 allow_negative_impls
: false,
284 is_in_const_context
: matches
!(constness
, hir
::Constness
::Const
),
285 query_mode
: TraitQueryMode
::Standard
,
289 /// Enables tracking of intercrate ambiguity causes. These are
290 /// used in coherence to give improved diagnostics. We don't do
291 /// this until we detect a coherence error because it can lead to
292 /// false overflow results (#47139) and because it costs
293 /// computation time.
294 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
295 assert
!(self.intercrate
);
296 assert
!(self.intercrate_ambiguity_causes
.is_none());
297 self.intercrate_ambiguity_causes
= Some(vec
![]);
298 debug
!("selcx: enable_tracking_intercrate_ambiguity_causes");
301 /// Gets the intercrate ambiguity causes collected since tracking
302 /// was enabled and disables tracking at the same time. If
303 /// tracking is not enabled, just returns an empty vector.
304 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec
<IntercrateAmbiguityCause
> {
305 assert
!(self.intercrate
);
306 self.intercrate_ambiguity_causes
.take().unwrap_or_default()
309 pub fn infcx(&self) -> &'cx InferCtxt
<'cx
, 'tcx
> {
313 pub fn tcx(&self) -> TyCtxt
<'tcx
> {
317 pub fn is_intercrate(&self) -> bool
{
321 /// Returns `true` if the trait predicate is considerd `const` to this selection context.
322 pub fn is_trait_predicate_const(&self, pred
: ty
::TraitPredicate
<'_
>) -> bool
{
323 match pred
.constness
{
324 ty
::BoundConstness
::ConstIfConst
if self.is_in_const_context
=> true,
329 /// Returns `true` if the predicate is considered `const` to
330 /// this selection context.
331 pub fn is_predicate_const(&self, pred
: ty
::Predicate
<'_
>) -> bool
{
332 match pred
.kind().skip_binder() {
333 ty
::PredicateKind
::Trait(pred
) => self.is_trait_predicate_const(pred
),
338 ///////////////////////////////////////////////////////////////////////////
341 // The selection phase tries to identify *how* an obligation will
342 // be resolved. For example, it will identify which impl or
343 // parameter bound is to be used. The process can be inconclusive
344 // if the self type in the obligation is not fully inferred. Selection
345 // can result in an error in one of two ways:
347 // 1. If no applicable impl or parameter bound can be found.
348 // 2. If the output type parameters in the obligation do not match
349 // those specified by the impl/bound. For example, if the obligation
350 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
351 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
353 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
354 /// type environment by performing unification.
355 #[instrument(level = "debug", skip(self))]
358 obligation
: &TraitObligation
<'tcx
>,
359 ) -> SelectionResult
<'tcx
, Selection
<'tcx
>> {
360 debug_assert
!(!obligation
.predicate
.has_escaping_bound_vars());
362 let pec
= &ProvisionalEvaluationCache
::default();
363 let stack
= self.push_stack(TraitObligationStackList
::empty(pec
), obligation
);
365 let candidate
= match self.candidate_from_obligation(&stack
) {
366 Err(SelectionError
::Overflow
) => {
367 // In standard mode, overflow must have been caught and reported
369 assert
!(self.query_mode
== TraitQueryMode
::Canonical
);
370 return Err(SelectionError
::Overflow
);
378 Ok(Some(candidate
)) => candidate
,
381 match self.confirm_candidate(obligation
, candidate
) {
382 Err(SelectionError
::Overflow
) => {
383 assert
!(self.query_mode
== TraitQueryMode
::Canonical
);
384 Err(SelectionError
::Overflow
)
394 ///////////////////////////////////////////////////////////////////////////
397 // Tests whether an obligation can be selected or whether an impl
398 // can be applied to particular types. It skips the "confirmation"
399 // step and hence completely ignores output type parameters.
401 // The result is "true" if the obligation *may* hold and "false" if
402 // we can be sure it does not.
404 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
405 pub fn predicate_may_hold_fatal(&mut self, obligation
: &PredicateObligation
<'tcx
>) -> bool
{
406 debug
!(?obligation
, "predicate_may_hold_fatal");
408 // This fatal query is a stopgap that should only be used in standard mode,
409 // where we do not expect overflow to be propagated.
410 assert
!(self.query_mode
== TraitQueryMode
::Standard
);
412 self.evaluate_root_obligation(obligation
)
413 .expect("Overflow should be caught earlier in standard query mode")
417 /// Evaluates whether the obligation `obligation` can be satisfied
418 /// and returns an `EvaluationResult`. This is meant for the
420 pub fn evaluate_root_obligation(
422 obligation
: &PredicateObligation
<'tcx
>,
423 ) -> Result
<EvaluationResult
, OverflowError
> {
424 self.evaluation_probe(|this
| {
425 this
.evaluate_predicate_recursively(
426 TraitObligationStackList
::empty(&ProvisionalEvaluationCache
::default()),
434 op
: impl FnOnce(&mut Self) -> Result
<EvaluationResult
, OverflowError
>,
435 ) -> Result
<EvaluationResult
, OverflowError
> {
436 self.infcx
.probe(|snapshot
| -> Result
<EvaluationResult
, OverflowError
> {
437 let result
= op(self)?
;
439 match self.infcx
.leak_check(true, snapshot
) {
441 Err(_
) => return Ok(EvaluatedToErr
),
444 match self.infcx
.region_constraints_added_in_snapshot(snapshot
) {
446 Some(_
) => Ok(result
.max(EvaluatedToOkModuloRegions
)),
451 /// Evaluates the predicates in `predicates` recursively. Note that
452 /// this applies projections in the predicates, and therefore
453 /// is run within an inference probe.
454 #[instrument(skip(self, stack), level = "debug")]
455 fn evaluate_predicates_recursively
<'o
, I
>(
457 stack
: TraitObligationStackList
<'o
, 'tcx
>,
459 ) -> Result
<EvaluationResult
, OverflowError
>
461 I
: IntoIterator
<Item
= PredicateObligation
<'tcx
>> + std
::fmt
::Debug
,
463 let mut result
= EvaluatedToOk
;
464 for obligation
in predicates
{
465 let eval
= self.evaluate_predicate_recursively(stack
, obligation
.clone())?
;
466 if let EvaluatedToErr
= eval
{
467 // fast-path - EvaluatedToErr is the top of the lattice,
468 // so we don't need to look on the other predicates.
469 return Ok(EvaluatedToErr
);
471 result
= cmp
::max(result
, eval
);
479 skip(self, previous_stack
),
480 fields(previous_stack
= ?previous_stack
.head())
482 fn evaluate_predicate_recursively
<'o
>(
484 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
485 obligation
: PredicateObligation
<'tcx
>,
486 ) -> Result
<EvaluationResult
, OverflowError
> {
487 // `previous_stack` stores a `TraitObligation`, while `obligation` is
488 // a `PredicateObligation`. These are distinct types, so we can't
489 // use any `Option` combinator method that would force them to be
491 match previous_stack
.head() {
492 Some(h
) => self.check_recursion_limit(&obligation
, h
.obligation
)?
,
493 None
=> self.check_recursion_limit(&obligation
, &obligation
)?
,
496 let result
= ensure_sufficient_stack(|| {
497 let bound_predicate
= obligation
.predicate
.kind();
498 match bound_predicate
.skip_binder() {
499 ty
::PredicateKind
::Trait(t
) => {
500 let t
= bound_predicate
.rebind(t
);
501 debug_assert
!(!t
.has_escaping_bound_vars());
502 let obligation
= obligation
.with(t
);
503 self.evaluate_trait_predicate_recursively(previous_stack
, obligation
)
506 ty
::PredicateKind
::Subtype(p
) => {
507 let p
= bound_predicate
.rebind(p
);
508 // Does this code ever run?
509 match self.infcx
.subtype_predicate(&obligation
.cause
, obligation
.param_env
, p
) {
510 Some(Ok(InferOk { mut obligations, .. }
)) => {
511 self.add_depth(obligations
.iter_mut(), obligation
.recursion_depth
);
512 self.evaluate_predicates_recursively(
514 obligations
.into_iter(),
517 Some(Err(_
)) => Ok(EvaluatedToErr
),
518 None
=> Ok(EvaluatedToAmbig
),
522 ty
::PredicateKind
::Coerce(p
) => {
523 let p
= bound_predicate
.rebind(p
);
524 // Does this code ever run?
525 match self.infcx
.coerce_predicate(&obligation
.cause
, obligation
.param_env
, p
) {
526 Some(Ok(InferOk { mut obligations, .. }
)) => {
527 self.add_depth(obligations
.iter_mut(), obligation
.recursion_depth
);
528 self.evaluate_predicates_recursively(
530 obligations
.into_iter(),
533 Some(Err(_
)) => Ok(EvaluatedToErr
),
534 None
=> Ok(EvaluatedToAmbig
),
538 ty
::PredicateKind
::WellFormed(arg
) => match wf
::obligations(
540 obligation
.param_env
,
541 obligation
.cause
.body_id
,
542 obligation
.recursion_depth
+ 1,
544 obligation
.cause
.span
,
546 Some(mut obligations
) => {
547 self.add_depth(obligations
.iter_mut(), obligation
.recursion_depth
);
548 self.evaluate_predicates_recursively(previous_stack
, obligations
)
550 None
=> Ok(EvaluatedToAmbig
),
553 ty
::PredicateKind
::TypeOutlives(pred
) => {
554 if pred
.0.is_known_global
() {
557 Ok(EvaluatedToOkModuloRegions
)
561 ty
::PredicateKind
::RegionOutlives(..) => {
562 // We do not consider region relationships when evaluating trait matches.
563 Ok(EvaluatedToOkModuloRegions
)
566 ty
::PredicateKind
::ObjectSafe(trait_def_id
) => {
567 if self.tcx().is_object_safe(trait_def_id
) {
574 ty
::PredicateKind
::Projection(data
) => {
575 let data
= bound_predicate
.rebind(data
);
576 let project_obligation
= obligation
.with(data
);
577 match project
::poly_project_and_unify_type(self, &project_obligation
) {
578 Ok(Ok(Some(mut subobligations
))) => {
579 self.add_depth(subobligations
.iter_mut(), obligation
.recursion_depth
);
580 self.evaluate_predicates_recursively(previous_stack
, subobligations
)
582 Ok(Ok(None
)) => Ok(EvaluatedToAmbig
),
583 Ok(Err(project
::InProgress
)) => Ok(EvaluatedToRecur
),
584 Err(_
) => Ok(EvaluatedToErr
),
588 ty
::PredicateKind
::ClosureKind(_
, closure_substs
, kind
) => {
589 match self.infcx
.closure_kind(closure_substs
) {
590 Some(closure_kind
) => {
591 if closure_kind
.extends(kind
) {
597 None
=> Ok(EvaluatedToAmbig
),
601 ty
::PredicateKind
::ConstEvaluatable(uv
) => {
602 match const_evaluatable
::is_const_evaluatable(
605 obligation
.param_env
,
606 obligation
.cause
.span
,
608 Ok(()) => Ok(EvaluatedToOk
),
609 Err(NotConstEvaluatable
::MentionsInfer
) => Ok(EvaluatedToAmbig
),
610 Err(NotConstEvaluatable
::MentionsParam
) => Ok(EvaluatedToErr
),
611 Err(_
) => Ok(EvaluatedToErr
),
615 ty
::PredicateKind
::ConstEquate(c1
, c2
) => {
616 debug
!(?c1
, ?c2
, "evaluate_predicate_recursively: equating consts");
618 if self.tcx().features().generic_const_exprs
{
619 // FIXME: we probably should only try to unify abstract constants
620 // if the constants depend on generic parameters.
622 // Let's just see where this breaks :shrug:
623 if let (ty
::ConstKind
::Unevaluated(a
), ty
::ConstKind
::Unevaluated(b
)) =
626 if self.infcx
.try_unify_abstract_consts(a
.shrink(), b
.shrink()) {
627 return Ok(EvaluatedToOk
);
632 let evaluate
= |c
: &'tcx ty
::Const
<'tcx
>| {
633 if let ty
::ConstKind
::Unevaluated(unevaluated
) = c
.val
{
636 obligation
.param_env
,
638 Some(obligation
.cause
.span
),
640 .map(|val
| ty
::Const
::from_value(self.tcx(), val
, c
.ty
))
646 match (evaluate(c1
), evaluate(c2
)) {
647 (Ok(c1
), Ok(c2
)) => {
650 .at(&obligation
.cause
, obligation
.param_env
)
653 Ok(_
) => Ok(EvaluatedToOk
),
654 Err(_
) => Ok(EvaluatedToErr
),
657 (Err(ErrorHandled
::Reported(ErrorReported
)), _
)
658 | (_
, Err(ErrorHandled
::Reported(ErrorReported
))) => Ok(EvaluatedToErr
),
659 (Err(ErrorHandled
::Linted
), _
) | (_
, Err(ErrorHandled
::Linted
)) => {
661 obligation
.cause
.span(self.tcx()),
662 "ConstEquate: const_eval_resolve returned an unexpected error"
665 (Err(ErrorHandled
::TooGeneric
), _
) | (_
, Err(ErrorHandled
::TooGeneric
)) => {
666 if c1
.has_infer_types_or_consts() || c2
.has_infer_types_or_consts() {
669 // Two different constants using generic parameters ~> error.
675 ty
::PredicateKind
::TypeWellFormedFromEnv(..) => {
676 bug
!("TypeWellFormedFromEnv is only used for chalk")
681 debug
!("finished: {:?} from {:?}", result
, obligation
);
686 #[instrument(skip(self, previous_stack), level = "debug")]
687 fn evaluate_trait_predicate_recursively
<'o
>(
689 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
690 mut obligation
: TraitObligation
<'tcx
>,
691 ) -> Result
<EvaluationResult
, OverflowError
> {
693 && obligation
.is_global(self.tcx())
698 .all(|bound
| bound
.definitely_needs_subst(self.tcx()))
700 // If a param env has no global bounds, global obligations do not
701 // depend on its particular value in order to work, so we can clear
702 // out the param env and get better caching.
704 obligation
.param_env
= obligation
.param_env
.without_caller_bounds();
707 let stack
= self.push_stack(previous_stack
, &obligation
);
708 let fresh_trait_ref
= stack
.fresh_trait_ref
;
710 debug
!(?fresh_trait_ref
);
712 if let Some(result
) = self.check_evaluation_cache(obligation
.param_env
, fresh_trait_ref
) {
713 debug
!(?result
, "CACHE HIT");
717 if let Some(result
) = stack
.cache().get_provisional(fresh_trait_ref
) {
718 debug
!(?result
, "PROVISIONAL CACHE HIT");
719 stack
.update_reached_depth(result
.reached_depth
);
720 return Ok(result
.result
);
723 // Check if this is a match for something already on the
724 // stack. If so, we don't want to insert the result into the
725 // main cache (it is cycle dependent) nor the provisional
726 // cache (which is meant for things that have completed but
727 // for a "backedge" -- this result *is* the backedge).
728 if let Some(cycle_result
) = self.check_evaluation_cycle(&stack
) {
729 return Ok(cycle_result
);
732 let (result
, dep_node
) = self.in_task(|this
| this
.evaluate_stack(&stack
));
733 let result
= result?
;
735 if !result
.must_apply_modulo_regions() {
736 stack
.cache().on_failure(stack
.dfn
);
739 let reached_depth
= stack
.reached_depth
.get();
740 if reached_depth
>= stack
.depth
{
741 debug
!(?result
, "CACHE MISS");
742 self.insert_evaluation_cache(obligation
.param_env
, fresh_trait_ref
, dep_node
, result
);
744 stack
.cache().on_completion(stack
.dfn
, |fresh_trait_ref
, provisional_result
| {
745 self.insert_evaluation_cache(
746 obligation
.param_env
,
749 provisional_result
.max(result
),
753 debug
!(?result
, "PROVISIONAL");
755 "caching provisionally because {:?} \
756 is a cycle participant (at depth {}, reached depth {})",
757 fresh_trait_ref
, stack
.depth
, reached_depth
,
760 stack
.cache().insert_provisional(stack
.dfn
, reached_depth
, fresh_trait_ref
, result
);
766 /// If there is any previous entry on the stack that precisely
767 /// matches this obligation, then we can assume that the
768 /// obligation is satisfied for now (still all other conditions
769 /// must be met of course). One obvious case this comes up is
770 /// marker traits like `Send`. Think of a linked list:
772 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
774 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
775 /// `Option<Box<List<T>>>` is `Send`, and in turn
776 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
779 /// Note that we do this comparison using the `fresh_trait_ref`
780 /// fields. Because these have all been freshened using
781 /// `self.freshener`, we can be sure that (a) this will not
782 /// affect the inferencer state and (b) that if we see two
783 /// fresh regions with the same index, they refer to the same
784 /// unbound type variable.
785 fn check_evaluation_cycle(
787 stack
: &TraitObligationStack
<'_
, 'tcx
>,
788 ) -> Option
<EvaluationResult
> {
789 if let Some(cycle_depth
) = stack
791 .skip(1) // Skip top-most frame.
793 stack
.obligation
.param_env
== prev
.obligation
.param_env
794 && stack
.fresh_trait_ref
== prev
.fresh_trait_ref
796 .map(|stack
| stack
.depth
)
798 debug
!("evaluate_stack --> recursive at depth {}", cycle_depth
);
800 // If we have a stack like `A B C D E A`, where the top of
801 // the stack is the final `A`, then this will iterate over
802 // `A, E, D, C, B` -- i.e., all the participants apart
803 // from the cycle head. We mark them as participating in a
804 // cycle. This suppresses caching for those nodes. See
805 // `in_cycle` field for more details.
806 stack
.update_reached_depth(cycle_depth
);
808 // Subtle: when checking for a coinductive cycle, we do
809 // not compare using the "freshened trait refs" (which
810 // have erased regions) but rather the fully explicit
811 // trait refs. This is important because it's only a cycle
812 // if the regions match exactly.
813 let cycle
= stack
.iter().skip(1).take_while(|s
| s
.depth
>= cycle_depth
);
814 let tcx
= self.tcx();
815 let cycle
= cycle
.map(|stack
| stack
.obligation
.predicate
.to_predicate(tcx
));
816 if self.coinductive_match(cycle
) {
817 debug
!("evaluate_stack --> recursive, coinductive");
820 debug
!("evaluate_stack --> recursive, inductive");
821 Some(EvaluatedToRecur
)
828 fn evaluate_stack
<'o
>(
830 stack
: &TraitObligationStack
<'o
, 'tcx
>,
831 ) -> Result
<EvaluationResult
, OverflowError
> {
832 // In intercrate mode, whenever any of the generics are unbound,
833 // there can always be an impl. Even if there are no impls in
834 // this crate, perhaps the type would be unified with
835 // something from another crate that does provide an impl.
837 // In intra mode, we must still be conservative. The reason is
838 // that we want to avoid cycles. Imagine an impl like:
840 // impl<T:Eq> Eq for Vec<T>
842 // and a trait reference like `$0 : Eq` where `$0` is an
843 // unbound variable. When we evaluate this trait-reference, we
844 // will unify `$0` with `Vec<$1>` (for some fresh variable
845 // `$1`), on the condition that `$1 : Eq`. We will then wind
846 // up with many candidates (since that are other `Eq` impls
847 // that apply) and try to winnow things down. This results in
848 // a recursive evaluation that `$1 : Eq` -- as you can
849 // imagine, this is just where we started. To avoid that, we
850 // check for unbound variables and return an ambiguous (hence possible)
851 // match if we've seen this trait before.
853 // This suffices to allow chains like `FnMut` implemented in
854 // terms of `Fn` etc, but we could probably make this more
856 let unbound_input_types
=
857 stack
.fresh_trait_ref
.value
.skip_binder().substs
.types().any(|ty
| ty
.is_fresh());
858 // This check was an imperfect workaround for a bug in the old
859 // intercrate mode; it should be removed when that goes away.
860 if unbound_input_types
&& self.intercrate
{
861 debug
!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
862 // Heuristics: show the diagnostics when there are no candidates in crate.
863 if self.intercrate_ambiguity_causes
.is_some() {
864 debug
!("evaluate_stack: intercrate_ambiguity_causes is some");
865 if let Ok(candidate_set
) = self.assemble_candidates(stack
) {
866 if !candidate_set
.ambiguous
&& candidate_set
.vec
.is_empty() {
867 let trait_ref
= stack
.obligation
.predicate
.skip_binder().trait_ref
;
868 let self_ty
= trait_ref
.self_ty();
870 with_no_trimmed_paths(|| IntercrateAmbiguityCause
::DownstreamCrate
{
871 trait_desc
: trait_ref
.print_only_trait_path().to_string(),
872 self_desc
: if self_ty
.has_concrete_skeleton() {
873 Some(self_ty
.to_string())
879 debug
!(?cause
, "evaluate_stack: pushing cause");
880 self.intercrate_ambiguity_causes
.as_mut().unwrap().push(cause
);
884 return Ok(EvaluatedToAmbig
);
886 if unbound_input_types
887 && stack
.iter().skip(1).any(|prev
| {
888 stack
.obligation
.param_env
== prev
.obligation
.param_env
889 && self.match_fresh_trait_refs(
890 stack
.fresh_trait_ref
,
891 prev
.fresh_trait_ref
,
892 prev
.obligation
.param_env
,
896 debug
!("evaluate_stack --> unbound argument, recursive --> giving up",);
897 return Ok(EvaluatedToUnknown
);
900 match self.candidate_from_obligation(stack
) {
901 Ok(Some(c
)) => self.evaluate_candidate(stack
, &c
),
902 Ok(None
) => Ok(EvaluatedToAmbig
),
903 Err(Overflow
) => Err(OverflowError
::Canonical
),
904 Err(ErrorReporting
) => Err(OverflowError
::ErrorReporting
),
905 Err(..) => Ok(EvaluatedToErr
),
909 /// For defaulted traits, we use a co-inductive strategy to solve, so
910 /// that recursion is ok. This routine returns `true` if the top of the
911 /// stack (`cycle[0]`):
913 /// - is a defaulted trait,
914 /// - it also appears in the backtrace at some position `X`,
915 /// - all the predicates at positions `X..` between `X` and the top are
916 /// also defaulted traits.
917 pub fn coinductive_match
<I
>(&mut self, mut cycle
: I
) -> bool
919 I
: Iterator
<Item
= ty
::Predicate
<'tcx
>>,
921 cycle
.all(|predicate
| self.coinductive_predicate(predicate
))
924 fn coinductive_predicate(&self, predicate
: ty
::Predicate
<'tcx
>) -> bool
{
925 let result
= match predicate
.kind().skip_binder() {
926 ty
::PredicateKind
::Trait(ref data
) => self.tcx().trait_is_auto(data
.def_id()),
929 debug
!(?predicate
, ?result
, "coinductive_predicate");
933 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
934 /// obligations are met. Returns whether `candidate` remains viable after this further
939 fields(depth
= stack
.obligation
.recursion_depth
)
941 fn evaluate_candidate
<'o
>(
943 stack
: &TraitObligationStack
<'o
, 'tcx
>,
944 candidate
: &SelectionCandidate
<'tcx
>,
945 ) -> Result
<EvaluationResult
, OverflowError
> {
946 let mut result
= self.evaluation_probe(|this
| {
947 let candidate
= (*candidate
).clone();
948 match this
.confirm_candidate(stack
.obligation
, candidate
) {
951 this
.evaluate_predicates_recursively(
953 selection
.nested_obligations().into_iter(),
956 Err(..) => Ok(EvaluatedToErr
),
960 // If we erased any lifetimes, then we want to use
961 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
962 // as your final result. The result will be cached using
963 // the freshened trait predicate as a key, so we need
964 // our result to be correct by *any* choice of original lifetimes,
965 // not just the lifetime choice for this particular (non-erased)
968 if stack
.fresh_trait_ref
.has_erased_regions() {
969 result
= result
.max(EvaluatedToOkModuloRegions
);
976 fn check_evaluation_cache(
978 param_env
: ty
::ParamEnv
<'tcx
>,
979 trait_ref
: ty
::ConstnessAnd
<ty
::PolyTraitRef
<'tcx
>>,
980 ) -> Option
<EvaluationResult
> {
981 // Neither the global nor local cache is aware of intercrate
982 // mode, so don't do any caching. In particular, we might
983 // re-use the same `InferCtxt` with both an intercrate
984 // and non-intercrate `SelectionContext`
989 let tcx
= self.tcx();
990 if self.can_use_global_caches(param_env
) {
991 if let Some(res
) = tcx
.evaluation_cache
.get(¶m_env
.and(trait_ref
), tcx
) {
995 self.infcx
.evaluation_cache
.get(¶m_env
.and(trait_ref
), tcx
)
998 fn insert_evaluation_cache(
1000 param_env
: ty
::ParamEnv
<'tcx
>,
1001 trait_ref
: ty
::ConstnessAnd
<ty
::PolyTraitRef
<'tcx
>>,
1002 dep_node
: DepNodeIndex
,
1003 result
: EvaluationResult
,
1005 // Avoid caching results that depend on more than just the trait-ref
1006 // - the stack can create recursion.
1007 if result
.is_stack_dependent() {
1011 // Neither the global nor local cache is aware of intercrate
1012 // mode, so don't do any caching. In particular, we might
1013 // re-use the same `InferCtxt` with both an intercrate
1014 // and non-intercrate `SelectionContext`
1015 if self.intercrate
{
1019 if self.can_use_global_caches(param_env
) {
1020 if !trait_ref
.needs_infer() {
1021 debug
!(?trait_ref
, ?result
, "insert_evaluation_cache global");
1022 // This may overwrite the cache with the same value
1023 // FIXME: Due to #50507 this overwrites the different values
1024 // This should be changed to use HashMapExt::insert_same
1025 // when that is fixed
1026 self.tcx().evaluation_cache
.insert(param_env
.and(trait_ref
), dep_node
, result
);
1031 debug
!(?trait_ref
, ?result
, "insert_evaluation_cache");
1032 self.infcx
.evaluation_cache
.insert(param_env
.and(trait_ref
), dep_node
, result
);
1035 /// For various reasons, it's possible for a subobligation
1036 /// to have a *lower* recursion_depth than the obligation used to create it.
1037 /// Projection sub-obligations may be returned from the projection cache,
1038 /// which results in obligations with an 'old' `recursion_depth`.
1039 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1040 /// subobligations without taking in a 'parent' depth, causing the
1041 /// generated subobligations to have a `recursion_depth` of `0`.
1043 /// To ensure that obligation_depth never decreases, we force all subobligations
1044 /// to have at least the depth of the original obligation.
1045 fn add_depth
<T
: 'cx
, I
: Iterator
<Item
= &'cx
mut Obligation
<'tcx
, T
>>>(
1050 it
.for_each(|o
| o
.recursion_depth
= cmp
::max(min_depth
, o
.recursion_depth
) + 1);
1053 fn check_recursion_depth
<T
: Display
+ TypeFoldable
<'tcx
>>(
1056 error_obligation
: &Obligation
<'tcx
, T
>,
1057 ) -> Result
<(), OverflowError
> {
1058 if !self.infcx
.tcx
.recursion_limit().value_within_limit(depth
) {
1059 match self.query_mode
{
1060 TraitQueryMode
::Standard
=> {
1061 if self.infcx
.is_tainted_by_errors() {
1062 return Err(OverflowError
::ErrorReporting
);
1064 self.infcx
.report_overflow_error(error_obligation
, true);
1066 TraitQueryMode
::Canonical
=> {
1067 return Err(OverflowError
::Canonical
);
1074 /// Checks that the recursion limit has not been exceeded.
1076 /// The weird return type of this function allows it to be used with the `try` (`?`)
1077 /// operator within certain functions.
1079 fn check_recursion_limit
<T
: Display
+ TypeFoldable
<'tcx
>, V
: Display
+ TypeFoldable
<'tcx
>>(
1081 obligation
: &Obligation
<'tcx
, T
>,
1082 error_obligation
: &Obligation
<'tcx
, V
>,
1083 ) -> Result
<(), OverflowError
> {
1084 self.check_recursion_depth(obligation
.recursion_depth
, error_obligation
)
1087 fn in_task
<OP
, R
>(&mut self, op
: OP
) -> (R
, DepNodeIndex
)
1089 OP
: FnOnce(&mut Self) -> R
,
1091 let (result
, dep_node
) =
1092 self.tcx().dep_graph
.with_anon_task(self.tcx(), DepKind
::TraitSelect
, || op(self));
1093 self.tcx().dep_graph
.read_index(dep_node
);
1097 #[instrument(level = "debug", skip(self))]
1100 candidate
: SelectionCandidate
<'tcx
>,
1101 obligation
: &TraitObligation
<'tcx
>,
1102 ) -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>> {
1103 let tcx
= self.tcx();
1104 // Respect const trait obligations
1105 if self.is_trait_predicate_const(obligation
.predicate
.skip_binder()) {
1108 ImplCandidate(def_id
) if tcx
.impl_constness(def_id
) == hir
::Constness
::Const
=> {}
1110 ParamCandidate(ty
::ConstnessAnd
{
1111 constness
: ty
::BoundConstness
::ConstIfConst
,
1115 AutoImplCandidate(..) => {}
1116 // generator, this will raise error in other places
1117 // or ignore error with const_async_blocks feature
1118 GeneratorCandidate
=> {}
1119 // FnDef where the function is const
1120 FnPointerCandidate { is_const: true }
=> {}
1121 ConstDropCandidate
=> {}
1123 // reject all other types of candidates
1124 return Err(Unimplemented
);
1128 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
1129 if let ImplCandidate(def_id
) = candidate
{
1130 match tcx
.impl_polarity(def_id
) {
1131 ty
::ImplPolarity
::Negative
if !self.allow_negative_impls
=> {
1132 return Err(Unimplemented
);
1134 ty
::ImplPolarity
::Reservation
=> {
1135 if let Some(intercrate_ambiguity_clauses
) =
1136 &mut self.intercrate_ambiguity_causes
1138 let attrs
= tcx
.get_attrs(def_id
);
1139 let attr
= tcx
.sess
.find_by_name(&attrs
, sym
::rustc_reservation_impl
);
1140 let value
= attr
.and_then(|a
| a
.value_str());
1141 if let Some(value
) = value
{
1144 reservation impl ambiguity on {:?}",
1147 intercrate_ambiguity_clauses
.push(
1148 IntercrateAmbiguityCause
::ReservationImpl
{
1149 message
: value
.to_string(),
1162 fn is_knowable
<'o
>(&mut self, stack
: &TraitObligationStack
<'o
, 'tcx
>) -> Option
<Conflict
> {
1163 debug
!("is_knowable(intercrate={:?})", self.intercrate
);
1165 if !self.intercrate
{
1169 let obligation
= &stack
.obligation
;
1170 let predicate
= self.infcx().resolve_vars_if_possible(obligation
.predicate
);
1172 // Okay to skip binder because of the nature of the
1173 // trait-ref-is-knowable check, which does not care about
1175 let trait_ref
= predicate
.skip_binder().trait_ref
;
1177 coherence
::trait_ref_is_knowable(self.tcx(), trait_ref
)
1180 /// Returns `true` if the global caches can be used.
1181 fn can_use_global_caches(&self, param_env
: ty
::ParamEnv
<'tcx
>) -> bool
{
1182 // If there are any inference variables in the `ParamEnv`, then we
1183 // always use a cache local to this particular scope. Otherwise, we
1184 // switch to a global cache.
1185 if param_env
.needs_infer() {
1189 // Avoid using the master cache during coherence and just rely
1190 // on the local cache. This effectively disables caching
1191 // during coherence. It is really just a simplification to
1192 // avoid us having to fear that coherence results "pollute"
1193 // the master cache. Since coherence executes pretty quickly,
1194 // it's not worth going to more trouble to increase the
1195 // hit-rate, I don't think.
1196 if self.intercrate
{
1200 // Otherwise, we can use the global cache.
1204 fn check_candidate_cache(
1206 param_env
: ty
::ParamEnv
<'tcx
>,
1207 cache_fresh_trait_pred
: ty
::PolyTraitPredicate
<'tcx
>,
1208 ) -> Option
<SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>> {
1209 // Neither the global nor local cache is aware of intercrate
1210 // mode, so don't do any caching. In particular, we might
1211 // re-use the same `InferCtxt` with both an intercrate
1212 // and non-intercrate `SelectionContext`
1213 if self.intercrate
{
1216 let tcx
= self.tcx();
1217 let pred
= &cache_fresh_trait_pred
.skip_binder();
1218 let trait_ref
= pred
.trait_ref
;
1219 if self.can_use_global_caches(param_env
) {
1220 if let Some(res
) = tcx
1222 .get(¶m_env
.and(trait_ref
).with_constness(pred
.constness
), tcx
)
1229 .get(¶m_env
.and(trait_ref
).with_constness(pred
.constness
), tcx
)
1232 /// Determines whether can we safely cache the result
1233 /// of selecting an obligation. This is almost always `true`,
1234 /// except when dealing with certain `ParamCandidate`s.
1236 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1237 /// since it was usually produced directly from a `DefId`. However,
1238 /// certain cases (currently only librustdoc's blanket impl finder),
1239 /// a `ParamEnv` may be explicitly constructed with inference types.
1240 /// When this is the case, we do *not* want to cache the resulting selection
1241 /// candidate. This is due to the fact that it might not always be possible
1242 /// to equate the obligation's trait ref and the candidate's trait ref,
1243 /// if more constraints end up getting added to an inference variable.
1245 /// Because of this, we always want to re-run the full selection
1246 /// process for our obligation the next time we see it, since
1247 /// we might end up picking a different `SelectionCandidate` (or none at all).
1248 fn can_cache_candidate(
1250 result
: &SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>,
1252 // Neither the global nor local cache is aware of intercrate
1253 // mode, so don't do any caching. In particular, we might
1254 // re-use the same `InferCtxt` with both an intercrate
1255 // and non-intercrate `SelectionContext`
1256 if self.intercrate
{
1260 Ok(Some(SelectionCandidate
::ParamCandidate(trait_ref
))) => !trait_ref
.needs_infer(),
1265 fn insert_candidate_cache(
1267 param_env
: ty
::ParamEnv
<'tcx
>,
1268 cache_fresh_trait_pred
: ty
::PolyTraitPredicate
<'tcx
>,
1269 dep_node
: DepNodeIndex
,
1270 candidate
: SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>,
1272 let tcx
= self.tcx();
1273 let pred
= cache_fresh_trait_pred
.skip_binder();
1274 let trait_ref
= pred
.trait_ref
;
1276 if !self.can_cache_candidate(&candidate
) {
1277 debug
!(?trait_ref
, ?candidate
, "insert_candidate_cache - candidate is not cacheable");
1281 if self.can_use_global_caches(param_env
) {
1282 if let Err(Overflow
) = candidate
{
1283 // Don't cache overflow globally; we only produce this in certain modes.
1284 } else if !trait_ref
.needs_infer() {
1285 if !candidate
.needs_infer() {
1286 debug
!(?trait_ref
, ?candidate
, "insert_candidate_cache global");
1287 // This may overwrite the cache with the same value.
1288 tcx
.selection_cache
.insert(
1289 param_env
.and(trait_ref
).with_constness(pred
.constness
),
1298 debug
!(?trait_ref
, ?candidate
, "insert_candidate_cache local");
1299 self.infcx
.selection_cache
.insert(
1300 param_env
.and(trait_ref
).with_constness(pred
.constness
),
1306 /// Matches a predicate against the bounds of its self type.
1308 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1309 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1310 /// `Baz` bound. We return indexes into the list returned by
1311 /// `tcx.item_bounds` for any applicable bounds.
1312 fn match_projection_obligation_against_definition_bounds(
1314 obligation
: &TraitObligation
<'tcx
>,
1315 ) -> smallvec
::SmallVec
<[usize; 2]> {
1316 let poly_trait_predicate
= self.infcx().resolve_vars_if_possible(obligation
.predicate
);
1317 let placeholder_trait_predicate
=
1318 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate
);
1320 ?placeholder_trait_predicate
,
1321 "match_projection_obligation_against_definition_bounds"
1324 let tcx
= self.infcx
.tcx
;
1325 let (def_id
, substs
) = match *placeholder_trait_predicate
.trait_ref
.self_ty().kind() {
1326 ty
::Projection(ref data
) => (data
.item_def_id
, data
.substs
),
1327 ty
::Opaque(def_id
, substs
) => (def_id
, substs
),
1330 obligation
.cause
.span
,
1331 "match_projection_obligation_against_definition_bounds() called \
1332 but self-ty is not a projection: {:?}",
1333 placeholder_trait_predicate
.trait_ref
.self_ty()
1337 let bounds
= tcx
.item_bounds(def_id
).subst(tcx
, substs
);
1339 // The bounds returned by `item_bounds` may contain duplicates after
1340 // normalization, so try to deduplicate when possible to avoid
1341 // unnecessary ambiguity.
1342 let mut distinct_normalized_bounds
= FxHashSet
::default();
1344 let matching_bounds
= bounds
1347 .filter_map(|(idx
, bound
)| {
1348 let bound_predicate
= bound
.kind();
1349 if let ty
::PredicateKind
::Trait(pred
) = bound_predicate
.skip_binder() {
1350 let bound
= bound_predicate
.rebind(pred
.trait_ref
);
1351 if self.infcx
.probe(|_
| {
1352 match self.match_normalize_trait_ref(
1355 placeholder_trait_predicate
.trait_ref
,
1358 Ok(Some(normalized_trait
))
1359 if distinct_normalized_bounds
.insert(normalized_trait
) =>
1373 debug
!(?matching_bounds
, "match_projection_obligation_against_definition_bounds");
1377 /// Equates the trait in `obligation` with trait bound. If the two traits
1378 /// can be equated and the normalized trait bound doesn't contain inference
1379 /// variables or placeholders, the normalized bound is returned.
1380 fn match_normalize_trait_ref(
1382 obligation
: &TraitObligation
<'tcx
>,
1383 trait_bound
: ty
::PolyTraitRef
<'tcx
>,
1384 placeholder_trait_ref
: ty
::TraitRef
<'tcx
>,
1385 ) -> Result
<Option
<ty
::PolyTraitRef
<'tcx
>>, ()> {
1386 debug_assert
!(!placeholder_trait_ref
.has_escaping_bound_vars());
1387 if placeholder_trait_ref
.def_id
!= trait_bound
.def_id() {
1388 // Avoid unnecessary normalization
1392 let Normalized { value: trait_bound, obligations: _ }
= ensure_sufficient_stack(|| {
1393 project
::normalize_with_depth(
1395 obligation
.param_env
,
1396 obligation
.cause
.clone(),
1397 obligation
.recursion_depth
+ 1,
1402 .at(&obligation
.cause
, obligation
.param_env
)
1403 .sup(ty
::Binder
::dummy(placeholder_trait_ref
), trait_bound
)
1404 .map(|InferOk { obligations: _, value: () }
| {
1405 // This method is called within a probe, so we can't have
1406 // inference variables and placeholders escape.
1407 if !trait_bound
.needs_infer() && !trait_bound
.has_placeholders() {
1416 fn evaluate_where_clause
<'o
>(
1418 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1419 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
1420 ) -> Result
<EvaluationResult
, OverflowError
> {
1421 self.evaluation_probe(|this
| {
1422 match this
.match_where_clause_trait_ref(stack
.obligation
, where_clause_trait_ref
) {
1423 Ok(obligations
) => this
.evaluate_predicates_recursively(stack
.list(), obligations
),
1424 Err(()) => Ok(EvaluatedToErr
),
1429 pub(super) fn match_projection_projections(
1431 obligation
: &ProjectionTyObligation
<'tcx
>,
1432 env_predicate
: PolyProjectionPredicate
<'tcx
>,
1433 potentially_unnormalized_candidates
: bool
,
1435 let mut nested_obligations
= Vec
::new();
1436 let (infer_predicate
, _
) = self.infcx
.replace_bound_vars_with_fresh_vars(
1437 obligation
.cause
.span
,
1438 LateBoundRegionConversionTime
::HigherRankedType
,
1441 let infer_projection
= if potentially_unnormalized_candidates
{
1442 ensure_sufficient_stack(|| {
1443 project
::normalize_with_depth_to(
1445 obligation
.param_env
,
1446 obligation
.cause
.clone(),
1447 obligation
.recursion_depth
+ 1,
1448 infer_predicate
.projection_ty
,
1449 &mut nested_obligations
,
1453 infer_predicate
.projection_ty
1457 .at(&obligation
.cause
, obligation
.param_env
)
1458 .sup(obligation
.predicate
, infer_projection
)
1459 .map_or(false, |InferOk { obligations, value: () }
| {
1460 self.evaluate_predicates_recursively(
1461 TraitObligationStackList
::empty(&ProvisionalEvaluationCache
::default()),
1462 nested_obligations
.into_iter().chain(obligations
),
1464 .map_or(false, |res
| res
.may_apply())
1468 ///////////////////////////////////////////////////////////////////////////
1471 // Winnowing is the process of attempting to resolve ambiguity by
1472 // probing further. During the winnowing process, we unify all
1473 // type variables and then we also attempt to evaluate recursive
1474 // bounds to see if they are satisfied.
1476 /// Returns `true` if `victim` should be dropped in favor of
1477 /// `other`. Generally speaking we will drop duplicate
1478 /// candidates and prefer where-clause candidates.
1480 /// See the comment for "SelectionCandidate" for more details.
1481 fn candidate_should_be_dropped_in_favor_of(
1483 victim
: &EvaluatedCandidate
<'tcx
>,
1484 other
: &EvaluatedCandidate
<'tcx
>,
1487 if victim
.candidate
== other
.candidate
{
1491 // Check if a bound would previously have been removed when normalizing
1492 // the param_env so that it can be given the lowest priority. See
1493 // #50825 for the motivation for this.
1495 |cand
: &ty
::PolyTraitRef
<'_
>| cand
.is_known_global() && !cand
.has_late_bound_regions();
1497 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
1498 // and `DiscriminantKindCandidate` to anything else.
1500 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1501 // lifetime of a variable.
1502 match (&other
.candidate
, &victim
.candidate
) {
1503 (_
, AutoImplCandidate(..)) | (AutoImplCandidate(..), _
) => {
1505 "default implementations shouldn't be recorded \
1506 when there are other valid candidates"
1512 BuiltinCandidate { has_nested: false }
1513 | DiscriminantKindCandidate
1515 | ConstDropCandidate
,
1520 BuiltinCandidate { has_nested: false }
1521 | DiscriminantKindCandidate
1523 | ConstDropCandidate
,
1526 (ParamCandidate(other
), ParamCandidate(victim
)) => {
1527 let same_except_bound_vars
= other
.value
.skip_binder()
1528 == victim
.value
.skip_binder()
1529 && other
.constness
== victim
.constness
1530 && !other
.value
.skip_binder().has_escaping_bound_vars();
1531 if same_except_bound_vars
{
1532 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1533 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1534 // or the current one if tied (they should both evaluate to the same answer). This is
1535 // probably best characterized as a "hack", since we might prefer to just do our
1536 // best to *not* create essentially duplicate candidates in the first place.
1537 other
.value
.bound_vars().len() <= victim
.value
.bound_vars().len()
1538 } else if other
.value
== victim
.value
1539 && victim
.constness
== ty
::BoundConstness
::NotConst
1541 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1548 // Drop otherwise equivalent non-const fn pointer candidates
1549 (FnPointerCandidate { .. }
, FnPointerCandidate { is_const: false }
) => true,
1551 // Global bounds from the where clause should be ignored
1552 // here (see issue #50825). Otherwise, we have a where
1553 // clause so don't go around looking for impls.
1554 // Arbitrarily give param candidates priority
1555 // over projection and object candidates.
1557 ParamCandidate(ref cand
),
1560 | GeneratorCandidate
1561 | FnPointerCandidate { .. }
1562 | BuiltinObjectCandidate
1563 | BuiltinUnsizeCandidate
1564 | TraitUpcastingUnsizeCandidate(_
)
1565 | BuiltinCandidate { .. }
1566 | TraitAliasCandidate(..)
1567 | ObjectCandidate(_
)
1568 | ProjectionCandidate(_
),
1569 ) => !is_global(&cand
.value
),
1570 (ObjectCandidate(_
) | ProjectionCandidate(_
), ParamCandidate(ref cand
)) => {
1571 // Prefer these to a global where-clause bound
1572 // (see issue #50825).
1573 is_global(&cand
.value
)
1578 | GeneratorCandidate
1579 | FnPointerCandidate { .. }
1580 | BuiltinObjectCandidate
1581 | BuiltinUnsizeCandidate
1582 | TraitUpcastingUnsizeCandidate(_
)
1583 | BuiltinCandidate { has_nested: true }
1584 | TraitAliasCandidate(..),
1585 ParamCandidate(ref cand
),
1587 // Prefer these to a global where-clause bound
1588 // (see issue #50825).
1589 is_global(&cand
.value
) && other
.evaluation
.must_apply_modulo_regions()
1592 (ProjectionCandidate(i
), ProjectionCandidate(j
))
1593 | (ObjectCandidate(i
), ObjectCandidate(j
)) => {
1594 // Arbitrarily pick the lower numbered candidate for backwards
1595 // compatibility reasons. Don't let this affect inference.
1596 i
< j
&& !needs_infer
1598 (ObjectCandidate(_
), ProjectionCandidate(_
))
1599 | (ProjectionCandidate(_
), ObjectCandidate(_
)) => {
1600 bug
!("Have both object and projection candidate")
1603 // Arbitrarily give projection and object candidates priority.
1605 ObjectCandidate(_
) | ProjectionCandidate(_
),
1608 | GeneratorCandidate
1609 | FnPointerCandidate { .. }
1610 | BuiltinObjectCandidate
1611 | BuiltinUnsizeCandidate
1612 | TraitUpcastingUnsizeCandidate(_
)
1613 | BuiltinCandidate { .. }
1614 | TraitAliasCandidate(..),
1620 | GeneratorCandidate
1621 | FnPointerCandidate { .. }
1622 | BuiltinObjectCandidate
1623 | BuiltinUnsizeCandidate
1624 | TraitUpcastingUnsizeCandidate(_
)
1625 | BuiltinCandidate { .. }
1626 | TraitAliasCandidate(..),
1627 ObjectCandidate(_
) | ProjectionCandidate(_
),
1630 (&ImplCandidate(other_def
), &ImplCandidate(victim_def
)) => {
1631 // See if we can toss out `victim` based on specialization.
1632 // This requires us to know *for sure* that the `other` impl applies
1633 // i.e., `EvaluatedToOk`.
1635 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1636 // to me but is required for `std` to compile, so I didn't change it
1638 let tcx
= self.tcx();
1639 if other
.evaluation
.must_apply_modulo_regions() {
1640 if tcx
.specializes((other_def
, victim_def
)) {
1645 if other
.evaluation
.must_apply_considering_regions() {
1646 match tcx
.impls_are_allowed_to_overlap(other_def
, victim_def
) {
1647 Some(ty
::ImplOverlapKind
::Permitted { marker: true }
) => {
1648 // Subtle: If the predicate we are evaluating has inference
1649 // variables, do *not* allow discarding candidates due to
1650 // marker trait impls.
1652 // Without this restriction, we could end up accidentally
1653 // constrainting inference variables based on an arbitrarily
1654 // chosen trait impl.
1656 // Imagine we have the following code:
1659 // #[marker] trait MyTrait {}
1660 // impl MyTrait for u8 {}
1661 // impl MyTrait for bool {}
1664 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1666 // During selection, we will end up with one candidate for each
1667 // impl of `MyTrait`. If we were to discard one impl in favor
1668 // of the other, we would be left with one candidate, causing
1669 // us to "successfully" select the predicate, unifying
1670 // _#0t with (for example) `u8`.
1672 // However, we have no reason to believe that this unification
1673 // is correct - we've essentially just picked an arbitrary
1674 // *possibility* for _#0t, and required that this be the *only*
1677 // Eventually, we will either:
1678 // 1) Unify all inference variables in the predicate through
1679 // some other means (e.g. type-checking of a function). We will
1680 // then be in a position to drop marker trait candidates
1681 // without constraining inference variables (since there are
1682 // none left to constrin)
1683 // 2) Be left with some unconstrained inference variables. We
1684 // will then correctly report an inference error, since the
1685 // existence of multiple marker trait impls tells us nothing
1686 // about which one should actually apply.
1697 // Everything else is ambiguous
1701 | GeneratorCandidate
1702 | FnPointerCandidate { .. }
1703 | BuiltinObjectCandidate
1704 | BuiltinUnsizeCandidate
1705 | TraitUpcastingUnsizeCandidate(_
)
1706 | BuiltinCandidate { has_nested: true }
1707 | TraitAliasCandidate(..),
1710 | GeneratorCandidate
1711 | FnPointerCandidate { .. }
1712 | BuiltinObjectCandidate
1713 | BuiltinUnsizeCandidate
1714 | TraitUpcastingUnsizeCandidate(_
)
1715 | BuiltinCandidate { has_nested: true }
1716 | TraitAliasCandidate(..),
1721 fn sized_conditions(
1723 obligation
: &TraitObligation
<'tcx
>,
1724 ) -> BuiltinImplConditions
<'tcx
> {
1725 use self::BuiltinImplConditions
::{Ambiguous, None, Where}
;
1727 // NOTE: binder moved to (*)
1728 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.skip_binder().self_ty());
1730 match self_ty
.kind() {
1731 ty
::Infer(ty
::IntVar(_
) | ty
::FloatVar(_
))
1742 | ty
::GeneratorWitness(..)
1747 // safe for everything
1748 Where(ty
::Binder
::dummy(Vec
::new()))
1751 ty
::Str
| ty
::Slice(_
) | ty
::Dynamic(..) | ty
::Foreign(..) => None
,
1753 ty
::Tuple(tys
) => Where(
1756 .rebind(tys
.last().into_iter().map(|k
| k
.expect_ty()).collect()),
1759 ty
::Adt(def
, substs
) => {
1760 let sized_crit
= def
.sized_constraint(self.tcx());
1761 // (*) binder moved here
1763 obligation
.predicate
.rebind({
1764 sized_crit
.iter().map(|ty
| ty
.subst(self.tcx(), substs
)).collect()
1769 ty
::Projection(_
) | ty
::Param(_
) | ty
::Opaque(..) => None
,
1770 ty
::Infer(ty
::TyVar(_
)) => Ambiguous
,
1774 | ty
::Infer(ty
::FreshTy(_
) | ty
::FreshIntTy(_
) | ty
::FreshFloatTy(_
)) => {
1775 bug
!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty
);
1780 fn copy_clone_conditions(
1782 obligation
: &TraitObligation
<'tcx
>,
1783 ) -> BuiltinImplConditions
<'tcx
> {
1784 // NOTE: binder moved to (*)
1785 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.skip_binder().self_ty());
1787 use self::BuiltinImplConditions
::{Ambiguous, None, Where}
;
1789 match *self_ty
.kind() {
1790 ty
::Infer(ty
::IntVar(_
))
1791 | ty
::Infer(ty
::FloatVar(_
))
1794 | ty
::Error(_
) => Where(ty
::Binder
::dummy(Vec
::new())),
1803 | ty
::Ref(_
, _
, hir
::Mutability
::Not
) => {
1804 // Implementations provided in libcore
1812 | ty
::GeneratorWitness(..)
1814 | ty
::Ref(_
, _
, hir
::Mutability
::Mut
) => None
,
1816 ty
::Array(element_ty
, _
) => {
1817 // (*) binder moved here
1818 Where(obligation
.predicate
.rebind(vec
![element_ty
]))
1822 // (*) binder moved here
1823 Where(obligation
.predicate
.rebind(tys
.iter().map(|k
| k
.expect_ty()).collect()))
1826 ty
::Closure(_
, substs
) => {
1827 // (*) binder moved here
1828 let ty
= self.infcx
.shallow_resolve(substs
.as_closure().tupled_upvars_ty());
1829 if let ty
::Infer(ty
::TyVar(_
)) = ty
.kind() {
1830 // Not yet resolved.
1833 Where(obligation
.predicate
.rebind(substs
.as_closure().upvar_tys().collect()))
1837 ty
::Adt(..) | ty
::Projection(..) | ty
::Param(..) | ty
::Opaque(..) => {
1838 // Fallback to whatever user-defined impls exist in this case.
1842 ty
::Infer(ty
::TyVar(_
)) => {
1843 // Unbound type variable. Might or might not have
1844 // applicable impls and so forth, depending on what
1845 // those type variables wind up being bound to.
1851 | ty
::Infer(ty
::FreshTy(_
) | ty
::FreshIntTy(_
) | ty
::FreshFloatTy(_
)) => {
1852 bug
!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty
);
1857 /// For default impls, we need to break apart a type into its
1858 /// "constituent types" -- meaning, the types that it contains.
1860 /// Here are some (simple) examples:
1863 /// (i32, u32) -> [i32, u32]
1864 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1865 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1866 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1868 fn constituent_types_for_ty(
1870 t
: ty
::Binder
<'tcx
, Ty
<'tcx
>>,
1871 ) -> ty
::Binder
<'tcx
, Vec
<Ty
<'tcx
>>> {
1872 match *t
.skip_binder().kind() {
1881 | ty
::Infer(ty
::IntVar(_
) | ty
::FloatVar(_
))
1883 | ty
::Char
=> ty
::Binder
::dummy(Vec
::new()),
1889 | ty
::Projection(..)
1891 | ty
::Infer(ty
::TyVar(_
) | ty
::FreshTy(_
) | ty
::FreshIntTy(_
) | ty
::FreshFloatTy(_
)) => {
1892 bug
!("asked to assemble constituent types of unexpected type: {:?}", t
);
1895 ty
::RawPtr(ty
::TypeAndMut { ty: element_ty, .. }
) | ty
::Ref(_
, element_ty
, _
) => {
1896 t
.rebind(vec
![element_ty
])
1899 ty
::Array(element_ty
, _
) | ty
::Slice(element_ty
) => t
.rebind(vec
![element_ty
]),
1901 ty
::Tuple(ref tys
) => {
1902 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1903 t
.rebind(tys
.iter().map(|k
| k
.expect_ty()).collect())
1906 ty
::Closure(_
, ref substs
) => {
1907 let ty
= self.infcx
.shallow_resolve(substs
.as_closure().tupled_upvars_ty());
1911 ty
::Generator(_
, ref substs
, _
) => {
1912 let ty
= self.infcx
.shallow_resolve(substs
.as_generator().tupled_upvars_ty());
1913 let witness
= substs
.as_generator().witness();
1914 t
.rebind(vec
![ty
].into_iter().chain(iter
::once(witness
)).collect())
1917 ty
::GeneratorWitness(types
) => {
1918 debug_assert
!(!types
.has_escaping_bound_vars());
1919 types
.map_bound(|types
| types
.to_vec())
1922 // For `PhantomData<T>`, we pass `T`.
1923 ty
::Adt(def
, substs
) if def
.is_phantom_data() => t
.rebind(substs
.types().collect()),
1925 ty
::Adt(def
, substs
) => {
1926 t
.rebind(def
.all_fields().map(|f
| f
.ty(self.tcx(), substs
)).collect())
1929 ty
::Opaque(def_id
, substs
) => {
1930 // We can resolve the `impl Trait` to its concrete type,
1931 // which enforces a DAG between the functions requiring
1932 // the auto trait bounds in question.
1933 t
.rebind(vec
![self.tcx().type_of(def_id
).subst(self.tcx(), substs
)])
1938 fn collect_predicates_for_types(
1940 param_env
: ty
::ParamEnv
<'tcx
>,
1941 cause
: ObligationCause
<'tcx
>,
1942 recursion_depth
: usize,
1943 trait_def_id
: DefId
,
1944 types
: ty
::Binder
<'tcx
, Vec
<Ty
<'tcx
>>>,
1945 ) -> Vec
<PredicateObligation
<'tcx
>> {
1946 // Because the types were potentially derived from
1947 // higher-ranked obligations they may reference late-bound
1948 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
1949 // yield a type like `for<'a> &'a i32`. In general, we
1950 // maintain the invariant that we never manipulate bound
1951 // regions, so we have to process these bound regions somehow.
1953 // The strategy is to:
1955 // 1. Instantiate those regions to placeholder regions (e.g.,
1956 // `for<'a> &'a i32` becomes `&0 i32`.
1957 // 2. Produce something like `&'0 i32 : Copy`
1958 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
1962 .skip_binder() // binder moved -\
1965 let ty
: ty
::Binder
<'tcx
, Ty
<'tcx
>> = types
.rebind(ty
); // <----/
1967 self.infcx
.commit_unconditionally(|_
| {
1968 let placeholder_ty
= self.infcx
.replace_bound_vars_with_placeholders(ty
);
1969 let Normalized { value: normalized_ty, mut obligations }
=
1970 ensure_sufficient_stack(|| {
1971 project
::normalize_with_depth(
1979 let placeholder_obligation
= predicate_for_trait_def(
1988 obligations
.push(placeholder_obligation
);
1995 ///////////////////////////////////////////////////////////////////////////
1998 // Matching is a common path used for both evaluation and
1999 // confirmation. It basically unifies types that appear in impls
2000 // and traits. This does affect the surrounding environment;
2001 // therefore, when used during evaluation, match routines must be
2002 // run inside of a `probe()` so that their side-effects are
2008 obligation
: &TraitObligation
<'tcx
>,
2009 ) -> Normalized
<'tcx
, SubstsRef
<'tcx
>> {
2010 match self.match_impl(impl_def_id
, obligation
) {
2011 Ok(substs
) => substs
,
2014 "Impl {:?} was matchable against {:?} but now is not",
2022 #[tracing::instrument(level = "debug", skip(self))]
2026 obligation
: &TraitObligation
<'tcx
>,
2027 ) -> Result
<Normalized
<'tcx
, SubstsRef
<'tcx
>>, ()> {
2028 let impl_trait_ref
= self.tcx().impl_trait_ref(impl_def_id
).unwrap();
2030 // Before we create the substitutions and everything, first
2031 // consider a "quick reject". This avoids creating more types
2032 // and so forth that we need to.
2033 if self.fast_reject_trait_refs(obligation
, &impl_trait_ref
) {
2037 let placeholder_obligation
=
2038 self.infcx().replace_bound_vars_with_placeholders(obligation
.predicate
);
2039 let placeholder_obligation_trait_ref
= placeholder_obligation
.trait_ref
;
2041 let impl_substs
= self.infcx
.fresh_substs_for_item(obligation
.cause
.span
, impl_def_id
);
2043 let impl_trait_ref
= impl_trait_ref
.subst(self.tcx(), impl_substs
);
2045 debug
!(?impl_trait_ref
);
2047 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations }
=
2048 ensure_sufficient_stack(|| {
2049 project
::normalize_with_depth(
2051 obligation
.param_env
,
2052 obligation
.cause
.clone(),
2053 obligation
.recursion_depth
+ 1,
2058 debug
!(?impl_trait_ref
, ?placeholder_obligation_trait_ref
);
2060 let cause
= ObligationCause
::new(
2061 obligation
.cause
.span
,
2062 obligation
.cause
.body_id
,
2063 ObligationCauseCode
::MatchImpl(obligation
.cause
.clone(), impl_def_id
),
2066 let InferOk { obligations, .. }
= self
2068 .at(&cause
, obligation
.param_env
)
2069 .eq(placeholder_obligation_trait_ref
, impl_trait_ref
)
2070 .map_err(|e
| debug
!("match_impl: failed eq_trait_refs due to `{}`", e
))?
;
2071 nested_obligations
.extend(obligations
);
2074 && self.tcx().impl_polarity(impl_def_id
) == ty
::ImplPolarity
::Reservation
2076 debug
!("match_impl: reservation impls only apply in intercrate mode");
2080 debug
!(?impl_substs
, ?nested_obligations
, "match_impl: success");
2081 Ok(Normalized { value: impl_substs, obligations: nested_obligations }
)
2084 fn fast_reject_trait_refs(
2086 obligation
: &TraitObligation
<'_
>,
2087 impl_trait_ref
: &ty
::TraitRef
<'_
>,
2089 // We can avoid creating type variables and doing the full
2090 // substitution if we find that any of the input types, when
2091 // simplified, do not match.
2093 iter
::zip(obligation
.predicate
.skip_binder().trait_ref
.substs
, impl_trait_ref
.substs
).any(
2094 |(obligation_arg
, impl_arg
)| {
2095 match (obligation_arg
.unpack(), impl_arg
.unpack()) {
2096 (GenericArgKind
::Type(obligation_ty
), GenericArgKind
::Type(impl_ty
)) => {
2097 let simplified_obligation_ty
=
2098 fast_reject
::simplify_type(self.tcx(), obligation_ty
, true);
2099 let simplified_impl_ty
=
2100 fast_reject
::simplify_type(self.tcx(), impl_ty
, false);
2102 simplified_obligation_ty
.is_some()
2103 && simplified_impl_ty
.is_some()
2104 && simplified_obligation_ty
!= simplified_impl_ty
2106 (GenericArgKind
::Lifetime(_
), GenericArgKind
::Lifetime(_
)) => {
2107 // Lifetimes can never cause a rejection.
2110 (GenericArgKind
::Const(_
), GenericArgKind
::Const(_
)) => {
2111 // Conservatively ignore consts (i.e. assume they might
2112 // unify later) until we have `fast_reject` support for
2113 // them (if we'll ever need it, even).
2116 _
=> unreachable
!(),
2122 /// Normalize `where_clause_trait_ref` and try to match it against
2123 /// `obligation`. If successful, return any predicates that
2124 /// result from the normalization.
2125 fn match_where_clause_trait_ref(
2127 obligation
: &TraitObligation
<'tcx
>,
2128 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
2129 ) -> Result
<Vec
<PredicateObligation
<'tcx
>>, ()> {
2130 self.match_poly_trait_ref(obligation
, where_clause_trait_ref
)
2133 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2134 /// obligation is satisfied.
2135 #[instrument(skip(self), level = "debug")]
2136 fn match_poly_trait_ref(
2138 obligation
: &TraitObligation
<'tcx
>,
2139 poly_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
2140 ) -> Result
<Vec
<PredicateObligation
<'tcx
>>, ()> {
2142 .at(&obligation
.cause
, obligation
.param_env
)
2143 .sup(obligation
.predicate
.to_poly_trait_ref(), poly_trait_ref
)
2144 .map(|InferOk { obligations, .. }
| obligations
)
2148 ///////////////////////////////////////////////////////////////////////////
2151 fn match_fresh_trait_refs(
2153 previous
: ty
::ConstnessAnd
<ty
::PolyTraitRef
<'tcx
>>,
2154 current
: ty
::ConstnessAnd
<ty
::PolyTraitRef
<'tcx
>>,
2155 param_env
: ty
::ParamEnv
<'tcx
>,
2157 let mut matcher
= ty
::_match
::Match
::new(self.tcx(), param_env
);
2158 matcher
.relate(previous
, current
).is_ok()
2163 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
2164 obligation
: &'o TraitObligation
<'tcx
>,
2165 ) -> TraitObligationStack
<'o
, 'tcx
> {
2166 let fresh_trait_ref
= obligation
2168 .to_poly_trait_ref()
2169 .fold_with(&mut self.freshener
)
2170 .with_constness(obligation
.predicate
.skip_binder().constness
);
2172 let dfn
= previous_stack
.cache
.next_dfn();
2173 let depth
= previous_stack
.depth() + 1;
2174 TraitObligationStack
{
2177 reached_depth
: Cell
::new(depth
),
2178 previous
: previous_stack
,
2184 #[instrument(skip(self), level = "debug")]
2185 fn closure_trait_ref_unnormalized(
2187 obligation
: &TraitObligation
<'tcx
>,
2188 substs
: SubstsRef
<'tcx
>,
2189 ) -> ty
::PolyTraitRef
<'tcx
> {
2190 let closure_sig
= substs
.as_closure().sig();
2192 debug
!(?closure_sig
);
2194 // (1) Feels icky to skip the binder here, but OTOH we know
2195 // that the self-type is an unboxed closure type and hence is
2196 // in fact unparameterized (or at least does not reference any
2197 // regions bound in the obligation). Still probably some
2198 // refactoring could make this nicer.
2199 closure_trait_ref_and_return_type(
2201 obligation
.predicate
.def_id(),
2202 obligation
.predicate
.skip_binder().self_ty(), // (1)
2204 util
::TupleArgumentsFlag
::No
,
2206 .map_bound(|(trait_ref
, _
)| trait_ref
)
2209 fn generator_trait_ref_unnormalized(
2211 obligation
: &TraitObligation
<'tcx
>,
2212 substs
: SubstsRef
<'tcx
>,
2213 ) -> ty
::PolyTraitRef
<'tcx
> {
2214 let gen_sig
= substs
.as_generator().poly_sig();
2216 // (1) Feels icky to skip the binder here, but OTOH we know
2217 // that the self-type is an generator type and hence is
2218 // in fact unparameterized (or at least does not reference any
2219 // regions bound in the obligation). Still probably some
2220 // refactoring could make this nicer.
2222 super::util
::generator_trait_ref_and_outputs(
2224 obligation
.predicate
.def_id(),
2225 obligation
.predicate
.skip_binder().self_ty(), // (1)
2228 .map_bound(|(trait_ref
, ..)| trait_ref
)
2231 /// Returns the obligations that are implied by instantiating an
2232 /// impl or trait. The obligations are substituted and fully
2233 /// normalized. This is used when confirming an impl or default
2235 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
2236 fn impl_or_trait_obligations(
2238 cause
: ObligationCause
<'tcx
>,
2239 recursion_depth
: usize,
2240 param_env
: ty
::ParamEnv
<'tcx
>,
2241 def_id
: DefId
, // of impl or trait
2242 substs
: SubstsRef
<'tcx
>, // for impl or trait
2243 ) -> Vec
<PredicateObligation
<'tcx
>> {
2244 let tcx
= self.tcx();
2246 // To allow for one-pass evaluation of the nested obligation,
2247 // each predicate must be preceded by the obligations required
2249 // for example, if we have:
2250 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2251 // the impl will have the following predicates:
2252 // <V as Iterator>::Item = U,
2253 // U: Iterator, U: Sized,
2254 // V: Iterator, V: Sized,
2255 // <U as Iterator>::Item: Copy
2256 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2257 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2258 // `$1: Copy`, so we must ensure the obligations are emitted in
2260 let predicates
= tcx
.predicates_of(def_id
);
2261 debug
!(?predicates
);
2262 assert_eq
!(predicates
.parent
, None
);
2263 let mut obligations
= Vec
::with_capacity(predicates
.predicates
.len());
2264 for (predicate
, _
) in predicates
.predicates
{
2266 let predicate
= normalize_with_depth_to(
2271 predicate
.subst(tcx
, substs
),
2274 obligations
.push(Obligation
{
2275 cause
: cause
.clone(),
2282 // We are performing deduplication here to avoid exponential blowups
2283 // (#38528) from happening, but the real cause of the duplication is
2284 // unknown. What we know is that the deduplication avoids exponential
2285 // amount of predicates being propagated when processing deeply nested
2288 // This code is hot enough that it's worth avoiding the allocation
2289 // required for the FxHashSet when possible. Special-casing lengths 0,
2290 // 1 and 2 covers roughly 75-80% of the cases.
2291 if obligations
.len() <= 1 {
2292 // No possibility of duplicates.
2293 } else if obligations
.len() == 2 {
2294 // Only two elements. Drop the second if they are equal.
2295 if obligations
[0] == obligations
[1] {
2296 obligations
.truncate(1);
2299 // Three or more elements. Use a general deduplication process.
2300 let mut seen
= FxHashSet
::default();
2301 obligations
.retain(|i
| seen
.insert(i
.clone()));
2308 trait TraitObligationExt
<'tcx
> {
2311 variant
: fn(DerivedObligationCause
<'tcx
>) -> ObligationCauseCode
<'tcx
>,
2312 ) -> ObligationCause
<'tcx
>;
2315 impl<'tcx
> TraitObligationExt
<'tcx
> for TraitObligation
<'tcx
> {
2318 variant
: fn(DerivedObligationCause
<'tcx
>) -> ObligationCauseCode
<'tcx
>,
2319 ) -> ObligationCause
<'tcx
> {
2321 * Creates a cause for obligations that are derived from
2322 * `obligation` by a recursive search (e.g., for a builtin
2323 * bound, or eventually a `auto trait Foo`). If `obligation`
2324 * is itself a derived obligation, this is just a clone, but
2325 * otherwise we create a "derived obligation" cause so as to
2326 * keep track of the original root obligation for error
2330 let obligation
= self;
2332 // NOTE(flaper87): As of now, it keeps track of the whole error
2333 // chain. Ideally, we should have a way to configure this either
2334 // by using -Z verbose or just a CLI argument.
2335 let derived_cause
= DerivedObligationCause
{
2336 parent_trait_ref
: obligation
.predicate
.to_poly_trait_ref(),
2337 parent_code
: Lrc
::new(obligation
.cause
.code
.clone()),
2339 let derived_code
= variant(derived_cause
);
2340 ObligationCause
::new(obligation
.cause
.span
, obligation
.cause
.body_id
, derived_code
)
2344 impl<'o
, 'tcx
> TraitObligationStack
<'o
, 'tcx
> {
2345 fn list(&'o
self) -> TraitObligationStackList
<'o
, 'tcx
> {
2346 TraitObligationStackList
::with(self)
2349 fn cache(&self) -> &'o ProvisionalEvaluationCache
<'tcx
> {
2353 fn iter(&'o
self) -> TraitObligationStackList
<'o
, 'tcx
> {
2357 /// Indicates that attempting to evaluate this stack entry
2358 /// required accessing something from the stack at depth `reached_depth`.
2359 fn update_reached_depth(&self, reached_depth
: usize) {
2361 self.depth
>= reached_depth
,
2362 "invoked `update_reached_depth` with something under this stack: \
2363 self.depth={} reached_depth={}",
2367 debug
!(reached_depth
, "update_reached_depth");
2369 while reached_depth
< p
.depth
{
2370 debug
!(?p
.fresh_trait_ref
, "update_reached_depth: marking as cycle participant");
2371 p
.reached_depth
.set(p
.reached_depth
.get().min(reached_depth
));
2372 p
= p
.previous
.head
.unwrap();
2377 /// The "provisional evaluation cache" is used to store intermediate cache results
2378 /// when solving auto traits. Auto traits are unusual in that they can support
2379 /// cycles. So, for example, a "proof tree" like this would be ok:
2381 /// - `Foo<T>: Send` :-
2382 /// - `Bar<T>: Send` :-
2383 /// - `Foo<T>: Send` -- cycle, but ok
2384 /// - `Baz<T>: Send`
2386 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2387 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2388 /// For non-auto traits, this cycle would be an error, but for auto traits (because
2389 /// they are coinductive) it is considered ok.
2391 /// However, there is a complication: at the point where we have
2392 /// "proven" `Bar<T>: Send`, we have in fact only proven it
2393 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
2394 /// *under the assumption* that `Foo<T>: Send`. But what if we later
2395 /// find out this assumption is wrong? Specifically, we could
2396 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
2397 /// `Bar<T>: Send` didn't turn out to be true.
2399 /// In Issue #60010, we found a bug in rustc where it would cache
2400 /// these intermediate results. This was fixed in #60444 by disabling
2401 /// *all* caching for things involved in a cycle -- in our example,
2402 /// that would mean we don't cache that `Bar<T>: Send`. But this led
2403 /// to large slowdowns.
2405 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2406 /// first requires proving `Bar<T>: Send` (which is true:
2408 /// - `Foo<T>: Send` :-
2409 /// - `Bar<T>: Send` :-
2410 /// - `Foo<T>: Send` -- cycle, but ok
2411 /// - `Baz<T>: Send`
2412 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2413 /// - `*const T: Send` -- but what if we later encounter an error?
2415 /// The *provisional evaluation cache* resolves this issue. It stores
2416 /// cache results that we've proven but which were involved in a cycle
2417 /// in some way. We track the minimal stack depth (i.e., the
2418 /// farthest from the top of the stack) that we are dependent on.
2419 /// The idea is that the cache results within are all valid -- so long as
2420 /// none of the nodes in between the current node and the node at that minimum
2421 /// depth result in an error (in which case the cached results are just thrown away).
2423 /// During evaluation, we consult this provisional cache and rely on
2424 /// it. Accessing a cached value is considered equivalent to accessing
2425 /// a result at `reached_depth`, so it marks the *current* solution as
2426 /// provisional as well. If an error is encountered, we toss out any
2427 /// provisional results added from the subtree that encountered the
2428 /// error. When we pop the node at `reached_depth` from the stack, we
2429 /// can commit all the things that remain in the provisional cache.
2430 struct ProvisionalEvaluationCache
<'tcx
> {
2431 /// next "depth first number" to issue -- just a counter
2434 /// Map from cache key to the provisionally evaluated thing.
2435 /// The cache entries contain the result but also the DFN in which they
2436 /// were added. The DFN is used to clear out values on failure.
2438 /// Imagine we have a stack like:
2440 /// - `A B C` and we add a cache for the result of C (DFN 2)
2441 /// - Then we have a stack `A B D` where `D` has DFN 3
2442 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2443 /// - `E` generates various cache entries which have cyclic dependices on `B`
2444 /// - `A B D E F` and so forth
2445 /// - the DFN of `F` for example would be 5
2446 /// - then we determine that `E` is in error -- we will then clear
2447 /// all cache values whose DFN is >= 4 -- in this case, that
2448 /// means the cached value for `F`.
2449 map
: RefCell
<FxHashMap
<ty
::ConstnessAnd
<ty
::PolyTraitRef
<'tcx
>>, ProvisionalEvaluation
>>,
2452 /// A cache value for the provisional cache: contains the depth-first
2453 /// number (DFN) and result.
2454 #[derive(Copy, Clone, Debug)]
2455 struct ProvisionalEvaluation
{
2457 reached_depth
: usize,
2458 result
: EvaluationResult
,
2461 impl<'tcx
> Default
for ProvisionalEvaluationCache
<'tcx
> {
2462 fn default() -> Self {
2463 Self { dfn: Cell::new(0), map: Default::default() }
2467 impl<'tcx
> ProvisionalEvaluationCache
<'tcx
> {
2468 /// Get the next DFN in sequence (basically a counter).
2469 fn next_dfn(&self) -> usize {
2470 let result
= self.dfn
.get();
2471 self.dfn
.set(result
+ 1);
2475 /// Check the provisional cache for any result for
2476 /// `fresh_trait_ref`. If there is a hit, then you must consider
2477 /// it an access to the stack slots at depth
2478 /// `reached_depth` (from the returned value).
2481 fresh_trait_ref
: ty
::ConstnessAnd
<ty
::PolyTraitRef
<'tcx
>>,
2482 ) -> Option
<ProvisionalEvaluation
> {
2485 "get_provisional = {:#?}",
2486 self.map
.borrow().get(&fresh_trait_ref
),
2488 Some(*self.map
.borrow().get(&fresh_trait_ref
)?
)
2491 /// Insert a provisional result into the cache. The result came
2492 /// from the node with the given DFN. It accessed a minimum depth
2493 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
2494 /// and resulted in `result`.
2495 fn insert_provisional(
2498 reached_depth
: usize,
2499 fresh_trait_ref
: ty
::ConstnessAnd
<ty
::PolyTraitRef
<'tcx
>>,
2500 result
: EvaluationResult
,
2502 debug
!(?from_dfn
, ?fresh_trait_ref
, ?result
, "insert_provisional");
2504 let mut map
= self.map
.borrow_mut();
2506 // Subtle: when we complete working on the DFN `from_dfn`, anything
2507 // that remains in the provisional cache must be dependent on some older
2508 // stack entry than `from_dfn`. We have to update their depth with our transitive
2509 // depth in that case or else it would be referring to some popped note.
2512 // A (reached depth 0)
2514 // B // depth 1 -- reached depth = 0
2515 // C // depth 2 -- reached depth = 1 (should be 0)
2518 // D (reached depth 1)
2519 // C (cache -- reached depth = 2)
2520 for (_k
, v
) in &mut *map
{
2521 if v
.from_dfn
>= from_dfn
{
2522 v
.reached_depth
= reached_depth
.min(v
.reached_depth
);
2526 map
.insert(fresh_trait_ref
, ProvisionalEvaluation { from_dfn, reached_depth, result }
);
2529 /// Invoked when the node with dfn `dfn` does not get a successful
2530 /// result. This will clear out any provisional cache entries
2531 /// that were added since `dfn` was created. This is because the
2532 /// provisional entries are things which must assume that the
2533 /// things on the stack at the time of their creation succeeded --
2534 /// since the failing node is presently at the top of the stack,
2535 /// these provisional entries must either depend on it or some
2537 fn on_failure(&self, dfn
: usize) {
2538 debug
!(?dfn
, "on_failure");
2539 self.map
.borrow_mut().retain(|key
, eval
| {
2540 if !eval
.from_dfn
>= dfn
{
2541 debug
!("on_failure: removing {:?}", key
);
2549 /// Invoked when the node at depth `depth` completed without
2550 /// depending on anything higher in the stack (if that completion
2551 /// was a failure, then `on_failure` should have been invoked
2552 /// already). The callback `op` will be invoked for each
2553 /// provisional entry that we can now confirm.
2555 /// Note that we may still have provisional cache items remaining
2556 /// in the cache when this is done. For example, if there is a
2559 /// * A depends on...
2560 /// * B depends on A
2561 /// * C depends on...
2562 /// * D depends on C
2565 /// Then as we complete the C node we will have a provisional cache
2566 /// with results for A, B, C, and D. This method would clear out
2567 /// the C and D results, but leave A and B provisional.
2569 /// This is determined based on the DFN: we remove any provisional
2570 /// results created since `dfn` started (e.g., in our example, dfn
2571 /// would be 2, representing the C node, and hence we would
2572 /// remove the result for D, which has DFN 3, but not the results for
2573 /// A and B, which have DFNs 0 and 1 respectively).
2577 mut op
: impl FnMut(ty
::ConstnessAnd
<ty
::PolyTraitRef
<'tcx
>>, EvaluationResult
),
2579 debug
!(?dfn
, "on_completion");
2581 for (fresh_trait_ref
, eval
) in
2582 self.map
.borrow_mut().drain_filter(|_k
, eval
| eval
.from_dfn
>= dfn
)
2584 debug
!(?fresh_trait_ref
, ?eval
, "on_completion");
2586 op(fresh_trait_ref
, eval
.result
);
2591 #[derive(Copy, Clone)]
2592 struct TraitObligationStackList
<'o
, 'tcx
> {
2593 cache
: &'o ProvisionalEvaluationCache
<'tcx
>,
2594 head
: Option
<&'o TraitObligationStack
<'o
, 'tcx
>>,
2597 impl<'o
, 'tcx
> TraitObligationStackList
<'o
, 'tcx
> {
2598 fn empty(cache
: &'o ProvisionalEvaluationCache
<'tcx
>) -> TraitObligationStackList
<'o
, 'tcx
> {
2599 TraitObligationStackList { cache, head: None }
2602 fn with(r
: &'o TraitObligationStack
<'o
, 'tcx
>) -> TraitObligationStackList
<'o
, 'tcx
> {
2603 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2606 fn head(&self) -> Option
<&'o TraitObligationStack
<'o
, 'tcx
>> {
2610 fn depth(&self) -> usize {
2611 if let Some(head
) = self.head { head.depth }
else { 0 }
2615 impl<'o
, 'tcx
> Iterator
for TraitObligationStackList
<'o
, 'tcx
> {
2616 type Item
= &'o TraitObligationStack
<'o
, 'tcx
>;
2618 fn next(&mut self) -> Option
<&'o TraitObligationStack
<'o
, 'tcx
>> {
2625 impl<'o
, 'tcx
> fmt
::Debug
for TraitObligationStack
<'o
, 'tcx
> {
2626 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2627 write
!(f
, "TraitObligationStack({:?})", self.obligation
)