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(&stack.fresh_trait_ref, &prev.fresh_trait_ref)
1088 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
1089 stack.fresh_trait_ref
1091 return Ok(EvaluatedToUnknown);
1094 match self.candidate_from_obligation(stack) {
1095 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1096 Ok(None) => Ok(EvaluatedToAmbig),
1097 Err(Overflow) => Err(OverflowError),
1098 Err(..) => Ok(EvaluatedToErr),
1102 /// For defaulted traits, we use a co-inductive strategy to solve, so
1103 /// that recursion is ok. This routine returns true if the top of the
1104 /// stack (`cycle[0]`):
1106 /// - is a defaulted trait,
1107 /// - it also appears in the backtrace at some position `X`,
1108 /// - all the predicates at positions `X..` between `X` and the top are
1109 /// also defaulted traits.
1110 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
1112 I: Iterator<Item = ty::Predicate<'tcx>>,
1114 let mut cycle = cycle;
1115 cycle.all(|predicate| self.coinductive_predicate(predicate))
1118 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1119 let result = match predicate {
1120 ty::Predicate::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1123 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
1127 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
1128 /// obligations are met. Returns whether `candidate` remains viable after this further
1130 fn evaluate_candidate<'o>(
1132 stack: &TraitObligationStack<'o, 'tcx>,
1133 candidate: &SelectionCandidate<'tcx>,
1134 ) -> Result<EvaluationResult, OverflowError> {
1136 "evaluate_candidate: depth={} candidate={:?}",
1137 stack.obligation.recursion_depth, candidate
1139 let result = self.evaluation_probe(|this| {
1140 let candidate = (*candidate).clone();
1141 match this.confirm_candidate(stack.obligation, candidate) {
1142 Ok(selection) => this.evaluate_predicates_recursively(
1144 selection.nested_obligations().into_iter()
1146 Err(..) => Ok(EvaluatedToErr),
1150 "evaluate_candidate: depth={} result={:?}",
1151 stack.obligation.recursion_depth, result
1156 fn check_evaluation_cache(
1158 param_env: ty::ParamEnv<'tcx>,
1159 trait_ref: ty::PolyTraitRef<'tcx>,
1160 ) -> Option<EvaluationResult> {
1161 let tcx = self.tcx();
1162 if self.can_use_global_caches(param_env) {
1163 let cache = tcx.evaluation_cache.hashmap.borrow();
1164 if let Some(cached) = cache.get(&trait_ref) {
1165 return Some(cached.get(tcx));
1173 .map(|v| v.get(tcx))
1176 fn insert_evaluation_cache(
1178 param_env: ty::ParamEnv<'tcx>,
1179 trait_ref: ty::PolyTraitRef<'tcx>,
1180 dep_node: DepNodeIndex,
1181 result: EvaluationResult,
1183 // Avoid caching results that depend on more than just the trait-ref
1184 // - the stack can create recursion.
1185 if result.is_stack_dependent() {
1189 if self.can_use_global_caches(param_env) {
1190 if !trait_ref.has_local_value() {
1192 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
1195 // This may overwrite the cache with the same value
1196 // FIXME: Due to #50507 this overwrites the different values
1197 // This should be changed to use HashMapExt::insert_same
1198 // when that is fixed
1203 .insert(trait_ref, WithDepNode::new(dep_node, result));
1209 "insert_evaluation_cache(trait_ref={:?}, candidate={:?})",
1216 .insert(trait_ref, WithDepNode::new(dep_node, result));
1219 // For various reasons, it's possible for a subobligation
1220 // to have a *lower* recursion_depth than the obligation used to create it.
1221 // Projection sub-obligations may be returned from the projection cache,
1222 // which results in obligations with an 'old' recursion_depth.
1223 // Additionally, methods like ty::wf::obligations and
1224 // InferCtxt.subtype_predicate produce subobligations without
1225 // taking in a 'parent' depth, causing the generated subobligations
1226 // to have a recursion_depth of 0
1228 // To ensure that obligation_depth never decreasees, we force all subobligations
1229 // to have at least the depth of the original obligation.
1230 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(&self, it: I,
1232 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1235 // Check that the recursion limit has not been exceeded.
1237 // The weird return type of this function allows it to be used with the 'try' (?)
1238 // operator within certain functions
1239 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1241 obligation: &Obligation<'tcx, T>,
1242 error_obligation: &Obligation<'tcx, V>
1243 ) -> Result<(), OverflowError> {
1244 let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
1245 if obligation.recursion_depth >= recursion_limit {
1246 match self.query_mode {
1247 TraitQueryMode::Standard => {
1248 self.infcx().report_overflow_error(error_obligation, true);
1250 TraitQueryMode::Canonical => {
1251 return Err(OverflowError);
1258 ///////////////////////////////////////////////////////////////////////////
1259 // CANDIDATE ASSEMBLY
1261 // The selection process begins by examining all in-scope impls,
1262 // caller obligations, and so forth and assembling a list of
1263 // candidates. See the [rustc guide] for more details.
1266 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#candidate-assembly
1268 fn candidate_from_obligation<'o>(
1270 stack: &TraitObligationStack<'o, 'tcx>,
1271 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1272 // Watch out for overflow. This intentionally bypasses (and does
1273 // not update) the cache.
1274 self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
1277 // Check the cache. Note that we freshen the trait-ref
1278 // separately rather than using `stack.fresh_trait_ref` --
1279 // this is because we want the unbound variables to be
1280 // replaced with fresh types starting from index 0.
1281 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate.clone());
1283 "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1284 cache_fresh_trait_pred, stack
1286 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
1289 self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
1291 debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
1295 // If no match, compute result and insert into cache.
1297 // FIXME(nikomatsakis) -- this cache is not taking into
1298 // account cycles that may have occurred in forming the
1299 // candidate. I don't know of any specific problems that
1300 // result but it seems awfully suspicious.
1301 let (candidate, dep_node) =
1302 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
1305 "CACHE MISS: SELECT({:?})={:?}",
1306 cache_fresh_trait_pred, candidate
1308 self.insert_candidate_cache(
1309 stack.obligation.param_env,
1310 cache_fresh_trait_pred,
1317 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1319 OP: FnOnce(&mut Self) -> R,
1321 let (result, dep_node) = self.tcx()
1323 .with_anon_task(DepKind::TraitSelect, || op(self));
1324 self.tcx().dep_graph.read_index(dep_node);
1328 // Treat negative impls as unimplemented
1329 fn filter_negative_impls(
1331 candidate: SelectionCandidate<'tcx>,
1332 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1333 if let ImplCandidate(def_id) = candidate {
1334 if !self.allow_negative_impls
1335 && self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative
1337 return Err(Unimplemented);
1343 fn candidate_from_obligation_no_cache<'o>(
1345 stack: &TraitObligationStack<'o, 'tcx>,
1346 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1347 if stack.obligation.predicate.references_error() {
1348 // If we encounter a `Error`, we generally prefer the
1349 // most "optimistic" result in response -- that is, the
1350 // one least likely to report downstream errors. But
1351 // because this routine is shared by coherence and by
1352 // trait selection, there isn't an obvious "right" choice
1353 // here in that respect, so we opt to just return
1354 // ambiguity and let the upstream clients sort it out.
1358 if let Some(conflict) = self.is_knowable(stack) {
1359 debug!("coherence stage: not knowable");
1360 if self.intercrate_ambiguity_causes.is_some() {
1361 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1362 // Heuristics: show the diagnostics when there are no candidates in crate.
1363 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1364 let mut no_candidates_apply = true;
1366 let evaluated_candidates = candidate_set
1369 .map(|c| self.evaluate_candidate(stack, &c));
1371 for ec in evaluated_candidates {
1375 no_candidates_apply = false;
1379 Err(e) => return Err(e.into()),
1384 if !candidate_set.ambiguous && no_candidates_apply {
1385 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1386 let self_ty = trait_ref.self_ty();
1387 let trait_desc = trait_ref.to_string();
1388 let self_desc = if self_ty.has_concrete_skeleton() {
1389 Some(self_ty.to_string())
1393 let cause = if let Conflict::Upstream = conflict {
1394 IntercrateAmbiguityCause::UpstreamCrateUpdate {
1399 IntercrateAmbiguityCause::DownstreamCrate {
1404 debug!("evaluate_stack: pushing cause = {:?}", cause);
1405 self.intercrate_ambiguity_causes
1415 let candidate_set = self.assemble_candidates(stack)?;
1417 if candidate_set.ambiguous {
1418 debug!("candidate set contains ambig");
1422 let mut candidates = candidate_set.vec;
1425 "assembled {} candidates for {:?}: {:?}",
1431 // At this point, we know that each of the entries in the
1432 // candidate set is *individually* applicable. Now we have to
1433 // figure out if they contain mutual incompatibilities. This
1434 // frequently arises if we have an unconstrained input type --
1435 // for example, we are looking for $0:Eq where $0 is some
1436 // unconstrained type variable. In that case, we'll get a
1437 // candidate which assumes $0 == int, one that assumes $0 ==
1438 // usize, etc. This spells an ambiguity.
1440 // If there is more than one candidate, first winnow them down
1441 // by considering extra conditions (nested obligations and so
1442 // forth). We don't winnow if there is exactly one
1443 // candidate. This is a relatively minor distinction but it
1444 // can lead to better inference and error-reporting. An
1445 // example would be if there was an impl:
1447 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1449 // and we were to see some code `foo.push_clone()` where `boo`
1450 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1451 // we were to winnow, we'd wind up with zero candidates.
1452 // Instead, we select the right impl now but report `Bar does
1453 // not implement Clone`.
1454 if candidates.len() == 1 {
1455 return self.filter_negative_impls(candidates.pop().unwrap());
1458 // Winnow, but record the exact outcome of evaluation, which
1459 // is needed for specialization. Propagate overflow if it occurs.
1460 let mut candidates = candidates
1462 .map(|c| match self.evaluate_candidate(stack, &c) {
1463 Ok(eval) if eval.may_apply() => Ok(Some(EvaluatedCandidate {
1468 Err(OverflowError) => Err(Overflow),
1470 .flat_map(Result::transpose)
1471 .collect::<Result<Vec<_>, _>>()?;
1474 "winnowed to {} candidates for {:?}: {:?}",
1480 // If there are STILL multiple candidates, we can further
1481 // reduce the list by dropping duplicates -- including
1482 // resolving specializations.
1483 if candidates.len() > 1 {
1485 while i < candidates.len() {
1486 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1487 self.candidate_should_be_dropped_in_favor_of(&candidates[i], &candidates[j])
1491 "Dropping candidate #{}/{}: {:?}",
1496 candidates.swap_remove(i);
1499 "Retaining candidate #{}/{}: {:?}",
1506 // If there are *STILL* multiple candidates, give up
1507 // and report ambiguity.
1509 debug!("multiple matches, ambig");
1516 // If there are *NO* candidates, then there are no impls --
1517 // that we know of, anyway. Note that in the case where there
1518 // are unbound type variables within the obligation, it might
1519 // be the case that you could still satisfy the obligation
1520 // from another crate by instantiating the type variables with
1521 // a type from another crate that does have an impl. This case
1522 // is checked for in `evaluate_stack` (and hence users
1523 // who might care about this case, like coherence, should use
1525 if candidates.is_empty() {
1526 return Err(Unimplemented);
1529 // Just one candidate left.
1530 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1533 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1534 debug!("is_knowable(intercrate={:?})", self.intercrate);
1536 if !self.intercrate.is_some() {
1540 let obligation = &stack.obligation;
1541 let predicate = self.infcx()
1542 .resolve_vars_if_possible(&obligation.predicate);
1544 // Okay to skip binder because of the nature of the
1545 // trait-ref-is-knowable check, which does not care about
1547 let trait_ref = predicate.skip_binder().trait_ref;
1549 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1551 Some(Conflict::Downstream {
1552 used_to_be_broken: true,
1554 Some(IntercrateMode::Issue43355),
1555 ) = (result, self.intercrate)
1557 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1564 /// Returns `true` if the global caches can be used.
1565 /// Do note that if the type itself is not in the
1566 /// global tcx, the local caches will be used.
1567 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1568 // If there are any where-clauses in scope, then we always use
1569 // a cache local to this particular scope. Otherwise, we
1570 // switch to a global cache. We used to try and draw
1571 // finer-grained distinctions, but that led to a serious of
1572 // annoying and weird bugs like #22019 and #18290. This simple
1573 // rule seems to be pretty clearly safe and also still retains
1574 // a very high hit rate (~95% when compiling rustc).
1575 if !param_env.caller_bounds.is_empty() {
1579 // Avoid using the master cache during coherence and just rely
1580 // on the local cache. This effectively disables caching
1581 // during coherence. It is really just a simplification to
1582 // avoid us having to fear that coherence results "pollute"
1583 // the master cache. Since coherence executes pretty quickly,
1584 // it's not worth going to more trouble to increase the
1585 // hit-rate I don't think.
1586 if self.intercrate.is_some() {
1590 // Otherwise, we can use the global cache.
1594 fn check_candidate_cache(
1596 param_env: ty::ParamEnv<'tcx>,
1597 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1598 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1599 let tcx = self.tcx();
1600 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1601 if self.can_use_global_caches(param_env) {
1602 let cache = tcx.selection_cache.hashmap.borrow();
1603 if let Some(cached) = cache.get(&trait_ref) {
1604 return Some(cached.get(tcx));
1612 .map(|v| v.get(tcx))
1615 /// Determines whether can we safely cache the result
1616 /// of selecting an obligation. This is almost always 'true',
1617 /// except when dealing with certain ParamCandidates.
1619 /// Ordinarily, a ParamCandidate will contain no inference variables,
1620 /// since it was usually produced directly from a DefId. However,
1621 /// certain cases (currently only librustdoc's blanket impl finder),
1622 /// a ParamEnv may be explicitly constructed with inference types.
1623 /// When this is the case, we do *not* want to cache the resulting selection
1624 /// candidate. This is due to the fact that it might not always be possible
1625 /// to equate the obligation's trait ref and the candidate's trait ref,
1626 /// if more constraints end up getting added to an inference variable.
1628 /// Because of this, we always want to re-run the full selection
1629 /// process for our obligation the next time we see it, since
1630 /// we might end up picking a different SelectionCandidate (or none at all)
1631 fn can_cache_candidate(&self,
1632 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>
1635 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => {
1636 !trait_ref.skip_binder().input_types().any(|t| t.walk().any(|t_| t_.is_ty_infer()))
1642 fn insert_candidate_cache(
1644 param_env: ty::ParamEnv<'tcx>,
1645 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1646 dep_node: DepNodeIndex,
1647 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1649 let tcx = self.tcx();
1650 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1652 if !self.can_cache_candidate(&candidate) {
1653 debug!("insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1654 candidate is not cacheable", trait_ref, candidate);
1659 if self.can_use_global_caches(param_env) {
1660 if let Err(Overflow) = candidate {
1661 // Don't cache overflow globally; we only produce this
1662 // in certain modes.
1663 } else if !trait_ref.has_local_value() {
1664 if !candidate.has_local_value() {
1666 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1667 trait_ref, candidate,
1669 // This may overwrite the cache with the same value
1673 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1680 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1681 trait_ref, candidate,
1687 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1690 fn assemble_candidates<'o>(
1692 stack: &TraitObligationStack<'o, 'tcx>,
1693 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1694 let TraitObligationStack { obligation, .. } = *stack;
1695 let ref obligation = Obligation {
1696 param_env: obligation.param_env,
1697 cause: obligation.cause.clone(),
1698 recursion_depth: obligation.recursion_depth,
1699 predicate: self.infcx()
1700 .resolve_vars_if_possible(&obligation.predicate),
1703 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1704 // Self is a type variable (e.g., `_: AsRef<str>`).
1706 // This is somewhat problematic, as the current scheme can't really
1707 // handle it turning to be a projection. This does end up as truly
1708 // ambiguous in most cases anyway.
1710 // Take the fast path out - this also improves
1711 // performance by preventing assemble_candidates_from_impls from
1712 // matching every impl for this trait.
1713 return Ok(SelectionCandidateSet {
1719 let mut candidates = SelectionCandidateSet {
1724 self.assemble_candidates_for_trait_alias(obligation, &mut candidates)?;
1726 // Other bounds. Consider both in-scope bounds from fn decl
1727 // and applicable impls. There is a certain set of precedence rules here.
1728 let def_id = obligation.predicate.def_id();
1729 let lang_items = self.tcx().lang_items();
1731 if lang_items.copy_trait() == Some(def_id) {
1733 "obligation self ty is {:?}",
1734 obligation.predicate.skip_binder().self_ty()
1737 // User-defined copy impls are permitted, but only for
1738 // structs and enums.
1739 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1741 // For other types, we'll use the builtin rules.
1742 let copy_conditions = self.copy_clone_conditions(obligation);
1743 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1744 } else if lang_items.sized_trait() == Some(def_id) {
1745 // Sized is never implementable by end-users, it is
1746 // always automatically computed.
1747 let sized_conditions = self.sized_conditions(obligation);
1748 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1749 } else if lang_items.unsize_trait() == Some(def_id) {
1750 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1752 if lang_items.clone_trait() == Some(def_id) {
1753 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
1754 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1755 // types have builtin support for `Clone`.
1756 let clone_conditions = self.copy_clone_conditions(obligation);
1757 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1760 self.assemble_generator_candidates(obligation, &mut candidates)?;
1761 self.assemble_closure_candidates(obligation, &mut candidates)?;
1762 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1763 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1764 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1767 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1768 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1769 // Auto implementations have lower priority, so we only
1770 // consider triggering a default if there is no other impl that can apply.
1771 if candidates.vec.is_empty() {
1772 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1774 debug!("candidate list size: {}", candidates.vec.len());
1778 fn assemble_candidates_from_projected_tys(
1780 obligation: &TraitObligation<'tcx>,
1781 candidates: &mut SelectionCandidateSet<'tcx>,
1783 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1785 // before we go into the whole placeholder thing, just
1786 // quickly check if the self-type is a projection at all.
1787 match obligation.predicate.skip_binder().trait_ref.self_ty().sty {
1788 ty::Projection(_) | ty::Opaque(..) => {}
1789 ty::Infer(ty::TyVar(_)) => {
1791 obligation.cause.span,
1792 "Self=_ should have been handled by assemble_candidates"
1798 let result = self.infcx.probe(|snapshot| {
1799 self.match_projection_obligation_against_definition_bounds(
1806 candidates.vec.push(ProjectionCandidate);
1810 fn match_projection_obligation_against_definition_bounds(
1812 obligation: &TraitObligation<'tcx>,
1813 snapshot: &CombinedSnapshot<'_, 'tcx>,
1815 let poly_trait_predicate = self.infcx()
1816 .resolve_vars_if_possible(&obligation.predicate);
1817 let (placeholder_trait_predicate, placeholder_map) = self.infcx()
1818 .replace_bound_vars_with_placeholders(&poly_trait_predicate);
1820 "match_projection_obligation_against_definition_bounds: \
1821 placeholder_trait_predicate={:?}",
1822 placeholder_trait_predicate,
1825 let (def_id, substs) = match placeholder_trait_predicate.trait_ref.self_ty().sty {
1826 ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1827 ty::Opaque(def_id, substs) => (def_id, substs),
1830 obligation.cause.span,
1831 "match_projection_obligation_against_definition_bounds() called \
1832 but self-ty is not a projection: {:?}",
1833 placeholder_trait_predicate.trait_ref.self_ty()
1838 "match_projection_obligation_against_definition_bounds: \
1839 def_id={:?}, substs={:?}",
1843 let predicates_of = self.tcx().predicates_of(def_id);
1844 let bounds = predicates_of.instantiate(self.tcx(), substs);
1846 "match_projection_obligation_against_definition_bounds: \
1851 let elaborated_predicates = util::elaborate_predicates(self.tcx(), bounds.predicates);
1852 let matching_bound = elaborated_predicates
1855 self.infcx.probe(|_| {
1856 self.match_projection(
1859 placeholder_trait_predicate.trait_ref.clone(),
1867 "match_projection_obligation_against_definition_bounds: \
1868 matching_bound={:?}",
1871 match matching_bound {
1874 // Repeat the successful match, if any, this time outside of a probe.
1875 let result = self.match_projection(
1878 placeholder_trait_predicate.trait_ref.clone(),
1889 fn match_projection(
1891 obligation: &TraitObligation<'tcx>,
1892 trait_bound: ty::PolyTraitRef<'tcx>,
1893 placeholder_trait_ref: ty::TraitRef<'tcx>,
1894 placeholder_map: &PlaceholderMap<'tcx>,
1895 snapshot: &CombinedSnapshot<'_, 'tcx>,
1897 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1899 .at(&obligation.cause, obligation.param_env)
1900 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1903 self.infcx.leak_check(false, placeholder_map, snapshot).is_ok()
1906 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1907 /// supplied to find out whether it is listed among them.
1909 /// Never affects inference environment.
1910 fn assemble_candidates_from_caller_bounds<'o>(
1912 stack: &TraitObligationStack<'o, 'tcx>,
1913 candidates: &mut SelectionCandidateSet<'tcx>,
1914 ) -> Result<(), SelectionError<'tcx>> {
1916 "assemble_candidates_from_caller_bounds({:?})",
1920 let all_bounds = stack
1925 .filter_map(|o| o.to_opt_poly_trait_ref());
1927 // Micro-optimization: filter out predicates relating to different traits.
1928 let matching_bounds =
1929 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1931 // Keep only those bounds which may apply, and propagate overflow if it occurs.
1932 let mut param_candidates = vec![];
1933 for bound in matching_bounds {
1934 let wc = self.evaluate_where_clause(stack, bound.clone())?;
1936 param_candidates.push(ParamCandidate(bound));
1940 candidates.vec.extend(param_candidates);
1945 fn evaluate_where_clause<'o>(
1947 stack: &TraitObligationStack<'o, 'tcx>,
1948 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1949 ) -> Result<EvaluationResult, OverflowError> {
1950 self.evaluation_probe(|this| {
1951 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1952 Ok(obligations) => {
1953 this.evaluate_predicates_recursively(stack.list(), obligations.into_iter())
1955 Err(()) => Ok(EvaluatedToErr),
1960 fn assemble_generator_candidates(
1962 obligation: &TraitObligation<'tcx>,
1963 candidates: &mut SelectionCandidateSet<'tcx>,
1964 ) -> Result<(), SelectionError<'tcx>> {
1965 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1969 // Okay to skip binder because the substs on generator types never
1970 // touch bound regions, they just capture the in-scope
1971 // type/region parameters.
1972 let self_ty = *obligation.self_ty().skip_binder();
1974 ty::Generator(..) => {
1976 "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1980 candidates.vec.push(GeneratorCandidate);
1982 ty::Infer(ty::TyVar(_)) => {
1983 debug!("assemble_generator_candidates: ambiguous self-type");
1984 candidates.ambiguous = true;
1992 /// Checks for the artificial impl that the compiler will create for an obligation like `X :
1993 /// FnMut<..>` where `X` is a closure type.
1995 /// Note: the type parameters on a closure candidate are modeled as *output* type
1996 /// parameters and hence do not affect whether this trait is a match or not. They will be
1997 /// unified during the confirmation step.
1998 fn assemble_closure_candidates(
2000 obligation: &TraitObligation<'tcx>,
2001 candidates: &mut SelectionCandidateSet<'tcx>,
2002 ) -> Result<(), SelectionError<'tcx>> {
2003 let kind = match self.tcx()
2005 .fn_trait_kind(obligation.predicate.def_id())
2013 // Okay to skip binder because the substs on closure types never
2014 // touch bound regions, they just capture the in-scope
2015 // type/region parameters
2016 match obligation.self_ty().skip_binder().sty {
2017 ty::Closure(closure_def_id, closure_substs) => {
2019 "assemble_unboxed_candidates: kind={:?} obligation={:?}",
2022 match self.infcx.closure_kind(closure_def_id, closure_substs) {
2023 Some(closure_kind) => {
2025 "assemble_unboxed_candidates: closure_kind = {:?}",
2028 if closure_kind.extends(kind) {
2029 candidates.vec.push(ClosureCandidate);
2033 debug!("assemble_unboxed_candidates: closure_kind not yet known");
2034 candidates.vec.push(ClosureCandidate);
2038 ty::Infer(ty::TyVar(_)) => {
2039 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
2040 candidates.ambiguous = true;
2048 /// Implement one of the `Fn()` family for a fn pointer.
2049 fn assemble_fn_pointer_candidates(
2051 obligation: &TraitObligation<'tcx>,
2052 candidates: &mut SelectionCandidateSet<'tcx>,
2053 ) -> Result<(), SelectionError<'tcx>> {
2054 // We provide impl of all fn traits for fn pointers.
2057 .fn_trait_kind(obligation.predicate.def_id())
2063 // Okay to skip binder because what we are inspecting doesn't involve bound regions
2064 let self_ty = *obligation.self_ty().skip_binder();
2066 ty::Infer(ty::TyVar(_)) => {
2067 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
2068 candidates.ambiguous = true; // could wind up being a fn() type
2070 // provide an impl, but only for suitable `fn` pointers
2071 ty::FnDef(..) | ty::FnPtr(_) => {
2073 unsafety: hir::Unsafety::Normal,
2077 } = self_ty.fn_sig(self.tcx()).skip_binder()
2079 candidates.vec.push(FnPointerCandidate);
2088 /// Search for impls that might apply to `obligation`.
2089 fn assemble_candidates_from_impls(
2091 obligation: &TraitObligation<'tcx>,
2092 candidates: &mut SelectionCandidateSet<'tcx>,
2093 ) -> Result<(), SelectionError<'tcx>> {
2095 "assemble_candidates_from_impls(obligation={:?})",
2099 self.tcx().for_each_relevant_impl(
2100 obligation.predicate.def_id(),
2101 obligation.predicate.skip_binder().trait_ref.self_ty(),
2103 self.infcx.probe(|snapshot| {
2104 if let Ok(_substs) = self.match_impl(impl_def_id, obligation, snapshot)
2106 candidates.vec.push(ImplCandidate(impl_def_id));
2115 fn assemble_candidates_from_auto_impls(
2117 obligation: &TraitObligation<'tcx>,
2118 candidates: &mut SelectionCandidateSet<'tcx>,
2119 ) -> Result<(), SelectionError<'tcx>> {
2120 // Okay to skip binder here because the tests we do below do not involve bound regions.
2121 let self_ty = *obligation.self_ty().skip_binder();
2122 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
2124 let def_id = obligation.predicate.def_id();
2126 if self.tcx().trait_is_auto(def_id) {
2128 ty::Dynamic(..) => {
2129 // For object types, we don't know what the closed
2130 // over types are. This means we conservatively
2131 // say nothing; a candidate may be added by
2132 // `assemble_candidates_from_object_ty`.
2134 ty::Foreign(..) => {
2135 // Since the contents of foreign types is unknown,
2136 // we don't add any `..` impl. Default traits could
2137 // still be provided by a manual implementation for
2138 // this trait and type.
2140 ty::Param(..) | ty::Projection(..) => {
2141 // In these cases, we don't know what the actual
2142 // type is. Therefore, we cannot break it down
2143 // into its constituent types. So we don't
2144 // consider the `..` impl but instead just add no
2145 // candidates: this means that typeck will only
2146 // succeed if there is another reason to believe
2147 // that this obligation holds. That could be a
2148 // where-clause or, in the case of an object type,
2149 // it could be that the object type lists the
2150 // trait (e.g., `Foo+Send : Send`). See
2151 // `compile-fail/typeck-default-trait-impl-send-param.rs`
2152 // for an example of a test case that exercises
2155 ty::Infer(ty::TyVar(_)) => {
2156 // the auto impl might apply, we don't know
2157 candidates.ambiguous = true;
2159 ty::Generator(_, _, movability)
2160 if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
2163 hir::GeneratorMovability::Static => {
2164 // Immovable generators are never `Unpin`, so
2165 // suppress the normal auto-impl candidate for it.
2167 hir::GeneratorMovability::Movable => {
2168 // Movable generators are always `Unpin`, so add an
2169 // unconditional builtin candidate.
2170 candidates.vec.push(BuiltinCandidate {
2177 _ => candidates.vec.push(AutoImplCandidate(def_id.clone())),
2184 /// Search for impls that might apply to `obligation`.
2185 fn assemble_candidates_from_object_ty(
2187 obligation: &TraitObligation<'tcx>,
2188 candidates: &mut SelectionCandidateSet<'tcx>,
2191 "assemble_candidates_from_object_ty(self_ty={:?})",
2192 obligation.self_ty().skip_binder()
2195 self.infcx.probe(|_snapshot| {
2196 // The code below doesn't care about regions, and the
2197 // self-ty here doesn't escape this probe, so just erase
2199 let self_ty = self.tcx().erase_late_bound_regions(&obligation.self_ty());
2200 let poly_trait_ref = match self_ty.sty {
2201 ty::Dynamic(ref data, ..) => {
2202 if data.auto_traits()
2203 .any(|did| did == obligation.predicate.def_id())
2206 "assemble_candidates_from_object_ty: matched builtin bound, \
2209 candidates.vec.push(BuiltinObjectCandidate);
2213 if let Some(principal) = data.principal() {
2214 principal.with_self_ty(self.tcx(), self_ty)
2216 // Only auto-trait bounds exist.
2220 ty::Infer(ty::TyVar(_)) => {
2221 debug!("assemble_candidates_from_object_ty: ambiguous");
2222 candidates.ambiguous = true; // could wind up being an object type
2229 "assemble_candidates_from_object_ty: poly_trait_ref={:?}",
2233 // Count only those upcast versions that match the trait-ref
2234 // we are looking for. Specifically, do not only check for the
2235 // correct trait, but also the correct type parameters.
2236 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
2237 // but `Foo` is declared as `trait Foo : Bar<u32>`.
2238 let upcast_trait_refs = util::supertraits(self.tcx(), poly_trait_ref)
2239 .filter(|upcast_trait_ref| {
2240 self.infcx.probe(|_| {
2241 let upcast_trait_ref = upcast_trait_ref.clone();
2242 self.match_poly_trait_ref(obligation, upcast_trait_ref)
2248 if upcast_trait_refs > 1 {
2249 // Can be upcast in many ways; need more type information.
2250 candidates.ambiguous = true;
2251 } else if upcast_trait_refs == 1 {
2252 candidates.vec.push(ObjectCandidate);
2257 /// Search for unsizing that might apply to `obligation`.
2258 fn assemble_candidates_for_unsizing(
2260 obligation: &TraitObligation<'tcx>,
2261 candidates: &mut SelectionCandidateSet<'tcx>,
2263 // We currently never consider higher-ranked obligations e.g.
2264 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
2265 // because they are a priori invalid, and we could potentially add support
2266 // for them later, it's just that there isn't really a strong need for it.
2267 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
2268 // impl, and those are generally applied to concrete types.
2270 // That said, one might try to write a fn with a where clause like
2271 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
2272 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
2273 // Still, you'd be more likely to write that where clause as
2275 // so it seems ok if we (conservatively) fail to accept that `Unsize`
2276 // obligation above. Should be possible to extend this in the future.
2277 let source = match obligation.self_ty().no_bound_vars() {
2280 // Don't add any candidates if there are bound regions.
2284 let target = obligation
2292 "assemble_candidates_for_unsizing(source={:?}, target={:?})",
2296 let may_apply = match (&source.sty, &target.sty) {
2297 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2298 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
2299 // Upcasts permit two things:
2301 // 1. Dropping builtin bounds, e.g., `Foo+Send` to `Foo`
2302 // 2. Tightening the region bound, e.g., `Foo+'a` to `Foo+'b` if `'a : 'b`
2304 // Note that neither of these changes requires any
2305 // change at runtime. Eventually this will be
2308 // We always upcast when we can because of reason
2309 // #2 (region bounds).
2310 data_a.principal_def_id() == data_b.principal_def_id()
2311 && data_b.auto_traits()
2312 // All of a's auto traits need to be in b's auto traits.
2313 .all(|b| data_a.auto_traits().any(|a| a == b))
2317 (_, &ty::Dynamic(..)) => true,
2319 // Ambiguous handling is below T -> Trait, because inference
2320 // variables can still implement Unsize<Trait> and nested
2321 // obligations will have the final say (likely deferred).
2322 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
2323 debug!("assemble_candidates_for_unsizing: ambiguous");
2324 candidates.ambiguous = true;
2329 (&ty::Array(..), &ty::Slice(_)) => true,
2331 // Struct<T> -> Struct<U>.
2332 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
2333 def_id_a == def_id_b
2336 // (.., T) -> (.., U).
2337 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
2343 candidates.vec.push(BuiltinUnsizeCandidate);
2347 fn assemble_candidates_for_trait_alias(
2349 obligation: &TraitObligation<'tcx>,
2350 candidates: &mut SelectionCandidateSet<'tcx>,
2351 ) -> Result<(), SelectionError<'tcx>> {
2352 // Okay to skip binder here because the tests we do below do not involve bound regions.
2353 let self_ty = *obligation.self_ty().skip_binder();
2354 debug!("assemble_candidates_for_trait_alias(self_ty={:?})", self_ty);
2356 let def_id = obligation.predicate.def_id();
2358 if self.tcx().is_trait_alias(def_id) {
2359 candidates.vec.push(TraitAliasCandidate(def_id.clone()));
2365 ///////////////////////////////////////////////////////////////////////////
2368 // Winnowing is the process of attempting to resolve ambiguity by
2369 // probing further. During the winnowing process, we unify all
2370 // type variables and then we also attempt to evaluate recursive
2371 // bounds to see if they are satisfied.
2373 /// Returns `true` if `victim` should be dropped in favor of
2374 /// `other`. Generally speaking we will drop duplicate
2375 /// candidates and prefer where-clause candidates.
2377 /// See the comment for "SelectionCandidate" for more details.
2378 fn candidate_should_be_dropped_in_favor_of(
2380 victim: &EvaluatedCandidate<'tcx>,
2381 other: &EvaluatedCandidate<'tcx>,
2383 if victim.candidate == other.candidate {
2387 // Check if a bound would previously have been removed when normalizing
2388 // the param_env so that it can be given the lowest priority. See
2389 // #50825 for the motivation for this.
2391 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
2393 match other.candidate {
2394 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2395 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2396 // lifetime of a variable.
2397 BuiltinCandidate { has_nested: false } => true,
2398 ParamCandidate(ref cand) => match victim.candidate {
2399 AutoImplCandidate(..) => {
2401 "default implementations shouldn't be recorded \
2402 when there are other valid candidates"
2405 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2406 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2407 // lifetime of a variable.
2408 BuiltinCandidate { has_nested: false } => false,
2411 | GeneratorCandidate
2412 | FnPointerCandidate
2413 | BuiltinObjectCandidate
2414 | BuiltinUnsizeCandidate
2415 | BuiltinCandidate { .. }
2416 | TraitAliasCandidate(..) => {
2417 // Global bounds from the where clause should be ignored
2418 // here (see issue #50825). Otherwise, we have a where
2419 // clause so don't go around looking for impls.
2422 ObjectCandidate | ProjectionCandidate => {
2423 // Arbitrarily give param candidates priority
2424 // over projection and object candidates.
2427 ParamCandidate(..) => false,
2429 ObjectCandidate | ProjectionCandidate => match victim.candidate {
2430 AutoImplCandidate(..) => {
2432 "default implementations shouldn't be recorded \
2433 when there are other valid candidates"
2436 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2437 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2438 // lifetime of a variable.
2439 BuiltinCandidate { has_nested: false } => false,
2442 | GeneratorCandidate
2443 | FnPointerCandidate
2444 | BuiltinObjectCandidate
2445 | BuiltinUnsizeCandidate
2446 | BuiltinCandidate { .. }
2447 | TraitAliasCandidate(..) => true,
2448 ObjectCandidate | ProjectionCandidate => {
2449 // Arbitrarily give param candidates priority
2450 // over projection and object candidates.
2453 ParamCandidate(ref cand) => is_global(cand),
2455 ImplCandidate(other_def) => {
2456 // See if we can toss out `victim` based on specialization.
2457 // This requires us to know *for sure* that the `other` impl applies
2458 // i.e., EvaluatedToOk:
2459 if other.evaluation.must_apply_modulo_regions() {
2460 match victim.candidate {
2461 ImplCandidate(victim_def) => {
2462 let tcx = self.tcx().global_tcx();
2463 return tcx.specializes((other_def, victim_def))
2464 || tcx.impls_are_allowed_to_overlap(
2465 other_def, victim_def).is_some();
2467 ParamCandidate(ref cand) => {
2468 // Prefer the impl to a global where clause candidate.
2469 return is_global(cand);
2478 | GeneratorCandidate
2479 | FnPointerCandidate
2480 | BuiltinObjectCandidate
2481 | BuiltinUnsizeCandidate
2482 | BuiltinCandidate { has_nested: true } => {
2483 match victim.candidate {
2484 ParamCandidate(ref cand) => {
2485 // Prefer these to a global where-clause bound
2486 // (see issue #50825)
2487 is_global(cand) && other.evaluation.must_apply_modulo_regions()
2496 ///////////////////////////////////////////////////////////////////////////
2499 // These cover the traits that are built-in to the language
2500 // itself: `Copy`, `Clone` and `Sized`.
2502 fn assemble_builtin_bound_candidates(
2504 conditions: BuiltinImplConditions<'tcx>,
2505 candidates: &mut SelectionCandidateSet<'tcx>,
2506 ) -> Result<(), SelectionError<'tcx>> {
2508 BuiltinImplConditions::Where(nested) => {
2509 debug!("builtin_bound: nested={:?}", nested);
2510 candidates.vec.push(BuiltinCandidate {
2511 has_nested: nested.skip_binder().len() > 0,
2514 BuiltinImplConditions::None => {}
2515 BuiltinImplConditions::Ambiguous => {
2516 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2517 candidates.ambiguous = true;
2524 fn sized_conditions(
2526 obligation: &TraitObligation<'tcx>,
2527 ) -> BuiltinImplConditions<'tcx> {
2528 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2530 // NOTE: binder moved to (*)
2531 let self_ty = self.infcx
2532 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2535 ty::Infer(ty::IntVar(_))
2536 | ty::Infer(ty::FloatVar(_))
2547 | ty::GeneratorWitness(..)
2552 // safe for everything
2553 Where(ty::Binder::dummy(Vec::new()))
2556 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2559 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
2562 ty::Adt(def, substs) => {
2563 let sized_crit = def.sized_constraint(self.tcx());
2564 // (*) binder moved here
2565 Where(ty::Binder::bind(
2568 .map(|ty| ty.subst(self.tcx(), substs))
2573 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2574 ty::Infer(ty::TyVar(_)) => Ambiguous,
2576 ty::UnnormalizedProjection(..)
2577 | ty::Placeholder(..)
2579 | ty::Infer(ty::FreshTy(_))
2580 | ty::Infer(ty::FreshIntTy(_))
2581 | ty::Infer(ty::FreshFloatTy(_)) => {
2583 "asked to assemble builtin bounds of unexpected type: {:?}",
2590 fn copy_clone_conditions(
2592 obligation: &TraitObligation<'tcx>,
2593 ) -> BuiltinImplConditions<'tcx> {
2594 // NOTE: binder moved to (*)
2595 let self_ty = self.infcx
2596 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2598 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2601 ty::Infer(ty::IntVar(_))
2602 | ty::Infer(ty::FloatVar(_))
2605 | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2614 | ty::Ref(_, _, hir::MutImmutable) => {
2615 // Implementations provided in libcore
2623 | ty::GeneratorWitness(..)
2625 | ty::Ref(_, _, hir::MutMutable) => None,
2627 ty::Array(element_ty, _) => {
2628 // (*) binder moved here
2629 Where(ty::Binder::bind(vec![element_ty]))
2633 // (*) binder moved here
2634 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
2637 ty::Closure(def_id, substs) => {
2638 // (*) binder moved here
2639 Where(ty::Binder::bind(
2640 substs.upvar_tys(def_id, self.tcx()).collect(),
2644 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2645 // Fallback to whatever user-defined impls exist in this case.
2649 ty::Infer(ty::TyVar(_)) => {
2650 // Unbound type variable. Might or might not have
2651 // applicable impls and so forth, depending on what
2652 // those type variables wind up being bound to.
2656 ty::UnnormalizedProjection(..)
2657 | ty::Placeholder(..)
2659 | ty::Infer(ty::FreshTy(_))
2660 | ty::Infer(ty::FreshIntTy(_))
2661 | ty::Infer(ty::FreshFloatTy(_)) => {
2663 "asked to assemble builtin bounds of unexpected type: {:?}",
2670 /// For default impls, we need to break apart a type into its
2671 /// "constituent types" -- meaning, the types that it contains.
2673 /// Here are some (simple) examples:
2676 /// (i32, u32) -> [i32, u32]
2677 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2678 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2679 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2681 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2691 | ty::Infer(ty::IntVar(_))
2692 | ty::Infer(ty::FloatVar(_))
2694 | ty::Char => Vec::new(),
2696 ty::UnnormalizedProjection(..)
2697 | ty::Placeholder(..)
2701 | ty::Projection(..)
2703 | ty::Infer(ty::TyVar(_))
2704 | ty::Infer(ty::FreshTy(_))
2705 | ty::Infer(ty::FreshIntTy(_))
2706 | ty::Infer(ty::FreshFloatTy(_)) => {
2708 "asked to assemble constituent types of unexpected type: {:?}",
2713 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2717 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2719 ty::Tuple(ref tys) => {
2720 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2721 tys.iter().map(|k| k.expect_ty()).collect()
2724 ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, self.tcx()).collect(),
2726 ty::Generator(def_id, ref substs, _) => {
2727 let witness = substs.witness(def_id, self.tcx());
2729 .upvar_tys(def_id, self.tcx())
2730 .chain(iter::once(witness))
2734 ty::GeneratorWitness(types) => {
2735 // This is sound because no regions in the witness can refer to
2736 // the binder outside the witness. So we'll effectivly reuse
2737 // the implicit binder around the witness.
2738 types.skip_binder().to_vec()
2741 // for `PhantomData<T>`, we pass `T`
2742 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2744 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2746 ty::Opaque(def_id, substs) => {
2747 // We can resolve the `impl Trait` to its concrete type,
2748 // which enforces a DAG between the functions requiring
2749 // the auto trait bounds in question.
2750 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2755 fn collect_predicates_for_types(
2757 param_env: ty::ParamEnv<'tcx>,
2758 cause: ObligationCause<'tcx>,
2759 recursion_depth: usize,
2760 trait_def_id: DefId,
2761 types: ty::Binder<Vec<Ty<'tcx>>>,
2762 ) -> Vec<PredicateObligation<'tcx>> {
2763 // Because the types were potentially derived from
2764 // higher-ranked obligations they may reference late-bound
2765 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2766 // yield a type like `for<'a> &'a int`. In general, we
2767 // maintain the invariant that we never manipulate bound
2768 // regions, so we have to process these bound regions somehow.
2770 // The strategy is to:
2772 // 1. Instantiate those regions to placeholder regions (e.g.,
2773 // `for<'a> &'a int` becomes `&0 int`.
2774 // 2. Produce something like `&'0 int : Copy`
2775 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2782 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2784 self.infcx.in_snapshot(|_| {
2785 let (skol_ty, _) = self.infcx
2786 .replace_bound_vars_with_placeholders(&ty);
2788 value: normalized_ty,
2790 } = project::normalize_with_depth(
2797 let skol_obligation = self.tcx().predicate_for_trait_def(
2805 obligations.push(skol_obligation);
2812 ///////////////////////////////////////////////////////////////////////////
2815 // Confirmation unifies the output type parameters of the trait
2816 // with the values found in the obligation, possibly yielding a
2817 // type error. See the [rustc guide] for more details.
2820 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#confirmation
2822 fn confirm_candidate(
2824 obligation: &TraitObligation<'tcx>,
2825 candidate: SelectionCandidate<'tcx>,
2826 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2827 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2830 BuiltinCandidate { has_nested } => {
2831 let data = self.confirm_builtin_candidate(obligation, has_nested);
2832 Ok(VtableBuiltin(data))
2835 ParamCandidate(param) => {
2836 let obligations = self.confirm_param_candidate(obligation, param);
2837 Ok(VtableParam(obligations))
2840 ImplCandidate(impl_def_id) => Ok(VtableImpl(self.confirm_impl_candidate(
2845 AutoImplCandidate(trait_def_id) => {
2846 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2847 Ok(VtableAutoImpl(data))
2850 ProjectionCandidate => {
2851 self.confirm_projection_candidate(obligation);
2852 Ok(VtableParam(Vec::new()))
2855 ClosureCandidate => {
2856 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2857 Ok(VtableClosure(vtable_closure))
2860 GeneratorCandidate => {
2861 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2862 Ok(VtableGenerator(vtable_generator))
2865 FnPointerCandidate => {
2866 let data = self.confirm_fn_pointer_candidate(obligation)?;
2867 Ok(VtableFnPointer(data))
2870 TraitAliasCandidate(alias_def_id) => {
2871 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
2872 Ok(VtableTraitAlias(data))
2875 ObjectCandidate => {
2876 let data = self.confirm_object_candidate(obligation);
2877 Ok(VtableObject(data))
2880 BuiltinObjectCandidate => {
2881 // This indicates something like `(Trait+Send) :
2882 // Send`. In this case, we know that this holds
2883 // because that's what the object type is telling us,
2884 // and there's really no additional obligations to
2885 // prove and no types in particular to unify etc.
2886 Ok(VtableParam(Vec::new()))
2889 BuiltinUnsizeCandidate => {
2890 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2891 Ok(VtableBuiltin(data))
2896 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2897 self.infcx.in_snapshot(|snapshot| {
2899 self.match_projection_obligation_against_definition_bounds(
2907 fn confirm_param_candidate(
2909 obligation: &TraitObligation<'tcx>,
2910 param: ty::PolyTraitRef<'tcx>,
2911 ) -> Vec<PredicateObligation<'tcx>> {
2912 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2914 // During evaluation, we already checked that this
2915 // where-clause trait-ref could be unified with the obligation
2916 // trait-ref. Repeat that unification now without any
2917 // transactional boundary; it should not fail.
2918 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2919 Ok(obligations) => obligations,
2922 "Where clause `{:?}` was applicable to `{:?}` but now is not",
2930 fn confirm_builtin_candidate(
2932 obligation: &TraitObligation<'tcx>,
2934 ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2936 "confirm_builtin_candidate({:?}, {:?})",
2937 obligation, has_nested
2940 let lang_items = self.tcx().lang_items();
2941 let obligations = if has_nested {
2942 let trait_def = obligation.predicate.def_id();
2943 let conditions = if Some(trait_def) == lang_items.sized_trait() {
2944 self.sized_conditions(obligation)
2945 } else if Some(trait_def) == lang_items.copy_trait() {
2946 self.copy_clone_conditions(obligation)
2947 } else if Some(trait_def) == lang_items.clone_trait() {
2948 self.copy_clone_conditions(obligation)
2950 bug!("unexpected builtin trait {:?}", trait_def)
2952 let nested = match conditions {
2953 BuiltinImplConditions::Where(nested) => nested,
2955 "obligation {:?} had matched a builtin impl but now doesn't",
2960 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2961 self.collect_predicates_for_types(
2962 obligation.param_env,
2964 obligation.recursion_depth + 1,
2972 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2975 nested: obligations,
2979 /// This handles the case where a `auto trait Foo` impl is being used.
2980 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2982 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2983 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2984 fn confirm_auto_impl_candidate(
2986 obligation: &TraitObligation<'tcx>,
2987 trait_def_id: DefId,
2988 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2990 "confirm_auto_impl_candidate({:?}, {:?})",
2991 obligation, trait_def_id
2994 let types = obligation.predicate.map_bound(|inner| {
2995 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2996 self.constituent_types_for_ty(self_ty)
2998 self.vtable_auto_impl(obligation, trait_def_id, types)
3001 /// See `confirm_auto_impl_candidate`.
3002 fn vtable_auto_impl(
3004 obligation: &TraitObligation<'tcx>,
3005 trait_def_id: DefId,
3006 nested: ty::Binder<Vec<Ty<'tcx>>>,
3007 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
3008 debug!("vtable_auto_impl: nested={:?}", nested);
3010 let cause = obligation.derived_cause(BuiltinDerivedObligation);
3011 let mut obligations = self.collect_predicates_for_types(
3012 obligation.param_env,
3014 obligation.recursion_depth + 1,
3019 let trait_obligations: Vec<PredicateObligation<'_>> = self.infcx.in_snapshot(|_| {
3020 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
3021 let (trait_ref, _) = self.infcx
3022 .replace_bound_vars_with_placeholders(&poly_trait_ref);
3023 let cause = obligation.derived_cause(ImplDerivedObligation);
3024 self.impl_or_trait_obligations(
3026 obligation.recursion_depth + 1,
3027 obligation.param_env,
3033 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
3034 // predicate as usual. It won't have any effect since auto traits are coinductive.
3035 obligations.extend(trait_obligations);
3037 debug!("vtable_auto_impl: obligations={:?}", obligations);
3039 VtableAutoImplData {
3041 nested: obligations,
3045 fn confirm_impl_candidate(
3047 obligation: &TraitObligation<'tcx>,
3049 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
3050 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
3052 // First, create the substitutions by matching the impl again,
3053 // this time not in a probe.
3054 self.infcx.in_snapshot(|snapshot| {
3055 let substs = self.rematch_impl(impl_def_id, obligation, snapshot);
3056 debug!("confirm_impl_candidate: substs={:?}", substs);
3057 let cause = obligation.derived_cause(ImplDerivedObligation);
3062 obligation.recursion_depth + 1,
3063 obligation.param_env,
3071 mut substs: Normalized<'tcx, SubstsRef<'tcx>>,
3072 cause: ObligationCause<'tcx>,
3073 recursion_depth: usize,
3074 param_env: ty::ParamEnv<'tcx>,
3075 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
3077 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={})",
3078 impl_def_id, substs, recursion_depth,
3081 let mut impl_obligations = self.impl_or_trait_obligations(
3090 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
3091 impl_def_id, impl_obligations
3094 // Because of RFC447, the impl-trait-ref and obligations
3095 // are sufficient to determine the impl substs, without
3096 // relying on projections in the impl-trait-ref.
3098 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
3099 impl_obligations.append(&mut substs.obligations);
3103 substs: substs.value,
3104 nested: impl_obligations,
3108 fn confirm_object_candidate(
3110 obligation: &TraitObligation<'tcx>,
3111 ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
3112 debug!("confirm_object_candidate({:?})", obligation);
3114 // FIXME(nmatsakis) skipping binder here seems wrong -- we should
3115 // probably flatten the binder from the obligation and the binder
3116 // from the object. Have to try to make a broken test case that
3118 let self_ty = self.infcx
3119 .shallow_resolve(*obligation.self_ty().skip_binder());
3120 let poly_trait_ref = match self_ty.sty {
3121 ty::Dynamic(ref data, ..) =>
3122 data.principal().unwrap_or_else(|| {
3123 span_bug!(obligation.cause.span, "object candidate with no principal")
3124 }).with_self_ty(self.tcx(), self_ty),
3125 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
3128 let mut upcast_trait_ref = None;
3129 let mut nested = vec![];
3133 let tcx = self.tcx();
3135 // We want to find the first supertrait in the list of
3136 // supertraits that we can unify with, and do that
3137 // unification. We know that there is exactly one in the list
3138 // where we can unify because otherwise select would have
3139 // reported an ambiguity. (When we do find a match, also
3140 // record it for later.)
3141 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(
3142 |&t| match self.infcx.commit_if_ok(|_| self.match_poly_trait_ref(obligation, t)) {
3143 Ok(obligations) => {
3144 upcast_trait_ref = Some(t);
3145 nested.extend(obligations);
3152 // Additionally, for each of the nonmatching predicates that
3153 // we pass over, we sum up the set of number of vtable
3154 // entries, so that we can compute the offset for the selected
3156 vtable_base = nonmatching.map(|t| tcx.count_own_vtable_entries(t)).sum();
3160 upcast_trait_ref: upcast_trait_ref.unwrap(),
3166 fn confirm_fn_pointer_candidate(
3168 obligation: &TraitObligation<'tcx>,
3169 ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3170 debug!("confirm_fn_pointer_candidate({:?})", obligation);
3172 // Okay to skip binder; it is reintroduced below.
3173 let self_ty = self.infcx
3174 .shallow_resolve(*obligation.self_ty().skip_binder());
3175 let sig = self_ty.fn_sig(self.tcx());
3176 let trait_ref = self.tcx()
3177 .closure_trait_ref_and_return_type(
3178 obligation.predicate.def_id(),
3181 util::TupleArgumentsFlag::Yes,
3183 .map_bound(|(trait_ref, _)| trait_ref);
3188 } = project::normalize_with_depth(
3190 obligation.param_env,
3191 obligation.cause.clone(),
3192 obligation.recursion_depth + 1,
3196 self.confirm_poly_trait_refs(
3197 obligation.cause.clone(),
3198 obligation.param_env,
3199 obligation.predicate.to_poly_trait_ref(),
3202 Ok(VtableFnPointerData {
3204 nested: obligations,
3208 fn confirm_trait_alias_candidate(
3210 obligation: &TraitObligation<'tcx>,
3211 alias_def_id: DefId,
3212 ) -> VtableTraitAliasData<'tcx, PredicateObligation<'tcx>> {
3214 "confirm_trait_alias_candidate({:?}, {:?})",
3215 obligation, alias_def_id
3218 self.infcx.in_snapshot(|_| {
3219 let (predicate, _) = self.infcx()
3220 .replace_bound_vars_with_placeholders(&obligation.predicate);
3221 let trait_ref = predicate.trait_ref;
3222 let trait_def_id = trait_ref.def_id;
3223 let substs = trait_ref.substs;
3225 let trait_obligations = self.impl_or_trait_obligations(
3226 obligation.cause.clone(),
3227 obligation.recursion_depth,
3228 obligation.param_env,
3234 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
3235 trait_def_id, trait_obligations
3238 VtableTraitAliasData {
3241 nested: trait_obligations,
3246 fn confirm_generator_candidate(
3248 obligation: &TraitObligation<'tcx>,
3249 ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3250 // Okay to skip binder because the substs on generator types never
3251 // touch bound regions, they just capture the in-scope
3252 // type/region parameters.
3253 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3254 let (generator_def_id, substs) = match self_ty.sty {
3255 ty::Generator(id, substs, _) => (id, substs),
3256 _ => bug!("closure candidate for non-closure {:?}", obligation),
3260 "confirm_generator_candidate({:?},{:?},{:?})",
3261 obligation, generator_def_id, substs
3264 let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
3268 } = normalize_with_depth(
3270 obligation.param_env,
3271 obligation.cause.clone(),
3272 obligation.recursion_depth + 1,
3277 "confirm_generator_candidate(generator_def_id={:?}, \
3278 trait_ref={:?}, obligations={:?})",
3279 generator_def_id, trait_ref, obligations
3282 obligations.extend(self.confirm_poly_trait_refs(
3283 obligation.cause.clone(),
3284 obligation.param_env,
3285 obligation.predicate.to_poly_trait_ref(),
3289 Ok(VtableGeneratorData {
3290 generator_def_id: generator_def_id,
3291 substs: substs.clone(),
3292 nested: obligations,
3296 fn confirm_closure_candidate(
3298 obligation: &TraitObligation<'tcx>,
3299 ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3300 debug!("confirm_closure_candidate({:?})", obligation);
3302 let kind = self.tcx()
3304 .fn_trait_kind(obligation.predicate.def_id())
3305 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
3307 // Okay to skip binder because the substs on closure types never
3308 // touch bound regions, they just capture the in-scope
3309 // type/region parameters.
3310 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3311 let (closure_def_id, substs) = match self_ty.sty {
3312 ty::Closure(id, substs) => (id, substs),
3313 _ => bug!("closure candidate for non-closure {:?}", obligation),
3316 let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
3320 } = normalize_with_depth(
3322 obligation.param_env,
3323 obligation.cause.clone(),
3324 obligation.recursion_depth + 1,
3329 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
3330 closure_def_id, trait_ref, obligations
3333 obligations.extend(self.confirm_poly_trait_refs(
3334 obligation.cause.clone(),
3335 obligation.param_env,
3336 obligation.predicate.to_poly_trait_ref(),
3341 if !self.tcx().sess.opts.debugging_opts.chalk {
3342 obligations.push(Obligation::new(
3343 obligation.cause.clone(),
3344 obligation.param_env,
3345 ty::Predicate::ClosureKind(closure_def_id, substs, kind),
3349 Ok(VtableClosureData {
3351 substs: substs.clone(),
3352 nested: obligations,
3356 /// In the case of closure types and fn pointers,
3357 /// we currently treat the input type parameters on the trait as
3358 /// outputs. This means that when we have a match we have only
3359 /// considered the self type, so we have to go back and make sure
3360 /// to relate the argument types too. This is kind of wrong, but
3361 /// since we control the full set of impls, also not that wrong,
3362 /// and it DOES yield better error messages (since we don't report
3363 /// errors as if there is no applicable impl, but rather report
3364 /// errors are about mismatched argument types.
3366 /// Here is an example. Imagine we have a closure expression
3367 /// and we desugared it so that the type of the expression is
3368 /// `Closure`, and `Closure` expects an int as argument. Then it
3369 /// is "as if" the compiler generated this impl:
3371 /// impl Fn(int) for Closure { ... }
3373 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
3374 /// we have matched the self type `Closure`. At this point we'll
3375 /// compare the `int` to `usize` and generate an error.
3377 /// Note that this checking occurs *after* the impl has selected,
3378 /// because these output type parameters should not affect the
3379 /// selection of the impl. Therefore, if there is a mismatch, we
3380 /// report an error to the user.
3381 fn confirm_poly_trait_refs(
3383 obligation_cause: ObligationCause<'tcx>,
3384 obligation_param_env: ty::ParamEnv<'tcx>,
3385 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
3386 expected_trait_ref: ty::PolyTraitRef<'tcx>,
3387 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3388 let obligation_trait_ref = obligation_trait_ref.clone();
3390 .at(&obligation_cause, obligation_param_env)
3391 .sup(obligation_trait_ref, expected_trait_ref)
3392 .map(|InferOk { obligations, .. }| obligations)
3393 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
3396 fn confirm_builtin_unsize_candidate(
3398 obligation: &TraitObligation<'tcx>,
3399 ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3400 let tcx = self.tcx();
3402 // assemble_candidates_for_unsizing should ensure there are no late bound
3403 // regions here. See the comment there for more details.
3404 let source = self.infcx
3405 .shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
3406 let target = obligation
3412 let target = self.infcx.shallow_resolve(target);
3415 "confirm_builtin_unsize_candidate(source={:?}, target={:?})",
3419 let mut nested = vec![];
3420 match (&source.sty, &target.sty) {
3421 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
3422 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
3423 // See assemble_candidates_for_unsizing for more info.
3424 let existential_predicates = data_a.map_bound(|data_a| {
3426 data_a.principal().map(|x| ty::ExistentialPredicate::Trait(x))
3429 .projection_bounds()
3430 .map(|x| ty::ExistentialPredicate::Projection(x)),
3435 .map(ty::ExistentialPredicate::AutoTrait),
3437 tcx.mk_existential_predicates(iter)
3439 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
3441 // Require that the traits involved in this upcast are **equal**;
3442 // only the **lifetime bound** is changed.
3444 // FIXME: This condition is arguably too strong -- it
3445 // would suffice for the source trait to be a
3446 // *subtype* of the target trait. In particular
3447 // changing from something like `for<'a, 'b> Foo<'a,
3448 // 'b>` to `for<'a> Foo<'a, 'a>` should be
3449 // permitted. And, indeed, in the in commit
3450 // 904a0bde93f0348f69914ee90b1f8b6e4e0d7cbc, this
3451 // condition was loosened. However, when the leak check was added
3452 // back, using subtype here actually guies the coercion code in
3453 // such a way that it accepts `old-lub-glb-object.rs`. This is probably
3454 // a good thing, but I've modified this to `.eq` because I want
3455 // to continue rejecting that test (as we have done for quite some time)
3456 // before we are firmly comfortable with what our behavior
3457 // should be there. -nikomatsakis
3458 let InferOk { obligations, .. } = self.infcx
3459 .at(&obligation.cause, obligation.param_env)
3460 .eq(target, source_trait) // FIXME -- see below
3461 .map_err(|_| Unimplemented)?;
3462 nested.extend(obligations);
3464 // Register one obligation for 'a: 'b.
3465 let cause = ObligationCause::new(
3466 obligation.cause.span,
3467 obligation.cause.body_id,
3468 ObjectCastObligation(target),
3470 let outlives = ty::OutlivesPredicate(r_a, r_b);
3471 nested.push(Obligation::with_depth(
3473 obligation.recursion_depth + 1,
3474 obligation.param_env,
3475 ty::Binder::bind(outlives).to_predicate(),
3480 (_, &ty::Dynamic(ref data, r)) => {
3481 let mut object_dids = data.auto_traits()
3482 .chain(data.principal_def_id());
3483 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3484 return Err(TraitNotObjectSafe(did));
3487 let cause = ObligationCause::new(
3488 obligation.cause.span,
3489 obligation.cause.body_id,
3490 ObjectCastObligation(target),
3493 let predicate_to_obligation = |predicate| {
3494 Obligation::with_depth(
3496 obligation.recursion_depth + 1,
3497 obligation.param_env,
3502 // Create obligations:
3503 // - Casting T to Trait
3504 // - For all the various builtin bounds attached to the object cast. (In other
3505 // words, if the object type is Foo+Send, this would create an obligation for the
3507 // - Projection predicates
3510 .map(|d| predicate_to_obligation(d.with_self_ty(tcx, source))),
3513 // We can only make objects from sized types.
3514 let tr = ty::TraitRef {
3515 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
3516 substs: tcx.mk_substs_trait(source, &[]),
3518 nested.push(predicate_to_obligation(tr.to_predicate()));
3520 // If the type is `Foo+'a`, ensures that the type
3521 // being cast to `Foo+'a` outlives `'a`:
3522 let outlives = ty::OutlivesPredicate(source, r);
3523 nested.push(predicate_to_obligation(
3524 ty::Binder::dummy(outlives).to_predicate(),
3529 (&ty::Array(a, _), &ty::Slice(b)) => {
3530 let InferOk { obligations, .. } = self.infcx
3531 .at(&obligation.cause, obligation.param_env)
3533 .map_err(|_| Unimplemented)?;
3534 nested.extend(obligations);
3537 // Struct<T> -> Struct<U>.
3538 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3539 let fields = def.all_fields()
3540 .map(|f| tcx.type_of(f.did))
3541 .collect::<Vec<_>>();
3543 // The last field of the structure has to exist and contain type parameters.
3544 let field = if let Some(&field) = fields.last() {
3547 return Err(Unimplemented);
3549 let mut ty_params = GrowableBitSet::new_empty();
3550 let mut found = false;
3551 for ty in field.walk() {
3552 if let ty::Param(p) = ty.sty {
3553 ty_params.insert(p.index as usize);
3558 return Err(Unimplemented);
3561 // Replace type parameters used in unsizing with
3562 // Error and ensure they do not affect any other fields.
3563 // This could be checked after type collection for any struct
3564 // with a potentially unsized trailing field.
3565 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3566 if ty_params.contains(i) {
3567 tcx.types.err.into()
3572 let substs = tcx.mk_substs(params);
3573 for &ty in fields.split_last().unwrap().1 {
3574 if ty.subst(tcx, substs).references_error() {
3575 return Err(Unimplemented);
3579 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
3580 let inner_source = field.subst(tcx, substs_a);
3581 let inner_target = field.subst(tcx, substs_b);
3583 // Check that the source struct with the target's
3584 // unsized parameters is equal to the target.
3585 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3586 if ty_params.contains(i) {
3587 substs_b.type_at(i).into()
3592 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3593 let InferOk { obligations, .. } = self.infcx
3594 .at(&obligation.cause, obligation.param_env)
3595 .eq(target, new_struct)
3596 .map_err(|_| Unimplemented)?;
3597 nested.extend(obligations);
3599 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
3600 nested.push(tcx.predicate_for_trait_def(
3601 obligation.param_env,
3602 obligation.cause.clone(),
3603 obligation.predicate.def_id(),
3604 obligation.recursion_depth + 1,
3606 &[inner_target.into()],
3610 // (.., T) -> (.., U).
3611 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3612 assert_eq!(tys_a.len(), tys_b.len());
3614 // The last field of the tuple has to exist.
3615 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3618 return Err(Unimplemented);
3620 let &b_last = tys_b.last().unwrap();
3622 // Check that the source tuple with the target's
3623 // last element is equal to the target.
3624 let new_tuple = tcx.mk_tup(
3625 a_mid.iter().map(|k| k.expect_ty()).chain(iter::once(b_last.expect_ty())),
3627 let InferOk { obligations, .. } = self.infcx
3628 .at(&obligation.cause, obligation.param_env)
3629 .eq(target, new_tuple)
3630 .map_err(|_| Unimplemented)?;
3631 nested.extend(obligations);
3633 // Construct the nested T: Unsize<U> predicate.
3634 nested.push(tcx.predicate_for_trait_def(
3635 obligation.param_env,
3636 obligation.cause.clone(),
3637 obligation.predicate.def_id(),
3638 obligation.recursion_depth + 1,
3647 Ok(VtableBuiltinData { nested })
3650 ///////////////////////////////////////////////////////////////////////////
3653 // Matching is a common path used for both evaluation and
3654 // confirmation. It basically unifies types that appear in impls
3655 // and traits. This does affect the surrounding environment;
3656 // therefore, when used during evaluation, match routines must be
3657 // run inside of a `probe()` so that their side-effects are
3663 obligation: &TraitObligation<'tcx>,
3664 snapshot: &CombinedSnapshot<'_, 'tcx>,
3665 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
3666 match self.match_impl(impl_def_id, obligation, snapshot) {
3667 Ok(substs) => substs,
3670 "Impl {:?} was matchable against {:?} but now is not",
3681 obligation: &TraitObligation<'tcx>,
3682 snapshot: &CombinedSnapshot<'_, 'tcx>,
3683 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
3684 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3686 // Before we create the substitutions and everything, first
3687 // consider a "quick reject". This avoids creating more types
3688 // and so forth that we need to.
3689 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3693 let (skol_obligation, placeholder_map) = self.infcx()
3694 .replace_bound_vars_with_placeholders(&obligation.predicate);
3695 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3697 let impl_substs = self.infcx
3698 .fresh_substs_for_item(obligation.cause.span, impl_def_id);
3700 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3703 value: impl_trait_ref,
3704 obligations: mut nested_obligations,
3705 } = project::normalize_with_depth(
3707 obligation.param_env,
3708 obligation.cause.clone(),
3709 obligation.recursion_depth + 1,
3714 "match_impl(impl_def_id={:?}, obligation={:?}, \
3715 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3716 impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3719 let InferOk { obligations, .. } = self.infcx
3720 .at(&obligation.cause, obligation.param_env)
3721 .eq(skol_obligation_trait_ref, impl_trait_ref)
3722 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3723 nested_obligations.extend(obligations);
3725 if let Err(e) = self.infcx.leak_check(false, &placeholder_map, snapshot) {
3726 debug!("match_impl: failed leak check due to `{}`", e);
3730 debug!("match_impl: success impl_substs={:?}", impl_substs);
3733 obligations: nested_obligations,
3737 fn fast_reject_trait_refs(
3739 obligation: &TraitObligation<'_>,
3740 impl_trait_ref: &ty::TraitRef<'_>,
3742 // We can avoid creating type variables and doing the full
3743 // substitution if we find that any of the input types, when
3744 // simplified, do not match.
3750 .zip(impl_trait_ref.input_types())
3751 .any(|(obligation_ty, impl_ty)| {
3752 let simplified_obligation_ty =
3753 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3754 let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
3756 simplified_obligation_ty.is_some()
3757 && simplified_impl_ty.is_some()
3758 && simplified_obligation_ty != simplified_impl_ty
3762 /// Normalize `where_clause_trait_ref` and try to match it against
3763 /// `obligation`. If successful, return any predicates that
3764 /// result from the normalization. Normalization is necessary
3765 /// because where-clauses are stored in the parameter environment
3767 fn match_where_clause_trait_ref(
3769 obligation: &TraitObligation<'tcx>,
3770 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3771 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3772 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3775 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3776 /// obligation is satisfied.
3777 fn match_poly_trait_ref(
3779 obligation: &TraitObligation<'tcx>,
3780 poly_trait_ref: ty::PolyTraitRef<'tcx>,
3781 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3783 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3784 obligation, poly_trait_ref
3788 .at(&obligation.cause, obligation.param_env)
3789 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3790 .map(|InferOk { obligations, .. }| obligations)
3794 ///////////////////////////////////////////////////////////////////////////
3797 fn match_fresh_trait_refs(
3799 previous: &ty::PolyTraitRef<'tcx>,
3800 current: &ty::PolyTraitRef<'tcx>,
3802 let mut matcher = ty::_match::Match::new(self.tcx());
3803 matcher.relate(previous, current).is_ok()
3808 previous_stack: TraitObligationStackList<'o, 'tcx>,
3809 obligation: &'o TraitObligation<'tcx>,
3810 ) -> TraitObligationStack<'o, 'tcx> {
3811 let fresh_trait_ref = obligation
3813 .to_poly_trait_ref()
3814 .fold_with(&mut self.freshener);
3816 let dfn = previous_stack.cache.next_dfn();
3817 let depth = previous_stack.depth() + 1;
3818 TraitObligationStack {
3821 reached_depth: Cell::new(depth),
3822 previous: previous_stack,
3828 fn closure_trait_ref_unnormalized(
3830 obligation: &TraitObligation<'tcx>,
3831 closure_def_id: DefId,
3832 substs: ty::ClosureSubsts<'tcx>,
3833 ) -> ty::PolyTraitRef<'tcx> {
3835 "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})",
3836 obligation, closure_def_id, substs,
3838 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3841 "closure_trait_ref_unnormalized: closure_type = {:?}",
3845 // (1) Feels icky to skip the binder here, but OTOH we know
3846 // that the self-type is an unboxed closure type and hence is
3847 // in fact unparameterized (or at least does not reference any
3848 // regions bound in the obligation). Still probably some
3849 // refactoring could make this nicer.
3851 .closure_trait_ref_and_return_type(
3852 obligation.predicate.def_id(),
3853 obligation.predicate.skip_binder().self_ty(), // (1)
3855 util::TupleArgumentsFlag::No,
3857 .map_bound(|(trait_ref, _)| trait_ref)
3860 fn generator_trait_ref_unnormalized(
3862 obligation: &TraitObligation<'tcx>,
3863 closure_def_id: DefId,
3864 substs: ty::GeneratorSubsts<'tcx>,
3865 ) -> ty::PolyTraitRef<'tcx> {
3866 let gen_sig = substs.poly_sig(closure_def_id, self.tcx());
3868 // (1) Feels icky to skip the binder here, but OTOH we know
3869 // that the self-type is an generator type and hence is
3870 // in fact unparameterized (or at least does not reference any
3871 // regions bound in the obligation). Still probably some
3872 // refactoring could make this nicer.
3875 .generator_trait_ref_and_outputs(
3876 obligation.predicate.def_id(),
3877 obligation.predicate.skip_binder().self_ty(), // (1)
3880 .map_bound(|(trait_ref, ..)| trait_ref)
3883 /// Returns the obligations that are implied by instantiating an
3884 /// impl or trait. The obligations are substituted and fully
3885 /// normalized. This is used when confirming an impl or default
3887 fn impl_or_trait_obligations(
3889 cause: ObligationCause<'tcx>,
3890 recursion_depth: usize,
3891 param_env: ty::ParamEnv<'tcx>,
3892 def_id: DefId, // of impl or trait
3893 substs: SubstsRef<'tcx>, // for impl or trait
3894 ) -> Vec<PredicateObligation<'tcx>> {
3895 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3896 let tcx = self.tcx();
3898 // To allow for one-pass evaluation of the nested obligation,
3899 // each predicate must be preceded by the obligations required
3901 // for example, if we have:
3902 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3903 // the impl will have the following predicates:
3904 // <V as Iterator>::Item = U,
3905 // U: Iterator, U: Sized,
3906 // V: Iterator, V: Sized,
3907 // <U as Iterator>::Item: Copy
3908 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3909 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3910 // `$1: Copy`, so we must ensure the obligations are emitted in
3912 let predicates = tcx.predicates_of(def_id);
3913 assert_eq!(predicates.parent, None);
3914 let mut predicates: Vec<_> = predicates
3917 .flat_map(|(predicate, _)| {
3918 let predicate = normalize_with_depth(
3923 &predicate.subst(tcx, substs),
3925 predicate.obligations.into_iter().chain(Some(Obligation {
3926 cause: cause.clone(),
3929 predicate: predicate.value,
3934 // We are performing deduplication here to avoid exponential blowups
3935 // (#38528) from happening, but the real cause of the duplication is
3936 // unknown. What we know is that the deduplication avoids exponential
3937 // amount of predicates being propagated when processing deeply nested
3940 // This code is hot enough that it's worth avoiding the allocation
3941 // required for the FxHashSet when possible. Special-casing lengths 0,
3942 // 1 and 2 covers roughly 75--80% of the cases.
3943 if predicates.len() <= 1 {
3944 // No possibility of duplicates.
3945 } else if predicates.len() == 2 {
3946 // Only two elements. Drop the second if they are equal.
3947 if predicates[0] == predicates[1] {
3948 predicates.truncate(1);
3951 // Three or more elements. Use a general deduplication process.
3952 let mut seen = FxHashSet::default();
3953 predicates.retain(|i| seen.insert(i.clone()));
3960 impl<'tcx> TraitObligation<'tcx> {
3961 #[allow(unused_comparisons)]
3962 pub fn derived_cause(
3964 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3965 ) -> ObligationCause<'tcx> {
3967 * Creates a cause for obligations that are derived from
3968 * `obligation` by a recursive search (e.g., for a builtin
3969 * bound, or eventually a `auto trait Foo`). If `obligation`
3970 * is itself a derived obligation, this is just a clone, but
3971 * otherwise we create a "derived obligation" cause so as to
3972 * keep track of the original root obligation for error
3976 let obligation = self;
3978 // NOTE(flaper87): As of now, it keeps track of the whole error
3979 // chain. Ideally, we should have a way to configure this either
3980 // by using -Z verbose or just a CLI argument.
3981 if obligation.recursion_depth >= 0 {
3982 let derived_cause = DerivedObligationCause {
3983 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3984 parent_code: Rc::new(obligation.cause.code.clone()),
3986 let derived_code = variant(derived_cause);
3987 ObligationCause::new(
3988 obligation.cause.span,
3989 obligation.cause.body_id,
3993 obligation.cause.clone()
3998 impl<'tcx> SelectionCache<'tcx> {
3999 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
4000 pub fn clear(&self) {
4001 *self.hashmap.borrow_mut() = Default::default();
4005 impl<'tcx> EvaluationCache<'tcx> {
4006 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
4007 pub fn clear(&self) {
4008 *self.hashmap.borrow_mut() = Default::default();
4012 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
4013 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
4014 TraitObligationStackList::with(self)
4017 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
4021 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
4025 /// Indicates that attempting to evaluate this stack entry
4026 /// required accessing something from the stack at depth `reached_depth`.
4027 fn update_reached_depth(&self, reached_depth: usize) {
4029 self.depth > reached_depth,
4030 "invoked `update_reached_depth` with something under this stack: \
4031 self.depth={} reached_depth={}",
4035 debug!("update_reached_depth(reached_depth={})", reached_depth);
4037 while reached_depth < p.depth {
4038 debug!("update_reached_depth: marking {:?} as cycle participant", p.fresh_trait_ref);
4039 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
4040 p = p.previous.head.unwrap();
4045 /// The "provisional evaluation cache" is used to store intermediate cache results
4046 /// when solving auto traits. Auto traits are unusual in that they can support
4047 /// cycles. So, for example, a "proof tree" like this would be ok:
4049 /// - `Foo<T>: Send` :-
4050 /// - `Bar<T>: Send` :-
4051 /// - `Foo<T>: Send` -- cycle, but ok
4052 /// - `Baz<T>: Send`
4054 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
4055 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
4056 /// For non-auto traits, this cycle would be an error, but for auto traits (because
4057 /// they are coinductive) it is considered ok.
4059 /// However, there is a complication: at the point where we have
4060 /// "proven" `Bar<T>: Send`, we have in fact only proven it
4061 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
4062 /// *under the assumption* that `Foo<T>: Send`. But what if we later
4063 /// find out this assumption is wrong? Specifically, we could
4064 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
4065 /// `Bar<T>: Send` didn't turn out to be true.
4067 /// In Issue #60010, we found a bug in rustc where it would cache
4068 /// these intermediate results. This was fixed in #60444 by disabling
4069 /// *all* caching for things involved in a cycle -- in our example,
4070 /// that would mean we don't cache that `Bar<T>: Send`. But this led
4071 /// to large slowdowns.
4073 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
4074 /// first requires proving `Bar<T>: Send` (which is true:
4076 /// - `Foo<T>: Send` :-
4077 /// - `Bar<T>: Send` :-
4078 /// - `Foo<T>: Send` -- cycle, but ok
4079 /// - `Baz<T>: Send`
4080 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
4081 /// - `*const T: Send` -- but what if we later encounter an error?
4083 /// The *provisional evaluation cache* resolves this issue. It stores
4084 /// cache results that we've proven but which were involved in a cycle
4085 /// in some way. We track the minimal stack depth (i.e., the
4086 /// farthest from the top of the stack) that we are dependent on.
4087 /// The idea is that the cache results within are all valid -- so long as
4088 /// none of the nodes in between the current node and the node at that minimum
4089 /// depth result in an error (in which case the cached results are just thrown away).
4091 /// During evaluation, we consult this provisional cache and rely on
4092 /// it. Accessing a cached value is considered equivalent to accessing
4093 /// a result at `reached_depth`, so it marks the *current* solution as
4094 /// provisional as well. If an error is encountered, we toss out any
4095 /// provisional results added from the subtree that encountered the
4096 /// error. When we pop the node at `reached_depth` from the stack, we
4097 /// can commit all the things that remain in the provisional cache.
4098 struct ProvisionalEvaluationCache<'tcx> {
4099 /// next "depth first number" to issue -- just a counter
4102 /// Stores the "coldest" depth (bottom of stack) reached by any of
4103 /// the evaluation entries. The idea here is that all things in the provisional
4104 /// cache are always dependent on *something* that is colder in the stack:
4105 /// therefore, if we add a new entry that is dependent on something *colder still*,
4106 /// we have to modify the depth for all entries at once.
4110 /// Imagine we have a stack `A B C D E` (with `E` being the top of
4111 /// the stack). We cache something with depth 2, which means that
4112 /// it was dependent on C. Then we pop E but go on and process a
4113 /// new node F: A B C D F. Now F adds something to the cache with
4114 /// depth 1, meaning it is dependent on B. Our original cache
4115 /// entry is also dependent on B, because there is a path from E
4116 /// to C and then from C to F and from F to B.
4117 reached_depth: Cell<usize>,
4119 /// Map from cache key to the provisionally evaluated thing.
4120 /// The cache entries contain the result but also the DFN in which they
4121 /// were added. The DFN is used to clear out values on failure.
4123 /// Imagine we have a stack like:
4125 /// - `A B C` and we add a cache for the result of C (DFN 2)
4126 /// - Then we have a stack `A B D` where `D` has DFN 3
4127 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
4128 /// - `E` generates various cache entries which have cyclic dependices on `B`
4129 /// - `A B D E F` and so forth
4130 /// - the DFN of `F` for example would be 5
4131 /// - then we determine that `E` is in error -- we will then clear
4132 /// all cache values whose DFN is >= 4 -- in this case, that
4133 /// means the cached value for `F`.
4134 map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
4137 /// A cache value for the provisional cache: contains the depth-first
4138 /// number (DFN) and result.
4139 #[derive(Copy, Clone, Debug)]
4140 struct ProvisionalEvaluation {
4142 result: EvaluationResult,
4145 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
4146 fn default() -> Self {
4149 reached_depth: Cell::new(std::usize::MAX),
4150 map: Default::default(),
4155 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
4156 /// Get the next DFN in sequence (basically a counter).
4157 fn next_dfn(&self) -> usize {
4158 let result = self.dfn.get();
4159 self.dfn.set(result + 1);
4163 /// Check the provisional cache for any result for
4164 /// `fresh_trait_ref`. If there is a hit, then you must consider
4165 /// it an access to the stack slots at depth
4166 /// `self.current_reached_depth()` and above.
4167 fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
4169 "get_provisional(fresh_trait_ref={:?}) = {:#?} with reached-depth {}",
4171 self.map.borrow().get(&fresh_trait_ref),
4172 self.reached_depth.get(),
4174 Some(self.map.borrow().get(&fresh_trait_ref)?.result)
4177 /// Current value of the `reached_depth` counter -- all the
4178 /// provisional cache entries are dependent on the item at this
4180 fn current_reached_depth(&self) -> usize {
4181 self.reached_depth.get()
4184 /// Insert a provisional result into the cache. The result came
4185 /// from the node with the given DFN. It accessed a minimum depth
4186 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
4187 /// and resulted in `result`.
4188 fn insert_provisional(
4191 reached_depth: usize,
4192 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
4193 result: EvaluationResult,
4196 "insert_provisional(from_dfn={}, reached_depth={}, fresh_trait_ref={:?}, result={:?})",
4202 let r_d = self.reached_depth.get();
4203 self.reached_depth.set(r_d.min(reached_depth));
4205 debug!("insert_provisional: reached_depth={:?}", self.reached_depth.get());
4207 self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
4210 /// Invoked when the node with dfn `dfn` does not get a successful
4211 /// result. This will clear out any provisional cache entries
4212 /// that were added since `dfn` was created. This is because the
4213 /// provisional entries are things which must assume that the
4214 /// things on the stack at the time of their creation succeeded --
4215 /// since the failing node is presently at the top of the stack,
4216 /// these provisional entries must either depend on it or some
4218 fn on_failure(&self, dfn: usize) {
4220 "on_failure(dfn={:?})",
4223 self.map.borrow_mut().retain(|key, eval| {
4224 if !eval.from_dfn >= dfn {
4225 debug!("on_failure: removing {:?}", key);
4233 /// Invoked when the node at depth `depth` completed without
4234 /// depending on anything higher in the stack (if that completion
4235 /// was a failure, then `on_failure` should have been invoked
4236 /// already). The callback `op` will be invoked for each
4237 /// provisional entry that we can now confirm.
4241 mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
4244 "on_completion(depth={}, reached_depth={})",
4246 self.reached_depth.get(),
4249 if self.reached_depth.get() < depth {
4250 debug!("on_completion: did not yet reach depth to complete");
4254 for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
4256 "on_completion: fresh_trait_ref={:?} eval={:?}",
4261 op(fresh_trait_ref, eval.result);
4264 self.reached_depth.set(std::usize::MAX);
4268 #[derive(Copy, Clone)]
4269 struct TraitObligationStackList<'o, 'tcx> {
4270 cache: &'o ProvisionalEvaluationCache<'tcx>,
4271 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
4274 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
4275 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4276 TraitObligationStackList { cache, head: None }
4279 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4280 TraitObligationStackList { cache: r.cache(), head: Some(r) }
4283 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4287 fn depth(&self) -> usize {
4288 if let Some(head) = self.head {
4296 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
4297 type Item = &'o TraitObligationStack<'o, 'tcx>;
4299 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4310 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
4311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4312 write!(f, "TraitObligationStack({:?})", self.obligation)
4316 #[derive(Clone, Eq, PartialEq)]
4317 pub struct WithDepNode<T> {
4318 dep_node: DepNodeIndex,
4322 impl<T: Clone> WithDepNode<T> {
4323 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
4330 pub fn get(&self, tcx: TyCtxt<'_>) -> T {
4331 tcx.dep_graph.read_index(self.dep_node);
4332 self.cached_value.clone()