1 // ignore-tidy-filelength
3 //! Candidate selection. See the [rustc guide] for more information on how this works.
5 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html#selection
7 use self::EvaluationResult::*;
8 use self::SelectionCandidate::*;
10 use super::coherence::{self, Conflict};
12 use super::project::{normalize_with_depth, Normalized, ProjectionCacheKey};
14 use super::util::{closure_trait_ref_and_return_type, predicate_for_trait_def};
15 use super::DerivedObligationCause;
17 use super::SelectionResult;
18 use super::TraitNotObjectSafe;
19 use super::{BuiltinDerivedObligation, ImplDerivedObligation, ObligationCauseCode};
20 use super::{IntercrateMode, TraitQueryMode};
21 use super::{ObjectCastObligation, Obligation};
22 use super::{ObligationCause, PredicateObligation, TraitObligation};
23 use super::{OutputTypeParameterMismatch, Overflow, SelectionError, Unimplemented};
25 VtableAutoImpl, VtableBuiltin, VtableClosure, VtableFnPointer, VtableGenerator, VtableImpl,
26 VtableObject, VtableParam, VtableTraitAlias,
29 VtableAutoImplData, VtableBuiltinData, VtableClosureData, VtableFnPointerData,
30 VtableGeneratorData, VtableImplData, VtableObjectData, VtableTraitAliasData,
33 use crate::dep_graph::{DepKind, DepNodeIndex};
34 use crate::infer::{CombinedSnapshot, InferCtxt, InferOk, PlaceholderMap, TypeFreshener};
35 use crate::middle::lang_items;
36 use crate::ty::fast_reject;
37 use crate::ty::relate::TypeRelation;
38 use crate::ty::subst::{Subst, SubstsRef};
39 use crate::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
40 use rustc_hir::def_id::DefId;
42 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
43 use rustc_data_structures::sync::Lock;
45 use rustc_index::bit_set::GrowableBitSet;
46 use rustc_span::symbol::sym;
47 use rustc_target::spec::abi::Abi;
48 use std::cell::{Cell, RefCell};
50 use std::fmt::{self, Display};
55 pub struct SelectionContext<'cx, 'tcx> {
56 infcx: &'cx InferCtxt<'cx, 'tcx>,
58 /// Freshener used specifically for entries on the obligation
59 /// stack. This ensures that all entries on the stack at one time
60 /// will have the same set of placeholder entries, which is
61 /// important for checking for trait bounds that recursively
62 /// require themselves.
63 freshener: TypeFreshener<'cx, 'tcx>,
65 /// If `true`, indicates that the evaluation should be conservative
66 /// and consider the possibility of types outside this crate.
67 /// This comes up primarily when resolving ambiguity. Imagine
68 /// there is some trait reference `$0: Bar` where `$0` is an
69 /// inference variable. If `intercrate` is true, then we can never
70 /// say for sure that this reference is not implemented, even if
71 /// there are *no impls at all for `Bar`*, because `$0` could be
72 /// bound to some type that in a downstream crate that implements
73 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
74 /// though, we set this to false, because we are only interested
75 /// in types that the user could actually have written --- in
76 /// other words, we consider `$0: Bar` to be unimplemented if
77 /// there is no type that the user could *actually name* that
78 /// would satisfy it. This avoids crippling inference, basically.
79 intercrate: Option<IntercrateMode>,
81 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
83 /// Controls whether or not to filter out negative impls when selecting.
84 /// This is used in librustdoc to distinguish between the lack of an impl
85 /// and a negative impl
86 allow_negative_impls: bool,
88 /// The mode that trait queries run in, which informs our error handling
89 /// policy. In essence, canonicalized queries need their errors propagated
90 /// rather than immediately reported because we do not have accurate spans.
91 query_mode: TraitQueryMode,
94 #[derive(Clone, Debug)]
95 pub enum IntercrateAmbiguityCause {
96 DownstreamCrate { trait_desc: String, self_desc: Option<String> },
97 UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
98 ReservationImpl { message: String },
101 impl IntercrateAmbiguityCause {
102 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
103 /// See #23980 for details.
104 pub fn add_intercrate_ambiguity_hint(&self, err: &mut errors::DiagnosticBuilder<'_>) {
105 err.note(&self.intercrate_ambiguity_hint());
108 pub fn intercrate_ambiguity_hint(&self) -> String {
110 &IntercrateAmbiguityCause::DownstreamCrate { ref trait_desc, ref self_desc } => {
111 let self_desc = if let &Some(ref ty) = self_desc {
112 format!(" for type `{}`", ty)
116 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
118 &IntercrateAmbiguityCause::UpstreamCrateUpdate { ref trait_desc, ref self_desc } => {
119 let self_desc = if let &Some(ref ty) = self_desc {
120 format!(" for type `{}`", ty)
125 "upstream crates may add a new impl of trait `{}`{} \
127 trait_desc, self_desc
130 &IntercrateAmbiguityCause::ReservationImpl { ref message } => message.clone(),
135 // A stack that walks back up the stack frame.
136 struct TraitObligationStack<'prev, 'tcx> {
137 obligation: &'prev TraitObligation<'tcx>,
139 /// The trait ref from `obligation` but "freshened" with the
140 /// selection-context's freshener. Used to check for recursion.
141 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
143 /// Starts out equal to `depth` -- if, during evaluation, we
144 /// encounter a cycle, then we will set this flag to the minimum
145 /// depth of that cycle for all participants in the cycle. These
146 /// participants will then forego caching their results. This is
147 /// not the most efficient solution, but it addresses #60010. The
148 /// problem we are trying to prevent:
150 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
151 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
152 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
154 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
155 /// is `EvaluatedToOk`; this is because they were only considered
156 /// ok on the premise that if `A: AutoTrait` held, but we indeed
157 /// encountered a problem (later on) with `A: AutoTrait. So we
158 /// currently set a flag on the stack node for `B: AutoTrait` (as
159 /// well as the second instance of `A: AutoTrait`) to suppress
162 /// This is a simple, targeted fix. A more-performant fix requires
163 /// deeper changes, but would permit more caching: we could
164 /// basically defer caching until we have fully evaluated the
165 /// tree, and then cache the entire tree at once. In any case, the
166 /// performance impact here shouldn't be so horrible: every time
167 /// this is hit, we do cache at least one trait, so we only
168 /// evaluate each member of a cycle up to N times, where N is the
169 /// length of the cycle. This means the performance impact is
170 /// bounded and we shouldn't have any terrible worst-cases.
171 reached_depth: Cell<usize>,
173 previous: TraitObligationStackList<'prev, 'tcx>,
175 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
178 /// The depth-first number of this node in the search graph -- a
179 /// pre-order index. Basically, a freshly incremented counter.
183 #[derive(Clone, Default)]
184 pub struct SelectionCache<'tcx> {
187 ty::ParamEnvAnd<'tcx, ty::TraitRef<'tcx>>,
188 WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>,
193 /// The selection process begins by considering all impls, where
194 /// clauses, and so forth that might resolve an obligation. Sometimes
195 /// we'll be able to say definitively that (e.g.) an impl does not
196 /// apply to the obligation: perhaps it is defined for `usize` but the
197 /// obligation is for `int`. In that case, we drop the impl out of the
198 /// list. But the other cases are considered *candidates*.
200 /// For selection to succeed, there must be exactly one matching
201 /// candidate. If the obligation is fully known, this is guaranteed
202 /// by coherence. However, if the obligation contains type parameters
203 /// or variables, there may be multiple such impls.
205 /// It is not a real problem if multiple matching impls exist because
206 /// of type variables - it just means the obligation isn't sufficiently
207 /// elaborated. In that case we report an ambiguity, and the caller can
208 /// try again after more type information has been gathered or report a
209 /// "type annotations needed" error.
211 /// However, with type parameters, this can be a real problem - type
212 /// parameters don't unify with regular types, but they *can* unify
213 /// with variables from blanket impls, and (unless we know its bounds
214 /// will always be satisfied) picking the blanket impl will be wrong
215 /// for at least *some* substitutions. To make this concrete, if we have
217 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
218 /// impl<T: fmt::Debug> AsDebug for T {
220 /// fn debug(self) -> fmt::Debug { self }
222 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
224 /// we can't just use the impl to resolve the `<T as AsDebug>` obligation
225 /// -- a type from another crate (that doesn't implement `fmt::Debug`) could
226 /// implement `AsDebug`.
228 /// Because where-clauses match the type exactly, multiple clauses can
229 /// only match if there are unresolved variables, and we can mostly just
230 /// report this ambiguity in that case. This is still a problem - we can't
231 /// *do anything* with ambiguities that involve only regions. This is issue
234 /// If a single where-clause matches and there are no inference
235 /// variables left, then it definitely matches and we can just select
238 /// In fact, we even select the where-clause when the obligation contains
239 /// inference variables. The can lead to inference making "leaps of logic",
240 /// for example in this situation:
242 /// pub trait Foo<T> { fn foo(&self) -> T; }
243 /// impl<T> Foo<()> for T { fn foo(&self) { } }
244 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
246 /// pub fn foo<T>(t: T) where T: Foo<bool> {
247 /// println!("{:?}", <T as Foo<_>>::foo(&t));
249 /// fn main() { foo(false); }
251 /// Here the obligation `<T as Foo<$0>>` can be matched by both the blanket
252 /// impl and the where-clause. We select the where-clause and unify `$0=bool`,
253 /// so the program prints "false". However, if the where-clause is omitted,
254 /// the blanket impl is selected, we unify `$0=()`, and the program prints
257 /// Exactly the same issues apply to projection and object candidates, except
258 /// that we can have both a projection candidate and a where-clause candidate
259 /// for the same obligation. In that case either would do (except that
260 /// different "leaps of logic" would occur if inference variables are
261 /// present), and we just pick the where-clause. This is, for example,
262 /// required for associated types to work in default impls, as the bounds
263 /// are visible both as projection bounds and as where-clauses from the
264 /// parameter environment.
265 #[derive(PartialEq, Eq, Debug, Clone, TypeFoldable)]
266 enum SelectionCandidate<'tcx> {
268 /// `false` if there are no *further* obligations.
271 ParamCandidate(ty::PolyTraitRef<'tcx>),
272 ImplCandidate(DefId),
273 AutoImplCandidate(DefId),
275 /// This is a trait matching with a projected type as `Self`, and
276 /// we found an applicable bound in the trait definition.
279 /// Implementation of a `Fn`-family trait by one of the anonymous types
280 /// generated for a `||` expression.
283 /// Implementation of a `Generator` trait by one of the anonymous types
284 /// generated for a generator.
287 /// Implementation of a `Fn`-family trait by one of the anonymous
288 /// types generated for a fn pointer type (e.g., `fn(int) -> int`)
291 TraitAliasCandidate(DefId),
295 BuiltinObjectCandidate,
297 BuiltinUnsizeCandidate,
300 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
301 type Lifted = SelectionCandidate<'tcx>;
302 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
304 BuiltinCandidate { has_nested } => BuiltinCandidate { has_nested },
305 ImplCandidate(def_id) => ImplCandidate(def_id),
306 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
307 ProjectionCandidate => ProjectionCandidate,
308 ClosureCandidate => ClosureCandidate,
309 GeneratorCandidate => GeneratorCandidate,
310 FnPointerCandidate => FnPointerCandidate,
311 TraitAliasCandidate(def_id) => TraitAliasCandidate(def_id),
312 ObjectCandidate => ObjectCandidate,
313 BuiltinObjectCandidate => BuiltinObjectCandidate,
314 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
316 ParamCandidate(ref trait_ref) => {
317 return tcx.lift(trait_ref).map(ParamCandidate);
323 struct SelectionCandidateSet<'tcx> {
324 // A list of candidates that definitely apply to the current
325 // obligation (meaning: types unify).
326 vec: Vec<SelectionCandidate<'tcx>>,
328 // If `true`, then there were candidates that might or might
329 // not have applied, but we couldn't tell. This occurs when some
330 // of the input types are type variables, in which case there are
331 // various "builtin" rules that might or might not trigger.
335 #[derive(PartialEq, Eq, Debug, Clone)]
336 struct EvaluatedCandidate<'tcx> {
337 candidate: SelectionCandidate<'tcx>,
338 evaluation: EvaluationResult,
341 /// When does the builtin impl for `T: Trait` apply?
342 enum BuiltinImplConditions<'tcx> {
343 /// The impl is conditional on `T1, T2, ...: Trait`.
344 Where(ty::Binder<Vec<Ty<'tcx>>>),
345 /// There is no built-in impl. There may be some other
346 /// candidate (a where-clause or user-defined impl).
348 /// It is unknown whether there is an impl.
352 /// The result of trait evaluation. The order is important
353 /// here as the evaluation of a list is the maximum of the
356 /// The evaluation results are ordered:
357 /// - `EvaluatedToOk` implies `EvaluatedToOkModuloRegions`
358 /// implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
359 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
360 /// - the "union" of evaluation results is equal to their maximum -
361 /// all the "potential success" candidates can potentially succeed,
362 /// so they are noops when unioned with a definite error, and within
363 /// the categories it's easy to see that the unions are correct.
364 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, HashStable)]
365 pub enum EvaluationResult {
366 /// Evaluation successful.
368 /// Evaluation successful, but there were unevaluated region obligations.
369 EvaluatedToOkModuloRegions,
370 /// Evaluation is known to be ambiguous -- it *might* hold for some
371 /// assignment of inference variables, but it might not.
373 /// While this has the same meaning as `EvaluatedToUnknown` -- we can't
374 /// know whether this obligation holds or not -- it is the result we
375 /// would get with an empty stack, and therefore is cacheable.
377 /// Evaluation failed because of recursion involving inference
378 /// variables. We are somewhat imprecise there, so we don't actually
379 /// know the real result.
381 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
383 /// Evaluation failed because we encountered an obligation we are already
384 /// trying to prove on this branch.
386 /// We know this branch can't be a part of a minimal proof-tree for
387 /// the "root" of our cycle, because then we could cut out the recursion
388 /// and maintain a valid proof tree. However, this does not mean
389 /// that all the obligations on this branch do not hold -- it's possible
390 /// that we entered this branch "speculatively", and that there
391 /// might be some other way to prove this obligation that does not
392 /// go through this cycle -- so we can't cache this as a failure.
394 /// For example, suppose we have this:
396 /// ```rust,ignore (pseudo-Rust)
397 /// pub trait Trait { fn xyz(); }
398 /// // This impl is "useless", but we can still have
399 /// // an `impl Trait for SomeUnsizedType` somewhere.
400 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
402 /// pub fn foo<T: Trait + ?Sized>() {
403 /// <T as Trait>::xyz();
407 /// When checking `foo`, we have to prove `T: Trait`. This basically
408 /// translates into this:
411 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
414 /// When we try to prove it, we first go the first option, which
415 /// recurses. This shows us that the impl is "useless" -- it won't
416 /// tell us that `T: Trait` unless it already implemented `Trait`
417 /// by some other means. However, that does not prevent `T: Trait`
418 /// does not hold, because of the bound (which can indeed be satisfied
419 /// by `SomeUnsizedType` from another crate).
421 // FIXME: when an `EvaluatedToRecur` goes past its parent root, we
422 // ought to convert it to an `EvaluatedToErr`, because we know
423 // there definitely isn't a proof tree for that obligation. Not
424 // doing so is still sound -- there isn't any proof tree, so the
425 // branch still can't be a part of a minimal one -- but does not re-enable caching.
427 /// Evaluation failed.
431 impl EvaluationResult {
432 /// Returns `true` if this evaluation result is known to apply, even
433 /// considering outlives constraints.
434 pub fn must_apply_considering_regions(self) -> bool {
435 self == EvaluatedToOk
438 /// Returns `true` if this evaluation result is known to apply, ignoring
439 /// outlives constraints.
440 pub fn must_apply_modulo_regions(self) -> bool {
441 self <= EvaluatedToOkModuloRegions
444 pub fn may_apply(self) -> bool {
446 EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToUnknown => {
450 EvaluatedToErr | EvaluatedToRecur => false,
454 fn is_stack_dependent(self) -> bool {
456 EvaluatedToUnknown | EvaluatedToRecur => true,
458 EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToErr => false,
463 /// Indicates that trait evaluation caused overflow.
464 #[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable)]
465 pub struct OverflowError;
467 impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
468 fn from(OverflowError: OverflowError) -> SelectionError<'tcx> {
469 SelectionError::Overflow
473 #[derive(Clone, Default)]
474 pub struct EvaluationCache<'tcx> {
476 FxHashMap<ty::ParamEnvAnd<'tcx, ty::PolyTraitRef<'tcx>>, WithDepNode<EvaluationResult>>,
480 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
481 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
484 freshener: infcx.freshener(),
486 intercrate_ambiguity_causes: None,
487 allow_negative_impls: false,
488 query_mode: TraitQueryMode::Standard,
493 infcx: &'cx InferCtxt<'cx, 'tcx>,
494 mode: IntercrateMode,
495 ) -> SelectionContext<'cx, 'tcx> {
496 debug!("intercrate({:?})", mode);
499 freshener: infcx.freshener(),
500 intercrate: Some(mode),
501 intercrate_ambiguity_causes: None,
502 allow_negative_impls: false,
503 query_mode: TraitQueryMode::Standard,
507 pub fn with_negative(
508 infcx: &'cx InferCtxt<'cx, 'tcx>,
509 allow_negative_impls: bool,
510 ) -> SelectionContext<'cx, 'tcx> {
511 debug!("with_negative({:?})", allow_negative_impls);
514 freshener: infcx.freshener(),
516 intercrate_ambiguity_causes: None,
517 allow_negative_impls,
518 query_mode: TraitQueryMode::Standard,
522 pub fn with_query_mode(
523 infcx: &'cx InferCtxt<'cx, 'tcx>,
524 query_mode: TraitQueryMode,
525 ) -> SelectionContext<'cx, 'tcx> {
526 debug!("with_query_mode({:?})", query_mode);
529 freshener: infcx.freshener(),
531 intercrate_ambiguity_causes: None,
532 allow_negative_impls: false,
537 /// Enables tracking of intercrate ambiguity causes. These are
538 /// used in coherence to give improved diagnostics. We don't do
539 /// this until we detect a coherence error because it can lead to
540 /// false overflow results (#47139) and because it costs
541 /// computation time.
542 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
543 assert!(self.intercrate.is_some());
544 assert!(self.intercrate_ambiguity_causes.is_none());
545 self.intercrate_ambiguity_causes = Some(vec![]);
546 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
549 /// Gets the intercrate ambiguity causes collected since tracking
550 /// was enabled and disables tracking at the same time. If
551 /// tracking is not enabled, just returns an empty vector.
552 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
553 assert!(self.intercrate.is_some());
554 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
557 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
561 pub fn tcx(&self) -> TyCtxt<'tcx> {
565 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
569 ///////////////////////////////////////////////////////////////////////////
572 // The selection phase tries to identify *how* an obligation will
573 // be resolved. For example, it will identify which impl or
574 // parameter bound is to be used. The process can be inconclusive
575 // if the self type in the obligation is not fully inferred. Selection
576 // can result in an error in one of two ways:
578 // 1. If no applicable impl or parameter bound can be found.
579 // 2. If the output type parameters in the obligation do not match
580 // those specified by the impl/bound. For example, if the obligation
581 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
582 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
584 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
585 /// type environment by performing unification.
588 obligation: &TraitObligation<'tcx>,
589 ) -> SelectionResult<'tcx, Selection<'tcx>> {
590 debug!("select({:?})", obligation);
591 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
593 let pec = &ProvisionalEvaluationCache::default();
594 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
596 let candidate = match self.candidate_from_obligation(&stack) {
597 Err(SelectionError::Overflow) => {
598 // In standard mode, overflow must have been caught and reported
600 assert!(self.query_mode == TraitQueryMode::Canonical);
601 return Err(SelectionError::Overflow);
609 Ok(Some(candidate)) => candidate,
612 match self.confirm_candidate(obligation, candidate) {
613 Err(SelectionError::Overflow) => {
614 assert!(self.query_mode == TraitQueryMode::Canonical);
615 Err(SelectionError::Overflow)
618 Ok(candidate) => Ok(Some(candidate)),
622 ///////////////////////////////////////////////////////////////////////////
625 // Tests whether an obligation can be selected or whether an impl
626 // can be applied to particular types. It skips the "confirmation"
627 // step and hence completely ignores output type parameters.
629 // The result is "true" if the obligation *may* hold and "false" if
630 // we can be sure it does not.
632 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
633 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
634 debug!("predicate_may_hold_fatal({:?})", obligation);
636 // This fatal query is a stopgap that should only be used in standard mode,
637 // where we do not expect overflow to be propagated.
638 assert!(self.query_mode == TraitQueryMode::Standard);
640 self.evaluate_root_obligation(obligation)
641 .expect("Overflow should be caught earlier in standard query mode")
645 /// Evaluates whether the obligation `obligation` can be satisfied
646 /// and returns an `EvaluationResult`. This is meant for the
648 pub fn evaluate_root_obligation(
650 obligation: &PredicateObligation<'tcx>,
651 ) -> Result<EvaluationResult, OverflowError> {
652 self.evaluation_probe(|this| {
653 this.evaluate_predicate_recursively(
654 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
662 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
663 ) -> Result<EvaluationResult, OverflowError> {
664 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
665 let result = op(self)?;
666 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
668 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
673 /// Evaluates the predicates in `predicates` recursively. Note that
674 /// this applies projections in the predicates, and therefore
675 /// is run within an inference probe.
676 fn evaluate_predicates_recursively<'o, I>(
678 stack: TraitObligationStackList<'o, 'tcx>,
680 ) -> Result<EvaluationResult, OverflowError>
682 I: IntoIterator<Item = PredicateObligation<'tcx>>,
684 let mut result = EvaluatedToOk;
685 for obligation in predicates {
686 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
687 debug!("evaluate_predicate_recursively({:?}) = {:?}", obligation, eval);
688 if let EvaluatedToErr = eval {
689 // fast-path - EvaluatedToErr is the top of the lattice,
690 // so we don't need to look on the other predicates.
691 return Ok(EvaluatedToErr);
693 result = cmp::max(result, eval);
699 fn evaluate_predicate_recursively<'o>(
701 previous_stack: TraitObligationStackList<'o, 'tcx>,
702 obligation: PredicateObligation<'tcx>,
703 ) -> Result<EvaluationResult, OverflowError> {
705 "evaluate_predicate_recursively(previous_stack={:?}, obligation={:?})",
706 previous_stack.head(),
710 // `previous_stack` stores a `TraitObligatiom`, while `obligation` is
711 // a `PredicateObligation`. These are distinct types, so we can't
712 // use any `Option` combinator method that would force them to be
714 match previous_stack.head() {
715 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
716 None => self.check_recursion_limit(&obligation, &obligation)?,
719 match obligation.predicate {
720 ty::Predicate::Trait(ref t) => {
721 debug_assert!(!t.has_escaping_bound_vars());
722 let obligation = obligation.with(t.clone());
723 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
726 ty::Predicate::Subtype(ref p) => {
727 // Does this code ever run?
728 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
729 Some(Ok(InferOk { mut obligations, .. })) => {
730 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
731 self.evaluate_predicates_recursively(
733 obligations.into_iter(),
736 Some(Err(_)) => Ok(EvaluatedToErr),
737 None => Ok(EvaluatedToAmbig),
741 ty::Predicate::WellFormed(ty) => match ty::wf::obligations(
743 obligation.param_env,
744 obligation.cause.body_id,
746 obligation.cause.span,
748 Some(mut obligations) => {
749 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
750 self.evaluate_predicates_recursively(previous_stack, obligations.into_iter())
752 None => Ok(EvaluatedToAmbig),
755 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
756 // We do not consider region relationships when evaluating trait matches.
757 Ok(EvaluatedToOkModuloRegions)
760 ty::Predicate::ObjectSafe(trait_def_id) => {
761 if self.tcx().is_object_safe(trait_def_id) {
768 ty::Predicate::Projection(ref data) => {
769 let project_obligation = obligation.with(data.clone());
770 match project::poly_project_and_unify_type(self, &project_obligation) {
771 Ok(Some(mut subobligations)) => {
772 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
773 let result = self.evaluate_predicates_recursively(
775 subobligations.into_iter(),
778 ProjectionCacheKey::from_poly_projection_predicate(self, data)
780 self.infcx.projection_cache.borrow_mut().complete(key);
784 Ok(None) => Ok(EvaluatedToAmbig),
785 Err(_) => Ok(EvaluatedToErr),
789 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
790 match self.infcx.closure_kind(closure_def_id, closure_substs) {
791 Some(closure_kind) => {
792 if closure_kind.extends(kind) {
798 None => Ok(EvaluatedToAmbig),
802 ty::Predicate::ConstEvaluatable(def_id, substs) => {
803 if !(obligation.param_env, substs).has_local_value() {
804 match self.tcx().const_eval_resolve(obligation.param_env, def_id, substs, None)
806 Ok(_) => Ok(EvaluatedToOk),
807 Err(_) => Ok(EvaluatedToErr),
810 // Inference variables still left in param_env or substs.
817 fn evaluate_trait_predicate_recursively<'o>(
819 previous_stack: TraitObligationStackList<'o, 'tcx>,
820 mut obligation: TraitObligation<'tcx>,
821 ) -> Result<EvaluationResult, OverflowError> {
822 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
824 if self.intercrate.is_none()
825 && obligation.is_global()
826 && obligation.param_env.caller_bounds.iter().all(|bound| bound.needs_subst())
828 // If a param env has no global bounds, global obligations do not
829 // depend on its particular value in order to work, so we can clear
830 // out the param env and get better caching.
831 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
832 obligation.param_env = obligation.param_env.without_caller_bounds();
835 let stack = self.push_stack(previous_stack, &obligation);
836 let fresh_trait_ref = stack.fresh_trait_ref;
837 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
838 debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
842 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
843 debug!("PROVISIONAL CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
844 stack.update_reached_depth(stack.cache().current_reached_depth());
848 // Check if this is a match for something already on the
849 // stack. If so, we don't want to insert the result into the
850 // main cache (it is cycle dependent) nor the provisional
851 // cache (which is meant for things that have completed but
852 // for a "backedge" -- this result *is* the backedge).
853 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
854 return Ok(cycle_result);
857 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
858 let result = result?;
860 if !result.must_apply_modulo_regions() {
861 stack.cache().on_failure(stack.dfn);
864 let reached_depth = stack.reached_depth.get();
865 if reached_depth >= stack.depth {
866 debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
867 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
869 stack.cache().on_completion(stack.depth, |fresh_trait_ref, provisional_result| {
870 self.insert_evaluation_cache(
871 obligation.param_env,
874 provisional_result.max(result),
878 debug!("PROVISIONAL: {:?}={:?}", fresh_trait_ref, result);
880 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
881 is a cycle participant (at depth {}, reached depth {})",
882 fresh_trait_ref, stack.depth, reached_depth,
885 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_ref, result);
891 /// If there is any previous entry on the stack that precisely
892 /// matches this obligation, then we can assume that the
893 /// obligation is satisfied for now (still all other conditions
894 /// must be met of course). One obvious case this comes up is
895 /// marker traits like `Send`. Think of a linked list:
897 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
899 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
900 /// `Option<Box<List<T>>>` is `Send`, and in turn
901 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
904 /// Note that we do this comparison using the `fresh_trait_ref`
905 /// fields. Because these have all been freshened using
906 /// `self.freshener`, we can be sure that (a) this will not
907 /// affect the inferencer state and (b) that if we see two
908 /// fresh regions with the same index, they refer to the same
909 /// unbound type variable.
910 fn check_evaluation_cycle(
912 stack: &TraitObligationStack<'_, 'tcx>,
913 ) -> Option<EvaluationResult> {
914 if let Some(cycle_depth) = stack
916 .skip(1) // Skip top-most frame.
918 stack.obligation.param_env == prev.obligation.param_env
919 && stack.fresh_trait_ref == prev.fresh_trait_ref
921 .map(|stack| stack.depth)
924 "evaluate_stack({:?}) --> recursive at depth {}",
925 stack.fresh_trait_ref, cycle_depth,
928 // If we have a stack like `A B C D E A`, where the top of
929 // the stack is the final `A`, then this will iterate over
930 // `A, E, D, C, B` -- i.e., all the participants apart
931 // from the cycle head. We mark them as participating in a
932 // cycle. This suppresses caching for those nodes. See
933 // `in_cycle` field for more details.
934 stack.update_reached_depth(cycle_depth);
936 // Subtle: when checking for a coinductive cycle, we do
937 // not compare using the "freshened trait refs" (which
938 // have erased regions) but rather the fully explicit
939 // trait refs. This is important because it's only a cycle
940 // if the regions match exactly.
941 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
942 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
943 if self.coinductive_match(cycle) {
944 debug!("evaluate_stack({:?}) --> recursive, coinductive", stack.fresh_trait_ref);
947 debug!("evaluate_stack({:?}) --> recursive, inductive", stack.fresh_trait_ref);
948 Some(EvaluatedToRecur)
955 fn evaluate_stack<'o>(
957 stack: &TraitObligationStack<'o, 'tcx>,
958 ) -> Result<EvaluationResult, OverflowError> {
959 // In intercrate mode, whenever any of the types are unbound,
960 // there can always be an impl. Even if there are no impls in
961 // this crate, perhaps the type would be unified with
962 // something from another crate that does provide an impl.
964 // In intra mode, we must still be conservative. The reason is
965 // that we want to avoid cycles. Imagine an impl like:
967 // impl<T:Eq> Eq for Vec<T>
969 // and a trait reference like `$0 : Eq` where `$0` is an
970 // unbound variable. When we evaluate this trait-reference, we
971 // will unify `$0` with `Vec<$1>` (for some fresh variable
972 // `$1`), on the condition that `$1 : Eq`. We will then wind
973 // up with many candidates (since that are other `Eq` impls
974 // that apply) and try to winnow things down. This results in
975 // a recursive evaluation that `$1 : Eq` -- as you can
976 // imagine, this is just where we started. To avoid that, we
977 // check for unbound variables and return an ambiguous (hence possible)
978 // match if we've seen this trait before.
980 // This suffices to allow chains like `FnMut` implemented in
981 // terms of `Fn` etc, but we could probably make this more
983 let unbound_input_types =
984 stack.fresh_trait_ref.skip_binder().input_types().any(|ty| ty.is_fresh());
985 // This check was an imperfect workaround for a bug in the old
986 // intercrate mode; it should be removed when that goes away.
987 if unbound_input_types && self.intercrate == Some(IntercrateMode::Issue43355) {
989 "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
990 stack.fresh_trait_ref
992 // Heuristics: show the diagnostics when there are no candidates in crate.
993 if self.intercrate_ambiguity_causes.is_some() {
994 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
995 if let Ok(candidate_set) = self.assemble_candidates(stack) {
996 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
997 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
998 let self_ty = trait_ref.self_ty();
999 let cause = IntercrateAmbiguityCause::DownstreamCrate {
1000 trait_desc: trait_ref.print_only_trait_path().to_string(),
1001 self_desc: if self_ty.has_concrete_skeleton() {
1002 Some(self_ty.to_string())
1007 debug!("evaluate_stack: pushing cause = {:?}", cause);
1008 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1012 return Ok(EvaluatedToAmbig);
1014 if unbound_input_types
1015 && stack.iter().skip(1).any(|prev| {
1016 stack.obligation.param_env == prev.obligation.param_env
1017 && self.match_fresh_trait_refs(
1018 &stack.fresh_trait_ref,
1019 &prev.fresh_trait_ref,
1020 prev.obligation.param_env,
1025 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
1026 stack.fresh_trait_ref
1028 return Ok(EvaluatedToUnknown);
1031 match self.candidate_from_obligation(stack) {
1032 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1033 Ok(None) => Ok(EvaluatedToAmbig),
1034 Err(Overflow) => Err(OverflowError),
1035 Err(..) => Ok(EvaluatedToErr),
1039 /// For defaulted traits, we use a co-inductive strategy to solve, so
1040 /// that recursion is ok. This routine returns `true` if the top of the
1041 /// stack (`cycle[0]`):
1043 /// - is a defaulted trait,
1044 /// - it also appears in the backtrace at some position `X`,
1045 /// - all the predicates at positions `X..` between `X` and the top are
1046 /// also defaulted traits.
1047 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
1049 I: Iterator<Item = ty::Predicate<'tcx>>,
1051 let mut cycle = cycle;
1052 cycle.all(|predicate| self.coinductive_predicate(predicate))
1055 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1056 let result = match predicate {
1057 ty::Predicate::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1060 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
1064 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
1065 /// obligations are met. Returns whether `candidate` remains viable after this further
1067 fn evaluate_candidate<'o>(
1069 stack: &TraitObligationStack<'o, 'tcx>,
1070 candidate: &SelectionCandidate<'tcx>,
1071 ) -> Result<EvaluationResult, OverflowError> {
1073 "evaluate_candidate: depth={} candidate={:?}",
1074 stack.obligation.recursion_depth, candidate
1076 let result = self.evaluation_probe(|this| {
1077 let candidate = (*candidate).clone();
1078 match this.confirm_candidate(stack.obligation, candidate) {
1079 Ok(selection) => this.evaluate_predicates_recursively(
1081 selection.nested_obligations().into_iter(),
1083 Err(..) => Ok(EvaluatedToErr),
1087 "evaluate_candidate: depth={} result={:?}",
1088 stack.obligation.recursion_depth, result
1093 fn check_evaluation_cache(
1095 param_env: ty::ParamEnv<'tcx>,
1096 trait_ref: ty::PolyTraitRef<'tcx>,
1097 ) -> Option<EvaluationResult> {
1098 let tcx = self.tcx();
1099 if self.can_use_global_caches(param_env) {
1100 let cache = tcx.evaluation_cache.hashmap.borrow();
1101 if let Some(cached) = cache.get(¶m_env.and(trait_ref)) {
1102 return Some(cached.get(tcx));
1109 .get(¶m_env.and(trait_ref))
1110 .map(|v| v.get(tcx))
1113 fn insert_evaluation_cache(
1115 param_env: ty::ParamEnv<'tcx>,
1116 trait_ref: ty::PolyTraitRef<'tcx>,
1117 dep_node: DepNodeIndex,
1118 result: EvaluationResult,
1120 // Avoid caching results that depend on more than just the trait-ref
1121 // - the stack can create recursion.
1122 if result.is_stack_dependent() {
1126 if self.can_use_global_caches(param_env) {
1127 if !trait_ref.has_local_value() {
1129 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
1132 // This may overwrite the cache with the same value
1133 // FIXME: Due to #50507 this overwrites the different values
1134 // This should be changed to use HashMapExt::insert_same
1135 // when that is fixed
1140 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
1145 debug!("insert_evaluation_cache(trait_ref={:?}, candidate={:?})", trait_ref, result,);
1150 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, result));
1153 /// For various reasons, it's possible for a subobligation
1154 /// to have a *lower* recursion_depth than the obligation used to create it.
1155 /// Projection sub-obligations may be returned from the projection cache,
1156 /// which results in obligations with an 'old' `recursion_depth`.
1157 /// Additionally, methods like `ty::wf::obligations` and
1158 /// `InferCtxt.subtype_predicate` produce subobligations without
1159 /// taking in a 'parent' depth, causing the generated subobligations
1160 /// to have a `recursion_depth` of `0`.
1162 /// To ensure that obligation_depth never decreasees, we force all subobligations
1163 /// to have at least the depth of the original obligation.
1164 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1169 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1172 /// Checks that the recursion limit has not been exceeded.
1174 /// The weird return type of this function allows it to be used with the `try` (`?`)
1175 /// operator within certain functions.
1176 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1178 obligation: &Obligation<'tcx, T>,
1179 error_obligation: &Obligation<'tcx, V>,
1180 ) -> Result<(), OverflowError> {
1181 let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
1182 if obligation.recursion_depth >= recursion_limit {
1183 match self.query_mode {
1184 TraitQueryMode::Standard => {
1185 self.infcx().report_overflow_error(error_obligation, true);
1187 TraitQueryMode::Canonical => {
1188 return Err(OverflowError);
1195 ///////////////////////////////////////////////////////////////////////////
1196 // CANDIDATE ASSEMBLY
1198 // The selection process begins by examining all in-scope impls,
1199 // caller obligations, and so forth and assembling a list of
1200 // candidates. See the [rustc guide] for more details.
1203 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#candidate-assembly
1205 fn candidate_from_obligation<'o>(
1207 stack: &TraitObligationStack<'o, 'tcx>,
1208 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1209 // Watch out for overflow. This intentionally bypasses (and does
1210 // not update) the cache.
1211 self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
1213 // Check the cache. Note that we freshen the trait-ref
1214 // separately rather than using `stack.fresh_trait_ref` --
1215 // this is because we want the unbound variables to be
1216 // replaced with fresh types starting from index 0.
1217 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate.clone());
1219 "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1220 cache_fresh_trait_pred, stack
1222 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
1225 self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
1227 debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
1231 // If no match, compute result and insert into cache.
1233 // FIXME(nikomatsakis) -- this cache is not taking into
1234 // account cycles that may have occurred in forming the
1235 // candidate. I don't know of any specific problems that
1236 // result but it seems awfully suspicious.
1237 let (candidate, dep_node) =
1238 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
1240 debug!("CACHE MISS: SELECT({:?})={:?}", cache_fresh_trait_pred, candidate);
1241 self.insert_candidate_cache(
1242 stack.obligation.param_env,
1243 cache_fresh_trait_pred,
1250 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1252 OP: FnOnce(&mut Self) -> R,
1254 let (result, dep_node) =
1255 self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || op(self));
1256 self.tcx().dep_graph.read_index(dep_node);
1260 // Treat negative impls as unimplemented, and reservation impls as ambiguity.
1261 fn filter_negative_and_reservation_impls(
1263 candidate: SelectionCandidate<'tcx>,
1264 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1265 if let ImplCandidate(def_id) = candidate {
1266 let tcx = self.tcx();
1267 match tcx.impl_polarity(def_id) {
1268 ty::ImplPolarity::Negative if !self.allow_negative_impls => {
1269 return Err(Unimplemented);
1271 ty::ImplPolarity::Reservation => {
1272 if let Some(intercrate_ambiguity_clauses) =
1273 &mut self.intercrate_ambiguity_causes
1275 let attrs = tcx.get_attrs(def_id);
1276 let attr = attr::find_by_name(&attrs, sym::rustc_reservation_impl);
1277 let value = attr.and_then(|a| a.value_str());
1278 if let Some(value) = value {
1280 "filter_negative_and_reservation_impls: \
1281 reservation impl ambiguity on {:?}",
1284 intercrate_ambiguity_clauses.push(
1285 IntercrateAmbiguityCause::ReservationImpl {
1286 message: value.to_string(),
1299 fn candidate_from_obligation_no_cache<'o>(
1301 stack: &TraitObligationStack<'o, 'tcx>,
1302 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1303 if stack.obligation.predicate.references_error() {
1304 // If we encounter a `Error`, we generally prefer the
1305 // most "optimistic" result in response -- that is, the
1306 // one least likely to report downstream errors. But
1307 // because this routine is shared by coherence and by
1308 // trait selection, there isn't an obvious "right" choice
1309 // here in that respect, so we opt to just return
1310 // ambiguity and let the upstream clients sort it out.
1314 if let Some(conflict) = self.is_knowable(stack) {
1315 debug!("coherence stage: not knowable");
1316 if self.intercrate_ambiguity_causes.is_some() {
1317 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1318 // Heuristics: show the diagnostics when there are no candidates in crate.
1319 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1320 let mut no_candidates_apply = true;
1322 let evaluated_candidates =
1323 candidate_set.vec.iter().map(|c| self.evaluate_candidate(stack, &c));
1325 for ec in evaluated_candidates {
1329 no_candidates_apply = false;
1333 Err(e) => return Err(e.into()),
1338 if !candidate_set.ambiguous && no_candidates_apply {
1339 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1340 let self_ty = trait_ref.self_ty();
1341 let trait_desc = trait_ref.print_only_trait_path().to_string();
1342 let self_desc = if self_ty.has_concrete_skeleton() {
1343 Some(self_ty.to_string())
1347 let cause = if let Conflict::Upstream = conflict {
1348 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
1350 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
1352 debug!("evaluate_stack: pushing cause = {:?}", cause);
1353 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
1360 let candidate_set = self.assemble_candidates(stack)?;
1362 if candidate_set.ambiguous {
1363 debug!("candidate set contains ambig");
1367 let mut candidates = candidate_set.vec;
1369 debug!("assembled {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1371 // At this point, we know that each of the entries in the
1372 // candidate set is *individually* applicable. Now we have to
1373 // figure out if they contain mutual incompatibilities. This
1374 // frequently arises if we have an unconstrained input type --
1375 // for example, we are looking for `$0: Eq` where `$0` is some
1376 // unconstrained type variable. In that case, we'll get a
1377 // candidate which assumes $0 == int, one that assumes `$0 ==
1378 // usize`, etc. This spells an ambiguity.
1380 // If there is more than one candidate, first winnow them down
1381 // by considering extra conditions (nested obligations and so
1382 // forth). We don't winnow if there is exactly one
1383 // candidate. This is a relatively minor distinction but it
1384 // can lead to better inference and error-reporting. An
1385 // example would be if there was an impl:
1387 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1389 // and we were to see some code `foo.push_clone()` where `boo`
1390 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1391 // we were to winnow, we'd wind up with zero candidates.
1392 // Instead, we select the right impl now but report "`Bar` does
1393 // not implement `Clone`".
1394 if candidates.len() == 1 {
1395 return self.filter_negative_and_reservation_impls(candidates.pop().unwrap());
1398 // Winnow, but record the exact outcome of evaluation, which
1399 // is needed for specialization. Propagate overflow if it occurs.
1400 let mut candidates = candidates
1402 .map(|c| match self.evaluate_candidate(stack, &c) {
1403 Ok(eval) if eval.may_apply() => {
1404 Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
1407 Err(OverflowError) => Err(Overflow),
1409 .flat_map(Result::transpose)
1410 .collect::<Result<Vec<_>, _>>()?;
1412 debug!("winnowed to {} candidates for {:?}: {:?}", candidates.len(), stack, candidates);
1414 // If there are STILL multiple candidates, we can further
1415 // reduce the list by dropping duplicates -- including
1416 // resolving specializations.
1417 if candidates.len() > 1 {
1419 while i < candidates.len() {
1420 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1421 self.candidate_should_be_dropped_in_favor_of(&candidates[i], &candidates[j])
1424 debug!("Dropping candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1425 candidates.swap_remove(i);
1427 debug!("Retaining candidate #{}/{}: {:?}", i, candidates.len(), candidates[i]);
1430 // If there are *STILL* multiple candidates, give up
1431 // and report ambiguity.
1433 debug!("multiple matches, ambig");
1440 // If there are *NO* candidates, then there are no impls --
1441 // that we know of, anyway. Note that in the case where there
1442 // are unbound type variables within the obligation, it might
1443 // be the case that you could still satisfy the obligation
1444 // from another crate by instantiating the type variables with
1445 // a type from another crate that does have an impl. This case
1446 // is checked for in `evaluate_stack` (and hence users
1447 // who might care about this case, like coherence, should use
1449 if candidates.is_empty() {
1450 return Err(Unimplemented);
1453 // Just one candidate left.
1454 self.filter_negative_and_reservation_impls(candidates.pop().unwrap().candidate)
1457 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1458 debug!("is_knowable(intercrate={:?})", self.intercrate);
1460 if !self.intercrate.is_some() {
1464 let obligation = &stack.obligation;
1465 let predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1467 // Okay to skip binder because of the nature of the
1468 // trait-ref-is-knowable check, which does not care about
1470 let trait_ref = predicate.skip_binder().trait_ref;
1472 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1474 Some(Conflict::Downstream { used_to_be_broken: true }),
1475 Some(IntercrateMode::Issue43355),
1476 ) = (result, self.intercrate)
1478 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1485 /// Returns `true` if the global caches can be used.
1486 /// Do note that if the type itself is not in the
1487 /// global tcx, the local caches will be used.
1488 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1489 // If there are any e.g. inference variables in the `ParamEnv`, then we
1490 // always use a cache local to this particular scope. Otherwise, we
1491 // switch to a global cache.
1492 if param_env.has_local_value() {
1496 // Avoid using the master cache during coherence and just rely
1497 // on the local cache. This effectively disables caching
1498 // during coherence. It is really just a simplification to
1499 // avoid us having to fear that coherence results "pollute"
1500 // the master cache. Since coherence executes pretty quickly,
1501 // it's not worth going to more trouble to increase the
1502 // hit-rate, I don't think.
1503 if self.intercrate.is_some() {
1507 // Otherwise, we can use the global cache.
1511 fn check_candidate_cache(
1513 param_env: ty::ParamEnv<'tcx>,
1514 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1515 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1516 let tcx = self.tcx();
1517 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1518 if self.can_use_global_caches(param_env) {
1519 let cache = tcx.selection_cache.hashmap.borrow();
1520 if let Some(cached) = cache.get(¶m_env.and(*trait_ref)) {
1521 return Some(cached.get(tcx));
1528 .get(¶m_env.and(*trait_ref))
1529 .map(|v| v.get(tcx))
1532 /// Determines whether can we safely cache the result
1533 /// of selecting an obligation. This is almost always `true`,
1534 /// except when dealing with certain `ParamCandidate`s.
1536 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1537 /// since it was usually produced directly from a `DefId`. However,
1538 /// certain cases (currently only librustdoc's blanket impl finder),
1539 /// a `ParamEnv` may be explicitly constructed with inference types.
1540 /// When this is the case, we do *not* want to cache the resulting selection
1541 /// candidate. This is due to the fact that it might not always be possible
1542 /// to equate the obligation's trait ref and the candidate's trait ref,
1543 /// if more constraints end up getting added to an inference variable.
1545 /// Because of this, we always want to re-run the full selection
1546 /// process for our obligation the next time we see it, since
1547 /// we might end up picking a different `SelectionCandidate` (or none at all).
1548 fn can_cache_candidate(
1550 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1553 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => {
1554 !trait_ref.skip_binder().input_types().any(|t| t.walk().any(|t_| t_.is_ty_infer()))
1560 fn insert_candidate_cache(
1562 param_env: ty::ParamEnv<'tcx>,
1563 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1564 dep_node: DepNodeIndex,
1565 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1567 let tcx = self.tcx();
1568 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1570 if !self.can_cache_candidate(&candidate) {
1572 "insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1573 candidate is not cacheable",
1574 trait_ref, candidate
1579 if self.can_use_global_caches(param_env) {
1580 if let Err(Overflow) = candidate {
1581 // Don't cache overflow globally; we only produce this in certain modes.
1582 } else if !trait_ref.has_local_value() {
1583 if !candidate.has_local_value() {
1585 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1586 trait_ref, candidate,
1588 // This may overwrite the cache with the same value.
1592 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1599 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1600 trait_ref, candidate,
1606 .insert(param_env.and(trait_ref), WithDepNode::new(dep_node, candidate));
1609 fn assemble_candidates<'o>(
1611 stack: &TraitObligationStack<'o, 'tcx>,
1612 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1613 let TraitObligationStack { obligation, .. } = *stack;
1614 let ref obligation = Obligation {
1615 param_env: obligation.param_env,
1616 cause: obligation.cause.clone(),
1617 recursion_depth: obligation.recursion_depth,
1618 predicate: self.infcx().resolve_vars_if_possible(&obligation.predicate),
1621 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1622 // Self is a type variable (e.g., `_: AsRef<str>`).
1624 // This is somewhat problematic, as the current scheme can't really
1625 // handle it turning to be a projection. This does end up as truly
1626 // ambiguous in most cases anyway.
1628 // Take the fast path out - this also improves
1629 // performance by preventing assemble_candidates_from_impls from
1630 // matching every impl for this trait.
1631 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1634 let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false };
1636 self.assemble_candidates_for_trait_alias(obligation, &mut candidates)?;
1638 // Other bounds. Consider both in-scope bounds from fn decl
1639 // and applicable impls. There is a certain set of precedence rules here.
1640 let def_id = obligation.predicate.def_id();
1641 let lang_items = self.tcx().lang_items();
1643 if lang_items.copy_trait() == Some(def_id) {
1644 debug!("obligation self ty is {:?}", obligation.predicate.skip_binder().self_ty());
1646 // User-defined copy impls are permitted, but only for
1647 // structs and enums.
1648 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1650 // For other types, we'll use the builtin rules.
1651 let copy_conditions = self.copy_clone_conditions(obligation);
1652 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1653 } else if lang_items.sized_trait() == Some(def_id) {
1654 // Sized is never implementable by end-users, it is
1655 // always automatically computed.
1656 let sized_conditions = self.sized_conditions(obligation);
1657 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1658 } else if lang_items.unsize_trait() == Some(def_id) {
1659 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1661 if lang_items.clone_trait() == Some(def_id) {
1662 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
1663 // for `Copy` also has builtin support for `Clone`, and tuples/arrays of `Clone`
1664 // types have builtin support for `Clone`.
1665 let clone_conditions = self.copy_clone_conditions(obligation);
1666 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1669 self.assemble_generator_candidates(obligation, &mut candidates)?;
1670 self.assemble_closure_candidates(obligation, &mut candidates)?;
1671 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1672 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1673 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1676 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1677 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1678 // Auto implementations have lower priority, so we only
1679 // consider triggering a default if there is no other impl that can apply.
1680 if candidates.vec.is_empty() {
1681 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1683 debug!("candidate list size: {}", candidates.vec.len());
1687 fn assemble_candidates_from_projected_tys(
1689 obligation: &TraitObligation<'tcx>,
1690 candidates: &mut SelectionCandidateSet<'tcx>,
1692 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1694 // Before we go into the whole placeholder thing, just
1695 // quickly check if the self-type is a projection at all.
1696 match obligation.predicate.skip_binder().trait_ref.self_ty().kind {
1697 ty::Projection(_) | ty::Opaque(..) => {}
1698 ty::Infer(ty::TyVar(_)) => {
1700 obligation.cause.span,
1701 "Self=_ should have been handled by assemble_candidates"
1707 let result = self.infcx.probe(|snapshot| {
1708 self.match_projection_obligation_against_definition_bounds(obligation, snapshot)
1712 candidates.vec.push(ProjectionCandidate);
1716 fn match_projection_obligation_against_definition_bounds(
1718 obligation: &TraitObligation<'tcx>,
1719 snapshot: &CombinedSnapshot<'_, 'tcx>,
1721 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
1722 let (placeholder_trait_predicate, placeholder_map) =
1723 self.infcx().replace_bound_vars_with_placeholders(&poly_trait_predicate);
1725 "match_projection_obligation_against_definition_bounds: \
1726 placeholder_trait_predicate={:?}",
1727 placeholder_trait_predicate,
1730 let (def_id, substs) = match placeholder_trait_predicate.trait_ref.self_ty().kind {
1731 ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1732 ty::Opaque(def_id, substs) => (def_id, substs),
1735 obligation.cause.span,
1736 "match_projection_obligation_against_definition_bounds() called \
1737 but self-ty is not a projection: {:?}",
1738 placeholder_trait_predicate.trait_ref.self_ty()
1743 "match_projection_obligation_against_definition_bounds: \
1744 def_id={:?}, substs={:?}",
1748 let predicates_of = self.tcx().predicates_of(def_id);
1749 let bounds = predicates_of.instantiate(self.tcx(), substs);
1751 "match_projection_obligation_against_definition_bounds: \
1756 let elaborated_predicates = util::elaborate_predicates(self.tcx(), bounds.predicates);
1757 let matching_bound = elaborated_predicates.filter_to_traits().find(|bound| {
1758 self.infcx.probe(|_| {
1759 self.match_projection(
1762 placeholder_trait_predicate.trait_ref.clone(),
1770 "match_projection_obligation_against_definition_bounds: \
1771 matching_bound={:?}",
1774 match matching_bound {
1777 // Repeat the successful match, if any, this time outside of a probe.
1778 let result = self.match_projection(
1781 placeholder_trait_predicate.trait_ref.clone(),
1792 fn match_projection(
1794 obligation: &TraitObligation<'tcx>,
1795 trait_bound: ty::PolyTraitRef<'tcx>,
1796 placeholder_trait_ref: ty::TraitRef<'tcx>,
1797 placeholder_map: &PlaceholderMap<'tcx>,
1798 snapshot: &CombinedSnapshot<'_, 'tcx>,
1800 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1802 .at(&obligation.cause, obligation.param_env)
1803 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1805 && self.infcx.leak_check(false, placeholder_map, snapshot).is_ok()
1808 /// Given an obligation like `<SomeTrait for T>`, searches the obligations that the caller
1809 /// supplied to find out whether it is listed among them.
1811 /// Never affects the inference environment.
1812 fn assemble_candidates_from_caller_bounds<'o>(
1814 stack: &TraitObligationStack<'o, 'tcx>,
1815 candidates: &mut SelectionCandidateSet<'tcx>,
1816 ) -> Result<(), SelectionError<'tcx>> {
1817 debug!("assemble_candidates_from_caller_bounds({:?})", stack.obligation);
1819 let all_bounds = stack
1824 .filter_map(|o| o.to_opt_poly_trait_ref());
1826 // Micro-optimization: filter out predicates relating to different traits.
1827 let matching_bounds =
1828 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1830 // Keep only those bounds which may apply, and propagate overflow if it occurs.
1831 let mut param_candidates = vec![];
1832 for bound in matching_bounds {
1833 let wc = self.evaluate_where_clause(stack, bound.clone())?;
1835 param_candidates.push(ParamCandidate(bound));
1839 candidates.vec.extend(param_candidates);
1844 fn evaluate_where_clause<'o>(
1846 stack: &TraitObligationStack<'o, 'tcx>,
1847 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1848 ) -> Result<EvaluationResult, OverflowError> {
1849 self.evaluation_probe(|this| {
1850 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1851 Ok(obligations) => {
1852 this.evaluate_predicates_recursively(stack.list(), obligations.into_iter())
1854 Err(()) => Ok(EvaluatedToErr),
1859 fn assemble_generator_candidates(
1861 obligation: &TraitObligation<'tcx>,
1862 candidates: &mut SelectionCandidateSet<'tcx>,
1863 ) -> Result<(), SelectionError<'tcx>> {
1864 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1868 // Okay to skip binder because the substs on generator types never
1869 // touch bound regions, they just capture the in-scope
1870 // type/region parameters.
1871 let self_ty = *obligation.self_ty().skip_binder();
1872 match self_ty.kind {
1873 ty::Generator(..) => {
1875 "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1879 candidates.vec.push(GeneratorCandidate);
1881 ty::Infer(ty::TyVar(_)) => {
1882 debug!("assemble_generator_candidates: ambiguous self-type");
1883 candidates.ambiguous = true;
1891 /// Checks for the artificial impl that the compiler will create for an obligation like `X :
1892 /// FnMut<..>` where `X` is a closure type.
1894 /// Note: the type parameters on a closure candidate are modeled as *output* type
1895 /// parameters and hence do not affect whether this trait is a match or not. They will be
1896 /// unified during the confirmation step.
1897 fn assemble_closure_candidates(
1899 obligation: &TraitObligation<'tcx>,
1900 candidates: &mut SelectionCandidateSet<'tcx>,
1901 ) -> Result<(), SelectionError<'tcx>> {
1902 let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()) {
1909 // Okay to skip binder because the substs on closure types never
1910 // touch bound regions, they just capture the in-scope
1911 // type/region parameters
1912 match obligation.self_ty().skip_binder().kind {
1913 ty::Closure(closure_def_id, closure_substs) => {
1914 debug!("assemble_unboxed_candidates: kind={:?} obligation={:?}", kind, obligation);
1915 match self.infcx.closure_kind(closure_def_id, closure_substs) {
1916 Some(closure_kind) => {
1917 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1918 if closure_kind.extends(kind) {
1919 candidates.vec.push(ClosureCandidate);
1923 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1924 candidates.vec.push(ClosureCandidate);
1928 ty::Infer(ty::TyVar(_)) => {
1929 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1930 candidates.ambiguous = true;
1938 /// Implements one of the `Fn()` family for a fn pointer.
1939 fn assemble_fn_pointer_candidates(
1941 obligation: &TraitObligation<'tcx>,
1942 candidates: &mut SelectionCandidateSet<'tcx>,
1943 ) -> Result<(), SelectionError<'tcx>> {
1944 // We provide impl of all fn traits for fn pointers.
1945 if self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()).is_none() {
1949 // Okay to skip binder because what we are inspecting doesn't involve bound regions.
1950 let self_ty = *obligation.self_ty().skip_binder();
1951 match self_ty.kind {
1952 ty::Infer(ty::TyVar(_)) => {
1953 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1954 candidates.ambiguous = true; // Could wind up being a fn() type.
1956 // Provide an impl, but only for suitable `fn` pointers.
1957 ty::FnDef(..) | ty::FnPtr(_) => {
1959 unsafety: hir::Unsafety::Normal,
1963 } = self_ty.fn_sig(self.tcx()).skip_binder()
1965 candidates.vec.push(FnPointerCandidate);
1974 /// Searches for impls that might apply to `obligation`.
1975 fn assemble_candidates_from_impls(
1977 obligation: &TraitObligation<'tcx>,
1978 candidates: &mut SelectionCandidateSet<'tcx>,
1979 ) -> Result<(), SelectionError<'tcx>> {
1980 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1982 self.tcx().for_each_relevant_impl(
1983 obligation.predicate.def_id(),
1984 obligation.predicate.skip_binder().trait_ref.self_ty(),
1986 self.infcx.probe(|snapshot| {
1987 if let Ok(_substs) = self.match_impl(impl_def_id, obligation, snapshot) {
1988 candidates.vec.push(ImplCandidate(impl_def_id));
1997 fn assemble_candidates_from_auto_impls(
1999 obligation: &TraitObligation<'tcx>,
2000 candidates: &mut SelectionCandidateSet<'tcx>,
2001 ) -> Result<(), SelectionError<'tcx>> {
2002 // Okay to skip binder here because the tests we do below do not involve bound regions.
2003 let self_ty = *obligation.self_ty().skip_binder();
2004 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
2006 let def_id = obligation.predicate.def_id();
2008 if self.tcx().trait_is_auto(def_id) {
2009 match self_ty.kind {
2010 ty::Dynamic(..) => {
2011 // For object types, we don't know what the closed
2012 // over types are. This means we conservatively
2013 // say nothing; a candidate may be added by
2014 // `assemble_candidates_from_object_ty`.
2016 ty::Foreign(..) => {
2017 // Since the contents of foreign types is unknown,
2018 // we don't add any `..` impl. Default traits could
2019 // still be provided by a manual implementation for
2020 // this trait and type.
2022 ty::Param(..) | ty::Projection(..) => {
2023 // In these cases, we don't know what the actual
2024 // type is. Therefore, we cannot break it down
2025 // into its constituent types. So we don't
2026 // consider the `..` impl but instead just add no
2027 // candidates: this means that typeck will only
2028 // succeed if there is another reason to believe
2029 // that this obligation holds. That could be a
2030 // where-clause or, in the case of an object type,
2031 // it could be that the object type lists the
2032 // trait (e.g., `Foo+Send : Send`). See
2033 // `compile-fail/typeck-default-trait-impl-send-param.rs`
2034 // for an example of a test case that exercises
2037 ty::Infer(ty::TyVar(_)) => {
2038 // The auto impl might apply; we don't know.
2039 candidates.ambiguous = true;
2041 ty::Generator(_, _, movability)
2042 if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
2045 hir::Movability::Static => {
2046 // Immovable generators are never `Unpin`, so
2047 // suppress the normal auto-impl candidate for it.
2049 hir::Movability::Movable => {
2050 // Movable generators are always `Unpin`, so add an
2051 // unconditional builtin candidate.
2052 candidates.vec.push(BuiltinCandidate { has_nested: false });
2057 _ => candidates.vec.push(AutoImplCandidate(def_id.clone())),
2064 /// Searches for impls that might apply to `obligation`.
2065 fn assemble_candidates_from_object_ty(
2067 obligation: &TraitObligation<'tcx>,
2068 candidates: &mut SelectionCandidateSet<'tcx>,
2071 "assemble_candidates_from_object_ty(self_ty={:?})",
2072 obligation.self_ty().skip_binder()
2075 self.infcx.probe(|_snapshot| {
2076 // The code below doesn't care about regions, and the
2077 // self-ty here doesn't escape this probe, so just erase
2079 let self_ty = self.tcx().erase_late_bound_regions(&obligation.self_ty());
2080 let poly_trait_ref = match self_ty.kind {
2081 ty::Dynamic(ref data, ..) => {
2082 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
2084 "assemble_candidates_from_object_ty: matched builtin bound, \
2087 candidates.vec.push(BuiltinObjectCandidate);
2091 if let Some(principal) = data.principal() {
2092 if !self.infcx.tcx.features().object_safe_for_dispatch {
2093 principal.with_self_ty(self.tcx(), self_ty)
2094 } else if self.tcx().is_object_safe(principal.def_id()) {
2095 principal.with_self_ty(self.tcx(), self_ty)
2100 // Only auto trait bounds exist.
2104 ty::Infer(ty::TyVar(_)) => {
2105 debug!("assemble_candidates_from_object_ty: ambiguous");
2106 candidates.ambiguous = true; // could wind up being an object type
2112 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}", poly_trait_ref);
2114 // Count only those upcast versions that match the trait-ref
2115 // we are looking for. Specifically, do not only check for the
2116 // correct trait, but also the correct type parameters.
2117 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
2118 // but `Foo` is declared as `trait Foo: Bar<u32>`.
2119 let upcast_trait_refs = util::supertraits(self.tcx(), poly_trait_ref)
2120 .filter(|upcast_trait_ref| {
2121 self.infcx.probe(|_| {
2122 let upcast_trait_ref = upcast_trait_ref.clone();
2123 self.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
2128 if upcast_trait_refs > 1 {
2129 // Can be upcast in many ways; need more type information.
2130 candidates.ambiguous = true;
2131 } else if upcast_trait_refs == 1 {
2132 candidates.vec.push(ObjectCandidate);
2137 /// Searches for unsizing that might apply to `obligation`.
2138 fn assemble_candidates_for_unsizing(
2140 obligation: &TraitObligation<'tcx>,
2141 candidates: &mut SelectionCandidateSet<'tcx>,
2143 // We currently never consider higher-ranked obligations e.g.
2144 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
2145 // because they are a priori invalid, and we could potentially add support
2146 // for them later, it's just that there isn't really a strong need for it.
2147 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
2148 // impl, and those are generally applied to concrete types.
2150 // That said, one might try to write a fn with a where clause like
2151 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
2152 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
2153 // Still, you'd be more likely to write that where clause as
2155 // so it seems ok if we (conservatively) fail to accept that `Unsize`
2156 // obligation above. Should be possible to extend this in the future.
2157 let source = match obligation.self_ty().no_bound_vars() {
2160 // Don't add any candidates if there are bound regions.
2164 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2166 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})", source, target);
2168 let may_apply = match (&source.kind, &target.kind) {
2169 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2170 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
2171 // Upcasts permit two things:
2173 // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo`
2174 // 2. Tightening the region bound, e.g., `Foo + 'a` to `Foo + 'b` if `'a: 'b`
2176 // Note that neither of these changes requires any
2177 // change at runtime. Eventually this will be
2180 // We always upcast when we can because of reason
2181 // #2 (region bounds).
2182 data_a.principal_def_id() == data_b.principal_def_id()
2185 // All of a's auto traits need to be in b's auto traits.
2186 .all(|b| data_a.auto_traits().any(|a| a == b))
2190 (_, &ty::Dynamic(..)) => true,
2192 // Ambiguous handling is below `T` -> `Trait`, because inference
2193 // variables can still implement `Unsize<Trait>` and nested
2194 // obligations will have the final say (likely deferred).
2195 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
2196 debug!("assemble_candidates_for_unsizing: ambiguous");
2197 candidates.ambiguous = true;
2201 // `[T; n]` -> `[T]`
2202 (&ty::Array(..), &ty::Slice(_)) => true,
2204 // `Struct<T>` -> `Struct<U>`
2205 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
2206 def_id_a == def_id_b
2209 // `(.., T)` -> `(.., U)`
2210 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
2216 candidates.vec.push(BuiltinUnsizeCandidate);
2220 fn assemble_candidates_for_trait_alias(
2222 obligation: &TraitObligation<'tcx>,
2223 candidates: &mut SelectionCandidateSet<'tcx>,
2224 ) -> Result<(), SelectionError<'tcx>> {
2225 // Okay to skip binder here because the tests we do below do not involve bound regions.
2226 let self_ty = *obligation.self_ty().skip_binder();
2227 debug!("assemble_candidates_for_trait_alias(self_ty={:?})", self_ty);
2229 let def_id = obligation.predicate.def_id();
2231 if self.tcx().is_trait_alias(def_id) {
2232 candidates.vec.push(TraitAliasCandidate(def_id.clone()));
2238 ///////////////////////////////////////////////////////////////////////////
2241 // Winnowing is the process of attempting to resolve ambiguity by
2242 // probing further. During the winnowing process, we unify all
2243 // type variables and then we also attempt to evaluate recursive
2244 // bounds to see if they are satisfied.
2246 /// Returns `true` if `victim` should be dropped in favor of
2247 /// `other`. Generally speaking we will drop duplicate
2248 /// candidates and prefer where-clause candidates.
2250 /// See the comment for "SelectionCandidate" for more details.
2251 fn candidate_should_be_dropped_in_favor_of(
2253 victim: &EvaluatedCandidate<'tcx>,
2254 other: &EvaluatedCandidate<'tcx>,
2256 if victim.candidate == other.candidate {
2260 // Check if a bound would previously have been removed when normalizing
2261 // the param_env so that it can be given the lowest priority. See
2262 // #50825 for the motivation for this.
2264 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
2266 match other.candidate {
2267 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2268 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2269 // lifetime of a variable.
2270 BuiltinCandidate { has_nested: false } => true,
2271 ParamCandidate(ref cand) => match victim.candidate {
2272 AutoImplCandidate(..) => {
2274 "default implementations shouldn't be recorded \
2275 when there are other valid candidates"
2278 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2279 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2280 // lifetime of a variable.
2281 BuiltinCandidate { has_nested: false } => false,
2284 | GeneratorCandidate
2285 | FnPointerCandidate
2286 | BuiltinObjectCandidate
2287 | BuiltinUnsizeCandidate
2288 | BuiltinCandidate { .. }
2289 | TraitAliasCandidate(..) => {
2290 // Global bounds from the where clause should be ignored
2291 // here (see issue #50825). Otherwise, we have a where
2292 // clause so don't go around looking for impls.
2295 ObjectCandidate | ProjectionCandidate => {
2296 // Arbitrarily give param candidates priority
2297 // over projection and object candidates.
2300 ParamCandidate(..) => false,
2302 ObjectCandidate | ProjectionCandidate => match victim.candidate {
2303 AutoImplCandidate(..) => {
2305 "default implementations shouldn't be recorded \
2306 when there are other valid candidates"
2309 // Prefer `BuiltinCandidate { has_nested: false }` to anything else.
2310 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2311 // lifetime of a variable.
2312 BuiltinCandidate { has_nested: false } => false,
2315 | GeneratorCandidate
2316 | FnPointerCandidate
2317 | BuiltinObjectCandidate
2318 | BuiltinUnsizeCandidate
2319 | BuiltinCandidate { .. }
2320 | TraitAliasCandidate(..) => true,
2321 ObjectCandidate | ProjectionCandidate => {
2322 // Arbitrarily give param candidates priority
2323 // over projection and object candidates.
2326 ParamCandidate(ref cand) => is_global(cand),
2328 ImplCandidate(other_def) => {
2329 // See if we can toss out `victim` based on specialization.
2330 // This requires us to know *for sure* that the `other` impl applies
2331 // i.e., `EvaluatedToOk`.
2332 if other.evaluation.must_apply_modulo_regions() {
2333 match victim.candidate {
2334 ImplCandidate(victim_def) => {
2335 let tcx = self.tcx();
2336 return tcx.specializes((other_def, victim_def))
2338 .impls_are_allowed_to_overlap(other_def, victim_def)
2341 ParamCandidate(ref cand) => {
2342 // Prefer the impl to a global where clause candidate.
2343 return is_global(cand);
2352 | GeneratorCandidate
2353 | FnPointerCandidate
2354 | BuiltinObjectCandidate
2355 | BuiltinUnsizeCandidate
2356 | BuiltinCandidate { has_nested: true } => {
2357 match victim.candidate {
2358 ParamCandidate(ref cand) => {
2359 // Prefer these to a global where-clause bound
2360 // (see issue #50825).
2361 is_global(cand) && other.evaluation.must_apply_modulo_regions()
2370 ///////////////////////////////////////////////////////////////////////////
2373 // These cover the traits that are built-in to the language
2374 // itself: `Copy`, `Clone` and `Sized`.
2376 fn assemble_builtin_bound_candidates(
2378 conditions: BuiltinImplConditions<'tcx>,
2379 candidates: &mut SelectionCandidateSet<'tcx>,
2380 ) -> Result<(), SelectionError<'tcx>> {
2382 BuiltinImplConditions::Where(nested) => {
2383 debug!("builtin_bound: nested={:?}", nested);
2386 .push(BuiltinCandidate { has_nested: nested.skip_binder().len() > 0 });
2388 BuiltinImplConditions::None => {}
2389 BuiltinImplConditions::Ambiguous => {
2390 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2391 candidates.ambiguous = true;
2398 fn sized_conditions(
2400 obligation: &TraitObligation<'tcx>,
2401 ) -> BuiltinImplConditions<'tcx> {
2402 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2404 // NOTE: binder moved to (*)
2405 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2407 match self_ty.kind {
2408 ty::Infer(ty::IntVar(_))
2409 | ty::Infer(ty::FloatVar(_))
2420 | ty::GeneratorWitness(..)
2425 // safe for everything
2426 Where(ty::Binder::dummy(Vec::new()))
2429 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2432 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
2435 ty::Adt(def, substs) => {
2436 let sized_crit = def.sized_constraint(self.tcx());
2437 // (*) binder moved here
2438 Where(ty::Binder::bind(
2439 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect(),
2443 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2444 ty::Infer(ty::TyVar(_)) => Ambiguous,
2446 ty::UnnormalizedProjection(..)
2447 | ty::Placeholder(..)
2449 | ty::Infer(ty::FreshTy(_))
2450 | ty::Infer(ty::FreshIntTy(_))
2451 | ty::Infer(ty::FreshFloatTy(_)) => {
2452 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2457 fn copy_clone_conditions(
2459 obligation: &TraitObligation<'tcx>,
2460 ) -> BuiltinImplConditions<'tcx> {
2461 // NOTE: binder moved to (*)
2462 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2464 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2466 match self_ty.kind {
2467 ty::Infer(ty::IntVar(_))
2468 | ty::Infer(ty::FloatVar(_))
2471 | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2480 | ty::Ref(_, _, hir::Mutability::Not) => {
2481 // Implementations provided in libcore
2489 | ty::GeneratorWitness(..)
2491 | ty::Ref(_, _, hir::Mutability::Mut) => None,
2493 ty::Array(element_ty, _) => {
2494 // (*) binder moved here
2495 Where(ty::Binder::bind(vec![element_ty]))
2499 // (*) binder moved here
2500 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
2503 ty::Closure(def_id, substs) => {
2504 // (*) binder moved here
2505 Where(ty::Binder::bind(substs.as_closure().upvar_tys(def_id, self.tcx()).collect()))
2508 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2509 // Fallback to whatever user-defined impls exist in this case.
2513 ty::Infer(ty::TyVar(_)) => {
2514 // Unbound type variable. Might or might not have
2515 // applicable impls and so forth, depending on what
2516 // those type variables wind up being bound to.
2520 ty::UnnormalizedProjection(..)
2521 | ty::Placeholder(..)
2523 | ty::Infer(ty::FreshTy(_))
2524 | ty::Infer(ty::FreshIntTy(_))
2525 | ty::Infer(ty::FreshFloatTy(_)) => {
2526 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2531 /// For default impls, we need to break apart a type into its
2532 /// "constituent types" -- meaning, the types that it contains.
2534 /// Here are some (simple) examples:
2537 /// (i32, u32) -> [i32, u32]
2538 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2539 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2540 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2542 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2552 | ty::Infer(ty::IntVar(_))
2553 | ty::Infer(ty::FloatVar(_))
2555 | ty::Char => Vec::new(),
2557 ty::UnnormalizedProjection(..)
2558 | ty::Placeholder(..)
2562 | ty::Projection(..)
2564 | ty::Infer(ty::TyVar(_))
2565 | ty::Infer(ty::FreshTy(_))
2566 | ty::Infer(ty::FreshIntTy(_))
2567 | ty::Infer(ty::FreshFloatTy(_)) => {
2568 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2571 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2575 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2577 ty::Tuple(ref tys) => {
2578 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2579 tys.iter().map(|k| k.expect_ty()).collect()
2582 ty::Closure(def_id, ref substs) => {
2583 substs.as_closure().upvar_tys(def_id, self.tcx()).collect()
2586 ty::Generator(def_id, ref substs, _) => {
2587 let witness = substs.as_generator().witness(def_id, self.tcx());
2590 .upvar_tys(def_id, self.tcx())
2591 .chain(iter::once(witness))
2595 ty::GeneratorWitness(types) => {
2596 // This is sound because no regions in the witness can refer to
2597 // the binder outside the witness. So we'll effectivly reuse
2598 // the implicit binder around the witness.
2599 types.skip_binder().to_vec()
2602 // For `PhantomData<T>`, we pass `T`.
2603 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2605 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2607 ty::Opaque(def_id, substs) => {
2608 // We can resolve the `impl Trait` to its concrete type,
2609 // which enforces a DAG between the functions requiring
2610 // the auto trait bounds in question.
2611 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2616 fn collect_predicates_for_types(
2618 param_env: ty::ParamEnv<'tcx>,
2619 cause: ObligationCause<'tcx>,
2620 recursion_depth: usize,
2621 trait_def_id: DefId,
2622 types: ty::Binder<Vec<Ty<'tcx>>>,
2623 ) -> Vec<PredicateObligation<'tcx>> {
2624 // Because the types were potentially derived from
2625 // higher-ranked obligations they may reference late-bound
2626 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2627 // yield a type like `for<'a> &'a int`. In general, we
2628 // maintain the invariant that we never manipulate bound
2629 // regions, so we have to process these bound regions somehow.
2631 // The strategy is to:
2633 // 1. Instantiate those regions to placeholder regions (e.g.,
2634 // `for<'a> &'a int` becomes `&0 int`.
2635 // 2. Produce something like `&'0 int : Copy`
2636 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2643 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2645 self.infcx.commit_unconditionally(|_| {
2646 let (skol_ty, _) = self.infcx.replace_bound_vars_with_placeholders(&ty);
2647 let Normalized { value: normalized_ty, mut obligations } =
2648 project::normalize_with_depth(
2655 let skol_obligation = predicate_for_trait_def(
2664 obligations.push(skol_obligation);
2671 ///////////////////////////////////////////////////////////////////////////
2674 // Confirmation unifies the output type parameters of the trait
2675 // with the values found in the obligation, possibly yielding a
2676 // type error. See the [rustc guide] for more details.
2679 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#confirmation
2681 fn confirm_candidate(
2683 obligation: &TraitObligation<'tcx>,
2684 candidate: SelectionCandidate<'tcx>,
2685 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2686 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2689 BuiltinCandidate { has_nested } => {
2690 let data = self.confirm_builtin_candidate(obligation, has_nested);
2691 Ok(VtableBuiltin(data))
2694 ParamCandidate(param) => {
2695 let obligations = self.confirm_param_candidate(obligation, param);
2696 Ok(VtableParam(obligations))
2699 ImplCandidate(impl_def_id) => {
2700 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2703 AutoImplCandidate(trait_def_id) => {
2704 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2705 Ok(VtableAutoImpl(data))
2708 ProjectionCandidate => {
2709 self.confirm_projection_candidate(obligation);
2710 Ok(VtableParam(Vec::new()))
2713 ClosureCandidate => {
2714 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2715 Ok(VtableClosure(vtable_closure))
2718 GeneratorCandidate => {
2719 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2720 Ok(VtableGenerator(vtable_generator))
2723 FnPointerCandidate => {
2724 let data = self.confirm_fn_pointer_candidate(obligation)?;
2725 Ok(VtableFnPointer(data))
2728 TraitAliasCandidate(alias_def_id) => {
2729 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
2730 Ok(VtableTraitAlias(data))
2733 ObjectCandidate => {
2734 let data = self.confirm_object_candidate(obligation);
2735 Ok(VtableObject(data))
2738 BuiltinObjectCandidate => {
2739 // This indicates something like `Trait + Send: Send`. In this case, we know that
2740 // this holds because that's what the object type is telling us, and there's really
2741 // no additional obligations to prove and no types in particular to unify, etc.
2742 Ok(VtableParam(Vec::new()))
2745 BuiltinUnsizeCandidate => {
2746 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2747 Ok(VtableBuiltin(data))
2752 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2753 self.infcx.commit_unconditionally(|snapshot| {
2755 self.match_projection_obligation_against_definition_bounds(obligation, snapshot);
2760 fn confirm_param_candidate(
2762 obligation: &TraitObligation<'tcx>,
2763 param: ty::PolyTraitRef<'tcx>,
2764 ) -> Vec<PredicateObligation<'tcx>> {
2765 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2767 // During evaluation, we already checked that this
2768 // where-clause trait-ref could be unified with the obligation
2769 // trait-ref. Repeat that unification now without any
2770 // transactional boundary; it should not fail.
2771 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2772 Ok(obligations) => obligations,
2775 "Where clause `{:?}` was applicable to `{:?}` but now is not",
2783 fn confirm_builtin_candidate(
2785 obligation: &TraitObligation<'tcx>,
2787 ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2788 debug!("confirm_builtin_candidate({:?}, {:?})", obligation, has_nested);
2790 let lang_items = self.tcx().lang_items();
2791 let obligations = if has_nested {
2792 let trait_def = obligation.predicate.def_id();
2793 let conditions = if Some(trait_def) == lang_items.sized_trait() {
2794 self.sized_conditions(obligation)
2795 } else if Some(trait_def) == lang_items.copy_trait() {
2796 self.copy_clone_conditions(obligation)
2797 } else if Some(trait_def) == lang_items.clone_trait() {
2798 self.copy_clone_conditions(obligation)
2800 bug!("unexpected builtin trait {:?}", trait_def)
2802 let nested = match conditions {
2803 BuiltinImplConditions::Where(nested) => nested,
2804 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation),
2807 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2808 self.collect_predicates_for_types(
2809 obligation.param_env,
2811 obligation.recursion_depth + 1,
2819 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2821 VtableBuiltinData { nested: obligations }
2824 /// This handles the case where a `auto trait Foo` impl is being used.
2825 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2827 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2828 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2829 fn confirm_auto_impl_candidate(
2831 obligation: &TraitObligation<'tcx>,
2832 trait_def_id: DefId,
2833 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2834 debug!("confirm_auto_impl_candidate({:?}, {:?})", obligation, trait_def_id);
2836 let types = obligation.predicate.map_bound(|inner| {
2837 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2838 self.constituent_types_for_ty(self_ty)
2840 self.vtable_auto_impl(obligation, trait_def_id, types)
2843 /// See `confirm_auto_impl_candidate`.
2844 fn vtable_auto_impl(
2846 obligation: &TraitObligation<'tcx>,
2847 trait_def_id: DefId,
2848 nested: ty::Binder<Vec<Ty<'tcx>>>,
2849 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2850 debug!("vtable_auto_impl: nested={:?}", nested);
2852 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2853 let mut obligations = self.collect_predicates_for_types(
2854 obligation.param_env,
2856 obligation.recursion_depth + 1,
2861 let trait_obligations: Vec<PredicateObligation<'_>> =
2862 self.infcx.commit_unconditionally(|_| {
2863 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2864 let (trait_ref, _) =
2865 self.infcx.replace_bound_vars_with_placeholders(&poly_trait_ref);
2866 let cause = obligation.derived_cause(ImplDerivedObligation);
2867 self.impl_or_trait_obligations(
2869 obligation.recursion_depth + 1,
2870 obligation.param_env,
2876 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
2877 // predicate as usual. It won't have any effect since auto traits are coinductive.
2878 obligations.extend(trait_obligations);
2880 debug!("vtable_auto_impl: obligations={:?}", obligations);
2882 VtableAutoImplData { trait_def_id, nested: obligations }
2885 fn confirm_impl_candidate(
2887 obligation: &TraitObligation<'tcx>,
2889 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2890 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
2892 // First, create the substitutions by matching the impl again,
2893 // this time not in a probe.
2894 self.infcx.commit_unconditionally(|snapshot| {
2895 let substs = self.rematch_impl(impl_def_id, obligation, snapshot);
2896 debug!("confirm_impl_candidate: substs={:?}", substs);
2897 let cause = obligation.derived_cause(ImplDerivedObligation);
2902 obligation.recursion_depth + 1,
2903 obligation.param_env,
2911 mut substs: Normalized<'tcx, SubstsRef<'tcx>>,
2912 cause: ObligationCause<'tcx>,
2913 recursion_depth: usize,
2914 param_env: ty::ParamEnv<'tcx>,
2915 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
2917 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={})",
2918 impl_def_id, substs, recursion_depth,
2921 let mut impl_obligations = self.impl_or_trait_obligations(
2930 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2931 impl_def_id, impl_obligations
2934 // Because of RFC447, the impl-trait-ref and obligations
2935 // are sufficient to determine the impl substs, without
2936 // relying on projections in the impl-trait-ref.
2938 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2939 impl_obligations.append(&mut substs.obligations);
2941 VtableImplData { impl_def_id, substs: substs.value, nested: impl_obligations }
2944 fn confirm_object_candidate(
2946 obligation: &TraitObligation<'tcx>,
2947 ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
2948 debug!("confirm_object_candidate({:?})", obligation);
2950 // FIXME(nmatsakis) skipping binder here seems wrong -- we should
2951 // probably flatten the binder from the obligation and the binder
2952 // from the object. Have to try to make a broken test case that
2954 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2955 let poly_trait_ref = match self_ty.kind {
2956 ty::Dynamic(ref data, ..) => data
2958 .unwrap_or_else(|| {
2959 span_bug!(obligation.cause.span, "object candidate with no principal")
2961 .with_self_ty(self.tcx(), self_ty),
2962 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
2965 let mut upcast_trait_ref = None;
2966 let mut nested = vec![];
2970 let tcx = self.tcx();
2972 // We want to find the first supertrait in the list of
2973 // supertraits that we can unify with, and do that
2974 // unification. We know that there is exactly one in the list
2975 // where we can unify, because otherwise select would have
2976 // reported an ambiguity. (When we do find a match, also
2977 // record it for later.)
2978 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(|&t| {
2979 match self.infcx.commit_if_ok(|_| self.match_poly_trait_ref(obligation, t)) {
2980 Ok(obligations) => {
2981 upcast_trait_ref = Some(t);
2982 nested.extend(obligations);
2989 // Additionally, for each of the non-matching predicates that
2990 // we pass over, we sum up the set of number of vtable
2991 // entries, so that we can compute the offset for the selected
2993 vtable_base = nonmatching.map(|t| super::util::count_own_vtable_entries(tcx, t)).sum();
2996 VtableObjectData { upcast_trait_ref: upcast_trait_ref.unwrap(), vtable_base, nested }
2999 fn confirm_fn_pointer_candidate(
3001 obligation: &TraitObligation<'tcx>,
3002 ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3003 debug!("confirm_fn_pointer_candidate({:?})", obligation);
3005 // Okay to skip binder; it is reintroduced below.
3006 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3007 let sig = self_ty.fn_sig(self.tcx());
3008 let trait_ref = closure_trait_ref_and_return_type(
3010 obligation.predicate.def_id(),
3013 util::TupleArgumentsFlag::Yes,
3015 .map_bound(|(trait_ref, _)| trait_ref);
3017 let Normalized { value: trait_ref, obligations } = project::normalize_with_depth(
3019 obligation.param_env,
3020 obligation.cause.clone(),
3021 obligation.recursion_depth + 1,
3025 self.confirm_poly_trait_refs(
3026 obligation.cause.clone(),
3027 obligation.param_env,
3028 obligation.predicate.to_poly_trait_ref(),
3031 Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
3034 fn confirm_trait_alias_candidate(
3036 obligation: &TraitObligation<'tcx>,
3037 alias_def_id: DefId,
3038 ) -> VtableTraitAliasData<'tcx, PredicateObligation<'tcx>> {
3039 debug!("confirm_trait_alias_candidate({:?}, {:?})", obligation, alias_def_id);
3041 self.infcx.commit_unconditionally(|_| {
3042 let (predicate, _) =
3043 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
3044 let trait_ref = predicate.trait_ref;
3045 let trait_def_id = trait_ref.def_id;
3046 let substs = trait_ref.substs;
3048 let trait_obligations = self.impl_or_trait_obligations(
3049 obligation.cause.clone(),
3050 obligation.recursion_depth,
3051 obligation.param_env,
3057 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
3058 trait_def_id, trait_obligations
3061 VtableTraitAliasData { alias_def_id, substs: substs, nested: trait_obligations }
3065 fn confirm_generator_candidate(
3067 obligation: &TraitObligation<'tcx>,
3068 ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3069 // Okay to skip binder because the substs on generator types never
3070 // touch bound regions, they just capture the in-scope
3071 // type/region parameters.
3072 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3073 let (generator_def_id, substs) = match self_ty.kind {
3074 ty::Generator(id, substs, _) => (id, substs),
3075 _ => bug!("closure candidate for non-closure {:?}", obligation),
3078 debug!("confirm_generator_candidate({:?},{:?},{:?})", obligation, generator_def_id, substs);
3080 let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
3081 let Normalized { value: trait_ref, mut obligations } = normalize_with_depth(
3083 obligation.param_env,
3084 obligation.cause.clone(),
3085 obligation.recursion_depth + 1,
3090 "confirm_generator_candidate(generator_def_id={:?}, \
3091 trait_ref={:?}, obligations={:?})",
3092 generator_def_id, trait_ref, obligations
3095 obligations.extend(self.confirm_poly_trait_refs(
3096 obligation.cause.clone(),
3097 obligation.param_env,
3098 obligation.predicate.to_poly_trait_ref(),
3102 Ok(VtableGeneratorData { generator_def_id, substs, nested: obligations })
3105 fn confirm_closure_candidate(
3107 obligation: &TraitObligation<'tcx>,
3108 ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3109 debug!("confirm_closure_candidate({:?})", obligation);
3114 .fn_trait_kind(obligation.predicate.def_id())
3115 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
3117 // Okay to skip binder because the substs on closure types never
3118 // touch bound regions, they just capture the in-scope
3119 // type/region parameters.
3120 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3121 let (closure_def_id, substs) = match self_ty.kind {
3122 ty::Closure(id, substs) => (id, substs),
3123 _ => bug!("closure candidate for non-closure {:?}", obligation),
3126 let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
3127 let Normalized { value: trait_ref, mut obligations } = normalize_with_depth(
3129 obligation.param_env,
3130 obligation.cause.clone(),
3131 obligation.recursion_depth + 1,
3136 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
3137 closure_def_id, trait_ref, obligations
3140 obligations.extend(self.confirm_poly_trait_refs(
3141 obligation.cause.clone(),
3142 obligation.param_env,
3143 obligation.predicate.to_poly_trait_ref(),
3149 if !self.tcx().sess.opts.debugging_opts.chalk {
3150 obligations.push(Obligation::new(
3151 obligation.cause.clone(),
3152 obligation.param_env,
3153 ty::Predicate::ClosureKind(closure_def_id, substs, kind),
3157 Ok(VtableClosureData { closure_def_id, substs: substs, nested: obligations })
3160 /// In the case of closure types and fn pointers,
3161 /// we currently treat the input type parameters on the trait as
3162 /// outputs. This means that when we have a match we have only
3163 /// considered the self type, so we have to go back and make sure
3164 /// to relate the argument types too. This is kind of wrong, but
3165 /// since we control the full set of impls, also not that wrong,
3166 /// and it DOES yield better error messages (since we don't report
3167 /// errors as if there is no applicable impl, but rather report
3168 /// errors are about mismatched argument types.
3170 /// Here is an example. Imagine we have a closure expression
3171 /// and we desugared it so that the type of the expression is
3172 /// `Closure`, and `Closure` expects an int as argument. Then it
3173 /// is "as if" the compiler generated this impl:
3175 /// impl Fn(int) for Closure { ... }
3177 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
3178 /// we have matched the self type `Closure`. At this point we'll
3179 /// compare the `int` to `usize` and generate an error.
3181 /// Note that this checking occurs *after* the impl has selected,
3182 /// because these output type parameters should not affect the
3183 /// selection of the impl. Therefore, if there is a mismatch, we
3184 /// report an error to the user.
3185 fn confirm_poly_trait_refs(
3187 obligation_cause: ObligationCause<'tcx>,
3188 obligation_param_env: ty::ParamEnv<'tcx>,
3189 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
3190 expected_trait_ref: ty::PolyTraitRef<'tcx>,
3191 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3192 let obligation_trait_ref = obligation_trait_ref.clone();
3194 .at(&obligation_cause, obligation_param_env)
3195 .sup(obligation_trait_ref, expected_trait_ref)
3196 .map(|InferOk { obligations, .. }| obligations)
3197 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
3200 fn confirm_builtin_unsize_candidate(
3202 obligation: &TraitObligation<'tcx>,
3203 ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3204 let tcx = self.tcx();
3206 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
3207 // regions here. See the comment there for more details.
3208 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
3209 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
3210 let target = self.infcx.shallow_resolve(target);
3212 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})", source, target);
3214 let mut nested = vec![];
3215 match (&source.kind, &target.kind) {
3216 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
3217 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
3218 // See `assemble_candidates_for_unsizing` for more info.
3219 let existential_predicates = data_a.map_bound(|data_a| {
3222 .map(|x| ty::ExistentialPredicate::Trait(x))
3226 .projection_bounds()
3227 .map(|x| ty::ExistentialPredicate::Projection(x)),
3229 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
3230 tcx.mk_existential_predicates(iter)
3232 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
3234 // Require that the traits involved in this upcast are **equal**;
3235 // only the **lifetime bound** is changed.
3237 // FIXME: This condition is arguably too strong -- it would
3238 // suffice for the source trait to be a *subtype* of the target
3239 // trait. In particular, changing from something like
3240 // `for<'a, 'b> Foo<'a, 'b>` to `for<'a> Foo<'a, 'a>` should be
3241 // permitted. And, indeed, in the in commit
3242 // 904a0bde93f0348f69914ee90b1f8b6e4e0d7cbc, this
3243 // condition was loosened. However, when the leak check was
3244 // added back, using subtype here actually guides the coercion
3245 // code in such a way that it accepts `old-lub-glb-object.rs`.
3246 // This is probably a good thing, but I've modified this to `.eq`
3247 // because I want to continue rejecting that test (as we have
3248 // done for quite some time) before we are firmly comfortable
3249 // with what our behavior should be there. -nikomatsakis
3250 let InferOk { obligations, .. } = self
3252 .at(&obligation.cause, obligation.param_env)
3253 .eq(target, source_trait) // FIXME -- see below
3254 .map_err(|_| Unimplemented)?;
3255 nested.extend(obligations);
3257 // Register one obligation for 'a: 'b.
3258 let cause = ObligationCause::new(
3259 obligation.cause.span,
3260 obligation.cause.body_id,
3261 ObjectCastObligation(target),
3263 let outlives = ty::OutlivesPredicate(r_a, r_b);
3264 nested.push(Obligation::with_depth(
3266 obligation.recursion_depth + 1,
3267 obligation.param_env,
3268 ty::Binder::bind(outlives).to_predicate(),
3273 (_, &ty::Dynamic(ref data, r)) => {
3274 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
3275 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3276 return Err(TraitNotObjectSafe(did));
3279 let cause = ObligationCause::new(
3280 obligation.cause.span,
3281 obligation.cause.body_id,
3282 ObjectCastObligation(target),
3285 let predicate_to_obligation = |predicate| {
3286 Obligation::with_depth(
3288 obligation.recursion_depth + 1,
3289 obligation.param_env,
3294 // Create obligations:
3295 // - Casting `T` to `Trait`
3296 // - For all the various builtin bounds attached to the object cast. (In other
3297 // words, if the object type is `Foo + Send`, this would create an obligation for
3298 // the `Send` check.)
3299 // - Projection predicates
3301 data.iter().map(|predicate| {
3302 predicate_to_obligation(predicate.with_self_ty(tcx, source))
3306 // We can only make objects from sized types.
3307 let tr = ty::TraitRef::new(
3308 tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
3309 tcx.mk_substs_trait(source, &[]),
3311 nested.push(predicate_to_obligation(tr.to_predicate()));
3313 // If the type is `Foo + 'a`, ensure that the type
3314 // being cast to `Foo + 'a` outlives `'a`:
3315 let outlives = ty::OutlivesPredicate(source, r);
3316 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate()));
3319 // `[T; n]` -> `[T]`
3320 (&ty::Array(a, _), &ty::Slice(b)) => {
3321 let InferOk { obligations, .. } = self
3323 .at(&obligation.cause, obligation.param_env)
3325 .map_err(|_| Unimplemented)?;
3326 nested.extend(obligations);
3329 // `Struct<T>` -> `Struct<U>`
3330 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3332 def.all_fields().map(|field| tcx.type_of(field.did)).collect::<Vec<_>>();
3334 // The last field of the structure has to exist and contain type parameters.
3335 let field = if let Some(&field) = fields.last() {
3338 return Err(Unimplemented);
3340 let mut ty_params = GrowableBitSet::new_empty();
3341 let mut found = false;
3342 for ty in field.walk() {
3343 if let ty::Param(p) = ty.kind {
3344 ty_params.insert(p.index as usize);
3349 return Err(Unimplemented);
3352 // Replace type parameters used in unsizing with
3353 // Error and ensure they do not affect any other fields.
3354 // This could be checked after type collection for any struct
3355 // with a potentially unsized trailing field.
3356 let params = substs_a
3359 .map(|(i, &k)| if ty_params.contains(i) { tcx.types.err.into() } else { k });
3360 let substs = tcx.mk_substs(params);
3361 for &ty in fields.split_last().unwrap().1 {
3362 if ty.subst(tcx, substs).references_error() {
3363 return Err(Unimplemented);
3367 // Extract `Field<T>` and `Field<U>` from `Struct<T>` and `Struct<U>`.
3368 let inner_source = field.subst(tcx, substs_a);
3369 let inner_target = field.subst(tcx, substs_b);
3371 // Check that the source struct with the target's
3372 // unsized parameters is equal to the target.
3373 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3374 if ty_params.contains(i) { substs_b.type_at(i).into() } else { k }
3376 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3377 let InferOk { obligations, .. } = self
3379 .at(&obligation.cause, obligation.param_env)
3380 .eq(target, new_struct)
3381 .map_err(|_| Unimplemented)?;
3382 nested.extend(obligations);
3384 // Construct the nested `Field<T>: Unsize<Field<U>>` predicate.
3385 nested.push(predicate_for_trait_def(
3387 obligation.param_env,
3388 obligation.cause.clone(),
3389 obligation.predicate.def_id(),
3390 obligation.recursion_depth + 1,
3392 &[inner_target.into()],
3396 // `(.., T)` -> `(.., U)`
3397 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3398 assert_eq!(tys_a.len(), tys_b.len());
3400 // The last field of the tuple has to exist.
3401 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3404 return Err(Unimplemented);
3406 let &b_last = tys_b.last().unwrap();
3408 // Check that the source tuple with the target's
3409 // last element is equal to the target.
3410 let new_tuple = tcx.mk_tup(
3411 a_mid.iter().map(|k| k.expect_ty()).chain(iter::once(b_last.expect_ty())),
3413 let InferOk { obligations, .. } = self
3415 .at(&obligation.cause, obligation.param_env)
3416 .eq(target, new_tuple)
3417 .map_err(|_| Unimplemented)?;
3418 nested.extend(obligations);
3420 // Construct the nested `T: Unsize<U>` predicate.
3421 nested.push(predicate_for_trait_def(
3423 obligation.param_env,
3424 obligation.cause.clone(),
3425 obligation.predicate.def_id(),
3426 obligation.recursion_depth + 1,
3435 Ok(VtableBuiltinData { nested })
3438 ///////////////////////////////////////////////////////////////////////////
3441 // Matching is a common path used for both evaluation and
3442 // confirmation. It basically unifies types that appear in impls
3443 // and traits. This does affect the surrounding environment;
3444 // therefore, when used during evaluation, match routines must be
3445 // run inside of a `probe()` so that their side-effects are
3451 obligation: &TraitObligation<'tcx>,
3452 snapshot: &CombinedSnapshot<'_, 'tcx>,
3453 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
3454 match self.match_impl(impl_def_id, obligation, snapshot) {
3455 Ok(substs) => substs,
3458 "Impl {:?} was matchable against {:?} but now is not",
3469 obligation: &TraitObligation<'tcx>,
3470 snapshot: &CombinedSnapshot<'_, 'tcx>,
3471 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
3472 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3474 // Before we create the substitutions and everything, first
3475 // consider a "quick reject". This avoids creating more types
3476 // and so forth that we need to.
3477 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3481 let (skol_obligation, placeholder_map) =
3482 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
3483 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3485 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
3487 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3489 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
3490 project::normalize_with_depth(
3492 obligation.param_env,
3493 obligation.cause.clone(),
3494 obligation.recursion_depth + 1,
3499 "match_impl(impl_def_id={:?}, obligation={:?}, \
3500 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3501 impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3504 let InferOk { obligations, .. } = self
3506 .at(&obligation.cause, obligation.param_env)
3507 .eq(skol_obligation_trait_ref, impl_trait_ref)
3508 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3509 nested_obligations.extend(obligations);
3511 if let Err(e) = self.infcx.leak_check(false, &placeholder_map, snapshot) {
3512 debug!("match_impl: failed leak check due to `{}`", e);
3516 if self.intercrate.is_none()
3517 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
3519 debug!("match_impl: reservation impls only apply in intercrate mode");
3523 debug!("match_impl: success impl_substs={:?}", impl_substs);
3524 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
3527 fn fast_reject_trait_refs(
3529 obligation: &TraitObligation<'_>,
3530 impl_trait_ref: &ty::TraitRef<'_>,
3532 // We can avoid creating type variables and doing the full
3533 // substitution if we find that any of the input types, when
3534 // simplified, do not match.
3536 obligation.predicate.skip_binder().input_types().zip(impl_trait_ref.input_types()).any(
3537 |(obligation_ty, impl_ty)| {
3538 let simplified_obligation_ty =
3539 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3540 let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
3542 simplified_obligation_ty.is_some()
3543 && simplified_impl_ty.is_some()
3544 && simplified_obligation_ty != simplified_impl_ty
3549 /// Normalize `where_clause_trait_ref` and try to match it against
3550 /// `obligation`. If successful, return any predicates that
3551 /// result from the normalization. Normalization is necessary
3552 /// because where-clauses are stored in the parameter environment
3554 fn match_where_clause_trait_ref(
3556 obligation: &TraitObligation<'tcx>,
3557 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3558 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3559 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3562 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3563 /// obligation is satisfied.
3564 fn match_poly_trait_ref(
3566 obligation: &TraitObligation<'tcx>,
3567 poly_trait_ref: ty::PolyTraitRef<'tcx>,
3568 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3570 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3571 obligation, poly_trait_ref
3575 .at(&obligation.cause, obligation.param_env)
3576 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3577 .map(|InferOk { obligations, .. }| obligations)
3581 ///////////////////////////////////////////////////////////////////////////
3584 fn match_fresh_trait_refs(
3586 previous: &ty::PolyTraitRef<'tcx>,
3587 current: &ty::PolyTraitRef<'tcx>,
3588 param_env: ty::ParamEnv<'tcx>,
3590 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
3591 matcher.relate(previous, current).is_ok()
3596 previous_stack: TraitObligationStackList<'o, 'tcx>,
3597 obligation: &'o TraitObligation<'tcx>,
3598 ) -> TraitObligationStack<'o, 'tcx> {
3599 let fresh_trait_ref =
3600 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
3602 let dfn = previous_stack.cache.next_dfn();
3603 let depth = previous_stack.depth() + 1;
3604 TraitObligationStack {
3607 reached_depth: Cell::new(depth),
3608 previous: previous_stack,
3614 fn closure_trait_ref_unnormalized(
3616 obligation: &TraitObligation<'tcx>,
3617 closure_def_id: DefId,
3618 substs: SubstsRef<'tcx>,
3619 ) -> ty::PolyTraitRef<'tcx> {
3621 "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})",
3622 obligation, closure_def_id, substs,
3624 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3626 debug!("closure_trait_ref_unnormalized: closure_type = {:?}", closure_type);
3628 // (1) Feels icky to skip the binder here, but OTOH we know
3629 // that the self-type is an unboxed closure type and hence is
3630 // in fact unparameterized (or at least does not reference any
3631 // regions bound in the obligation). Still probably some
3632 // refactoring could make this nicer.
3633 closure_trait_ref_and_return_type(
3635 obligation.predicate.def_id(),
3636 obligation.predicate.skip_binder().self_ty(), // (1)
3638 util::TupleArgumentsFlag::No,
3640 .map_bound(|(trait_ref, _)| trait_ref)
3643 fn generator_trait_ref_unnormalized(
3645 obligation: &TraitObligation<'tcx>,
3646 closure_def_id: DefId,
3647 substs: SubstsRef<'tcx>,
3648 ) -> ty::PolyTraitRef<'tcx> {
3649 let gen_sig = substs.as_generator().poly_sig(closure_def_id, self.tcx());
3651 // (1) Feels icky to skip the binder here, but OTOH we know
3652 // that the self-type is an generator type and hence is
3653 // in fact unparameterized (or at least does not reference any
3654 // regions bound in the obligation). Still probably some
3655 // refactoring could make this nicer.
3657 super::util::generator_trait_ref_and_outputs(
3659 obligation.predicate.def_id(),
3660 obligation.predicate.skip_binder().self_ty(), // (1)
3663 .map_bound(|(trait_ref, ..)| trait_ref)
3666 /// Returns the obligations that are implied by instantiating an
3667 /// impl or trait. The obligations are substituted and fully
3668 /// normalized. This is used when confirming an impl or default
3670 fn impl_or_trait_obligations(
3672 cause: ObligationCause<'tcx>,
3673 recursion_depth: usize,
3674 param_env: ty::ParamEnv<'tcx>,
3675 def_id: DefId, // of impl or trait
3676 substs: SubstsRef<'tcx>, // for impl or trait
3677 ) -> Vec<PredicateObligation<'tcx>> {
3678 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3679 let tcx = self.tcx();
3681 // To allow for one-pass evaluation of the nested obligation,
3682 // each predicate must be preceded by the obligations required
3684 // for example, if we have:
3685 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
3686 // the impl will have the following predicates:
3687 // <V as Iterator>::Item = U,
3688 // U: Iterator, U: Sized,
3689 // V: Iterator, V: Sized,
3690 // <U as Iterator>::Item: Copy
3691 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3692 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3693 // `$1: Copy`, so we must ensure the obligations are emitted in
3695 let predicates = tcx.predicates_of(def_id);
3696 assert_eq!(predicates.parent, None);
3697 let mut predicates: Vec<_> = predicates
3700 .flat_map(|(predicate, _)| {
3701 let predicate = normalize_with_depth(
3706 &predicate.subst(tcx, substs),
3708 predicate.obligations.into_iter().chain(Some(Obligation {
3709 cause: cause.clone(),
3712 predicate: predicate.value,
3717 // We are performing deduplication here to avoid exponential blowups
3718 // (#38528) from happening, but the real cause of the duplication is
3719 // unknown. What we know is that the deduplication avoids exponential
3720 // amount of predicates being propagated when processing deeply nested
3723 // This code is hot enough that it's worth avoiding the allocation
3724 // required for the FxHashSet when possible. Special-casing lengths 0,
3725 // 1 and 2 covers roughly 75-80% of the cases.
3726 if predicates.len() <= 1 {
3727 // No possibility of duplicates.
3728 } else if predicates.len() == 2 {
3729 // Only two elements. Drop the second if they are equal.
3730 if predicates[0] == predicates[1] {
3731 predicates.truncate(1);
3734 // Three or more elements. Use a general deduplication process.
3735 let mut seen = FxHashSet::default();
3736 predicates.retain(|i| seen.insert(i.clone()));
3743 impl<'tcx> TraitObligation<'tcx> {
3744 #[allow(unused_comparisons)]
3745 pub fn derived_cause(
3747 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3748 ) -> ObligationCause<'tcx> {
3750 * Creates a cause for obligations that are derived from
3751 * `obligation` by a recursive search (e.g., for a builtin
3752 * bound, or eventually a `auto trait Foo`). If `obligation`
3753 * is itself a derived obligation, this is just a clone, but
3754 * otherwise we create a "derived obligation" cause so as to
3755 * keep track of the original root obligation for error
3759 let obligation = self;
3761 // NOTE(flaper87): As of now, it keeps track of the whole error
3762 // chain. Ideally, we should have a way to configure this either
3763 // by using -Z verbose or just a CLI argument.
3764 if obligation.recursion_depth >= 0 {
3765 let derived_cause = DerivedObligationCause {
3766 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3767 parent_code: Rc::new(obligation.cause.code.clone()),
3769 let derived_code = variant(derived_cause);
3770 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3772 obligation.cause.clone()
3777 impl<'tcx> SelectionCache<'tcx> {
3778 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
3779 pub fn clear(&self) {
3780 *self.hashmap.borrow_mut() = Default::default();
3784 impl<'tcx> EvaluationCache<'tcx> {
3785 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
3786 pub fn clear(&self) {
3787 *self.hashmap.borrow_mut() = Default::default();
3791 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
3792 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3793 TraitObligationStackList::with(self)
3796 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
3800 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
3804 /// Indicates that attempting to evaluate this stack entry
3805 /// required accessing something from the stack at depth `reached_depth`.
3806 fn update_reached_depth(&self, reached_depth: usize) {
3808 self.depth > reached_depth,
3809 "invoked `update_reached_depth` with something under this stack: \
3810 self.depth={} reached_depth={}",
3814 debug!("update_reached_depth(reached_depth={})", reached_depth);
3816 while reached_depth < p.depth {
3817 debug!("update_reached_depth: marking {:?} as cycle participant", p.fresh_trait_ref);
3818 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
3819 p = p.previous.head.unwrap();
3824 /// The "provisional evaluation cache" is used to store intermediate cache results
3825 /// when solving auto traits. Auto traits are unusual in that they can support
3826 /// cycles. So, for example, a "proof tree" like this would be ok:
3828 /// - `Foo<T>: Send` :-
3829 /// - `Bar<T>: Send` :-
3830 /// - `Foo<T>: Send` -- cycle, but ok
3831 /// - `Baz<T>: Send`
3833 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
3834 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
3835 /// For non-auto traits, this cycle would be an error, but for auto traits (because
3836 /// they are coinductive) it is considered ok.
3838 /// However, there is a complication: at the point where we have
3839 /// "proven" `Bar<T>: Send`, we have in fact only proven it
3840 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
3841 /// *under the assumption* that `Foo<T>: Send`. But what if we later
3842 /// find out this assumption is wrong? Specifically, we could
3843 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
3844 /// `Bar<T>: Send` didn't turn out to be true.
3846 /// In Issue #60010, we found a bug in rustc where it would cache
3847 /// these intermediate results. This was fixed in #60444 by disabling
3848 /// *all* caching for things involved in a cycle -- in our example,
3849 /// that would mean we don't cache that `Bar<T>: Send`. But this led
3850 /// to large slowdowns.
3852 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
3853 /// first requires proving `Bar<T>: Send` (which is true:
3855 /// - `Foo<T>: Send` :-
3856 /// - `Bar<T>: Send` :-
3857 /// - `Foo<T>: Send` -- cycle, but ok
3858 /// - `Baz<T>: Send`
3859 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
3860 /// - `*const T: Send` -- but what if we later encounter an error?
3862 /// The *provisional evaluation cache* resolves this issue. It stores
3863 /// cache results that we've proven but which were involved in a cycle
3864 /// in some way. We track the minimal stack depth (i.e., the
3865 /// farthest from the top of the stack) that we are dependent on.
3866 /// The idea is that the cache results within are all valid -- so long as
3867 /// none of the nodes in between the current node and the node at that minimum
3868 /// depth result in an error (in which case the cached results are just thrown away).
3870 /// During evaluation, we consult this provisional cache and rely on
3871 /// it. Accessing a cached value is considered equivalent to accessing
3872 /// a result at `reached_depth`, so it marks the *current* solution as
3873 /// provisional as well. If an error is encountered, we toss out any
3874 /// provisional results added from the subtree that encountered the
3875 /// error. When we pop the node at `reached_depth` from the stack, we
3876 /// can commit all the things that remain in the provisional cache.
3877 struct ProvisionalEvaluationCache<'tcx> {
3878 /// next "depth first number" to issue -- just a counter
3881 /// Stores the "coldest" depth (bottom of stack) reached by any of
3882 /// the evaluation entries. The idea here is that all things in the provisional
3883 /// cache are always dependent on *something* that is colder in the stack:
3884 /// therefore, if we add a new entry that is dependent on something *colder still*,
3885 /// we have to modify the depth for all entries at once.
3889 /// Imagine we have a stack `A B C D E` (with `E` being the top of
3890 /// the stack). We cache something with depth 2, which means that
3891 /// it was dependent on C. Then we pop E but go on and process a
3892 /// new node F: A B C D F. Now F adds something to the cache with
3893 /// depth 1, meaning it is dependent on B. Our original cache
3894 /// entry is also dependent on B, because there is a path from E
3895 /// to C and then from C to F and from F to B.
3896 reached_depth: Cell<usize>,
3898 /// Map from cache key to the provisionally evaluated thing.
3899 /// The cache entries contain the result but also the DFN in which they
3900 /// were added. The DFN is used to clear out values on failure.
3902 /// Imagine we have a stack like:
3904 /// - `A B C` and we add a cache for the result of C (DFN 2)
3905 /// - Then we have a stack `A B D` where `D` has DFN 3
3906 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
3907 /// - `E` generates various cache entries which have cyclic dependices on `B`
3908 /// - `A B D E F` and so forth
3909 /// - the DFN of `F` for example would be 5
3910 /// - then we determine that `E` is in error -- we will then clear
3911 /// all cache values whose DFN is >= 4 -- in this case, that
3912 /// means the cached value for `F`.
3913 map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
3916 /// A cache value for the provisional cache: contains the depth-first
3917 /// number (DFN) and result.
3918 #[derive(Copy, Clone, Debug)]
3919 struct ProvisionalEvaluation {
3921 result: EvaluationResult,
3924 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
3925 fn default() -> Self {
3928 reached_depth: Cell::new(std::usize::MAX),
3929 map: Default::default(),
3934 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
3935 /// Get the next DFN in sequence (basically a counter).
3936 fn next_dfn(&self) -> usize {
3937 let result = self.dfn.get();
3938 self.dfn.set(result + 1);
3942 /// Check the provisional cache for any result for
3943 /// `fresh_trait_ref`. If there is a hit, then you must consider
3944 /// it an access to the stack slots at depth
3945 /// `self.current_reached_depth()` and above.
3946 fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
3948 "get_provisional(fresh_trait_ref={:?}) = {:#?} with reached-depth {}",
3950 self.map.borrow().get(&fresh_trait_ref),
3951 self.reached_depth.get(),
3953 Some(self.map.borrow().get(&fresh_trait_ref)?.result)
3956 /// Current value of the `reached_depth` counter -- all the
3957 /// provisional cache entries are dependent on the item at this
3959 fn current_reached_depth(&self) -> usize {
3960 self.reached_depth.get()
3963 /// Insert a provisional result into the cache. The result came
3964 /// from the node with the given DFN. It accessed a minimum depth
3965 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
3966 /// and resulted in `result`.
3967 fn insert_provisional(
3970 reached_depth: usize,
3971 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
3972 result: EvaluationResult,
3975 "insert_provisional(from_dfn={}, reached_depth={}, fresh_trait_ref={:?}, result={:?})",
3976 from_dfn, reached_depth, fresh_trait_ref, result,
3978 let r_d = self.reached_depth.get();
3979 self.reached_depth.set(r_d.min(reached_depth));
3981 debug!("insert_provisional: reached_depth={:?}", self.reached_depth.get());
3983 self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
3986 /// Invoked when the node with dfn `dfn` does not get a successful
3987 /// result. This will clear out any provisional cache entries
3988 /// that were added since `dfn` was created. This is because the
3989 /// provisional entries are things which must assume that the
3990 /// things on the stack at the time of their creation succeeded --
3991 /// since the failing node is presently at the top of the stack,
3992 /// these provisional entries must either depend on it or some
3994 fn on_failure(&self, dfn: usize) {
3995 debug!("on_failure(dfn={:?})", dfn,);
3996 self.map.borrow_mut().retain(|key, eval| {
3997 if !eval.from_dfn >= dfn {
3998 debug!("on_failure: removing {:?}", key);
4006 /// Invoked when the node at depth `depth` completed without
4007 /// depending on anything higher in the stack (if that completion
4008 /// was a failure, then `on_failure` should have been invoked
4009 /// already). The callback `op` will be invoked for each
4010 /// provisional entry that we can now confirm.
4014 mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
4016 debug!("on_completion(depth={}, reached_depth={})", depth, self.reached_depth.get(),);
4018 if self.reached_depth.get() < depth {
4019 debug!("on_completion: did not yet reach depth to complete");
4023 for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
4024 debug!("on_completion: fresh_trait_ref={:?} eval={:?}", fresh_trait_ref, eval,);
4026 op(fresh_trait_ref, eval.result);
4029 self.reached_depth.set(std::usize::MAX);
4033 #[derive(Copy, Clone)]
4034 struct TraitObligationStackList<'o, 'tcx> {
4035 cache: &'o ProvisionalEvaluationCache<'tcx>,
4036 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
4039 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
4040 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4041 TraitObligationStackList { cache, head: None }
4044 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4045 TraitObligationStackList { cache: r.cache(), head: Some(r) }
4048 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4052 fn depth(&self) -> usize {
4053 if let Some(head) = self.head { head.depth } else { 0 }
4057 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
4058 type Item = &'o TraitObligationStack<'o, 'tcx>;
4060 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4071 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
4072 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4073 write!(f, "TraitObligationStack({:?})", self.obligation)
4077 #[derive(Clone, Eq, PartialEq)]
4078 pub struct WithDepNode<T> {
4079 dep_node: DepNodeIndex,
4083 impl<T: Clone> WithDepNode<T> {
4084 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
4085 WithDepNode { dep_node, cached_value }
4088 pub fn get(&self, tcx: TyCtxt<'_>) -> T {
4089 tcx.dep_graph.read_index(self.dep_node);
4090 self.cached_value.clone()