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::DerivedObligationCause;
16 use super::SelectionResult;
17 use super::TraitNotObjectSafe;
18 use super::{BuiltinDerivedObligation, ImplDerivedObligation, ObligationCauseCode};
19 use super::{IntercrateMode, TraitQueryMode};
20 use super::{ObjectCastObligation, Obligation};
21 use super::{ObligationCause, PredicateObligation, TraitObligation};
22 use super::{OutputTypeParameterMismatch, Overflow, SelectionError, Unimplemented};
24 VtableAutoImpl, VtableBuiltin, VtableClosure, VtableFnPointer, VtableGenerator, VtableImpl,
25 VtableObject, VtableParam, VtableTraitAlias,
28 VtableAutoImplData, VtableBuiltinData, VtableClosureData, VtableFnPointerData,
29 VtableGeneratorData, VtableImplData, VtableObjectData, VtableTraitAliasData,
32 use crate::dep_graph::{DepKind, DepNodeIndex};
33 use crate::hir::def_id::DefId;
34 use crate::infer::{CombinedSnapshot, InferCtxt, InferOk, PlaceholderMap, TypeFreshener};
35 use crate::middle::lang_items;
36 use crate::mir::interpret::GlobalId;
37 use crate::ty::fast_reject;
38 use crate::ty::relate::TypeRelation;
39 use crate::ty::subst::{Subst, SubstsRef};
40 use crate::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
43 use rustc_data_structures::bit_set::GrowableBitSet;
44 use rustc_data_structures::sync::Lock;
45 use rustc_target::spec::abi::Abi;
46 use std::cell::{Cell, RefCell};
48 use std::fmt::{self, Display};
51 use crate::util::nodemap::{FxHashMap, FxHashSet};
53 pub struct SelectionContext<'cx, 'tcx> {
54 infcx: &'cx InferCtxt<'cx, 'tcx>,
56 /// Freshener used specifically for entries on the obligation
57 /// stack. This ensures that all entries on the stack at one time
58 /// will have the same set of placeholder entries, which is
59 /// important for checking for trait bounds that recursively
60 /// require themselves.
61 freshener: TypeFreshener<'cx, 'tcx>,
63 /// If `true`, indicates that the evaluation should be conservative
64 /// and consider the possibility of types outside this crate.
65 /// This comes up primarily when resolving ambiguity. Imagine
66 /// there is some trait reference `$0: Bar` where `$0` is an
67 /// inference variable. If `intercrate` is true, then we can never
68 /// say for sure that this reference is not implemented, even if
69 /// there are *no impls at all for `Bar`*, because `$0` could be
70 /// bound to some type that in a downstream crate that implements
71 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
72 /// though, we set this to false, because we are only interested
73 /// in types that the user could actually have written --- in
74 /// other words, we consider `$0: Bar` to be unimplemented if
75 /// there is no type that the user could *actually name* that
76 /// would satisfy it. This avoids crippling inference, basically.
77 intercrate: Option<IntercrateMode>,
79 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
81 /// Controls whether or not to filter out negative impls when selecting.
82 /// This is used in librustdoc to distinguish between the lack of an impl
83 /// and a negative impl
84 allow_negative_impls: bool,
86 /// The mode that trait queries run in, which informs our error handling
87 /// policy. In essence, canonicalized queries need their errors propagated
88 /// rather than immediately reported because we do not have accurate spans.
89 query_mode: TraitQueryMode,
92 #[derive(Clone, Debug)]
93 pub enum IntercrateAmbiguityCause {
96 self_desc: Option<String>,
100 self_desc: Option<String>,
104 impl IntercrateAmbiguityCause {
105 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
106 /// See #23980 for details.
107 pub fn add_intercrate_ambiguity_hint(&self, err: &mut errors::DiagnosticBuilder<'_>) {
108 err.note(&self.intercrate_ambiguity_hint());
111 pub fn intercrate_ambiguity_hint(&self) -> String {
113 &IntercrateAmbiguityCause::DownstreamCrate {
117 let self_desc = if let &Some(ref ty) = self_desc {
118 format!(" for type `{}`", ty)
123 "downstream crates may implement trait `{}`{}",
124 trait_desc, self_desc
127 &IntercrateAmbiguityCause::UpstreamCrateUpdate {
131 let self_desc = if let &Some(ref ty) = self_desc {
132 format!(" for type `{}`", ty)
137 "upstream crates may add new impl of trait `{}`{} \
139 trait_desc, self_desc
146 // A stack that walks back up the stack frame.
147 struct TraitObligationStack<'prev, 'tcx> {
148 obligation: &'prev TraitObligation<'tcx>,
150 /// Trait ref from `obligation` but "freshened" with the
151 /// selection-context's freshener. Used to check for recursion.
152 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
154 /// Starts out equal to `depth` -- if, during evaluation, we
155 /// encounter a cycle, then we will set this flag to the minimum
156 /// depth of that cycle for all participants in the cycle. These
157 /// participants will then forego caching their results. This is
158 /// not the most efficient solution, but it addresses #60010. The
159 /// problem we are trying to prevent:
161 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
162 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
163 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
165 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
166 /// is `EvaluatedToOk`; this is because they were only considered
167 /// ok on the premise that if `A: AutoTrait` held, but we indeed
168 /// encountered a problem (later on) with `A: AutoTrait. So we
169 /// currently set a flag on the stack node for `B: AutoTrait` (as
170 /// well as the second instance of `A: AutoTrait`) to suppress
173 /// This is a simple, targeted fix. A more-performant fix requires
174 /// deeper changes, but would permit more caching: we could
175 /// basically defer caching until we have fully evaluated the
176 /// tree, and then cache the entire tree at once. In any case, the
177 /// performance impact here shouldn't be so horrible: every time
178 /// this is hit, we do cache at least one trait, so we only
179 /// evaluate each member of a cycle up to N times, where N is the
180 /// length of the cycle. This means the performance impact is
181 /// bounded and we shouldn't have any terrible worst-cases.
182 reached_depth: Cell<usize>,
184 previous: TraitObligationStackList<'prev, 'tcx>,
186 /// Number of parent frames plus one -- so the topmost frame has depth 1.
189 /// Depth-first number of this node in the search graph -- a
190 /// pre-order index. Basically a freshly incremented counter.
194 #[derive(Clone, Default)]
195 pub struct SelectionCache<'tcx> {
197 FxHashMap<ty::TraitRef<'tcx>, WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
201 /// The selection process begins by considering all impls, where
202 /// clauses, and so forth that might resolve an obligation. Sometimes
203 /// we'll be able to say definitively that (e.g.) an impl does not
204 /// apply to the obligation: perhaps it is defined for `usize` but the
205 /// obligation is for `int`. In that case, we drop the impl out of the
206 /// list. But the other cases are considered *candidates*.
208 /// For selection to succeed, there must be exactly one matching
209 /// candidate. If the obligation is fully known, this is guaranteed
210 /// by coherence. However, if the obligation contains type parameters
211 /// or variables, there may be multiple such impls.
213 /// It is not a real problem if multiple matching impls exist because
214 /// of type variables - it just means the obligation isn't sufficiently
215 /// elaborated. In that case we report an ambiguity, and the caller can
216 /// try again after more type information has been gathered or report a
217 /// "type annotations required" error.
219 /// However, with type parameters, this can be a real problem - type
220 /// parameters don't unify with regular types, but they *can* unify
221 /// with variables from blanket impls, and (unless we know its bounds
222 /// will always be satisfied) picking the blanket impl will be wrong
223 /// for at least *some* substitutions. To make this concrete, if we have
225 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
226 /// impl<T: fmt::Debug> AsDebug for T {
228 /// fn debug(self) -> fmt::Debug { self }
230 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
232 /// we can't just use the impl to resolve the <T as AsDebug> obligation
233 /// - a type from another crate (that doesn't implement fmt::Debug) could
234 /// implement AsDebug.
236 /// Because where-clauses match the type exactly, multiple clauses can
237 /// only match if there are unresolved variables, and we can mostly just
238 /// report this ambiguity in that case. This is still a problem - we can't
239 /// *do anything* with ambiguities that involve only regions. This is issue
242 /// If a single where-clause matches and there are no inference
243 /// variables left, then it definitely matches and we can just select
246 /// In fact, we even select the where-clause when the obligation contains
247 /// inference variables. The can lead to inference making "leaps of logic",
248 /// for example in this situation:
250 /// pub trait Foo<T> { fn foo(&self) -> T; }
251 /// impl<T> Foo<()> for T { fn foo(&self) { } }
252 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
254 /// pub fn foo<T>(t: T) where T: Foo<bool> {
255 /// println!("{:?}", <T as Foo<_>>::foo(&t));
257 /// fn main() { foo(false); }
259 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
260 /// impl and the where-clause. We select the where-clause and unify $0=bool,
261 /// so the program prints "false". However, if the where-clause is omitted,
262 /// the blanket impl is selected, we unify $0=(), and the program prints
265 /// Exactly the same issues apply to projection and object candidates, except
266 /// that we can have both a projection candidate and a where-clause candidate
267 /// for the same obligation. In that case either would do (except that
268 /// different "leaps of logic" would occur if inference variables are
269 /// present), and we just pick the where-clause. This is, for example,
270 /// required for associated types to work in default impls, as the bounds
271 /// are visible both as projection bounds and as where-clauses from the
272 /// parameter environment.
273 #[derive(PartialEq, Eq, Debug, Clone)]
274 enum SelectionCandidate<'tcx> {
275 /// If has_nested is false, there are no *further* obligations
279 ParamCandidate(ty::PolyTraitRef<'tcx>),
280 ImplCandidate(DefId),
281 AutoImplCandidate(DefId),
283 /// This is a trait matching with a projected type as `Self`, and
284 /// we found an applicable bound in the trait definition.
287 /// Implementation of a `Fn`-family trait by one of the anonymous types
288 /// generated for a `||` expression.
291 /// Implementation of a `Generator` trait by one of the anonymous types
292 /// generated for a generator.
295 /// Implementation of a `Fn`-family trait by one of the anonymous
296 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
299 TraitAliasCandidate(DefId),
303 BuiltinObjectCandidate,
305 BuiltinUnsizeCandidate,
308 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
309 type Lifted = SelectionCandidate<'tcx>;
310 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
312 BuiltinCandidate { has_nested } => BuiltinCandidate { has_nested },
313 ImplCandidate(def_id) => ImplCandidate(def_id),
314 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
315 ProjectionCandidate => ProjectionCandidate,
316 ClosureCandidate => ClosureCandidate,
317 GeneratorCandidate => GeneratorCandidate,
318 FnPointerCandidate => FnPointerCandidate,
319 TraitAliasCandidate(def_id) => TraitAliasCandidate(def_id),
320 ObjectCandidate => ObjectCandidate,
321 BuiltinObjectCandidate => BuiltinObjectCandidate,
322 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
324 ParamCandidate(ref trait_ref) => {
325 return tcx.lift(trait_ref).map(ParamCandidate);
331 EnumTypeFoldableImpl! {
332 impl<'tcx> TypeFoldable<'tcx> for SelectionCandidate<'tcx> {
333 (SelectionCandidate::BuiltinCandidate) { has_nested },
334 (SelectionCandidate::ParamCandidate)(poly_trait_ref),
335 (SelectionCandidate::ImplCandidate)(def_id),
336 (SelectionCandidate::AutoImplCandidate)(def_id),
337 (SelectionCandidate::ProjectionCandidate),
338 (SelectionCandidate::ClosureCandidate),
339 (SelectionCandidate::GeneratorCandidate),
340 (SelectionCandidate::FnPointerCandidate),
341 (SelectionCandidate::TraitAliasCandidate)(def_id),
342 (SelectionCandidate::ObjectCandidate),
343 (SelectionCandidate::BuiltinObjectCandidate),
344 (SelectionCandidate::BuiltinUnsizeCandidate),
348 struct SelectionCandidateSet<'tcx> {
349 // a list of candidates that definitely apply to the current
350 // obligation (meaning: types unify).
351 vec: Vec<SelectionCandidate<'tcx>>,
353 // if this is true, then there were candidates that might or might
354 // not have applied, but we couldn't tell. This occurs when some
355 // of the input types are type variables, in which case there are
356 // various "builtin" rules that might or might not trigger.
360 #[derive(PartialEq, Eq, Debug, Clone)]
361 struct EvaluatedCandidate<'tcx> {
362 candidate: SelectionCandidate<'tcx>,
363 evaluation: EvaluationResult,
366 /// When does the builtin impl for `T: Trait` apply?
367 enum BuiltinImplConditions<'tcx> {
368 /// The impl is conditional on T1,T2,.. : Trait
369 Where(ty::Binder<Vec<Ty<'tcx>>>),
370 /// There is no built-in impl. There may be some other
371 /// candidate (a where-clause or user-defined impl).
373 /// It is unknown whether there is an impl.
377 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
378 /// The result of trait evaluation. The order is important
379 /// here as the evaluation of a list is the maximum of the
382 /// The evaluation results are ordered:
383 /// - `EvaluatedToOk` implies `EvaluatedToOkModuloRegions`
384 /// implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
385 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
386 /// - the "union" of evaluation results is equal to their maximum -
387 /// all the "potential success" candidates can potentially succeed,
388 /// so they are noops when unioned with a definite error, and within
389 /// the categories it's easy to see that the unions are correct.
390 pub enum EvaluationResult {
391 /// Evaluation successful
393 /// Evaluation successful, but there were unevaluated region obligations
394 EvaluatedToOkModuloRegions,
395 /// Evaluation is known to be ambiguous - it *might* hold for some
396 /// assignment of inference variables, but it might not.
398 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
399 /// know whether this obligation holds or not - it is the result we
400 /// would get with an empty stack, and therefore is cacheable.
402 /// Evaluation failed because of recursion involving inference
403 /// variables. We are somewhat imprecise there, so we don't actually
404 /// know the real result.
406 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
408 /// Evaluation failed because we encountered an obligation we are already
409 /// trying to prove on this branch.
411 /// We know this branch can't be a part of a minimal proof-tree for
412 /// the "root" of our cycle, because then we could cut out the recursion
413 /// and maintain a valid proof tree. However, this does not mean
414 /// that all the obligations on this branch do not hold - it's possible
415 /// that we entered this branch "speculatively", and that there
416 /// might be some other way to prove this obligation that does not
417 /// go through this cycle - so we can't cache this as a failure.
419 /// For example, suppose we have this:
421 /// ```rust,ignore (pseudo-Rust)
422 /// pub trait Trait { fn xyz(); }
423 /// // This impl is "useless", but we can still have
424 /// // an `impl Trait for SomeUnsizedType` somewhere.
425 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
427 /// pub fn foo<T: Trait + ?Sized>() {
428 /// <T as Trait>::xyz();
432 /// When checking `foo`, we have to prove `T: Trait`. This basically
433 /// translates into this:
436 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
439 /// When we try to prove it, we first go the first option, which
440 /// recurses. This shows us that the impl is "useless" -- it won't
441 /// tell us that `T: Trait` unless it already implemented `Trait`
442 /// by some other means. However, that does not prevent `T: Trait`
443 /// does not hold, because of the bound (which can indeed be satisfied
444 /// by `SomeUnsizedType` from another crate).
446 // FIXME: when an `EvaluatedToRecur` goes past its parent root, we
447 // ought to convert it to an `EvaluatedToErr`, because we know
448 // there definitely isn't a proof tree for that obligation. Not
449 // doing so is still sound -- there isn't any proof tree, so the
450 // branch still can't be a part of a minimal one -- but does not re-enable caching.
452 /// Evaluation failed.
456 impl EvaluationResult {
457 /// Returns `true` if this evaluation result is known to apply, even
458 /// considering outlives constraints.
459 pub fn must_apply_considering_regions(self) -> bool {
460 self == EvaluatedToOk
463 /// Returns `true` if this evaluation result is known to apply, ignoring
464 /// outlives constraints.
465 pub fn must_apply_modulo_regions(self) -> bool {
466 self <= EvaluatedToOkModuloRegions
469 pub fn may_apply(self) -> bool {
471 EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToUnknown => {
475 EvaluatedToErr | EvaluatedToRecur => false,
479 fn is_stack_dependent(self) -> bool {
481 EvaluatedToUnknown | EvaluatedToRecur => true,
483 EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToErr => false,
488 impl_stable_hash_for!(enum self::EvaluationResult {
490 EvaluatedToOkModuloRegions,
497 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
498 /// Indicates that trait evaluation caused overflow.
499 pub struct OverflowError;
501 impl_stable_hash_for!(struct OverflowError {});
503 impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
504 fn from(OverflowError: OverflowError) -> SelectionError<'tcx> {
505 SelectionError::Overflow
509 #[derive(Clone, Default)]
510 pub struct EvaluationCache<'tcx> {
511 hashmap: Lock<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>,
514 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
515 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
518 freshener: infcx.freshener(),
520 intercrate_ambiguity_causes: None,
521 allow_negative_impls: false,
522 query_mode: TraitQueryMode::Standard,
527 infcx: &'cx InferCtxt<'cx, 'tcx>,
528 mode: IntercrateMode,
529 ) -> SelectionContext<'cx, 'tcx> {
530 debug!("intercrate({:?})", mode);
533 freshener: infcx.freshener(),
534 intercrate: Some(mode),
535 intercrate_ambiguity_causes: None,
536 allow_negative_impls: false,
537 query_mode: TraitQueryMode::Standard,
541 pub fn with_negative(
542 infcx: &'cx InferCtxt<'cx, 'tcx>,
543 allow_negative_impls: bool,
544 ) -> SelectionContext<'cx, 'tcx> {
545 debug!("with_negative({:?})", allow_negative_impls);
548 freshener: infcx.freshener(),
550 intercrate_ambiguity_causes: None,
551 allow_negative_impls,
552 query_mode: TraitQueryMode::Standard,
556 pub fn with_query_mode(
557 infcx: &'cx InferCtxt<'cx, 'tcx>,
558 query_mode: TraitQueryMode,
559 ) -> SelectionContext<'cx, 'tcx> {
560 debug!("with_query_mode({:?})", query_mode);
563 freshener: infcx.freshener(),
565 intercrate_ambiguity_causes: None,
566 allow_negative_impls: false,
571 /// Enables tracking of intercrate ambiguity causes. These are
572 /// used in coherence to give improved diagnostics. We don't do
573 /// this until we detect a coherence error because it can lead to
574 /// false overflow results (#47139) and because it costs
575 /// computation time.
576 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
577 assert!(self.intercrate.is_some());
578 assert!(self.intercrate_ambiguity_causes.is_none());
579 self.intercrate_ambiguity_causes = Some(vec![]);
580 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
583 /// Gets the intercrate ambiguity causes collected since tracking
584 /// was enabled and disables tracking at the same time. If
585 /// tracking is not enabled, just returns an empty vector.
586 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
587 assert!(self.intercrate.is_some());
588 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
591 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
595 pub fn tcx(&self) -> TyCtxt<'tcx> {
599 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
603 ///////////////////////////////////////////////////////////////////////////
606 // The selection phase tries to identify *how* an obligation will
607 // be resolved. For example, it will identify which impl or
608 // parameter bound is to be used. The process can be inconclusive
609 // if the self type in the obligation is not fully inferred. Selection
610 // can result in an error in one of two ways:
612 // 1. If no applicable impl or parameter bound can be found.
613 // 2. If the output type parameters in the obligation do not match
614 // those specified by the impl/bound. For example, if the obligation
615 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
616 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
618 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
619 /// type environment by performing unification.
622 obligation: &TraitObligation<'tcx>,
623 ) -> SelectionResult<'tcx, Selection<'tcx>> {
624 debug!("select({:?})", obligation);
625 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
627 let pec = &ProvisionalEvaluationCache::default();
628 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
630 let candidate = match self.candidate_from_obligation(&stack) {
631 Err(SelectionError::Overflow) => {
632 // In standard mode, overflow must have been caught and reported
634 assert!(self.query_mode == TraitQueryMode::Canonical);
635 return Err(SelectionError::Overflow);
643 Ok(Some(candidate)) => candidate,
646 match self.confirm_candidate(obligation, candidate) {
647 Err(SelectionError::Overflow) => {
648 assert!(self.query_mode == TraitQueryMode::Canonical);
649 Err(SelectionError::Overflow)
652 Ok(candidate) => Ok(Some(candidate)),
656 ///////////////////////////////////////////////////////////////////////////
659 // Tests whether an obligation can be selected or whether an impl
660 // can be applied to particular types. It skips the "confirmation"
661 // step and hence completely ignores output type parameters.
663 // The result is "true" if the obligation *may* hold and "false" if
664 // we can be sure it does not.
666 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
667 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
668 debug!("predicate_may_hold_fatal({:?})", obligation);
670 // This fatal query is a stopgap that should only be used in standard mode,
671 // where we do not expect overflow to be propagated.
672 assert!(self.query_mode == TraitQueryMode::Standard);
674 self.evaluate_root_obligation(obligation)
675 .expect("Overflow should be caught earlier in standard query mode")
679 /// Evaluates whether the obligation `obligation` can be satisfied
680 /// and returns an `EvaluationResult`. This is meant for the
682 pub fn evaluate_root_obligation(
684 obligation: &PredicateObligation<'tcx>,
685 ) -> Result<EvaluationResult, OverflowError> {
686 self.evaluation_probe(|this| {
687 this.evaluate_predicate_recursively(
688 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
696 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
697 ) -> Result<EvaluationResult, OverflowError> {
698 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
699 let result = op(self)?;
700 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
702 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
707 /// Evaluates the predicates in `predicates` recursively. Note that
708 /// this applies projections in the predicates, and therefore
709 /// is run within an inference probe.
710 fn evaluate_predicates_recursively<'o, I>(
712 stack: TraitObligationStackList<'o, 'tcx>,
714 ) -> Result<EvaluationResult, OverflowError>
716 I: IntoIterator<Item = PredicateObligation<'tcx>>,
718 let mut result = EvaluatedToOk;
719 for obligation in predicates {
720 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
722 "evaluate_predicate_recursively({:?}) = {:?}",
725 if let EvaluatedToErr = eval {
726 // fast-path - EvaluatedToErr is the top of the lattice,
727 // so we don't need to look on the other predicates.
728 return Ok(EvaluatedToErr);
730 result = cmp::max(result, eval);
736 fn evaluate_predicate_recursively<'o>(
738 previous_stack: TraitObligationStackList<'o, 'tcx>,
739 obligation: PredicateObligation<'tcx>,
740 ) -> Result<EvaluationResult, OverflowError> {
741 debug!("evaluate_predicate_recursively(previous_stack={:?}, obligation={:?})",
742 previous_stack.head(), obligation);
744 // Previous_stack stores a TraitObligatiom, while 'obligation' is
745 // a PredicateObligation. These are distinct types, so we can't
746 // use any Option combinator method that would force them to be
748 match previous_stack.head() {
749 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
750 None => self.check_recursion_limit(&obligation, &obligation)?
753 match obligation.predicate {
754 ty::Predicate::Trait(ref t) => {
755 debug_assert!(!t.has_escaping_bound_vars());
756 let obligation = obligation.with(t.clone());
757 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
760 ty::Predicate::Subtype(ref p) => {
761 // does this code ever run?
763 .subtype_predicate(&obligation.cause, obligation.param_env, p)
765 Some(Ok(InferOk { mut obligations, .. })) => {
766 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
767 self.evaluate_predicates_recursively(previous_stack,obligations.into_iter())
769 Some(Err(_)) => Ok(EvaluatedToErr),
770 None => Ok(EvaluatedToAmbig),
774 ty::Predicate::WellFormed(ty) => match ty::wf::obligations(
776 obligation.param_env,
777 obligation.cause.body_id,
779 obligation.cause.span,
781 Some(mut obligations) => {
782 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
783 self.evaluate_predicates_recursively(previous_stack, obligations.into_iter())
785 None => Ok(EvaluatedToAmbig),
788 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
789 // we do not consider region relationships when
790 // evaluating trait matches
791 Ok(EvaluatedToOkModuloRegions)
794 ty::Predicate::ObjectSafe(trait_def_id) => {
795 if self.tcx().is_object_safe(trait_def_id) {
802 ty::Predicate::Projection(ref data) => {
803 let project_obligation = obligation.with(data.clone());
804 match project::poly_project_and_unify_type(self, &project_obligation) {
805 Ok(Some(mut subobligations)) => {
806 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
807 let result = self.evaluate_predicates_recursively(
809 subobligations.into_iter(),
812 ProjectionCacheKey::from_poly_projection_predicate(self, data)
814 self.infcx.projection_cache.borrow_mut().complete(key);
818 Ok(None) => Ok(EvaluatedToAmbig),
819 Err(_) => Ok(EvaluatedToErr),
823 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
824 match self.infcx.closure_kind(closure_def_id, closure_substs) {
825 Some(closure_kind) => {
826 if closure_kind.extends(kind) {
832 None => Ok(EvaluatedToAmbig),
836 ty::Predicate::ConstEvaluatable(def_id, substs) => {
837 let tcx = self.tcx();
838 if !(obligation.param_env, substs).has_local_value() {
839 let param_env = obligation.param_env;
841 ty::Instance::resolve(tcx, param_env, def_id, substs);
842 if let Some(instance) = instance {
847 match self.tcx().const_eval(param_env.and(cid)) {
848 Ok(_) => Ok(EvaluatedToOk),
849 Err(_) => Ok(EvaluatedToErr),
855 // Inference variables still left in param_env or substs.
862 fn evaluate_trait_predicate_recursively<'o>(
864 previous_stack: TraitObligationStackList<'o, 'tcx>,
865 mut obligation: TraitObligation<'tcx>,
866 ) -> Result<EvaluationResult, OverflowError> {
867 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
869 if self.intercrate.is_none() && obligation.is_global()
874 .all(|bound| bound.needs_subst())
876 // If a param env has no global bounds, global obligations do not
877 // depend on its particular value in order to work, so we can clear
878 // out the param env and get better caching.
880 "evaluate_trait_predicate_recursively({:?}) - in global",
883 obligation.param_env = obligation.param_env.without_caller_bounds();
886 let stack = self.push_stack(previous_stack, &obligation);
887 let fresh_trait_ref = stack.fresh_trait_ref;
888 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
889 debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
893 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
894 debug!("PROVISIONAL CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
895 stack.update_reached_depth(stack.cache().current_reached_depth());
899 // Check if this is a match for something already on the
900 // stack. If so, we don't want to insert the result into the
901 // main cache (it is cycle dependent) nor the provisional
902 // cache (which is meant for things that have completed but
903 // for a "backedge" -- this result *is* the backedge).
904 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
905 return Ok(cycle_result);
908 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
909 let result = result?;
911 if !result.must_apply_modulo_regions() {
912 stack.cache().on_failure(stack.dfn);
915 let reached_depth = stack.reached_depth.get();
916 if reached_depth >= stack.depth {
917 debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
918 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
920 stack.cache().on_completion(stack.depth, |fresh_trait_ref, provisional_result| {
921 self.insert_evaluation_cache(
922 obligation.param_env,
925 provisional_result.max(result),
929 debug!("PROVISIONAL: {:?}={:?}", fresh_trait_ref, result);
931 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
932 is a cycle participant (at depth {}, reached depth {})",
938 stack.cache().insert_provisional(
950 /// If there is any previous entry on the stack that precisely
951 /// matches this obligation, then we can assume that the
952 /// obligation is satisfied for now (still all other conditions
953 /// must be met of course). One obvious case this comes up is
954 /// marker traits like `Send`. Think of a linked list:
956 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
958 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
959 /// `Option<Box<List<T>>>` is `Send`, and in turn
960 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
963 /// Note that we do this comparison using the `fresh_trait_ref`
964 /// fields. Because these have all been freshened using
965 /// `self.freshener`, we can be sure that (a) this will not
966 /// affect the inferencer state and (b) that if we see two
967 /// fresh regions with the same index, they refer to the same
968 /// unbound type variable.
969 fn check_evaluation_cycle(
971 stack: &TraitObligationStack<'_, 'tcx>,
972 ) -> Option<EvaluationResult> {
973 if let Some(cycle_depth) = stack.iter()
974 .skip(1) // skip top-most frame
975 .find(|prev| stack.obligation.param_env == prev.obligation.param_env &&
976 stack.fresh_trait_ref == prev.fresh_trait_ref)
977 .map(|stack| stack.depth)
980 "evaluate_stack({:?}) --> recursive at depth {}",
981 stack.fresh_trait_ref,
985 // If we have a stack like `A B C D E A`, where the top of
986 // the stack is the final `A`, then this will iterate over
987 // `A, E, D, C, B` -- i.e., all the participants apart
988 // from the cycle head. We mark them as participating in a
989 // cycle. This suppresses caching for those nodes. See
990 // `in_cycle` field for more details.
991 stack.update_reached_depth(cycle_depth);
993 // Subtle: when checking for a coinductive cycle, we do
994 // not compare using the "freshened trait refs" (which
995 // have erased regions) but rather the fully explicit
996 // trait refs. This is important because it's only a cycle
997 // if the regions match exactly.
998 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
999 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
1000 if self.coinductive_match(cycle) {
1002 "evaluate_stack({:?}) --> recursive, coinductive",
1003 stack.fresh_trait_ref
1008 "evaluate_stack({:?}) --> recursive, inductive",
1009 stack.fresh_trait_ref
1011 Some(EvaluatedToRecur)
1018 fn evaluate_stack<'o>(
1020 stack: &TraitObligationStack<'o, 'tcx>,
1021 ) -> Result<EvaluationResult, OverflowError> {
1022 // In intercrate mode, whenever any of the types are unbound,
1023 // there can always be an impl. Even if there are no impls in
1024 // this crate, perhaps the type would be unified with
1025 // something from another crate that does provide an impl.
1027 // In intra mode, we must still be conservative. The reason is
1028 // that we want to avoid cycles. Imagine an impl like:
1030 // impl<T:Eq> Eq for Vec<T>
1032 // and a trait reference like `$0 : Eq` where `$0` is an
1033 // unbound variable. When we evaluate this trait-reference, we
1034 // will unify `$0` with `Vec<$1>` (for some fresh variable
1035 // `$1`), on the condition that `$1 : Eq`. We will then wind
1036 // up with many candidates (since that are other `Eq` impls
1037 // that apply) and try to winnow things down. This results in
1038 // a recursive evaluation that `$1 : Eq` -- as you can
1039 // imagine, this is just where we started. To avoid that, we
1040 // check for unbound variables and return an ambiguous (hence possible)
1041 // match if we've seen this trait before.
1043 // This suffices to allow chains like `FnMut` implemented in
1044 // terms of `Fn` etc, but we could probably make this more
1046 let unbound_input_types = stack
1050 .any(|ty| ty.is_fresh());
1051 // this check was an imperfect workaround for a bug n the old
1052 // intercrate mode, it should be removed when that goes away.
1053 if unbound_input_types && self.intercrate == Some(IntercrateMode::Issue43355) {
1055 "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
1056 stack.fresh_trait_ref
1058 // Heuristics: show the diagnostics when there are no candidates in crate.
1059 if self.intercrate_ambiguity_causes.is_some() {
1060 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1061 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1062 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
1063 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1064 let self_ty = trait_ref.self_ty();
1065 let cause = IntercrateAmbiguityCause::DownstreamCrate {
1066 trait_desc: trait_ref.to_string(),
1067 self_desc: if self_ty.has_concrete_skeleton() {
1068 Some(self_ty.to_string())
1073 debug!("evaluate_stack: pushing cause = {:?}", cause);
1074 self.intercrate_ambiguity_causes
1081 return Ok(EvaluatedToAmbig);
1083 if unbound_input_types && stack.iter().skip(1).any(|prev| {
1084 stack.obligation.param_env == prev.obligation.param_env
1085 && self.match_fresh_trait_refs(
1086 &stack.fresh_trait_ref, &prev.fresh_trait_ref, prev.obligation.param_env)
1089 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
1090 stack.fresh_trait_ref
1092 return Ok(EvaluatedToUnknown);
1095 match self.candidate_from_obligation(stack) {
1096 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1097 Ok(None) => Ok(EvaluatedToAmbig),
1098 Err(Overflow) => Err(OverflowError),
1099 Err(..) => Ok(EvaluatedToErr),
1103 /// For defaulted traits, we use a co-inductive strategy to solve, so
1104 /// that recursion is ok. This routine returns true if the top of the
1105 /// stack (`cycle[0]`):
1107 /// - is a defaulted trait,
1108 /// - it also appears in the backtrace at some position `X`,
1109 /// - all the predicates at positions `X..` between `X` and the top are
1110 /// also defaulted traits.
1111 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
1113 I: Iterator<Item = ty::Predicate<'tcx>>,
1115 let mut cycle = cycle;
1116 cycle.all(|predicate| self.coinductive_predicate(predicate))
1119 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1120 let result = match predicate {
1121 ty::Predicate::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1124 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
1128 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
1129 /// obligations are met. Returns whether `candidate` remains viable after this further
1131 fn evaluate_candidate<'o>(
1133 stack: &TraitObligationStack<'o, 'tcx>,
1134 candidate: &SelectionCandidate<'tcx>,
1135 ) -> Result<EvaluationResult, OverflowError> {
1137 "evaluate_candidate: depth={} candidate={:?}",
1138 stack.obligation.recursion_depth, candidate
1140 let result = self.evaluation_probe(|this| {
1141 let candidate = (*candidate).clone();
1142 match this.confirm_candidate(stack.obligation, candidate) {
1143 Ok(selection) => this.evaluate_predicates_recursively(
1145 selection.nested_obligations().into_iter()
1147 Err(..) => Ok(EvaluatedToErr),
1151 "evaluate_candidate: depth={} result={:?}",
1152 stack.obligation.recursion_depth, result
1157 fn check_evaluation_cache(
1159 param_env: ty::ParamEnv<'tcx>,
1160 trait_ref: ty::PolyTraitRef<'tcx>,
1161 ) -> Option<EvaluationResult> {
1162 let tcx = self.tcx();
1163 if self.can_use_global_caches(param_env) {
1164 let cache = tcx.evaluation_cache.hashmap.borrow();
1165 if let Some(cached) = cache.get(&trait_ref) {
1166 return Some(cached.get(tcx));
1174 .map(|v| v.get(tcx))
1177 fn insert_evaluation_cache(
1179 param_env: ty::ParamEnv<'tcx>,
1180 trait_ref: ty::PolyTraitRef<'tcx>,
1181 dep_node: DepNodeIndex,
1182 result: EvaluationResult,
1184 // Avoid caching results that depend on more than just the trait-ref
1185 // - the stack can create recursion.
1186 if result.is_stack_dependent() {
1190 if self.can_use_global_caches(param_env) {
1191 if !trait_ref.has_local_value() {
1193 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
1196 // This may overwrite the cache with the same value
1197 // FIXME: Due to #50507 this overwrites the different values
1198 // This should be changed to use HashMapExt::insert_same
1199 // when that is fixed
1204 .insert(trait_ref, WithDepNode::new(dep_node, result));
1210 "insert_evaluation_cache(trait_ref={:?}, candidate={:?})",
1217 .insert(trait_ref, WithDepNode::new(dep_node, result));
1220 // For various reasons, it's possible for a subobligation
1221 // to have a *lower* recursion_depth than the obligation used to create it.
1222 // Projection sub-obligations may be returned from the projection cache,
1223 // which results in obligations with an 'old' recursion_depth.
1224 // Additionally, methods like ty::wf::obligations and
1225 // InferCtxt.subtype_predicate produce subobligations without
1226 // taking in a 'parent' depth, causing the generated subobligations
1227 // to have a recursion_depth of 0
1229 // To ensure that obligation_depth never decreasees, we force all subobligations
1230 // to have at least the depth of the original obligation.
1231 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(&self, it: I,
1233 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1236 // Check that the recursion limit has not been exceeded.
1238 // The weird return type of this function allows it to be used with the 'try' (?)
1239 // operator within certain functions
1240 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1242 obligation: &Obligation<'tcx, T>,
1243 error_obligation: &Obligation<'tcx, V>
1244 ) -> Result<(), OverflowError> {
1245 let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
1246 if obligation.recursion_depth >= recursion_limit {
1247 match self.query_mode {
1248 TraitQueryMode::Standard => {
1249 self.infcx().report_overflow_error(error_obligation, true);
1251 TraitQueryMode::Canonical => {
1252 return Err(OverflowError);
1259 ///////////////////////////////////////////////////////////////////////////
1260 // CANDIDATE ASSEMBLY
1262 // The selection process begins by examining all in-scope impls,
1263 // caller obligations, and so forth and assembling a list of
1264 // candidates. See the [rustc guide] for more details.
1267 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#candidate-assembly
1269 fn candidate_from_obligation<'o>(
1271 stack: &TraitObligationStack<'o, 'tcx>,
1272 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1273 // Watch out for overflow. This intentionally bypasses (and does
1274 // not update) the cache.
1275 self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
1278 // Check the cache. Note that we freshen the trait-ref
1279 // separately rather than using `stack.fresh_trait_ref` --
1280 // this is because we want the unbound variables to be
1281 // replaced with fresh types starting from index 0.
1282 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate.clone());
1284 "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1285 cache_fresh_trait_pred, stack
1287 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
1290 self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
1292 debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
1296 // If no match, compute result and insert into cache.
1298 // FIXME(nikomatsakis) -- this cache is not taking into
1299 // account cycles that may have occurred in forming the
1300 // candidate. I don't know of any specific problems that
1301 // result but it seems awfully suspicious.
1302 let (candidate, dep_node) =
1303 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
1306 "CACHE MISS: SELECT({:?})={:?}",
1307 cache_fresh_trait_pred, candidate
1309 self.insert_candidate_cache(
1310 stack.obligation.param_env,
1311 cache_fresh_trait_pred,
1318 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1320 OP: FnOnce(&mut Self) -> R,
1322 let (result, dep_node) = self.tcx()
1324 .with_anon_task(DepKind::TraitSelect, || op(self));
1325 self.tcx().dep_graph.read_index(dep_node);
1329 // Treat negative impls as unimplemented
1330 fn filter_negative_impls(
1332 candidate: SelectionCandidate<'tcx>,
1333 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1334 if let ImplCandidate(def_id) = candidate {
1335 if !self.allow_negative_impls
1336 && self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative
1338 return Err(Unimplemented);
1344 fn candidate_from_obligation_no_cache<'o>(
1346 stack: &TraitObligationStack<'o, 'tcx>,
1347 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1348 if stack.obligation.predicate.references_error() {
1349 // If we encounter a `Error`, we generally prefer the
1350 // most "optimistic" result in response -- that is, the
1351 // one least likely to report downstream errors. But
1352 // because this routine is shared by coherence and by
1353 // trait selection, there isn't an obvious "right" choice
1354 // here in that respect, so we opt to just return
1355 // ambiguity and let the upstream clients sort it out.
1359 if let Some(conflict) = self.is_knowable(stack) {
1360 debug!("coherence stage: not knowable");
1361 if self.intercrate_ambiguity_causes.is_some() {
1362 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1363 // Heuristics: show the diagnostics when there are no candidates in crate.
1364 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1365 let mut no_candidates_apply = true;
1367 let evaluated_candidates = candidate_set
1370 .map(|c| self.evaluate_candidate(stack, &c));
1372 for ec in evaluated_candidates {
1376 no_candidates_apply = false;
1380 Err(e) => return Err(e.into()),
1385 if !candidate_set.ambiguous && no_candidates_apply {
1386 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1387 let self_ty = trait_ref.self_ty();
1388 let trait_desc = trait_ref.to_string();
1389 let self_desc = if self_ty.has_concrete_skeleton() {
1390 Some(self_ty.to_string())
1394 let cause = if let Conflict::Upstream = conflict {
1395 IntercrateAmbiguityCause::UpstreamCrateUpdate {
1400 IntercrateAmbiguityCause::DownstreamCrate {
1405 debug!("evaluate_stack: pushing cause = {:?}", cause);
1406 self.intercrate_ambiguity_causes
1416 let candidate_set = self.assemble_candidates(stack)?;
1418 if candidate_set.ambiguous {
1419 debug!("candidate set contains ambig");
1423 let mut candidates = candidate_set.vec;
1426 "assembled {} candidates for {:?}: {:?}",
1432 // At this point, we know that each of the entries in the
1433 // candidate set is *individually* applicable. Now we have to
1434 // figure out if they contain mutual incompatibilities. This
1435 // frequently arises if we have an unconstrained input type --
1436 // for example, we are looking for $0:Eq where $0 is some
1437 // unconstrained type variable. In that case, we'll get a
1438 // candidate which assumes $0 == int, one that assumes $0 ==
1439 // usize, etc. This spells an ambiguity.
1441 // If there is more than one candidate, first winnow them down
1442 // by considering extra conditions (nested obligations and so
1443 // forth). We don't winnow if there is exactly one
1444 // candidate. This is a relatively minor distinction but it
1445 // can lead to better inference and error-reporting. An
1446 // example would be if there was an impl:
1448 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1450 // and we were to see some code `foo.push_clone()` where `boo`
1451 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1452 // we were to winnow, we'd wind up with zero candidates.
1453 // Instead, we select the right impl now but report `Bar does
1454 // not implement Clone`.
1455 if candidates.len() == 1 {
1456 return self.filter_negative_impls(candidates.pop().unwrap());
1459 // Winnow, but record the exact outcome of evaluation, which
1460 // is needed for specialization. Propagate overflow if it occurs.
1461 let mut candidates = candidates
1463 .map(|c| match self.evaluate_candidate(stack, &c) {
1464 Ok(eval) if eval.may_apply() => Ok(Some(EvaluatedCandidate {
1469 Err(OverflowError) => Err(Overflow),
1471 .flat_map(Result::transpose)
1472 .collect::<Result<Vec<_>, _>>()?;
1475 "winnowed to {} candidates for {:?}: {:?}",
1481 // If there are STILL multiple candidates, we can further
1482 // reduce the list by dropping duplicates -- including
1483 // resolving specializations.
1484 if candidates.len() > 1 {
1486 while i < candidates.len() {
1487 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1488 self.candidate_should_be_dropped_in_favor_of(&candidates[i], &candidates[j])
1492 "Dropping candidate #{}/{}: {:?}",
1497 candidates.swap_remove(i);
1500 "Retaining candidate #{}/{}: {:?}",
1507 // If there are *STILL* multiple candidates, give up
1508 // and report ambiguity.
1510 debug!("multiple matches, ambig");
1517 // If there are *NO* candidates, then there are no impls --
1518 // that we know of, anyway. Note that in the case where there
1519 // are unbound type variables within the obligation, it might
1520 // be the case that you could still satisfy the obligation
1521 // from another crate by instantiating the type variables with
1522 // a type from another crate that does have an impl. This case
1523 // is checked for in `evaluate_stack` (and hence users
1524 // who might care about this case, like coherence, should use
1526 if candidates.is_empty() {
1527 return Err(Unimplemented);
1530 // Just one candidate left.
1531 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1534 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1535 debug!("is_knowable(intercrate={:?})", self.intercrate);
1537 if !self.intercrate.is_some() {
1541 let obligation = &stack.obligation;
1542 let predicate = self.infcx()
1543 .resolve_vars_if_possible(&obligation.predicate);
1545 // Okay to skip binder because of the nature of the
1546 // trait-ref-is-knowable check, which does not care about
1548 let trait_ref = predicate.skip_binder().trait_ref;
1550 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1552 Some(Conflict::Downstream {
1553 used_to_be_broken: true,
1555 Some(IntercrateMode::Issue43355),
1556 ) = (result, self.intercrate)
1558 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1565 /// Returns `true` if the global caches can be used.
1566 /// Do note that if the type itself is not in the
1567 /// global tcx, the local caches will be used.
1568 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1569 // If there are any where-clauses in scope, then we always use
1570 // a cache local to this particular scope. Otherwise, we
1571 // switch to a global cache. We used to try and draw
1572 // finer-grained distinctions, but that led to a serious of
1573 // annoying and weird bugs like #22019 and #18290. This simple
1574 // rule seems to be pretty clearly safe and also still retains
1575 // a very high hit rate (~95% when compiling rustc).
1576 if !param_env.caller_bounds.is_empty() {
1580 // Avoid using the master cache during coherence and just rely
1581 // on the local cache. This effectively disables caching
1582 // during coherence. It is really just a simplification to
1583 // avoid us having to fear that coherence results "pollute"
1584 // the master cache. Since coherence executes pretty quickly,
1585 // it's not worth going to more trouble to increase the
1586 // hit-rate I don't think.
1587 if self.intercrate.is_some() {
1591 // Otherwise, we can use the global cache.
1595 fn check_candidate_cache(
1597 param_env: ty::ParamEnv<'tcx>,
1598 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1599 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1600 let tcx = self.tcx();
1601 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1602 if self.can_use_global_caches(param_env) {
1603 let cache = tcx.selection_cache.hashmap.borrow();
1604 if let Some(cached) = cache.get(&trait_ref) {
1605 return Some(cached.get(tcx));
1613 .map(|v| v.get(tcx))
1616 /// Determines whether can we safely cache the result
1617 /// of selecting an obligation. This is almost always 'true',
1618 /// except when dealing with certain ParamCandidates.
1620 /// Ordinarily, a ParamCandidate will contain no inference variables,
1621 /// since it was usually produced directly from a DefId. However,
1622 /// certain cases (currently only librustdoc's blanket impl finder),
1623 /// a ParamEnv may be explicitly constructed with inference types.
1624 /// When this is the case, we do *not* want to cache the resulting selection
1625 /// candidate. This is due to the fact that it might not always be possible
1626 /// to equate the obligation's trait ref and the candidate's trait ref,
1627 /// if more constraints end up getting added to an inference variable.
1629 /// Because of this, we always want to re-run the full selection
1630 /// process for our obligation the next time we see it, since
1631 /// we might end up picking a different SelectionCandidate (or none at all)
1632 fn can_cache_candidate(&self,
1633 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>
1636 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => {
1637 !trait_ref.skip_binder().input_types().any(|t| t.walk().any(|t_| t_.is_ty_infer()))
1643 fn insert_candidate_cache(
1645 param_env: ty::ParamEnv<'tcx>,
1646 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1647 dep_node: DepNodeIndex,
1648 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1650 let tcx = self.tcx();
1651 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1653 if !self.can_cache_candidate(&candidate) {
1654 debug!("insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1655 candidate is not cacheable", trait_ref, candidate);
1660 if self.can_use_global_caches(param_env) {
1661 if let Err(Overflow) = candidate {
1662 // Don't cache overflow globally; we only produce this
1663 // in certain modes.
1664 } else if !trait_ref.has_local_value() {
1665 if !candidate.has_local_value() {
1667 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1668 trait_ref, candidate,
1670 // This may overwrite the cache with the same value
1674 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1681 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1682 trait_ref, candidate,
1688 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1691 fn assemble_candidates<'o>(
1693 stack: &TraitObligationStack<'o, 'tcx>,
1694 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1695 let TraitObligationStack { obligation, .. } = *stack;
1696 let ref obligation = Obligation {
1697 param_env: obligation.param_env,
1698 cause: obligation.cause.clone(),
1699 recursion_depth: obligation.recursion_depth,
1700 predicate: self.infcx()
1701 .resolve_vars_if_possible(&obligation.predicate),
1704 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1705 // Self is a type variable (e.g., `_: AsRef<str>`).
1707 // This is somewhat problematic, as the current scheme can't really
1708 // handle it turning to be a projection. This does end up as truly
1709 // ambiguous in most cases anyway.
1711 // Take the fast path out - this also improves
1712 // performance by preventing assemble_candidates_from_impls from
1713 // matching every impl for this trait.
1714 return Ok(SelectionCandidateSet {
1720 let mut candidates = SelectionCandidateSet {
1725 self.assemble_candidates_for_trait_alias(obligation, &mut candidates)?;
1727 // Other bounds. Consider both in-scope bounds from fn decl
1728 // and applicable impls. There is a certain set of precedence rules here.
1729 let def_id = obligation.predicate.def_id();
1730 let lang_items = self.tcx().lang_items();
1732 if lang_items.copy_trait() == Some(def_id) {
1734 "obligation self ty is {:?}",
1735 obligation.predicate.skip_binder().self_ty()
1738 // User-defined copy impls are permitted, but only for
1739 // structs and enums.
1740 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1742 // For other types, we'll use the builtin rules.
1743 let copy_conditions = self.copy_clone_conditions(obligation);
1744 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1745 } else if lang_items.sized_trait() == Some(def_id) {
1746 // Sized is never implementable by end-users, it is
1747 // always automatically computed.
1748 let sized_conditions = self.sized_conditions(obligation);
1749 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1750 } else if lang_items.unsize_trait() == Some(def_id) {
1751 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1753 if lang_items.clone_trait() == Some(def_id) {
1754 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
1755 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1756 // types have builtin support for `Clone`.
1757 let clone_conditions = self.copy_clone_conditions(obligation);
1758 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1761 self.assemble_generator_candidates(obligation, &mut candidates)?;
1762 self.assemble_closure_candidates(obligation, &mut candidates)?;
1763 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1764 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1765 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1768 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1769 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1770 // Auto implementations have lower priority, so we only
1771 // consider triggering a default if there is no other impl that can apply.
1772 if candidates.vec.is_empty() {
1773 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1775 debug!("candidate list size: {}", candidates.vec.len());
1779 fn assemble_candidates_from_projected_tys(
1781 obligation: &TraitObligation<'tcx>,
1782 candidates: &mut SelectionCandidateSet<'tcx>,
1784 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1786 // before we go into the whole placeholder thing, just
1787 // quickly check if the self-type is a projection at all.
1788 match obligation.predicate.skip_binder().trait_ref.self_ty().sty {
1789 ty::Projection(_) | ty::Opaque(..) => {}
1790 ty::Infer(ty::TyVar(_)) => {
1792 obligation.cause.span,
1793 "Self=_ should have been handled by assemble_candidates"
1799 let result = self.infcx.probe(|snapshot| {
1800 self.match_projection_obligation_against_definition_bounds(
1807 candidates.vec.push(ProjectionCandidate);
1811 fn match_projection_obligation_against_definition_bounds(
1813 obligation: &TraitObligation<'tcx>,
1814 snapshot: &CombinedSnapshot<'_, 'tcx>,
1816 let poly_trait_predicate = self.infcx()
1817 .resolve_vars_if_possible(&obligation.predicate);
1818 let (placeholder_trait_predicate, placeholder_map) = self.infcx()
1819 .replace_bound_vars_with_placeholders(&poly_trait_predicate);
1821 "match_projection_obligation_against_definition_bounds: \
1822 placeholder_trait_predicate={:?}",
1823 placeholder_trait_predicate,
1826 let (def_id, substs) = match placeholder_trait_predicate.trait_ref.self_ty().sty {
1827 ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1828 ty::Opaque(def_id, substs) => (def_id, substs),
1831 obligation.cause.span,
1832 "match_projection_obligation_against_definition_bounds() called \
1833 but self-ty is not a projection: {:?}",
1834 placeholder_trait_predicate.trait_ref.self_ty()
1839 "match_projection_obligation_against_definition_bounds: \
1840 def_id={:?}, substs={:?}",
1844 let predicates_of = self.tcx().predicates_of(def_id);
1845 let bounds = predicates_of.instantiate(self.tcx(), substs);
1847 "match_projection_obligation_against_definition_bounds: \
1852 let elaborated_predicates = util::elaborate_predicates(self.tcx(), bounds.predicates);
1853 let matching_bound = elaborated_predicates
1856 self.infcx.probe(|_| {
1857 self.match_projection(
1860 placeholder_trait_predicate.trait_ref.clone(),
1868 "match_projection_obligation_against_definition_bounds: \
1869 matching_bound={:?}",
1872 match matching_bound {
1875 // Repeat the successful match, if any, this time outside of a probe.
1876 let result = self.match_projection(
1879 placeholder_trait_predicate.trait_ref.clone(),
1890 fn match_projection(
1892 obligation: &TraitObligation<'tcx>,
1893 trait_bound: ty::PolyTraitRef<'tcx>,
1894 placeholder_trait_ref: ty::TraitRef<'tcx>,
1895 placeholder_map: &PlaceholderMap<'tcx>,
1896 snapshot: &CombinedSnapshot<'_, 'tcx>,
1898 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1900 .at(&obligation.cause, obligation.param_env)
1901 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1904 self.infcx.leak_check(false, placeholder_map, snapshot).is_ok()
1907 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1908 /// supplied to find out whether it is listed among them.
1910 /// Never affects inference environment.
1911 fn assemble_candidates_from_caller_bounds<'o>(
1913 stack: &TraitObligationStack<'o, 'tcx>,
1914 candidates: &mut SelectionCandidateSet<'tcx>,
1915 ) -> Result<(), SelectionError<'tcx>> {
1917 "assemble_candidates_from_caller_bounds({:?})",
1921 let all_bounds = stack
1926 .filter_map(|o| o.to_opt_poly_trait_ref());
1928 // Micro-optimization: filter out predicates relating to different traits.
1929 let matching_bounds =
1930 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1932 // Keep only those bounds which may apply, and propagate overflow if it occurs.
1933 let mut param_candidates = vec![];
1934 for bound in matching_bounds {
1935 let wc = self.evaluate_where_clause(stack, bound.clone())?;
1937 param_candidates.push(ParamCandidate(bound));
1941 candidates.vec.extend(param_candidates);
1946 fn evaluate_where_clause<'o>(
1948 stack: &TraitObligationStack<'o, 'tcx>,
1949 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1950 ) -> Result<EvaluationResult, OverflowError> {
1951 self.evaluation_probe(|this| {
1952 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1953 Ok(obligations) => {
1954 this.evaluate_predicates_recursively(stack.list(), obligations.into_iter())
1956 Err(()) => Ok(EvaluatedToErr),
1961 fn assemble_generator_candidates(
1963 obligation: &TraitObligation<'tcx>,
1964 candidates: &mut SelectionCandidateSet<'tcx>,
1965 ) -> Result<(), SelectionError<'tcx>> {
1966 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1970 // Okay to skip binder because the substs on generator types never
1971 // touch bound regions, they just capture the in-scope
1972 // type/region parameters.
1973 let self_ty = *obligation.self_ty().skip_binder();
1975 ty::Generator(..) => {
1977 "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1981 candidates.vec.push(GeneratorCandidate);
1983 ty::Infer(ty::TyVar(_)) => {
1984 debug!("assemble_generator_candidates: ambiguous self-type");
1985 candidates.ambiguous = true;
1993 /// Checks for the artificial impl that the compiler will create for an obligation like `X :
1994 /// FnMut<..>` where `X` is a closure type.
1996 /// Note: the type parameters on a closure candidate are modeled as *output* type
1997 /// parameters and hence do not affect whether this trait is a match or not. They will be
1998 /// unified during the confirmation step.
1999 fn assemble_closure_candidates(
2001 obligation: &TraitObligation<'tcx>,
2002 candidates: &mut SelectionCandidateSet<'tcx>,
2003 ) -> Result<(), SelectionError<'tcx>> {
2004 let kind = match self.tcx()
2006 .fn_trait_kind(obligation.predicate.def_id())
2014 // Okay to skip binder because the substs on closure types never
2015 // touch bound regions, they just capture the in-scope
2016 // type/region parameters
2017 match obligation.self_ty().skip_binder().sty {
2018 ty::Closure(closure_def_id, closure_substs) => {
2020 "assemble_unboxed_candidates: kind={:?} obligation={:?}",
2023 match self.infcx.closure_kind(closure_def_id, closure_substs) {
2024 Some(closure_kind) => {
2026 "assemble_unboxed_candidates: closure_kind = {:?}",
2029 if closure_kind.extends(kind) {
2030 candidates.vec.push(ClosureCandidate);
2034 debug!("assemble_unboxed_candidates: closure_kind not yet known");
2035 candidates.vec.push(ClosureCandidate);
2039 ty::Infer(ty::TyVar(_)) => {
2040 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
2041 candidates.ambiguous = true;
2049 /// Implement one of the `Fn()` family for a fn pointer.
2050 fn assemble_fn_pointer_candidates(
2052 obligation: &TraitObligation<'tcx>,
2053 candidates: &mut SelectionCandidateSet<'tcx>,
2054 ) -> Result<(), SelectionError<'tcx>> {
2055 // We provide impl of all fn traits for fn pointers.
2058 .fn_trait_kind(obligation.predicate.def_id())
2064 // Okay to skip binder because what we are inspecting doesn't involve bound regions
2065 let self_ty = *obligation.self_ty().skip_binder();
2067 ty::Infer(ty::TyVar(_)) => {
2068 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
2069 candidates.ambiguous = true; // could wind up being a fn() type
2071 // provide an impl, but only for suitable `fn` pointers
2072 ty::FnDef(..) | ty::FnPtr(_) => {
2074 unsafety: hir::Unsafety::Normal,
2078 } = self_ty.fn_sig(self.tcx()).skip_binder()
2080 candidates.vec.push(FnPointerCandidate);
2089 /// Search for impls that might apply to `obligation`.
2090 fn assemble_candidates_from_impls(
2092 obligation: &TraitObligation<'tcx>,
2093 candidates: &mut SelectionCandidateSet<'tcx>,
2094 ) -> Result<(), SelectionError<'tcx>> {
2096 "assemble_candidates_from_impls(obligation={:?})",
2100 self.tcx().for_each_relevant_impl(
2101 obligation.predicate.def_id(),
2102 obligation.predicate.skip_binder().trait_ref.self_ty(),
2104 self.infcx.probe(|snapshot| {
2105 if let Ok(_substs) = self.match_impl(impl_def_id, obligation, snapshot)
2107 candidates.vec.push(ImplCandidate(impl_def_id));
2116 fn assemble_candidates_from_auto_impls(
2118 obligation: &TraitObligation<'tcx>,
2119 candidates: &mut SelectionCandidateSet<'tcx>,
2120 ) -> Result<(), SelectionError<'tcx>> {
2121 // Okay to skip binder here because the tests we do below do not involve bound regions.
2122 let self_ty = *obligation.self_ty().skip_binder();
2123 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
2125 let def_id = obligation.predicate.def_id();
2127 if self.tcx().trait_is_auto(def_id) {
2129 ty::Dynamic(..) => {
2130 // For object types, we don't know what the closed
2131 // over types are. This means we conservatively
2132 // say nothing; a candidate may be added by
2133 // `assemble_candidates_from_object_ty`.
2135 ty::Foreign(..) => {
2136 // Since the contents of foreign types is unknown,
2137 // we don't add any `..` impl. Default traits could
2138 // still be provided by a manual implementation for
2139 // this trait and type.
2141 ty::Param(..) | ty::Projection(..) => {
2142 // In these cases, we don't know what the actual
2143 // type is. Therefore, we cannot break it down
2144 // into its constituent types. So we don't
2145 // consider the `..` impl but instead just add no
2146 // candidates: this means that typeck will only
2147 // succeed if there is another reason to believe
2148 // that this obligation holds. That could be a
2149 // where-clause or, in the case of an object type,
2150 // it could be that the object type lists the
2151 // trait (e.g., `Foo+Send : Send`). See
2152 // `compile-fail/typeck-default-trait-impl-send-param.rs`
2153 // for an example of a test case that exercises
2156 ty::Infer(ty::TyVar(_)) => {
2157 // the auto impl might apply, we don't know
2158 candidates.ambiguous = true;
2160 ty::Generator(_, _, movability)
2161 if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
2164 hir::GeneratorMovability::Static => {
2165 // Immovable generators are never `Unpin`, so
2166 // suppress the normal auto-impl candidate for it.
2168 hir::GeneratorMovability::Movable => {
2169 // Movable generators are always `Unpin`, so add an
2170 // unconditional builtin candidate.
2171 candidates.vec.push(BuiltinCandidate {
2178 _ => candidates.vec.push(AutoImplCandidate(def_id.clone())),
2185 /// Search for impls that might apply to `obligation`.
2186 fn assemble_candidates_from_object_ty(
2188 obligation: &TraitObligation<'tcx>,
2189 candidates: &mut SelectionCandidateSet<'tcx>,
2192 "assemble_candidates_from_object_ty(self_ty={:?})",
2193 obligation.self_ty().skip_binder()
2196 self.infcx.probe(|_snapshot| {
2197 // The code below doesn't care about regions, and the
2198 // self-ty here doesn't escape this probe, so just erase
2200 let self_ty = self.tcx().erase_late_bound_regions(&obligation.self_ty());
2201 let poly_trait_ref = match self_ty.sty {
2202 ty::Dynamic(ref data, ..) => {
2203 if data.auto_traits()
2204 .any(|did| did == obligation.predicate.def_id())
2207 "assemble_candidates_from_object_ty: matched builtin bound, \
2210 candidates.vec.push(BuiltinObjectCandidate);
2214 if let Some(principal) = data.principal() {
2215 principal.with_self_ty(self.tcx(), self_ty)
2217 // Only auto-trait bounds exist.
2221 ty::Infer(ty::TyVar(_)) => {
2222 debug!("assemble_candidates_from_object_ty: ambiguous");
2223 candidates.ambiguous = true; // could wind up being an object type
2230 "assemble_candidates_from_object_ty: poly_trait_ref={:?}",
2234 // Count only those upcast versions that match the trait-ref
2235 // we are looking for. Specifically, do not only check for the
2236 // correct trait, but also the correct type parameters.
2237 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
2238 // but `Foo` is declared as `trait Foo : Bar<u32>`.
2239 let upcast_trait_refs = util::supertraits(self.tcx(), poly_trait_ref)
2240 .filter(|upcast_trait_ref| {
2241 self.infcx.probe(|_| {
2242 let upcast_trait_ref = upcast_trait_ref.clone();
2243 self.match_poly_trait_ref(obligation, upcast_trait_ref)
2249 if upcast_trait_refs > 1 {
2250 // Can be upcast in many ways; need more type information.
2251 candidates.ambiguous = true;
2252 } else if upcast_trait_refs == 1 {
2253 candidates.vec.push(ObjectCandidate);
2258 /// Search for unsizing that might apply to `obligation`.
2259 fn assemble_candidates_for_unsizing(
2261 obligation: &TraitObligation<'tcx>,
2262 candidates: &mut SelectionCandidateSet<'tcx>,
2264 // We currently never consider higher-ranked obligations e.g.
2265 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
2266 // because they are a priori invalid, and we could potentially add support
2267 // for them later, it's just that there isn't really a strong need for it.
2268 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
2269 // impl, and those are generally applied to concrete types.
2271 // That said, one might try to write a fn with a where clause like
2272 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
2273 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
2274 // Still, you'd be more likely to write that where clause as
2276 // so it seems ok if we (conservatively) fail to accept that `Unsize`
2277 // obligation above. Should be possible to extend this in the future.
2278 let source = match obligation.self_ty().no_bound_vars() {
2281 // Don't add any candidates if there are bound regions.
2285 let target = obligation
2293 "assemble_candidates_for_unsizing(source={:?}, target={:?})",
2297 let may_apply = match (&source.sty, &target.sty) {
2298 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2299 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
2300 // Upcasts permit two things:
2302 // 1. Dropping builtin bounds, e.g., `Foo+Send` to `Foo`
2303 // 2. Tightening the region bound, e.g., `Foo+'a` to `Foo+'b` if `'a : 'b`
2305 // Note that neither of these changes requires any
2306 // change at runtime. Eventually this will be
2309 // We always upcast when we can because of reason
2310 // #2 (region bounds).
2311 data_a.principal_def_id() == data_b.principal_def_id()
2312 && data_b.auto_traits()
2313 // All of a's auto traits need to be in b's auto traits.
2314 .all(|b| data_a.auto_traits().any(|a| a == b))
2318 (_, &ty::Dynamic(..)) => true,
2320 // Ambiguous handling is below T -> Trait, because inference
2321 // variables can still implement Unsize<Trait> and nested
2322 // obligations will have the final say (likely deferred).
2323 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
2324 debug!("assemble_candidates_for_unsizing: ambiguous");
2325 candidates.ambiguous = true;
2330 (&ty::Array(..), &ty::Slice(_)) => true,
2332 // Struct<T> -> Struct<U>.
2333 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
2334 def_id_a == def_id_b
2337 // (.., T) -> (.., U).
2338 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
2344 candidates.vec.push(BuiltinUnsizeCandidate);
2348 fn assemble_candidates_for_trait_alias(
2350 obligation: &TraitObligation<'tcx>,
2351 candidates: &mut SelectionCandidateSet<'tcx>,
2352 ) -> Result<(), SelectionError<'tcx>> {
2353 // Okay to skip binder here because the tests we do below do not involve bound regions.
2354 let self_ty = *obligation.self_ty().skip_binder();
2355 debug!("assemble_candidates_for_trait_alias(self_ty={:?})", self_ty);
2357 let def_id = obligation.predicate.def_id();
2359 if self.tcx().is_trait_alias(def_id) {
2360 candidates.vec.push(TraitAliasCandidate(def_id.clone()));
2366 ///////////////////////////////////////////////////////////////////////////
2369 // Winnowing is the process of attempting to resolve ambiguity by
2370 // probing further. During the winnowing process, we unify all
2371 // type variables and then we also attempt to evaluate recursive
2372 // bounds to see if they are satisfied.
2374 /// Returns `true` if `victim` should be dropped in favor of
2375 /// `other`. Generally speaking we will drop duplicate
2376 /// candidates and prefer where-clause candidates.
2378 /// See the comment for "SelectionCandidate" for more details.
2379 fn candidate_should_be_dropped_in_favor_of(
2381 victim: &EvaluatedCandidate<'tcx>,
2382 other: &EvaluatedCandidate<'tcx>,
2384 if victim.candidate == other.candidate {
2388 // Check if a bound would previously have been removed when normalizing
2389 // the param_env so that it can be given the lowest priority. See
2390 // #50825 for the motivation for this.
2392 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
2394 match other.candidate {
2395 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2396 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2397 // lifetime of a variable.
2398 BuiltinCandidate { has_nested: false } => true,
2399 ParamCandidate(ref cand) => match victim.candidate {
2400 AutoImplCandidate(..) => {
2402 "default implementations shouldn't be recorded \
2403 when there are other valid candidates"
2406 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2407 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2408 // lifetime of a variable.
2409 BuiltinCandidate { has_nested: false } => false,
2412 | GeneratorCandidate
2413 | FnPointerCandidate
2414 | BuiltinObjectCandidate
2415 | BuiltinUnsizeCandidate
2416 | BuiltinCandidate { .. }
2417 | TraitAliasCandidate(..) => {
2418 // Global bounds from the where clause should be ignored
2419 // here (see issue #50825). Otherwise, we have a where
2420 // clause so don't go around looking for impls.
2423 ObjectCandidate | ProjectionCandidate => {
2424 // Arbitrarily give param candidates priority
2425 // over projection and object candidates.
2428 ParamCandidate(..) => false,
2430 ObjectCandidate | ProjectionCandidate => match victim.candidate {
2431 AutoImplCandidate(..) => {
2433 "default implementations shouldn't be recorded \
2434 when there are other valid candidates"
2437 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2438 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2439 // lifetime of a variable.
2440 BuiltinCandidate { has_nested: false } => false,
2443 | GeneratorCandidate
2444 | FnPointerCandidate
2445 | BuiltinObjectCandidate
2446 | BuiltinUnsizeCandidate
2447 | BuiltinCandidate { .. }
2448 | TraitAliasCandidate(..) => true,
2449 ObjectCandidate | ProjectionCandidate => {
2450 // Arbitrarily give param candidates priority
2451 // over projection and object candidates.
2454 ParamCandidate(ref cand) => is_global(cand),
2456 ImplCandidate(other_def) => {
2457 // See if we can toss out `victim` based on specialization.
2458 // This requires us to know *for sure* that the `other` impl applies
2459 // i.e., EvaluatedToOk:
2460 if other.evaluation.must_apply_modulo_regions() {
2461 match victim.candidate {
2462 ImplCandidate(victim_def) => {
2463 let tcx = self.tcx().global_tcx();
2464 return tcx.specializes((other_def, victim_def))
2465 || tcx.impls_are_allowed_to_overlap(
2466 other_def, victim_def).is_some();
2468 ParamCandidate(ref cand) => {
2469 // Prefer the impl to a global where clause candidate.
2470 return is_global(cand);
2479 | GeneratorCandidate
2480 | FnPointerCandidate
2481 | BuiltinObjectCandidate
2482 | BuiltinUnsizeCandidate
2483 | BuiltinCandidate { has_nested: true } => {
2484 match victim.candidate {
2485 ParamCandidate(ref cand) => {
2486 // Prefer these to a global where-clause bound
2487 // (see issue #50825)
2488 is_global(cand) && other.evaluation.must_apply_modulo_regions()
2497 ///////////////////////////////////////////////////////////////////////////
2500 // These cover the traits that are built-in to the language
2501 // itself: `Copy`, `Clone` and `Sized`.
2503 fn assemble_builtin_bound_candidates(
2505 conditions: BuiltinImplConditions<'tcx>,
2506 candidates: &mut SelectionCandidateSet<'tcx>,
2507 ) -> Result<(), SelectionError<'tcx>> {
2509 BuiltinImplConditions::Where(nested) => {
2510 debug!("builtin_bound: nested={:?}", nested);
2511 candidates.vec.push(BuiltinCandidate {
2512 has_nested: nested.skip_binder().len() > 0,
2515 BuiltinImplConditions::None => {}
2516 BuiltinImplConditions::Ambiguous => {
2517 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2518 candidates.ambiguous = true;
2525 fn sized_conditions(
2527 obligation: &TraitObligation<'tcx>,
2528 ) -> BuiltinImplConditions<'tcx> {
2529 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2531 // NOTE: binder moved to (*)
2532 let self_ty = self.infcx
2533 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2536 ty::Infer(ty::IntVar(_))
2537 | ty::Infer(ty::FloatVar(_))
2548 | ty::GeneratorWitness(..)
2553 // safe for everything
2554 Where(ty::Binder::dummy(Vec::new()))
2557 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2560 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
2563 ty::Adt(def, substs) => {
2564 let sized_crit = def.sized_constraint(self.tcx());
2565 // (*) binder moved here
2566 Where(ty::Binder::bind(
2569 .map(|ty| ty.subst(self.tcx(), substs))
2574 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2575 ty::Infer(ty::TyVar(_)) => Ambiguous,
2577 ty::UnnormalizedProjection(..)
2578 | ty::Placeholder(..)
2580 | ty::Infer(ty::FreshTy(_))
2581 | ty::Infer(ty::FreshIntTy(_))
2582 | ty::Infer(ty::FreshFloatTy(_)) => {
2584 "asked to assemble builtin bounds of unexpected type: {:?}",
2591 fn copy_clone_conditions(
2593 obligation: &TraitObligation<'tcx>,
2594 ) -> BuiltinImplConditions<'tcx> {
2595 // NOTE: binder moved to (*)
2596 let self_ty = self.infcx
2597 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2599 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2602 ty::Infer(ty::IntVar(_))
2603 | ty::Infer(ty::FloatVar(_))
2606 | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2615 | ty::Ref(_, _, hir::MutImmutable) => {
2616 // Implementations provided in libcore
2624 | ty::GeneratorWitness(..)
2626 | ty::Ref(_, _, hir::MutMutable) => None,
2628 ty::Array(element_ty, _) => {
2629 // (*) binder moved here
2630 Where(ty::Binder::bind(vec![element_ty]))
2634 // (*) binder moved here
2635 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
2638 ty::Closure(def_id, substs) => {
2639 // (*) binder moved here
2640 Where(ty::Binder::bind(
2641 substs.upvar_tys(def_id, self.tcx()).collect(),
2645 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2646 // Fallback to whatever user-defined impls exist in this case.
2650 ty::Infer(ty::TyVar(_)) => {
2651 // Unbound type variable. Might or might not have
2652 // applicable impls and so forth, depending on what
2653 // those type variables wind up being bound to.
2657 ty::UnnormalizedProjection(..)
2658 | ty::Placeholder(..)
2660 | ty::Infer(ty::FreshTy(_))
2661 | ty::Infer(ty::FreshIntTy(_))
2662 | ty::Infer(ty::FreshFloatTy(_)) => {
2664 "asked to assemble builtin bounds of unexpected type: {:?}",
2671 /// For default impls, we need to break apart a type into its
2672 /// "constituent types" -- meaning, the types that it contains.
2674 /// Here are some (simple) examples:
2677 /// (i32, u32) -> [i32, u32]
2678 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2679 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2680 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2682 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2692 | ty::Infer(ty::IntVar(_))
2693 | ty::Infer(ty::FloatVar(_))
2695 | ty::Char => Vec::new(),
2697 ty::UnnormalizedProjection(..)
2698 | ty::Placeholder(..)
2702 | ty::Projection(..)
2704 | ty::Infer(ty::TyVar(_))
2705 | ty::Infer(ty::FreshTy(_))
2706 | ty::Infer(ty::FreshIntTy(_))
2707 | ty::Infer(ty::FreshFloatTy(_)) => {
2709 "asked to assemble constituent types of unexpected type: {:?}",
2714 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2718 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2720 ty::Tuple(ref tys) => {
2721 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2722 tys.iter().map(|k| k.expect_ty()).collect()
2725 ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, self.tcx()).collect(),
2727 ty::Generator(def_id, ref substs, _) => {
2728 let witness = substs.witness(def_id, self.tcx());
2730 .upvar_tys(def_id, self.tcx())
2731 .chain(iter::once(witness))
2735 ty::GeneratorWitness(types) => {
2736 // This is sound because no regions in the witness can refer to
2737 // the binder outside the witness. So we'll effectivly reuse
2738 // the implicit binder around the witness.
2739 types.skip_binder().to_vec()
2742 // for `PhantomData<T>`, we pass `T`
2743 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2745 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2747 ty::Opaque(def_id, substs) => {
2748 // We can resolve the `impl Trait` to its concrete type,
2749 // which enforces a DAG between the functions requiring
2750 // the auto trait bounds in question.
2751 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2756 fn collect_predicates_for_types(
2758 param_env: ty::ParamEnv<'tcx>,
2759 cause: ObligationCause<'tcx>,
2760 recursion_depth: usize,
2761 trait_def_id: DefId,
2762 types: ty::Binder<Vec<Ty<'tcx>>>,
2763 ) -> Vec<PredicateObligation<'tcx>> {
2764 // Because the types were potentially derived from
2765 // higher-ranked obligations they may reference late-bound
2766 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2767 // yield a type like `for<'a> &'a int`. In general, we
2768 // maintain the invariant that we never manipulate bound
2769 // regions, so we have to process these bound regions somehow.
2771 // The strategy is to:
2773 // 1. Instantiate those regions to placeholder regions (e.g.,
2774 // `for<'a> &'a int` becomes `&0 int`.
2775 // 2. Produce something like `&'0 int : Copy`
2776 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2783 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2785 self.infcx.in_snapshot(|_| {
2786 let (skol_ty, _) = self.infcx
2787 .replace_bound_vars_with_placeholders(&ty);
2789 value: normalized_ty,
2791 } = project::normalize_with_depth(
2798 let skol_obligation = self.tcx().predicate_for_trait_def(
2806 obligations.push(skol_obligation);
2813 ///////////////////////////////////////////////////////////////////////////
2816 // Confirmation unifies the output type parameters of the trait
2817 // with the values found in the obligation, possibly yielding a
2818 // type error. See the [rustc guide] for more details.
2821 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#confirmation
2823 fn confirm_candidate(
2825 obligation: &TraitObligation<'tcx>,
2826 candidate: SelectionCandidate<'tcx>,
2827 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2828 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2831 BuiltinCandidate { has_nested } => {
2832 let data = self.confirm_builtin_candidate(obligation, has_nested);
2833 Ok(VtableBuiltin(data))
2836 ParamCandidate(param) => {
2837 let obligations = self.confirm_param_candidate(obligation, param);
2838 Ok(VtableParam(obligations))
2841 ImplCandidate(impl_def_id) => Ok(VtableImpl(self.confirm_impl_candidate(
2846 AutoImplCandidate(trait_def_id) => {
2847 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2848 Ok(VtableAutoImpl(data))
2851 ProjectionCandidate => {
2852 self.confirm_projection_candidate(obligation);
2853 Ok(VtableParam(Vec::new()))
2856 ClosureCandidate => {
2857 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2858 Ok(VtableClosure(vtable_closure))
2861 GeneratorCandidate => {
2862 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2863 Ok(VtableGenerator(vtable_generator))
2866 FnPointerCandidate => {
2867 let data = self.confirm_fn_pointer_candidate(obligation)?;
2868 Ok(VtableFnPointer(data))
2871 TraitAliasCandidate(alias_def_id) => {
2872 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
2873 Ok(VtableTraitAlias(data))
2876 ObjectCandidate => {
2877 let data = self.confirm_object_candidate(obligation);
2878 Ok(VtableObject(data))
2881 BuiltinObjectCandidate => {
2882 // This indicates something like `(Trait+Send) :
2883 // Send`. In this case, we know that this holds
2884 // because that's what the object type is telling us,
2885 // and there's really no additional obligations to
2886 // prove and no types in particular to unify etc.
2887 Ok(VtableParam(Vec::new()))
2890 BuiltinUnsizeCandidate => {
2891 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2892 Ok(VtableBuiltin(data))
2897 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2898 self.infcx.in_snapshot(|snapshot| {
2900 self.match_projection_obligation_against_definition_bounds(
2908 fn confirm_param_candidate(
2910 obligation: &TraitObligation<'tcx>,
2911 param: ty::PolyTraitRef<'tcx>,
2912 ) -> Vec<PredicateObligation<'tcx>> {
2913 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2915 // During evaluation, we already checked that this
2916 // where-clause trait-ref could be unified with the obligation
2917 // trait-ref. Repeat that unification now without any
2918 // transactional boundary; it should not fail.
2919 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2920 Ok(obligations) => obligations,
2923 "Where clause `{:?}` was applicable to `{:?}` but now is not",
2931 fn confirm_builtin_candidate(
2933 obligation: &TraitObligation<'tcx>,
2935 ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2937 "confirm_builtin_candidate({:?}, {:?})",
2938 obligation, has_nested
2941 let lang_items = self.tcx().lang_items();
2942 let obligations = if has_nested {
2943 let trait_def = obligation.predicate.def_id();
2944 let conditions = if Some(trait_def) == lang_items.sized_trait() {
2945 self.sized_conditions(obligation)
2946 } else if Some(trait_def) == lang_items.copy_trait() {
2947 self.copy_clone_conditions(obligation)
2948 } else if Some(trait_def) == lang_items.clone_trait() {
2949 self.copy_clone_conditions(obligation)
2951 bug!("unexpected builtin trait {:?}", trait_def)
2953 let nested = match conditions {
2954 BuiltinImplConditions::Where(nested) => nested,
2956 "obligation {:?} had matched a builtin impl but now doesn't",
2961 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2962 self.collect_predicates_for_types(
2963 obligation.param_env,
2965 obligation.recursion_depth + 1,
2973 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2976 nested: obligations,
2980 /// This handles the case where a `auto trait Foo` impl is being used.
2981 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2983 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2984 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2985 fn confirm_auto_impl_candidate(
2987 obligation: &TraitObligation<'tcx>,
2988 trait_def_id: DefId,
2989 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2991 "confirm_auto_impl_candidate({:?}, {:?})",
2992 obligation, trait_def_id
2995 let types = obligation.predicate.map_bound(|inner| {
2996 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2997 self.constituent_types_for_ty(self_ty)
2999 self.vtable_auto_impl(obligation, trait_def_id, types)
3002 /// See `confirm_auto_impl_candidate`.
3003 fn vtable_auto_impl(
3005 obligation: &TraitObligation<'tcx>,
3006 trait_def_id: DefId,
3007 nested: ty::Binder<Vec<Ty<'tcx>>>,
3008 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
3009 debug!("vtable_auto_impl: nested={:?}", nested);
3011 let cause = obligation.derived_cause(BuiltinDerivedObligation);
3012 let mut obligations = self.collect_predicates_for_types(
3013 obligation.param_env,
3015 obligation.recursion_depth + 1,
3020 let trait_obligations: Vec<PredicateObligation<'_>> = self.infcx.in_snapshot(|_| {
3021 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
3022 let (trait_ref, _) = self.infcx
3023 .replace_bound_vars_with_placeholders(&poly_trait_ref);
3024 let cause = obligation.derived_cause(ImplDerivedObligation);
3025 self.impl_or_trait_obligations(
3027 obligation.recursion_depth + 1,
3028 obligation.param_env,
3034 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
3035 // predicate as usual. It won't have any effect since auto traits are coinductive.
3036 obligations.extend(trait_obligations);
3038 debug!("vtable_auto_impl: obligations={:?}", obligations);
3040 VtableAutoImplData {
3042 nested: obligations,
3046 fn confirm_impl_candidate(
3048 obligation: &TraitObligation<'tcx>,
3050 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
3051 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
3053 // First, create the substitutions by matching the impl again,
3054 // this time not in a probe.
3055 self.infcx.in_snapshot(|snapshot| {
3056 let substs = self.rematch_impl(impl_def_id, obligation, snapshot);
3057 debug!("confirm_impl_candidate: substs={:?}", substs);
3058 let cause = obligation.derived_cause(ImplDerivedObligation);
3063 obligation.recursion_depth + 1,
3064 obligation.param_env,
3072 mut substs: Normalized<'tcx, SubstsRef<'tcx>>,
3073 cause: ObligationCause<'tcx>,
3074 recursion_depth: usize,
3075 param_env: ty::ParamEnv<'tcx>,
3076 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
3078 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={})",
3079 impl_def_id, substs, recursion_depth,
3082 let mut impl_obligations = self.impl_or_trait_obligations(
3091 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
3092 impl_def_id, impl_obligations
3095 // Because of RFC447, the impl-trait-ref and obligations
3096 // are sufficient to determine the impl substs, without
3097 // relying on projections in the impl-trait-ref.
3099 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
3100 impl_obligations.append(&mut substs.obligations);
3104 substs: substs.value,
3105 nested: impl_obligations,
3109 fn confirm_object_candidate(
3111 obligation: &TraitObligation<'tcx>,
3112 ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
3113 debug!("confirm_object_candidate({:?})", obligation);
3115 // FIXME(nmatsakis) skipping binder here seems wrong -- we should
3116 // probably flatten the binder from the obligation and the binder
3117 // from the object. Have to try to make a broken test case that
3119 let self_ty = self.infcx
3120 .shallow_resolve(*obligation.self_ty().skip_binder());
3121 let poly_trait_ref = match self_ty.sty {
3122 ty::Dynamic(ref data, ..) =>
3123 data.principal().unwrap_or_else(|| {
3124 span_bug!(obligation.cause.span, "object candidate with no principal")
3125 }).with_self_ty(self.tcx(), self_ty),
3126 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
3129 let mut upcast_trait_ref = None;
3130 let mut nested = vec![];
3134 let tcx = self.tcx();
3136 // We want to find the first supertrait in the list of
3137 // supertraits that we can unify with, and do that
3138 // unification. We know that there is exactly one in the list
3139 // where we can unify because otherwise select would have
3140 // reported an ambiguity. (When we do find a match, also
3141 // record it for later.)
3142 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(
3143 |&t| match self.infcx.commit_if_ok(|_| self.match_poly_trait_ref(obligation, t)) {
3144 Ok(obligations) => {
3145 upcast_trait_ref = Some(t);
3146 nested.extend(obligations);
3153 // Additionally, for each of the nonmatching predicates that
3154 // we pass over, we sum up the set of number of vtable
3155 // entries, so that we can compute the offset for the selected
3157 vtable_base = nonmatching.map(|t| tcx.count_own_vtable_entries(t)).sum();
3161 upcast_trait_ref: upcast_trait_ref.unwrap(),
3167 fn confirm_fn_pointer_candidate(
3169 obligation: &TraitObligation<'tcx>,
3170 ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3171 debug!("confirm_fn_pointer_candidate({:?})", obligation);
3173 // Okay to skip binder; it is reintroduced below.
3174 let self_ty = self.infcx
3175 .shallow_resolve(*obligation.self_ty().skip_binder());
3176 let sig = self_ty.fn_sig(self.tcx());
3177 let trait_ref = self.tcx()
3178 .closure_trait_ref_and_return_type(
3179 obligation.predicate.def_id(),
3182 util::TupleArgumentsFlag::Yes,
3184 .map_bound(|(trait_ref, _)| trait_ref);
3189 } = project::normalize_with_depth(
3191 obligation.param_env,
3192 obligation.cause.clone(),
3193 obligation.recursion_depth + 1,
3197 self.confirm_poly_trait_refs(
3198 obligation.cause.clone(),
3199 obligation.param_env,
3200 obligation.predicate.to_poly_trait_ref(),
3203 Ok(VtableFnPointerData {
3205 nested: obligations,
3209 fn confirm_trait_alias_candidate(
3211 obligation: &TraitObligation<'tcx>,
3212 alias_def_id: DefId,
3213 ) -> VtableTraitAliasData<'tcx, PredicateObligation<'tcx>> {
3215 "confirm_trait_alias_candidate({:?}, {:?})",
3216 obligation, alias_def_id
3219 self.infcx.in_snapshot(|_| {
3220 let (predicate, _) = self.infcx()
3221 .replace_bound_vars_with_placeholders(&obligation.predicate);
3222 let trait_ref = predicate.trait_ref;
3223 let trait_def_id = trait_ref.def_id;
3224 let substs = trait_ref.substs;
3226 let trait_obligations = self.impl_or_trait_obligations(
3227 obligation.cause.clone(),
3228 obligation.recursion_depth,
3229 obligation.param_env,
3235 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
3236 trait_def_id, trait_obligations
3239 VtableTraitAliasData {
3242 nested: trait_obligations,
3247 fn confirm_generator_candidate(
3249 obligation: &TraitObligation<'tcx>,
3250 ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3251 // Okay to skip binder because the substs on generator types never
3252 // touch bound regions, they just capture the in-scope
3253 // type/region parameters.
3254 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3255 let (generator_def_id, substs) = match self_ty.sty {
3256 ty::Generator(id, substs, _) => (id, substs),
3257 _ => bug!("closure candidate for non-closure {:?}", obligation),
3261 "confirm_generator_candidate({:?},{:?},{:?})",
3262 obligation, generator_def_id, substs
3265 let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
3269 } = normalize_with_depth(
3271 obligation.param_env,
3272 obligation.cause.clone(),
3273 obligation.recursion_depth + 1,
3278 "confirm_generator_candidate(generator_def_id={:?}, \
3279 trait_ref={:?}, obligations={:?})",
3280 generator_def_id, trait_ref, obligations
3283 obligations.extend(self.confirm_poly_trait_refs(
3284 obligation.cause.clone(),
3285 obligation.param_env,
3286 obligation.predicate.to_poly_trait_ref(),
3290 Ok(VtableGeneratorData {
3291 generator_def_id: generator_def_id,
3292 substs: substs.clone(),
3293 nested: obligations,
3297 fn confirm_closure_candidate(
3299 obligation: &TraitObligation<'tcx>,
3300 ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3301 debug!("confirm_closure_candidate({:?})", obligation);
3303 let kind = self.tcx()
3305 .fn_trait_kind(obligation.predicate.def_id())
3306 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
3308 // Okay to skip binder because the substs on closure types never
3309 // touch bound regions, they just capture the in-scope
3310 // type/region parameters.
3311 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3312 let (closure_def_id, substs) = match self_ty.sty {
3313 ty::Closure(id, substs) => (id, substs),
3314 _ => bug!("closure candidate for non-closure {:?}", obligation),
3317 let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
3321 } = normalize_with_depth(
3323 obligation.param_env,
3324 obligation.cause.clone(),
3325 obligation.recursion_depth + 1,
3330 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
3331 closure_def_id, trait_ref, obligations
3334 obligations.extend(self.confirm_poly_trait_refs(
3335 obligation.cause.clone(),
3336 obligation.param_env,
3337 obligation.predicate.to_poly_trait_ref(),
3342 if !self.tcx().sess.opts.debugging_opts.chalk {
3343 obligations.push(Obligation::new(
3344 obligation.cause.clone(),
3345 obligation.param_env,
3346 ty::Predicate::ClosureKind(closure_def_id, substs, kind),
3350 Ok(VtableClosureData {
3352 substs: substs.clone(),
3353 nested: obligations,
3357 /// In the case of closure types and fn pointers,
3358 /// we currently treat the input type parameters on the trait as
3359 /// outputs. This means that when we have a match we have only
3360 /// considered the self type, so we have to go back and make sure
3361 /// to relate the argument types too. This is kind of wrong, but
3362 /// since we control the full set of impls, also not that wrong,
3363 /// and it DOES yield better error messages (since we don't report
3364 /// errors as if there is no applicable impl, but rather report
3365 /// errors are about mismatched argument types.
3367 /// Here is an example. Imagine we have a closure expression
3368 /// and we desugared it so that the type of the expression is
3369 /// `Closure`, and `Closure` expects an int as argument. Then it
3370 /// is "as if" the compiler generated this impl:
3372 /// impl Fn(int) for Closure { ... }
3374 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
3375 /// we have matched the self type `Closure`. At this point we'll
3376 /// compare the `int` to `usize` and generate an error.
3378 /// Note that this checking occurs *after* the impl has selected,
3379 /// because these output type parameters should not affect the
3380 /// selection of the impl. Therefore, if there is a mismatch, we
3381 /// report an error to the user.
3382 fn confirm_poly_trait_refs(
3384 obligation_cause: ObligationCause<'tcx>,
3385 obligation_param_env: ty::ParamEnv<'tcx>,
3386 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
3387 expected_trait_ref: ty::PolyTraitRef<'tcx>,
3388 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3389 let obligation_trait_ref = obligation_trait_ref.clone();
3391 .at(&obligation_cause, obligation_param_env)
3392 .sup(obligation_trait_ref, expected_trait_ref)
3393 .map(|InferOk { obligations, .. }| obligations)
3394 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
3397 fn confirm_builtin_unsize_candidate(
3399 obligation: &TraitObligation<'tcx>,
3400 ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3401 let tcx = self.tcx();
3403 // assemble_candidates_for_unsizing should ensure there are no late bound
3404 // regions here. See the comment there for more details.
3405 let source = self.infcx
3406 .shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
3407 let target = obligation
3413 let target = self.infcx.shallow_resolve(target);
3416 "confirm_builtin_unsize_candidate(source={:?}, target={:?})",
3420 let mut nested = vec![];
3421 match (&source.sty, &target.sty) {
3422 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
3423 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
3424 // See assemble_candidates_for_unsizing for more info.
3425 let existential_predicates = data_a.map_bound(|data_a| {
3427 data_a.principal().map(|x| ty::ExistentialPredicate::Trait(x))
3430 .projection_bounds()
3431 .map(|x| ty::ExistentialPredicate::Projection(x)),
3436 .map(ty::ExistentialPredicate::AutoTrait),
3438 tcx.mk_existential_predicates(iter)
3440 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
3442 // Require that the traits involved in this upcast are **equal**;
3443 // only the **lifetime bound** is changed.
3445 // FIXME: This condition is arguably too strong -- it
3446 // would suffice for the source trait to be a
3447 // *subtype* of the target trait. In particular
3448 // changing from something like `for<'a, 'b> Foo<'a,
3449 // 'b>` to `for<'a> Foo<'a, 'a>` should be
3450 // permitted. And, indeed, in the in commit
3451 // 904a0bde93f0348f69914ee90b1f8b6e4e0d7cbc, this
3452 // condition was loosened. However, when the leak check was added
3453 // back, using subtype here actually guies the coercion code in
3454 // such a way that it accepts `old-lub-glb-object.rs`. This is probably
3455 // a good thing, but I've modified this to `.eq` because I want
3456 // to continue rejecting that test (as we have done for quite some time)
3457 // before we are firmly comfortable with what our behavior
3458 // should be there. -nikomatsakis
3459 let InferOk { obligations, .. } = self.infcx
3460 .at(&obligation.cause, obligation.param_env)
3461 .eq(target, source_trait) // FIXME -- see below
3462 .map_err(|_| Unimplemented)?;
3463 nested.extend(obligations);
3465 // Register one obligation for 'a: 'b.
3466 let cause = ObligationCause::new(
3467 obligation.cause.span,
3468 obligation.cause.body_id,
3469 ObjectCastObligation(target),
3471 let outlives = ty::OutlivesPredicate(r_a, r_b);
3472 nested.push(Obligation::with_depth(
3474 obligation.recursion_depth + 1,
3475 obligation.param_env,
3476 ty::Binder::bind(outlives).to_predicate(),
3481 (_, &ty::Dynamic(ref data, r)) => {
3482 let mut object_dids = data.auto_traits()
3483 .chain(data.principal_def_id());
3484 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3485 return Err(TraitNotObjectSafe(did));
3488 let cause = ObligationCause::new(
3489 obligation.cause.span,
3490 obligation.cause.body_id,
3491 ObjectCastObligation(target),
3494 let predicate_to_obligation = |predicate| {
3495 Obligation::with_depth(
3497 obligation.recursion_depth + 1,
3498 obligation.param_env,
3503 // Create obligations:
3504 // - Casting T to Trait
3505 // - For all the various builtin bounds attached to the object cast. (In other
3506 // words, if the object type is Foo+Send, this would create an obligation for the
3508 // - Projection predicates
3511 .map(|d| predicate_to_obligation(d.with_self_ty(tcx, source))),
3514 // We can only make objects from sized types.
3515 let tr = ty::TraitRef {
3516 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
3517 substs: tcx.mk_substs_trait(source, &[]),
3519 nested.push(predicate_to_obligation(tr.to_predicate()));
3521 // If the type is `Foo+'a`, ensures that the type
3522 // being cast to `Foo+'a` outlives `'a`:
3523 let outlives = ty::OutlivesPredicate(source, r);
3524 nested.push(predicate_to_obligation(
3525 ty::Binder::dummy(outlives).to_predicate(),
3530 (&ty::Array(a, _), &ty::Slice(b)) => {
3531 let InferOk { obligations, .. } = self.infcx
3532 .at(&obligation.cause, obligation.param_env)
3534 .map_err(|_| Unimplemented)?;
3535 nested.extend(obligations);
3538 // Struct<T> -> Struct<U>.
3539 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3540 let fields = def.all_fields()
3541 .map(|f| tcx.type_of(f.did))
3542 .collect::<Vec<_>>();
3544 // The last field of the structure has to exist and contain type parameters.
3545 let field = if let Some(&field) = fields.last() {
3548 return Err(Unimplemented);
3550 let mut ty_params = GrowableBitSet::new_empty();
3551 let mut found = false;
3552 for ty in field.walk() {
3553 if let ty::Param(p) = ty.sty {
3554 ty_params.insert(p.index as usize);
3559 return Err(Unimplemented);
3562 // Replace type parameters used in unsizing with
3563 // Error and ensure they do not affect any other fields.
3564 // This could be checked after type collection for any struct
3565 // with a potentially unsized trailing field.
3566 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3567 if ty_params.contains(i) {
3568 tcx.types.err.into()
3573 let substs = tcx.mk_substs(params);
3574 for &ty in fields.split_last().unwrap().1 {
3575 if ty.subst(tcx, substs).references_error() {
3576 return Err(Unimplemented);
3580 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
3581 let inner_source = field.subst(tcx, substs_a);
3582 let inner_target = field.subst(tcx, substs_b);
3584 // Check that the source struct with the target's
3585 // unsized parameters is equal to the target.
3586 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3587 if ty_params.contains(i) {
3588 substs_b.type_at(i).into()
3593 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3594 let InferOk { obligations, .. } = self.infcx
3595 .at(&obligation.cause, obligation.param_env)
3596 .eq(target, new_struct)
3597 .map_err(|_| Unimplemented)?;
3598 nested.extend(obligations);
3600 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
3601 nested.push(tcx.predicate_for_trait_def(
3602 obligation.param_env,
3603 obligation.cause.clone(),
3604 obligation.predicate.def_id(),
3605 obligation.recursion_depth + 1,
3607 &[inner_target.into()],
3611 // (.., T) -> (.., U).
3612 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3613 assert_eq!(tys_a.len(), tys_b.len());
3615 // The last field of the tuple has to exist.
3616 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3619 return Err(Unimplemented);
3621 let &b_last = tys_b.last().unwrap();
3623 // Check that the source tuple with the target's
3624 // last element is equal to the target.
3625 let new_tuple = tcx.mk_tup(
3626 a_mid.iter().map(|k| k.expect_ty()).chain(iter::once(b_last.expect_ty())),
3628 let InferOk { obligations, .. } = self.infcx
3629 .at(&obligation.cause, obligation.param_env)
3630 .eq(target, new_tuple)
3631 .map_err(|_| Unimplemented)?;
3632 nested.extend(obligations);
3634 // Construct the nested T: Unsize<U> predicate.
3635 nested.push(tcx.predicate_for_trait_def(
3636 obligation.param_env,
3637 obligation.cause.clone(),
3638 obligation.predicate.def_id(),
3639 obligation.recursion_depth + 1,
3648 Ok(VtableBuiltinData { nested })
3651 ///////////////////////////////////////////////////////////////////////////
3654 // Matching is a common path used for both evaluation and
3655 // confirmation. It basically unifies types that appear in impls
3656 // and traits. This does affect the surrounding environment;
3657 // therefore, when used during evaluation, match routines must be
3658 // run inside of a `probe()` so that their side-effects are
3664 obligation: &TraitObligation<'tcx>,
3665 snapshot: &CombinedSnapshot<'_, 'tcx>,
3666 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
3667 match self.match_impl(impl_def_id, obligation, snapshot) {
3668 Ok(substs) => substs,
3671 "Impl {:?} was matchable against {:?} but now is not",
3682 obligation: &TraitObligation<'tcx>,
3683 snapshot: &CombinedSnapshot<'_, 'tcx>,
3684 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
3685 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3687 // Before we create the substitutions and everything, first
3688 // consider a "quick reject". This avoids creating more types
3689 // and so forth that we need to.
3690 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3694 let (skol_obligation, placeholder_map) = self.infcx()
3695 .replace_bound_vars_with_placeholders(&obligation.predicate);
3696 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3698 let impl_substs = self.infcx
3699 .fresh_substs_for_item(obligation.cause.span, impl_def_id);
3701 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3704 value: impl_trait_ref,
3705 obligations: mut nested_obligations,
3706 } = project::normalize_with_depth(
3708 obligation.param_env,
3709 obligation.cause.clone(),
3710 obligation.recursion_depth + 1,
3715 "match_impl(impl_def_id={:?}, obligation={:?}, \
3716 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3717 impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3720 let InferOk { obligations, .. } = self.infcx
3721 .at(&obligation.cause, obligation.param_env)
3722 .eq(skol_obligation_trait_ref, impl_trait_ref)
3723 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3724 nested_obligations.extend(obligations);
3726 if let Err(e) = self.infcx.leak_check(false, &placeholder_map, snapshot) {
3727 debug!("match_impl: failed leak check due to `{}`", e);
3731 debug!("match_impl: success impl_substs={:?}", impl_substs);
3734 obligations: nested_obligations,
3738 fn fast_reject_trait_refs(
3740 obligation: &TraitObligation<'_>,
3741 impl_trait_ref: &ty::TraitRef<'_>,
3743 // We can avoid creating type variables and doing the full
3744 // substitution if we find that any of the input types, when
3745 // simplified, do not match.
3751 .zip(impl_trait_ref.input_types())
3752 .any(|(obligation_ty, impl_ty)| {
3753 let simplified_obligation_ty =
3754 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3755 let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
3757 simplified_obligation_ty.is_some()
3758 && simplified_impl_ty.is_some()
3759 && simplified_obligation_ty != simplified_impl_ty
3763 /// Normalize `where_clause_trait_ref` and try to match it against
3764 /// `obligation`. If successful, return any predicates that
3765 /// result from the normalization. Normalization is necessary
3766 /// because where-clauses are stored in the parameter environment
3768 fn match_where_clause_trait_ref(
3770 obligation: &TraitObligation<'tcx>,
3771 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3772 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3773 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3776 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3777 /// obligation is satisfied.
3778 fn match_poly_trait_ref(
3780 obligation: &TraitObligation<'tcx>,
3781 poly_trait_ref: ty::PolyTraitRef<'tcx>,
3782 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3784 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3785 obligation, poly_trait_ref
3789 .at(&obligation.cause, obligation.param_env)
3790 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3791 .map(|InferOk { obligations, .. }| obligations)
3795 ///////////////////////////////////////////////////////////////////////////
3798 fn match_fresh_trait_refs(
3800 previous: &ty::PolyTraitRef<'tcx>,
3801 current: &ty::PolyTraitRef<'tcx>,
3802 param_env: ty::ParamEnv<'tcx>,
3804 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
3805 matcher.relate(previous, current).is_ok()
3810 previous_stack: TraitObligationStackList<'o, 'tcx>,
3811 obligation: &'o TraitObligation<'tcx>,
3812 ) -> TraitObligationStack<'o, 'tcx> {
3813 let fresh_trait_ref = obligation
3815 .to_poly_trait_ref()
3816 .fold_with(&mut self.freshener);
3818 let dfn = previous_stack.cache.next_dfn();
3819 let depth = previous_stack.depth() + 1;
3820 TraitObligationStack {
3823 reached_depth: Cell::new(depth),
3824 previous: previous_stack,
3830 fn closure_trait_ref_unnormalized(
3832 obligation: &TraitObligation<'tcx>,
3833 closure_def_id: DefId,
3834 substs: ty::ClosureSubsts<'tcx>,
3835 ) -> ty::PolyTraitRef<'tcx> {
3837 "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})",
3838 obligation, closure_def_id, substs,
3840 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3843 "closure_trait_ref_unnormalized: closure_type = {:?}",
3847 // (1) Feels icky to skip the binder here, but OTOH we know
3848 // that the self-type is an unboxed closure type and hence is
3849 // in fact unparameterized (or at least does not reference any
3850 // regions bound in the obligation). Still probably some
3851 // refactoring could make this nicer.
3853 .closure_trait_ref_and_return_type(
3854 obligation.predicate.def_id(),
3855 obligation.predicate.skip_binder().self_ty(), // (1)
3857 util::TupleArgumentsFlag::No,
3859 .map_bound(|(trait_ref, _)| trait_ref)
3862 fn generator_trait_ref_unnormalized(
3864 obligation: &TraitObligation<'tcx>,
3865 closure_def_id: DefId,
3866 substs: ty::GeneratorSubsts<'tcx>,
3867 ) -> ty::PolyTraitRef<'tcx> {
3868 let gen_sig = substs.poly_sig(closure_def_id, self.tcx());
3870 // (1) Feels icky to skip the binder here, but OTOH we know
3871 // that the self-type is an generator type and hence is
3872 // in fact unparameterized (or at least does not reference any
3873 // regions bound in the obligation). Still probably some
3874 // refactoring could make this nicer.
3877 .generator_trait_ref_and_outputs(
3878 obligation.predicate.def_id(),
3879 obligation.predicate.skip_binder().self_ty(), // (1)
3882 .map_bound(|(trait_ref, ..)| trait_ref)
3885 /// Returns the obligations that are implied by instantiating an
3886 /// impl or trait. The obligations are substituted and fully
3887 /// normalized. This is used when confirming an impl or default
3889 fn impl_or_trait_obligations(
3891 cause: ObligationCause<'tcx>,
3892 recursion_depth: usize,
3893 param_env: ty::ParamEnv<'tcx>,
3894 def_id: DefId, // of impl or trait
3895 substs: SubstsRef<'tcx>, // for impl or trait
3896 ) -> Vec<PredicateObligation<'tcx>> {
3897 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3898 let tcx = self.tcx();
3900 // To allow for one-pass evaluation of the nested obligation,
3901 // each predicate must be preceded by the obligations required
3903 // for example, if we have:
3904 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3905 // the impl will have the following predicates:
3906 // <V as Iterator>::Item = U,
3907 // U: Iterator, U: Sized,
3908 // V: Iterator, V: Sized,
3909 // <U as Iterator>::Item: Copy
3910 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3911 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3912 // `$1: Copy`, so we must ensure the obligations are emitted in
3914 let predicates = tcx.predicates_of(def_id);
3915 assert_eq!(predicates.parent, None);
3916 let mut predicates: Vec<_> = predicates
3919 .flat_map(|(predicate, _)| {
3920 let predicate = normalize_with_depth(
3925 &predicate.subst(tcx, substs),
3927 predicate.obligations.into_iter().chain(Some(Obligation {
3928 cause: cause.clone(),
3931 predicate: predicate.value,
3936 // We are performing deduplication here to avoid exponential blowups
3937 // (#38528) from happening, but the real cause of the duplication is
3938 // unknown. What we know is that the deduplication avoids exponential
3939 // amount of predicates being propagated when processing deeply nested
3942 // This code is hot enough that it's worth avoiding the allocation
3943 // required for the FxHashSet when possible. Special-casing lengths 0,
3944 // 1 and 2 covers roughly 75--80% of the cases.
3945 if predicates.len() <= 1 {
3946 // No possibility of duplicates.
3947 } else if predicates.len() == 2 {
3948 // Only two elements. Drop the second if they are equal.
3949 if predicates[0] == predicates[1] {
3950 predicates.truncate(1);
3953 // Three or more elements. Use a general deduplication process.
3954 let mut seen = FxHashSet::default();
3955 predicates.retain(|i| seen.insert(i.clone()));
3962 impl<'tcx> TraitObligation<'tcx> {
3963 #[allow(unused_comparisons)]
3964 pub fn derived_cause(
3966 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3967 ) -> ObligationCause<'tcx> {
3969 * Creates a cause for obligations that are derived from
3970 * `obligation` by a recursive search (e.g., for a builtin
3971 * bound, or eventually a `auto trait Foo`). If `obligation`
3972 * is itself a derived obligation, this is just a clone, but
3973 * otherwise we create a "derived obligation" cause so as to
3974 * keep track of the original root obligation for error
3978 let obligation = self;
3980 // NOTE(flaper87): As of now, it keeps track of the whole error
3981 // chain. Ideally, we should have a way to configure this either
3982 // by using -Z verbose or just a CLI argument.
3983 if obligation.recursion_depth >= 0 {
3984 let derived_cause = DerivedObligationCause {
3985 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3986 parent_code: Rc::new(obligation.cause.code.clone()),
3988 let derived_code = variant(derived_cause);
3989 ObligationCause::new(
3990 obligation.cause.span,
3991 obligation.cause.body_id,
3995 obligation.cause.clone()
4000 impl<'tcx> SelectionCache<'tcx> {
4001 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
4002 pub fn clear(&self) {
4003 *self.hashmap.borrow_mut() = Default::default();
4007 impl<'tcx> EvaluationCache<'tcx> {
4008 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
4009 pub fn clear(&self) {
4010 *self.hashmap.borrow_mut() = Default::default();
4014 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
4015 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
4016 TraitObligationStackList::with(self)
4019 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
4023 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
4027 /// Indicates that attempting to evaluate this stack entry
4028 /// required accessing something from the stack at depth `reached_depth`.
4029 fn update_reached_depth(&self, reached_depth: usize) {
4031 self.depth > reached_depth,
4032 "invoked `update_reached_depth` with something under this stack: \
4033 self.depth={} reached_depth={}",
4037 debug!("update_reached_depth(reached_depth={})", reached_depth);
4039 while reached_depth < p.depth {
4040 debug!("update_reached_depth: marking {:?} as cycle participant", p.fresh_trait_ref);
4041 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
4042 p = p.previous.head.unwrap();
4047 /// The "provisional evaluation cache" is used to store intermediate cache results
4048 /// when solving auto traits. Auto traits are unusual in that they can support
4049 /// cycles. So, for example, a "proof tree" like this would be ok:
4051 /// - `Foo<T>: Send` :-
4052 /// - `Bar<T>: Send` :-
4053 /// - `Foo<T>: Send` -- cycle, but ok
4054 /// - `Baz<T>: Send`
4056 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
4057 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
4058 /// For non-auto traits, this cycle would be an error, but for auto traits (because
4059 /// they are coinductive) it is considered ok.
4061 /// However, there is a complication: at the point where we have
4062 /// "proven" `Bar<T>: Send`, we have in fact only proven it
4063 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
4064 /// *under the assumption* that `Foo<T>: Send`. But what if we later
4065 /// find out this assumption is wrong? Specifically, we could
4066 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
4067 /// `Bar<T>: Send` didn't turn out to be true.
4069 /// In Issue #60010, we found a bug in rustc where it would cache
4070 /// these intermediate results. This was fixed in #60444 by disabling
4071 /// *all* caching for things involved in a cycle -- in our example,
4072 /// that would mean we don't cache that `Bar<T>: Send`. But this led
4073 /// to large slowdowns.
4075 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
4076 /// first requires proving `Bar<T>: Send` (which is true:
4078 /// - `Foo<T>: Send` :-
4079 /// - `Bar<T>: Send` :-
4080 /// - `Foo<T>: Send` -- cycle, but ok
4081 /// - `Baz<T>: Send`
4082 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
4083 /// - `*const T: Send` -- but what if we later encounter an error?
4085 /// The *provisional evaluation cache* resolves this issue. It stores
4086 /// cache results that we've proven but which were involved in a cycle
4087 /// in some way. We track the minimal stack depth (i.e., the
4088 /// farthest from the top of the stack) that we are dependent on.
4089 /// The idea is that the cache results within are all valid -- so long as
4090 /// none of the nodes in between the current node and the node at that minimum
4091 /// depth result in an error (in which case the cached results are just thrown away).
4093 /// During evaluation, we consult this provisional cache and rely on
4094 /// it. Accessing a cached value is considered equivalent to accessing
4095 /// a result at `reached_depth`, so it marks the *current* solution as
4096 /// provisional as well. If an error is encountered, we toss out any
4097 /// provisional results added from the subtree that encountered the
4098 /// error. When we pop the node at `reached_depth` from the stack, we
4099 /// can commit all the things that remain in the provisional cache.
4100 struct ProvisionalEvaluationCache<'tcx> {
4101 /// next "depth first number" to issue -- just a counter
4104 /// Stores the "coldest" depth (bottom of stack) reached by any of
4105 /// the evaluation entries. The idea here is that all things in the provisional
4106 /// cache are always dependent on *something* that is colder in the stack:
4107 /// therefore, if we add a new entry that is dependent on something *colder still*,
4108 /// we have to modify the depth for all entries at once.
4112 /// Imagine we have a stack `A B C D E` (with `E` being the top of
4113 /// the stack). We cache something with depth 2, which means that
4114 /// it was dependent on C. Then we pop E but go on and process a
4115 /// new node F: A B C D F. Now F adds something to the cache with
4116 /// depth 1, meaning it is dependent on B. Our original cache
4117 /// entry is also dependent on B, because there is a path from E
4118 /// to C and then from C to F and from F to B.
4119 reached_depth: Cell<usize>,
4121 /// Map from cache key to the provisionally evaluated thing.
4122 /// The cache entries contain the result but also the DFN in which they
4123 /// were added. The DFN is used to clear out values on failure.
4125 /// Imagine we have a stack like:
4127 /// - `A B C` and we add a cache for the result of C (DFN 2)
4128 /// - Then we have a stack `A B D` where `D` has DFN 3
4129 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
4130 /// - `E` generates various cache entries which have cyclic dependices on `B`
4131 /// - `A B D E F` and so forth
4132 /// - the DFN of `F` for example would be 5
4133 /// - then we determine that `E` is in error -- we will then clear
4134 /// all cache values whose DFN is >= 4 -- in this case, that
4135 /// means the cached value for `F`.
4136 map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
4139 /// A cache value for the provisional cache: contains the depth-first
4140 /// number (DFN) and result.
4141 #[derive(Copy, Clone, Debug)]
4142 struct ProvisionalEvaluation {
4144 result: EvaluationResult,
4147 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
4148 fn default() -> Self {
4151 reached_depth: Cell::new(std::usize::MAX),
4152 map: Default::default(),
4157 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
4158 /// Get the next DFN in sequence (basically a counter).
4159 fn next_dfn(&self) -> usize {
4160 let result = self.dfn.get();
4161 self.dfn.set(result + 1);
4165 /// Check the provisional cache for any result for
4166 /// `fresh_trait_ref`. If there is a hit, then you must consider
4167 /// it an access to the stack slots at depth
4168 /// `self.current_reached_depth()` and above.
4169 fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
4171 "get_provisional(fresh_trait_ref={:?}) = {:#?} with reached-depth {}",
4173 self.map.borrow().get(&fresh_trait_ref),
4174 self.reached_depth.get(),
4176 Some(self.map.borrow().get(&fresh_trait_ref)?.result)
4179 /// Current value of the `reached_depth` counter -- all the
4180 /// provisional cache entries are dependent on the item at this
4182 fn current_reached_depth(&self) -> usize {
4183 self.reached_depth.get()
4186 /// Insert a provisional result into the cache. The result came
4187 /// from the node with the given DFN. It accessed a minimum depth
4188 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
4189 /// and resulted in `result`.
4190 fn insert_provisional(
4193 reached_depth: usize,
4194 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
4195 result: EvaluationResult,
4198 "insert_provisional(from_dfn={}, reached_depth={}, fresh_trait_ref={:?}, result={:?})",
4204 let r_d = self.reached_depth.get();
4205 self.reached_depth.set(r_d.min(reached_depth));
4207 debug!("insert_provisional: reached_depth={:?}", self.reached_depth.get());
4209 self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
4212 /// Invoked when the node with dfn `dfn` does not get a successful
4213 /// result. This will clear out any provisional cache entries
4214 /// that were added since `dfn` was created. This is because the
4215 /// provisional entries are things which must assume that the
4216 /// things on the stack at the time of their creation succeeded --
4217 /// since the failing node is presently at the top of the stack,
4218 /// these provisional entries must either depend on it or some
4220 fn on_failure(&self, dfn: usize) {
4222 "on_failure(dfn={:?})",
4225 self.map.borrow_mut().retain(|key, eval| {
4226 if !eval.from_dfn >= dfn {
4227 debug!("on_failure: removing {:?}", key);
4235 /// Invoked when the node at depth `depth` completed without
4236 /// depending on anything higher in the stack (if that completion
4237 /// was a failure, then `on_failure` should have been invoked
4238 /// already). The callback `op` will be invoked for each
4239 /// provisional entry that we can now confirm.
4243 mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
4246 "on_completion(depth={}, reached_depth={})",
4248 self.reached_depth.get(),
4251 if self.reached_depth.get() < depth {
4252 debug!("on_completion: did not yet reach depth to complete");
4256 for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
4258 "on_completion: fresh_trait_ref={:?} eval={:?}",
4263 op(fresh_trait_ref, eval.result);
4266 self.reached_depth.set(std::usize::MAX);
4270 #[derive(Copy, Clone)]
4271 struct TraitObligationStackList<'o, 'tcx> {
4272 cache: &'o ProvisionalEvaluationCache<'tcx>,
4273 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
4276 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
4277 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4278 TraitObligationStackList { cache, head: None }
4281 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4282 TraitObligationStackList { cache: r.cache(), head: Some(r) }
4285 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4289 fn depth(&self) -> usize {
4290 if let Some(head) = self.head {
4298 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
4299 type Item = &'o TraitObligationStack<'o, 'tcx>;
4301 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4312 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
4313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4314 write!(f, "TraitObligationStack({:?})", self.obligation)
4318 #[derive(Clone, Eq, PartialEq)]
4319 pub struct WithDepNode<T> {
4320 dep_node: DepNodeIndex,
4324 impl<T: Clone> WithDepNode<T> {
4325 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
4332 pub fn get(&self, tcx: TyCtxt<'_>) -> T {
4333 tcx.dep_graph.read_index(self.dep_node);
4334 self.cached_value.clone()