1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! See `README.md` for high-level documentation
13 use self::SelectionCandidate::*;
14 use self::EvaluationResult::*;
17 use super::DerivedObligationCause;
19 use super::project::{normalize_with_depth, Normalized, ProjectionCacheKey};
20 use super::{PredicateObligation, TraitObligation, ObligationCause};
21 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation};
22 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch};
23 use super::{ObjectCastObligation, Obligation};
24 use super::TraitNotObjectSafe;
26 use super::SelectionResult;
27 use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure, VtableGenerator,
28 VtableFnPointer, VtableObject, VtableDefaultImpl};
29 use super::{VtableImplData, VtableObjectData, VtableBuiltinData, VtableGeneratorData,
30 VtableClosureData, VtableDefaultImplData, VtableFnPointerData};
33 use dep_graph::{DepNodeIndex, DepKind};
34 use hir::def_id::DefId;
36 use infer::{InferCtxt, InferOk, TypeFreshener};
37 use ty::subst::{Kind, Subst, Substs};
38 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
41 use ty::relate::TypeRelation;
42 use middle::lang_items;
44 use rustc_data_structures::bitvec::BitVector;
45 use rustc_data_structures::snapshot_vec::{SnapshotVecDelegate, SnapshotVec};
47 use std::cell::RefCell;
50 use std::marker::PhantomData;
56 use util::nodemap::FxHashMap;
58 struct InferredObligationsSnapshotVecDelegate<'tcx> {
59 phantom: PhantomData<&'tcx i32>,
61 impl<'tcx> SnapshotVecDelegate for InferredObligationsSnapshotVecDelegate<'tcx> {
62 type Value = PredicateObligation<'tcx>;
64 fn reverse(_: &mut Vec<Self::Value>, _: Self::Undo) {}
67 pub struct SelectionContext<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
68 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
70 /// Freshener used specifically for skolemizing entries on the
71 /// obligation stack. This ensures that all entries on the stack
72 /// at one time will have the same set of skolemized entries,
73 /// which is important for checking for trait bounds that
74 /// recursively require themselves.
75 freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
77 /// If true, indicates that the evaluation should be conservative
78 /// and consider the possibility of types outside this crate.
79 /// This comes up primarily when resolving ambiguity. Imagine
80 /// there is some trait reference `$0 : Bar` where `$0` is an
81 /// inference variable. If `intercrate` is true, then we can never
82 /// say for sure that this reference is not implemented, even if
83 /// there are *no impls at all for `Bar`*, because `$0` could be
84 /// bound to some type that in a downstream crate that implements
85 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
86 /// though, we set this to false, because we are only interested
87 /// in types that the user could actually have written --- in
88 /// other words, we consider `$0 : Bar` to be unimplemented if
89 /// there is no type that the user could *actually name* that
90 /// would satisfy it. This avoids crippling inference, basically.
93 inferred_obligations: SnapshotVec<InferredObligationsSnapshotVecDelegate<'tcx>>,
96 // A stack that walks back up the stack frame.
97 struct TraitObligationStack<'prev, 'tcx: 'prev> {
98 obligation: &'prev TraitObligation<'tcx>,
100 /// Trait ref from `obligation` but skolemized with the
101 /// selection-context's freshener. Used to check for recursion.
102 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
104 previous: TraitObligationStackList<'prev, 'tcx>,
108 pub struct SelectionCache<'tcx> {
109 hashmap: RefCell<FxHashMap<ty::TraitRef<'tcx>,
110 WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>>,
113 /// The selection process begins by considering all impls, where
114 /// clauses, and so forth that might resolve an obligation. Sometimes
115 /// we'll be able to say definitively that (e.g.) an impl does not
116 /// apply to the obligation: perhaps it is defined for `usize` but the
117 /// obligation is for `int`. In that case, we drop the impl out of the
118 /// list. But the other cases are considered *candidates*.
120 /// For selection to succeed, there must be exactly one matching
121 /// candidate. If the obligation is fully known, this is guaranteed
122 /// by coherence. However, if the obligation contains type parameters
123 /// or variables, there may be multiple such impls.
125 /// It is not a real problem if multiple matching impls exist because
126 /// of type variables - it just means the obligation isn't sufficiently
127 /// elaborated. In that case we report an ambiguity, and the caller can
128 /// try again after more type information has been gathered or report a
129 /// "type annotations required" error.
131 /// However, with type parameters, this can be a real problem - type
132 /// parameters don't unify with regular types, but they *can* unify
133 /// with variables from blanket impls, and (unless we know its bounds
134 /// will always be satisfied) picking the blanket impl will be wrong
135 /// for at least *some* substitutions. To make this concrete, if we have
137 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
138 /// impl<T: fmt::Debug> AsDebug for T {
140 /// fn debug(self) -> fmt::Debug { self }
142 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
144 /// we can't just use the impl to resolve the <T as AsDebug> obligation
145 /// - a type from another crate (that doesn't implement fmt::Debug) could
146 /// implement AsDebug.
148 /// Because where-clauses match the type exactly, multiple clauses can
149 /// only match if there are unresolved variables, and we can mostly just
150 /// report this ambiguity in that case. This is still a problem - we can't
151 /// *do anything* with ambiguities that involve only regions. This is issue
154 /// If a single where-clause matches and there are no inference
155 /// variables left, then it definitely matches and we can just select
158 /// In fact, we even select the where-clause when the obligation contains
159 /// inference variables. The can lead to inference making "leaps of logic",
160 /// for example in this situation:
162 /// pub trait Foo<T> { fn foo(&self) -> T; }
163 /// impl<T> Foo<()> for T { fn foo(&self) { } }
164 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
166 /// pub fn foo<T>(t: T) where T: Foo<bool> {
167 /// println!("{:?}", <T as Foo<_>>::foo(&t));
169 /// fn main() { foo(false); }
171 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
172 /// impl and the where-clause. We select the where-clause and unify $0=bool,
173 /// so the program prints "false". However, if the where-clause is omitted,
174 /// the blanket impl is selected, we unify $0=(), and the program prints
177 /// Exactly the same issues apply to projection and object candidates, except
178 /// that we can have both a projection candidate and a where-clause candidate
179 /// for the same obligation. In that case either would do (except that
180 /// different "leaps of logic" would occur if inference variables are
181 /// present), and we just pick the where-clause. This is, for example,
182 /// required for associated types to work in default impls, as the bounds
183 /// are visible both as projection bounds and as where-clauses from the
184 /// parameter environment.
185 #[derive(PartialEq,Eq,Debug,Clone)]
186 enum SelectionCandidate<'tcx> {
187 BuiltinCandidate { has_nested: bool },
188 ParamCandidate(ty::PolyTraitRef<'tcx>),
189 ImplCandidate(DefId),
190 DefaultImplCandidate(DefId),
192 /// This is a trait matching with a projected type as `Self`, and
193 /// we found an applicable bound in the trait definition.
196 /// Implementation of a `Fn`-family trait by one of the anonymous types
197 /// generated for a `||` expression.
200 /// Implementation of a `Generator` trait by one of the anonymous types
201 /// generated for a generator.
204 /// Implementation of a `Fn`-family trait by one of the anonymous
205 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
210 BuiltinObjectCandidate,
212 BuiltinUnsizeCandidate,
215 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
216 type Lifted = SelectionCandidate<'tcx>;
217 fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
219 BuiltinCandidate { has_nested } => {
224 ImplCandidate(def_id) => ImplCandidate(def_id),
225 DefaultImplCandidate(def_id) => DefaultImplCandidate(def_id),
226 ProjectionCandidate => ProjectionCandidate,
227 FnPointerCandidate => FnPointerCandidate,
228 ObjectCandidate => ObjectCandidate,
229 BuiltinObjectCandidate => BuiltinObjectCandidate,
230 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
231 ClosureCandidate => ClosureCandidate,
232 GeneratorCandidate => GeneratorCandidate,
234 ParamCandidate(ref trait_ref) => {
235 return tcx.lift(trait_ref).map(ParamCandidate);
241 struct SelectionCandidateSet<'tcx> {
242 // a list of candidates that definitely apply to the current
243 // obligation (meaning: types unify).
244 vec: Vec<SelectionCandidate<'tcx>>,
246 // if this is true, then there were candidates that might or might
247 // not have applied, but we couldn't tell. This occurs when some
248 // of the input types are type variables, in which case there are
249 // various "builtin" rules that might or might not trigger.
253 #[derive(PartialEq,Eq,Debug,Clone)]
254 struct EvaluatedCandidate<'tcx> {
255 candidate: SelectionCandidate<'tcx>,
256 evaluation: EvaluationResult,
259 /// When does the builtin impl for `T: Trait` apply?
260 enum BuiltinImplConditions<'tcx> {
261 /// The impl is conditional on T1,T2,.. : Trait
262 Where(ty::Binder<Vec<Ty<'tcx>>>),
263 /// There is no built-in impl. There may be some other
264 /// candidate (a where-clause or user-defined impl).
266 /// There is *no* impl for this, builtin or not. Ignore
267 /// all where-clauses.
269 /// It is unknown whether there is an impl.
273 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
274 /// The result of trait evaluation. The order is important
275 /// here as the evaluation of a list is the maximum of the
278 /// The evaluation results are ordered:
279 /// - `EvaluatedToOk` implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
280 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
281 /// - the "union" of evaluation results is equal to their maximum -
282 /// all the "potential success" candidates can potentially succeed,
283 /// so they are no-ops when unioned with a definite error, and within
284 /// the categories it's easy to see that the unions are correct.
285 enum EvaluationResult {
286 /// Evaluation successful
288 /// Evaluation is known to be ambiguous - it *might* hold for some
289 /// assignment of inference variables, but it might not.
291 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
292 /// know whether this obligation holds or not - it is the result we
293 /// would get with an empty stack, and therefore is cacheable.
295 /// Evaluation failed because of recursion involving inference
296 /// variables. We are somewhat imprecise there, so we don't actually
297 /// know the real result.
299 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
301 /// Evaluation failed because we encountered an obligation we are already
302 /// trying to prove on this branch.
304 /// We know this branch can't be a part of a minimal proof-tree for
305 /// the "root" of our cycle, because then we could cut out the recursion
306 /// and maintain a valid proof tree. However, this does not mean
307 /// that all the obligations on this branch do not hold - it's possible
308 /// that we entered this branch "speculatively", and that there
309 /// might be some other way to prove this obligation that does not
310 /// go through this cycle - so we can't cache this as a failure.
312 /// For example, suppose we have this:
314 /// ```rust,ignore (pseudo-Rust)
315 /// pub trait Trait { fn xyz(); }
316 /// // This impl is "useless", but we can still have
317 /// // an `impl Trait for SomeUnsizedType` somewhere.
318 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
320 /// pub fn foo<T: Trait + ?Sized>() {
321 /// <T as Trait>::xyz();
325 /// When checking `foo`, we have to prove `T: Trait`. This basically
326 /// translates into this:
328 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
330 /// When we try to prove it, we first go the first option, which
331 /// recurses. This shows us that the impl is "useless" - it won't
332 /// tell us that `T: Trait` unless it already implemented `Trait`
333 /// by some other means. However, that does not prevent `T: Trait`
334 /// does not hold, because of the bound (which can indeed be satisfied
335 /// by `SomeUnsizedType` from another crate).
337 /// FIXME: when an `EvaluatedToRecur` goes past its parent root, we
338 /// ought to convert it to an `EvaluatedToErr`, because we know
339 /// there definitely isn't a proof tree for that obligation. Not
340 /// doing so is still sound - there isn't any proof tree, so the
341 /// branch still can't be a part of a minimal one - but does not
342 /// re-enable caching.
344 /// Evaluation failed
348 impl EvaluationResult {
349 fn may_apply(self) -> bool {
353 EvaluatedToUnknown => true,
356 EvaluatedToRecur => false
360 fn is_stack_dependent(self) -> bool {
363 EvaluatedToRecur => true,
367 EvaluatedToErr => false,
373 pub struct EvaluationCache<'tcx> {
374 hashmap: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>
377 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
378 pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
381 freshener: infcx.freshener(),
383 inferred_obligations: SnapshotVec::new(),
387 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
390 freshener: infcx.freshener(),
392 inferred_obligations: SnapshotVec::new(),
396 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
400 pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
404 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
408 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
410 fn in_snapshot<R, F>(&mut self, f: F) -> R
411 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
413 // The irrefutable nature of the operation means we don't need to snapshot the
414 // inferred_obligations vector.
415 self.infcx.in_snapshot(|snapshot| f(self, snapshot))
418 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
420 fn probe<R, F>(&mut self, f: F) -> R
421 where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
423 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
424 let result = self.infcx.probe(|snapshot| f(self, snapshot));
425 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
429 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
430 /// the transaction fails and s.t. old obligations are retained.
431 fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E> where
432 F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> Result<T, E>
434 let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
435 match self.infcx.commit_if_ok(|snapshot| f(self, snapshot)) {
437 self.inferred_obligations.commit(inferred_obligations_snapshot);
441 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
448 ///////////////////////////////////////////////////////////////////////////
451 // The selection phase tries to identify *how* an obligation will
452 // be resolved. For example, it will identify which impl or
453 // parameter bound is to be used. The process can be inconclusive
454 // if the self type in the obligation is not fully inferred. Selection
455 // can result in an error in one of two ways:
457 // 1. If no applicable impl or parameter bound can be found.
458 // 2. If the output type parameters in the obligation do not match
459 // those specified by the impl/bound. For example, if the obligation
460 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
461 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
463 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
464 /// type environment by performing unification.
465 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
466 -> SelectionResult<'tcx, Selection<'tcx>> {
467 debug!("select({:?})", obligation);
468 assert!(!obligation.predicate.has_escaping_regions());
470 let tcx = self.tcx();
472 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
473 let ret = match self.candidate_from_obligation(&stack)? {
476 let mut candidate = self.confirm_candidate(obligation, candidate)?;
477 let inferred_obligations = (*self.inferred_obligations).into_iter().cloned();
478 candidate.nested_obligations_mut().extend(inferred_obligations);
483 // Test whether this is a `()` which was produced by defaulting a
484 // diverging type variable with `!` disabled. If so, we may need
485 // to raise a warning.
486 if obligation.predicate.skip_binder().self_ty().is_defaulted_unit() {
487 let mut raise_warning = true;
488 // Don't raise a warning if the trait is implemented for ! and only
489 // permits a trivial implementation for !. This stops us warning
490 // about (for example) `(): Clone` becoming `!: Clone` because such
491 // a switch can't cause code to stop compiling or execute
493 let mut never_obligation = obligation.clone();
494 let def_id = never_obligation.predicate.skip_binder().trait_ref.def_id;
495 never_obligation.predicate = never_obligation.predicate.map_bound(|mut trait_pred| {
496 // Swap out () with ! so we can check if the trait is impld for !
498 let trait_ref = &mut trait_pred.trait_ref;
499 let unit_substs = trait_ref.substs;
500 let mut never_substs = Vec::with_capacity(unit_substs.len());
501 never_substs.push(From::from(tcx.types.never));
502 never_substs.extend(&unit_substs[1..]);
503 trait_ref.substs = tcx.intern_substs(&never_substs);
507 if let Ok(Some(..)) = self.select(&never_obligation) {
508 if !tcx.trait_relevant_for_never(def_id) {
509 // The trait is also implemented for ! and the resulting
510 // implementation cannot actually be invoked in any way.
511 raise_warning = false;
516 tcx.lint_node(lint::builtin::RESOLVE_TRAIT_ON_DEFAULTED_UNIT,
517 obligation.cause.body_id,
518 obligation.cause.span,
519 &format!("code relies on type inference rules which are likely \
526 ///////////////////////////////////////////////////////////////////////////
529 // Tests whether an obligation can be selected or whether an impl
530 // can be applied to particular types. It skips the "confirmation"
531 // step and hence completely ignores output type parameters.
533 // The result is "true" if the obligation *may* hold and "false" if
534 // we can be sure it does not.
536 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
537 pub fn evaluate_obligation(&mut self,
538 obligation: &PredicateObligation<'tcx>)
541 debug!("evaluate_obligation({:?})",
544 self.probe(|this, _| {
545 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
550 /// Evaluates whether the obligation `obligation` can be satisfied,
551 /// and returns `false` if not certain. However, this is not entirely
552 /// accurate if inference variables are involved.
553 pub fn evaluate_obligation_conservatively(&mut self,
554 obligation: &PredicateObligation<'tcx>)
557 debug!("evaluate_obligation_conservatively({:?})",
560 self.probe(|this, _| {
561 this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
566 /// Evaluates the predicates in `predicates` recursively. Note that
567 /// this applies projections in the predicates, and therefore
568 /// is run within an inference probe.
569 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
570 stack: TraitObligationStackList<'o, 'tcx>,
573 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
575 let mut result = EvaluatedToOk;
576 for obligation in predicates {
577 let eval = self.evaluate_predicate_recursively(stack, obligation);
578 debug!("evaluate_predicate_recursively({:?}) = {:?}",
580 if let EvaluatedToErr = eval {
581 // fast-path - EvaluatedToErr is the top of the lattice,
582 // so we don't need to look on the other predicates.
583 return EvaluatedToErr;
585 result = cmp::max(result, eval);
591 fn evaluate_predicate_recursively<'o>(&mut self,
592 previous_stack: TraitObligationStackList<'o, 'tcx>,
593 obligation: &PredicateObligation<'tcx>)
596 debug!("evaluate_predicate_recursively({:?})",
599 match obligation.predicate {
600 ty::Predicate::Trait(ref t) => {
601 assert!(!t.has_escaping_regions());
602 let obligation = obligation.with(t.clone());
603 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
606 ty::Predicate::Equate(ref p) => {
607 // does this code ever run?
608 match self.infcx.equality_predicate(&obligation.cause, obligation.param_env, p) {
609 Ok(InferOk { obligations, .. }) => {
610 self.inferred_obligations.extend(obligations);
613 Err(_) => EvaluatedToErr
617 ty::Predicate::Subtype(ref p) => {
618 // does this code ever run?
619 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
620 Some(Ok(InferOk { obligations, .. })) => {
621 self.inferred_obligations.extend(obligations);
624 Some(Err(_)) => EvaluatedToErr,
625 None => EvaluatedToAmbig,
629 ty::Predicate::WellFormed(ty) => {
630 match ty::wf::obligations(self.infcx,
631 obligation.param_env,
632 obligation.cause.body_id,
633 ty, obligation.cause.span) {
635 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
641 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
642 // we do not consider region relationships when
643 // evaluating trait matches
647 ty::Predicate::ObjectSafe(trait_def_id) => {
648 if self.tcx().is_object_safe(trait_def_id) {
655 ty::Predicate::Projection(ref data) => {
656 let project_obligation = obligation.with(data.clone());
657 match project::poly_project_and_unify_type(self, &project_obligation) {
658 Ok(Some(subobligations)) => {
659 let result = self.evaluate_predicates_recursively(previous_stack,
660 subobligations.iter());
662 ProjectionCacheKey::from_poly_projection_predicate(self, data)
664 self.infcx.projection_cache.borrow_mut().complete(key);
677 ty::Predicate::ClosureKind(closure_def_id, kind) => {
678 match self.infcx.closure_kind(closure_def_id) {
679 Some(closure_kind) => {
680 if closure_kind.extends(kind) {
694 fn evaluate_trait_predicate_recursively<'o>(&mut self,
695 previous_stack: TraitObligationStackList<'o, 'tcx>,
696 mut obligation: TraitObligation<'tcx>)
699 debug!("evaluate_trait_predicate_recursively({:?})",
702 if !self.intercrate && obligation.is_global() {
703 // If a param env is consistent, global obligations do not depend on its particular
704 // value in order to work, so we can clear out the param env and get better
705 // caching. (If the current param env is inconsistent, we don't care what happens).
706 debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
707 obligation.param_env = ty::ParamEnv::empty(obligation.param_env.reveal);
710 let stack = self.push_stack(previous_stack, &obligation);
711 let fresh_trait_ref = stack.fresh_trait_ref;
712 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
713 debug!("CACHE HIT: EVAL({:?})={:?}",
719 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
721 debug!("CACHE MISS: EVAL({:?})={:?}",
724 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
729 fn evaluate_stack<'o>(&mut self,
730 stack: &TraitObligationStack<'o, 'tcx>)
733 // In intercrate mode, whenever any of the types are unbound,
734 // there can always be an impl. Even if there are no impls in
735 // this crate, perhaps the type would be unified with
736 // something from another crate that does provide an impl.
738 // In intra mode, we must still be conservative. The reason is
739 // that we want to avoid cycles. Imagine an impl like:
741 // impl<T:Eq> Eq for Vec<T>
743 // and a trait reference like `$0 : Eq` where `$0` is an
744 // unbound variable. When we evaluate this trait-reference, we
745 // will unify `$0` with `Vec<$1>` (for some fresh variable
746 // `$1`), on the condition that `$1 : Eq`. We will then wind
747 // up with many candidates (since that are other `Eq` impls
748 // that apply) and try to winnow things down. This results in
749 // a recursive evaluation that `$1 : Eq` -- as you can
750 // imagine, this is just where we started. To avoid that, we
751 // check for unbound variables and return an ambiguous (hence possible)
752 // match if we've seen this trait before.
754 // This suffices to allow chains like `FnMut` implemented in
755 // terms of `Fn` etc, but we could probably make this more
757 let unbound_input_types = stack.fresh_trait_ref.input_types().any(|ty| ty.is_fresh());
758 if unbound_input_types && self.intercrate {
759 debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
760 stack.fresh_trait_ref);
761 return EvaluatedToAmbig;
763 if unbound_input_types &&
764 stack.iter().skip(1).any(
765 |prev| stack.obligation.param_env == prev.obligation.param_env &&
766 self.match_fresh_trait_refs(&stack.fresh_trait_ref,
767 &prev.fresh_trait_ref))
769 debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
770 stack.fresh_trait_ref);
771 return EvaluatedToUnknown;
774 // If there is any previous entry on the stack that precisely
775 // matches this obligation, then we can assume that the
776 // obligation is satisfied for now (still all other conditions
777 // must be met of course). One obvious case this comes up is
778 // marker traits like `Send`. Think of a linked list:
780 // struct List<T> { data: T, next: Option<Box<List<T>>> {
782 // `Box<List<T>>` will be `Send` if `T` is `Send` and
783 // `Option<Box<List<T>>>` is `Send`, and in turn
784 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
787 // Note that we do this comparison using the `fresh_trait_ref`
788 // fields. Because these have all been skolemized using
789 // `self.freshener`, we can be sure that (a) this will not
790 // affect the inferencer state and (b) that if we see two
791 // skolemized types with the same index, they refer to the
792 // same unbound type variable.
793 if let Some(rec_index) =
795 .skip(1) // skip top-most frame
796 .position(|prev| stack.obligation.param_env == prev.obligation.param_env &&
797 stack.fresh_trait_ref == prev.fresh_trait_ref)
799 debug!("evaluate_stack({:?}) --> recursive",
800 stack.fresh_trait_ref);
801 let cycle = stack.iter().skip(1).take(rec_index+1);
802 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
803 if self.coinductive_match(cycle) {
804 debug!("evaluate_stack({:?}) --> recursive, coinductive",
805 stack.fresh_trait_ref);
806 return EvaluatedToOk;
808 debug!("evaluate_stack({:?}) --> recursive, inductive",
809 stack.fresh_trait_ref);
810 return EvaluatedToRecur;
814 match self.candidate_from_obligation(stack) {
815 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
816 Ok(None) => EvaluatedToAmbig,
817 Err(..) => EvaluatedToErr
821 /// For defaulted traits, we use a co-inductive strategy to solve, so
822 /// that recursion is ok. This routine returns true if the top of the
823 /// stack (`cycle[0]`):
824 /// - is a defaulted trait, and
825 /// - it also appears in the backtrace at some position `X`; and,
826 /// - all the predicates at positions `X..` between `X` an the top are
827 /// also defaulted traits.
828 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
829 where I: Iterator<Item=ty::Predicate<'tcx>>
831 let mut cycle = cycle;
832 cycle.all(|predicate| self.coinductive_predicate(predicate))
835 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
836 let result = match predicate {
837 ty::Predicate::Trait(ref data) => {
838 self.tcx().trait_has_default_impl(data.def_id())
844 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
848 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
849 /// obligations are met. Returns true if `candidate` remains viable after this further
851 fn evaluate_candidate<'o>(&mut self,
852 stack: &TraitObligationStack<'o, 'tcx>,
853 candidate: &SelectionCandidate<'tcx>)
856 debug!("evaluate_candidate: depth={} candidate={:?}",
857 stack.obligation.recursion_depth, candidate);
858 let result = self.probe(|this, _| {
859 let candidate = (*candidate).clone();
860 match this.confirm_candidate(stack.obligation, candidate) {
862 this.evaluate_predicates_recursively(
864 selection.nested_obligations().iter())
866 Err(..) => EvaluatedToErr
869 debug!("evaluate_candidate: depth={} result={:?}",
870 stack.obligation.recursion_depth, result);
874 fn check_evaluation_cache(&self,
875 param_env: ty::ParamEnv<'tcx>,
876 trait_ref: ty::PolyTraitRef<'tcx>)
877 -> Option<EvaluationResult>
879 let tcx = self.tcx();
880 if self.can_use_global_caches(param_env) {
881 let cache = tcx.evaluation_cache.hashmap.borrow();
882 if let Some(cached) = cache.get(&trait_ref) {
883 return Some(cached.get(tcx));
886 self.infcx.evaluation_cache.hashmap
892 fn insert_evaluation_cache(&mut self,
893 param_env: ty::ParamEnv<'tcx>,
894 trait_ref: ty::PolyTraitRef<'tcx>,
895 dep_node: DepNodeIndex,
896 result: EvaluationResult)
898 // Avoid caching results that depend on more than just the trait-ref
899 // - the stack can create recursion.
900 if result.is_stack_dependent() {
904 if self.can_use_global_caches(param_env) {
905 let mut cache = self.tcx().evaluation_cache.hashmap.borrow_mut();
906 if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
907 cache.insert(trait_ref, WithDepNode::new(dep_node, result));
912 self.infcx.evaluation_cache.hashmap
914 .insert(trait_ref, WithDepNode::new(dep_node, result));
917 ///////////////////////////////////////////////////////////////////////////
918 // CANDIDATE ASSEMBLY
920 // The selection process begins by examining all in-scope impls,
921 // caller obligations, and so forth and assembling a list of
922 // candidates. See `README.md` and the `Candidate` type for more
925 fn candidate_from_obligation<'o>(&mut self,
926 stack: &TraitObligationStack<'o, 'tcx>)
927 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
929 // Watch out for overflow. This intentionally bypasses (and does
930 // not update) the cache.
931 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
932 if stack.obligation.recursion_depth >= recursion_limit {
933 self.infcx().report_overflow_error(&stack.obligation, true);
936 // Check the cache. Note that we skolemize the trait-ref
937 // separately rather than using `stack.fresh_trait_ref` -- this
938 // is because we want the unbound variables to be replaced
939 // with fresh skolemized types starting from index 0.
940 let cache_fresh_trait_pred =
941 self.infcx.freshen(stack.obligation.predicate.clone());
942 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
943 cache_fresh_trait_pred,
945 assert!(!stack.obligation.predicate.has_escaping_regions());
947 if let Some(c) = self.check_candidate_cache(stack.obligation.param_env,
948 &cache_fresh_trait_pred) {
949 debug!("CACHE HIT: SELECT({:?})={:?}",
950 cache_fresh_trait_pred,
955 // If no match, compute result and insert into cache.
956 let (candidate, dep_node) = self.in_task(|this| {
957 this.candidate_from_obligation_no_cache(stack)
960 debug!("CACHE MISS: SELECT({:?})={:?}",
961 cache_fresh_trait_pred, candidate);
962 self.insert_candidate_cache(stack.obligation.param_env,
963 cache_fresh_trait_pred,
969 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
970 where OP: FnOnce(&mut Self) -> R
972 let (result, dep_node) = self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || {
975 self.tcx().dep_graph.read_index(dep_node);
979 // Treat negative impls as unimplemented
980 fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
981 -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
982 if let ImplCandidate(def_id) = candidate {
983 if self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative {
984 return Err(Unimplemented)
990 fn candidate_from_obligation_no_cache<'o>(&mut self,
991 stack: &TraitObligationStack<'o, 'tcx>)
992 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
994 if stack.obligation.predicate.references_error() {
995 // If we encounter a `TyError`, we generally prefer the
996 // most "optimistic" result in response -- that is, the
997 // one least likely to report downstream errors. But
998 // because this routine is shared by coherence and by
999 // trait selection, there isn't an obvious "right" choice
1000 // here in that respect, so we opt to just return
1001 // ambiguity and let the upstream clients sort it out.
1005 if !self.is_knowable(stack) {
1006 debug!("coherence stage: not knowable");
1010 let candidate_set = self.assemble_candidates(stack)?;
1012 if candidate_set.ambiguous {
1013 debug!("candidate set contains ambig");
1017 let mut candidates = candidate_set.vec;
1019 debug!("assembled {} candidates for {:?}: {:?}",
1024 // At this point, we know that each of the entries in the
1025 // candidate set is *individually* applicable. Now we have to
1026 // figure out if they contain mutual incompatibilities. This
1027 // frequently arises if we have an unconstrained input type --
1028 // for example, we are looking for $0:Eq where $0 is some
1029 // unconstrained type variable. In that case, we'll get a
1030 // candidate which assumes $0 == int, one that assumes $0 ==
1031 // usize, etc. This spells an ambiguity.
1033 // If there is more than one candidate, first winnow them down
1034 // by considering extra conditions (nested obligations and so
1035 // forth). We don't winnow if there is exactly one
1036 // candidate. This is a relatively minor distinction but it
1037 // can lead to better inference and error-reporting. An
1038 // example would be if there was an impl:
1040 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1042 // and we were to see some code `foo.push_clone()` where `boo`
1043 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1044 // we were to winnow, we'd wind up with zero candidates.
1045 // Instead, we select the right impl now but report `Bar does
1046 // not implement Clone`.
1047 if candidates.len() == 1 {
1048 return self.filter_negative_impls(candidates.pop().unwrap());
1051 // Winnow, but record the exact outcome of evaluation, which
1052 // is needed for specialization.
1053 let mut candidates: Vec<_> = candidates.into_iter().filter_map(|c| {
1054 let eval = self.evaluate_candidate(stack, &c);
1055 if eval.may_apply() {
1056 Some(EvaluatedCandidate {
1065 // If there are STILL multiple candidate, we can further
1066 // reduce the list by dropping duplicates -- including
1067 // resolving specializations.
1068 if candidates.len() > 1 {
1070 while i < candidates.len() {
1072 (0..candidates.len())
1073 .filter(|&j| i != j)
1074 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
1077 debug!("Dropping candidate #{}/{}: {:?}",
1078 i, candidates.len(), candidates[i]);
1079 candidates.swap_remove(i);
1081 debug!("Retaining candidate #{}/{}: {:?}",
1082 i, candidates.len(), candidates[i]);
1085 // If there are *STILL* multiple candidates, give up
1086 // and report ambiguity.
1088 debug!("multiple matches, ambig");
1095 // If there are *NO* candidates, then there are no impls --
1096 // that we know of, anyway. Note that in the case where there
1097 // are unbound type variables within the obligation, it might
1098 // be the case that you could still satisfy the obligation
1099 // from another crate by instantiating the type variables with
1100 // a type from another crate that does have an impl. This case
1101 // is checked for in `evaluate_stack` (and hence users
1102 // who might care about this case, like coherence, should use
1104 if candidates.is_empty() {
1105 return Err(Unimplemented);
1108 // Just one candidate left.
1109 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1112 fn is_knowable<'o>(&mut self,
1113 stack: &TraitObligationStack<'o, 'tcx>)
1116 debug!("is_knowable(intercrate={})", self.intercrate);
1118 if !self.intercrate {
1122 let obligation = &stack.obligation;
1123 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1125 // ok to skip binder because of the nature of the
1126 // trait-ref-is-knowable check, which does not care about
1128 let trait_ref = &predicate.skip_binder().trait_ref;
1130 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1133 /// Returns true if the global caches can be used.
1134 /// Do note that if the type itself is not in the
1135 /// global tcx, the local caches will be used.
1136 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1137 // If there are any where-clauses in scope, then we always use
1138 // a cache local to this particular scope. Otherwise, we
1139 // switch to a global cache. We used to try and draw
1140 // finer-grained distinctions, but that led to a serious of
1141 // annoying and weird bugs like #22019 and #18290. This simple
1142 // rule seems to be pretty clearly safe and also still retains
1143 // a very high hit rate (~95% when compiling rustc).
1144 if !param_env.caller_bounds.is_empty() {
1148 // Avoid using the master cache during coherence and just rely
1149 // on the local cache. This effectively disables caching
1150 // during coherence. It is really just a simplification to
1151 // avoid us having to fear that coherence results "pollute"
1152 // the master cache. Since coherence executes pretty quickly,
1153 // it's not worth going to more trouble to increase the
1154 // hit-rate I don't think.
1155 if self.intercrate {
1159 // Otherwise, we can use the global cache.
1163 fn check_candidate_cache(&mut self,
1164 param_env: ty::ParamEnv<'tcx>,
1165 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
1166 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
1168 let tcx = self.tcx();
1169 let trait_ref = &cache_fresh_trait_pred.0.trait_ref;
1170 if self.can_use_global_caches(param_env) {
1171 let cache = tcx.selection_cache.hashmap.borrow();
1172 if let Some(cached) = cache.get(&trait_ref) {
1173 return Some(cached.get(tcx));
1176 self.infcx.selection_cache.hashmap
1179 .map(|v| v.get(tcx))
1182 fn insert_candidate_cache(&mut self,
1183 param_env: ty::ParamEnv<'tcx>,
1184 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1185 dep_node: DepNodeIndex,
1186 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1188 let tcx = self.tcx();
1189 let trait_ref = cache_fresh_trait_pred.0.trait_ref;
1190 if self.can_use_global_caches(param_env) {
1191 let mut cache = tcx.selection_cache.hashmap.borrow_mut();
1192 if let Some(trait_ref) = tcx.lift_to_global(&trait_ref) {
1193 if let Some(candidate) = tcx.lift_to_global(&candidate) {
1194 cache.insert(trait_ref, WithDepNode::new(dep_node, candidate));
1200 self.infcx.selection_cache.hashmap
1202 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1205 fn assemble_candidates<'o>(&mut self,
1206 stack: &TraitObligationStack<'o, 'tcx>)
1207 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
1209 let TraitObligationStack { obligation, .. } = *stack;
1210 let ref obligation = Obligation {
1211 param_env: obligation.param_env,
1212 cause: obligation.cause.clone(),
1213 recursion_depth: obligation.recursion_depth,
1214 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
1217 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1218 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
1220 // This is somewhat problematic, as the current scheme can't really
1221 // handle it turning to be a projection. This does end up as truly
1222 // ambiguous in most cases anyway.
1224 // Until this is fixed, take the fast path out - this also improves
1225 // performance by preventing assemble_candidates_from_impls from
1226 // matching every impl for this trait.
1227 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1230 let mut candidates = SelectionCandidateSet {
1235 // Other bounds. Consider both in-scope bounds from fn decl
1236 // and applicable impls. There is a certain set of precedence rules here.
1238 let def_id = obligation.predicate.def_id();
1239 if self.tcx().lang_items.copy_trait() == Some(def_id) {
1240 debug!("obligation self ty is {:?}",
1241 obligation.predicate.0.self_ty());
1243 // User-defined copy impls are permitted, but only for
1244 // structs and enums.
1245 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1247 // For other types, we'll use the builtin rules.
1248 let copy_conditions = self.copy_conditions(obligation);
1249 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1250 } else if self.tcx().lang_items.sized_trait() == Some(def_id) {
1251 // Sized is never implementable by end-users, it is
1252 // always automatically computed.
1253 let sized_conditions = self.sized_conditions(obligation);
1254 self.assemble_builtin_bound_candidates(sized_conditions,
1256 } else if self.tcx().lang_items.unsize_trait() == Some(def_id) {
1257 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1259 if self.tcx().lang_items.clone_trait() == Some(def_id) {
1260 // Same builtin conditions as `Copy`, i.e. every type which has builtin support
1261 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1262 // types have builtin support for `Clone`.
1263 let clone_conditions = self.copy_conditions(obligation);
1264 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1267 self.assemble_generator_candidates(obligation, &mut candidates)?;
1268 self.assemble_closure_candidates(obligation, &mut candidates)?;
1269 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1270 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1271 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1274 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1275 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1276 // Default implementations have lower priority, so we only
1277 // consider triggering a default if there is no other impl that can apply.
1278 if candidates.vec.is_empty() {
1279 self.assemble_candidates_from_default_impls(obligation, &mut candidates)?;
1281 debug!("candidate list size: {}", candidates.vec.len());
1285 fn assemble_candidates_from_projected_tys(&mut self,
1286 obligation: &TraitObligation<'tcx>,
1287 candidates: &mut SelectionCandidateSet<'tcx>)
1289 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1291 // FIXME(#20297) -- just examining the self-type is very simplistic
1293 // before we go into the whole skolemization thing, just
1294 // quickly check if the self-type is a projection at all.
1295 match obligation.predicate.0.trait_ref.self_ty().sty {
1296 ty::TyProjection(_) | ty::TyAnon(..) => {}
1297 ty::TyInfer(ty::TyVar(_)) => {
1298 span_bug!(obligation.cause.span,
1299 "Self=_ should have been handled by assemble_candidates");
1304 let result = self.probe(|this, snapshot| {
1305 this.match_projection_obligation_against_definition_bounds(obligation,
1310 candidates.vec.push(ProjectionCandidate);
1314 fn match_projection_obligation_against_definition_bounds(
1316 obligation: &TraitObligation<'tcx>,
1317 snapshot: &infer::CombinedSnapshot)
1320 let poly_trait_predicate =
1321 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1322 let (skol_trait_predicate, skol_map) =
1323 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1324 debug!("match_projection_obligation_against_definition_bounds: \
1325 skol_trait_predicate={:?} skol_map={:?}",
1326 skol_trait_predicate,
1329 let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1330 ty::TyProjection(ref data) =>
1331 (data.trait_ref(self.tcx()).def_id, data.substs),
1332 ty::TyAnon(def_id, substs) => (def_id, substs),
1335 obligation.cause.span,
1336 "match_projection_obligation_against_definition_bounds() called \
1337 but self-ty not a projection: {:?}",
1338 skol_trait_predicate.trait_ref.self_ty());
1341 debug!("match_projection_obligation_against_definition_bounds: \
1342 def_id={:?}, substs={:?}",
1345 let predicates_of = self.tcx().predicates_of(def_id);
1346 let bounds = predicates_of.instantiate(self.tcx(), substs);
1347 debug!("match_projection_obligation_against_definition_bounds: \
1351 let matching_bound =
1352 util::elaborate_predicates(self.tcx(), bounds.predicates)
1356 |this, _| this.match_projection(obligation,
1358 skol_trait_predicate.trait_ref.clone(),
1362 debug!("match_projection_obligation_against_definition_bounds: \
1363 matching_bound={:?}",
1365 match matching_bound {
1368 // Repeat the successful match, if any, this time outside of a probe.
1369 let result = self.match_projection(obligation,
1371 skol_trait_predicate.trait_ref.clone(),
1375 self.infcx.pop_skolemized(skol_map, snapshot);
1383 fn match_projection(&mut self,
1384 obligation: &TraitObligation<'tcx>,
1385 trait_bound: ty::PolyTraitRef<'tcx>,
1386 skol_trait_ref: ty::TraitRef<'tcx>,
1387 skol_map: &infer::SkolemizationMap<'tcx>,
1388 snapshot: &infer::CombinedSnapshot)
1391 assert!(!skol_trait_ref.has_escaping_regions());
1392 match self.infcx.at(&obligation.cause, obligation.param_env)
1393 .sup(ty::Binder(skol_trait_ref), trait_bound) {
1394 Ok(InferOk { obligations, .. }) => {
1395 self.inferred_obligations.extend(obligations);
1397 Err(_) => { return false; }
1400 self.infcx.leak_check(false, obligation.cause.span, skol_map, snapshot).is_ok()
1403 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1404 /// supplied to find out whether it is listed among them.
1406 /// Never affects inference environment.
1407 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1408 stack: &TraitObligationStack<'o, 'tcx>,
1409 candidates: &mut SelectionCandidateSet<'tcx>)
1410 -> Result<(),SelectionError<'tcx>>
1412 debug!("assemble_candidates_from_caller_bounds({:?})",
1416 stack.obligation.param_env.caller_bounds
1418 .filter_map(|o| o.to_opt_poly_trait_ref());
1420 // micro-optimization: filter out predicates relating to different
1422 let matching_bounds =
1423 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1425 let matching_bounds =
1426 matching_bounds.filter(
1427 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1429 let param_candidates =
1430 matching_bounds.map(|bound| ParamCandidate(bound));
1432 candidates.vec.extend(param_candidates);
1437 fn evaluate_where_clause<'o>(&mut self,
1438 stack: &TraitObligationStack<'o, 'tcx>,
1439 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1442 self.probe(move |this, _| {
1443 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1444 Ok(obligations) => {
1445 this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1447 Err(()) => EvaluatedToErr
1452 fn assemble_generator_candidates(&mut self,
1453 obligation: &TraitObligation<'tcx>,
1454 candidates: &mut SelectionCandidateSet<'tcx>)
1455 -> Result<(),SelectionError<'tcx>>
1457 if self.tcx().lang_items.gen_trait() != Some(obligation.predicate.def_id()) {
1461 // ok to skip binder because the substs on generator types never
1462 // touch bound regions, they just capture the in-scope
1463 // type/region parameters
1464 let self_ty = *obligation.self_ty().skip_binder();
1466 ty::TyGenerator(..) => {
1467 debug!("assemble_generator_candidates: self_ty={:?} obligation={:?}",
1471 candidates.vec.push(GeneratorCandidate);
1474 ty::TyInfer(ty::TyVar(_)) => {
1475 debug!("assemble_generator_candidates: ambiguous self-type");
1476 candidates.ambiguous = true;
1479 _ => { return Ok(()); }
1483 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1484 /// FnMut<..>` where `X` is a closure type.
1486 /// Note: the type parameters on a closure candidate are modeled as *output* type
1487 /// parameters and hence do not affect whether this trait is a match or not. They will be
1488 /// unified during the confirmation step.
1489 fn assemble_closure_candidates(&mut self,
1490 obligation: &TraitObligation<'tcx>,
1491 candidates: &mut SelectionCandidateSet<'tcx>)
1492 -> Result<(),SelectionError<'tcx>>
1494 let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1496 None => { return Ok(()); }
1499 // ok to skip binder because the substs on closure types never
1500 // touch bound regions, they just capture the in-scope
1501 // type/region parameters
1502 match obligation.self_ty().skip_binder().sty {
1503 ty::TyClosure(closure_def_id, _) => {
1504 debug!("assemble_unboxed_candidates: kind={:?} obligation={:?}",
1506 match self.infcx.closure_kind(closure_def_id) {
1507 Some(closure_kind) => {
1508 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1509 if closure_kind.extends(kind) {
1510 candidates.vec.push(ClosureCandidate);
1514 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1515 candidates.vec.push(ClosureCandidate);
1520 ty::TyInfer(ty::TyVar(_)) => {
1521 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1522 candidates.ambiguous = true;
1525 _ => { return Ok(()); }
1529 /// Implement one of the `Fn()` family for a fn pointer.
1530 fn assemble_fn_pointer_candidates(&mut self,
1531 obligation: &TraitObligation<'tcx>,
1532 candidates: &mut SelectionCandidateSet<'tcx>)
1533 -> Result<(),SelectionError<'tcx>>
1535 // We provide impl of all fn traits for fn pointers.
1536 if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
1540 // ok to skip binder because what we are inspecting doesn't involve bound regions
1541 let self_ty = *obligation.self_ty().skip_binder();
1543 ty::TyInfer(ty::TyVar(_)) => {
1544 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1545 candidates.ambiguous = true; // could wind up being a fn() type
1548 // provide an impl, but only for suitable `fn` pointers
1549 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
1550 if let ty::Binder(ty::FnSig {
1551 unsafety: hir::Unsafety::Normal,
1555 }) = self_ty.fn_sig(self.tcx()) {
1556 candidates.vec.push(FnPointerCandidate);
1566 /// Search for impls that might apply to `obligation`.
1567 fn assemble_candidates_from_impls(&mut self,
1568 obligation: &TraitObligation<'tcx>,
1569 candidates: &mut SelectionCandidateSet<'tcx>)
1570 -> Result<(), SelectionError<'tcx>>
1572 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1574 self.tcx().for_each_relevant_impl(
1575 obligation.predicate.def_id(),
1576 obligation.predicate.0.trait_ref.self_ty(),
1578 self.probe(|this, snapshot| { /* [1] */
1579 match this.match_impl(impl_def_id, obligation, snapshot) {
1581 candidates.vec.push(ImplCandidate(impl_def_id));
1583 // NB: we can safely drop the skol map
1584 // since we are in a probe [1]
1585 mem::drop(skol_map);
1596 fn assemble_candidates_from_default_impls(&mut self,
1597 obligation: &TraitObligation<'tcx>,
1598 candidates: &mut SelectionCandidateSet<'tcx>)
1599 -> Result<(), SelectionError<'tcx>>
1601 // OK to skip binder here because the tests we do below do not involve bound regions
1602 let self_ty = *obligation.self_ty().skip_binder();
1603 debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty);
1605 let def_id = obligation.predicate.def_id();
1607 if self.tcx().trait_has_default_impl(def_id) {
1609 ty::TyDynamic(..) => {
1610 // For object types, we don't know what the closed
1611 // over types are. This means we conservatively
1612 // say nothing; a candidate may be added by
1613 // `assemble_candidates_from_object_ty`.
1616 ty::TyProjection(..) => {
1617 // In these cases, we don't know what the actual
1618 // type is. Therefore, we cannot break it down
1619 // into its constituent types. So we don't
1620 // consider the `..` impl but instead just add no
1621 // candidates: this means that typeck will only
1622 // succeed if there is another reason to believe
1623 // that this obligation holds. That could be a
1624 // where-clause or, in the case of an object type,
1625 // it could be that the object type lists the
1626 // trait (e.g. `Foo+Send : Send`). See
1627 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1628 // for an example of a test case that exercises
1631 ty::TyInfer(ty::TyVar(_)) => {
1632 // the defaulted impl might apply, we don't know
1633 candidates.ambiguous = true;
1636 candidates.vec.push(DefaultImplCandidate(def_id.clone()))
1644 /// Search for impls that might apply to `obligation`.
1645 fn assemble_candidates_from_object_ty(&mut self,
1646 obligation: &TraitObligation<'tcx>,
1647 candidates: &mut SelectionCandidateSet<'tcx>)
1649 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1650 obligation.self_ty().skip_binder());
1652 // Object-safety candidates are only applicable to object-safe
1653 // traits. Including this check is useful because it helps
1654 // inference in cases of traits like `BorrowFrom`, which are
1655 // not object-safe, and which rely on being able to infer the
1656 // self-type from one of the other inputs. Without this check,
1657 // these cases wind up being considered ambiguous due to a
1658 // (spurious) ambiguity introduced here.
1659 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1660 if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1664 self.probe(|this, _snapshot| {
1665 // the code below doesn't care about regions, and the
1666 // self-ty here doesn't escape this probe, so just erase
1668 let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1669 let poly_trait_ref = match self_ty.sty {
1670 ty::TyDynamic(ref data, ..) => {
1671 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1672 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1673 pushing candidate");
1674 candidates.vec.push(BuiltinObjectCandidate);
1678 match data.principal() {
1679 Some(p) => p.with_self_ty(this.tcx(), self_ty),
1683 ty::TyInfer(ty::TyVar(_)) => {
1684 debug!("assemble_candidates_from_object_ty: ambiguous");
1685 candidates.ambiguous = true; // could wind up being an object type
1693 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1696 // Count only those upcast versions that match the trait-ref
1697 // we are looking for. Specifically, do not only check for the
1698 // correct trait, but also the correct type parameters.
1699 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1700 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1701 let upcast_trait_refs =
1702 util::supertraits(this.tcx(), poly_trait_ref)
1703 .filter(|upcast_trait_ref| {
1704 this.probe(|this, _| {
1705 let upcast_trait_ref = upcast_trait_ref.clone();
1706 this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1711 if upcast_trait_refs > 1 {
1712 // can be upcast in many ways; need more type information
1713 candidates.ambiguous = true;
1714 } else if upcast_trait_refs == 1 {
1715 candidates.vec.push(ObjectCandidate);
1720 /// Search for unsizing that might apply to `obligation`.
1721 fn assemble_candidates_for_unsizing(&mut self,
1722 obligation: &TraitObligation<'tcx>,
1723 candidates: &mut SelectionCandidateSet<'tcx>) {
1724 // We currently never consider higher-ranked obligations e.g.
1725 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1726 // because they are a priori invalid, and we could potentially add support
1727 // for them later, it's just that there isn't really a strong need for it.
1728 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1729 // impl, and those are generally applied to concrete types.
1731 // That said, one might try to write a fn with a where clause like
1732 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1733 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1734 // Still, you'd be more likely to write that where clause as
1736 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1737 // obligation above. Should be possible to extend this in the future.
1738 let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) {
1741 // Don't add any candidates if there are bound regions.
1745 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1747 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1750 let may_apply = match (&source.sty, &target.sty) {
1751 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1752 (&ty::TyDynamic(ref data_a, ..), &ty::TyDynamic(ref data_b, ..)) => {
1753 // Upcasts permit two things:
1755 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1756 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1758 // Note that neither of these changes requires any
1759 // change at runtime. Eventually this will be
1762 // We always upcast when we can because of reason
1763 // #2 (region bounds).
1764 match (data_a.principal(), data_b.principal()) {
1765 (Some(a), Some(b)) => a.def_id() == b.def_id() &&
1766 data_b.auto_traits()
1767 // All of a's auto traits need to be in b's auto traits.
1768 .all(|b| data_a.auto_traits().any(|a| a == b)),
1774 (_, &ty::TyDynamic(..)) => true,
1776 // Ambiguous handling is below T -> Trait, because inference
1777 // variables can still implement Unsize<Trait> and nested
1778 // obligations will have the final say (likely deferred).
1779 (&ty::TyInfer(ty::TyVar(_)), _) |
1780 (_, &ty::TyInfer(ty::TyVar(_))) => {
1781 debug!("assemble_candidates_for_unsizing: ambiguous");
1782 candidates.ambiguous = true;
1787 (&ty::TyArray(..), &ty::TySlice(_)) => true,
1789 // Struct<T> -> Struct<U>.
1790 (&ty::TyAdt(def_id_a, _), &ty::TyAdt(def_id_b, _)) if def_id_a.is_struct() => {
1791 def_id_a == def_id_b
1794 // (.., T) -> (.., U).
1795 (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
1796 tys_a.len() == tys_b.len()
1803 candidates.vec.push(BuiltinUnsizeCandidate);
1807 ///////////////////////////////////////////////////////////////////////////
1810 // Winnowing is the process of attempting to resolve ambiguity by
1811 // probing further. During the winnowing process, we unify all
1812 // type variables (ignoring skolemization) and then we also
1813 // attempt to evaluate recursive bounds to see if they are
1816 /// Returns true if `candidate_i` should be dropped in favor of
1817 /// `candidate_j`. Generally speaking we will drop duplicate
1818 /// candidates and prefer where-clause candidates.
1819 /// Returns true if `victim` should be dropped in favor of
1820 /// `other`. Generally speaking we will drop duplicate
1821 /// candidates and prefer where-clause candidates.
1823 /// See the comment for "SelectionCandidate" for more details.
1824 fn candidate_should_be_dropped_in_favor_of<'o>(
1826 victim: &EvaluatedCandidate<'tcx>,
1827 other: &EvaluatedCandidate<'tcx>)
1830 if victim.candidate == other.candidate {
1834 match other.candidate {
1836 ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
1837 DefaultImplCandidate(..) => {
1839 "default implementations shouldn't be recorded \
1840 when there are other valid candidates");
1844 GeneratorCandidate |
1845 FnPointerCandidate |
1846 BuiltinObjectCandidate |
1847 BuiltinUnsizeCandidate |
1848 BuiltinCandidate { .. } => {
1849 // We have a where-clause so don't go around looking
1854 ProjectionCandidate => {
1855 // Arbitrarily give param candidates priority
1856 // over projection and object candidates.
1859 ParamCandidate(..) => false,
1861 ImplCandidate(other_def) => {
1862 // See if we can toss out `victim` based on specialization.
1863 // This requires us to know *for sure* that the `other` impl applies
1864 // i.e. EvaluatedToOk:
1865 if other.evaluation == EvaluatedToOk {
1866 if let ImplCandidate(victim_def) = victim.candidate {
1867 let tcx = self.tcx().global_tcx();
1868 return traits::specializes(tcx, other_def, victim_def) ||
1869 tcx.impls_are_allowed_to_overlap(other_def, victim_def);
1879 ///////////////////////////////////////////////////////////////////////////
1882 // These cover the traits that are built-in to the language
1883 // itself. This includes `Copy` and `Sized` for sure. For the
1884 // moment, it also includes `Send` / `Sync` and a few others, but
1885 // those will hopefully change to library-defined traits in the
1888 // HACK: if this returns an error, selection exits without considering
1890 fn assemble_builtin_bound_candidates<'o>(&mut self,
1891 conditions: BuiltinImplConditions<'tcx>,
1892 candidates: &mut SelectionCandidateSet<'tcx>)
1893 -> Result<(),SelectionError<'tcx>>
1896 BuiltinImplConditions::Where(nested) => {
1897 debug!("builtin_bound: nested={:?}", nested);
1898 candidates.vec.push(BuiltinCandidate {
1899 has_nested: nested.skip_binder().len() > 0
1903 BuiltinImplConditions::None => { Ok(()) }
1904 BuiltinImplConditions::Ambiguous => {
1905 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1906 Ok(candidates.ambiguous = true)
1908 BuiltinImplConditions::Never => { Err(Unimplemented) }
1912 fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1913 -> BuiltinImplConditions<'tcx>
1915 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1917 // NOTE: binder moved to (*)
1918 let self_ty = self.infcx.shallow_resolve(
1919 obligation.predicate.skip_binder().self_ty());
1922 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1923 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1924 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyRawPtr(..) |
1925 ty::TyChar | ty::TyRef(..) | ty::TyGenerator(..) |
1926 ty::TyArray(..) | ty::TyClosure(..) | ty::TyNever |
1928 // safe for everything
1929 Where(ty::Binder(Vec::new()))
1932 ty::TyStr | ty::TySlice(_) | ty::TyDynamic(..) => Never,
1934 ty::TyTuple(tys, _) => {
1935 Where(ty::Binder(tys.last().into_iter().cloned().collect()))
1938 ty::TyAdt(def, substs) => {
1939 let sized_crit = def.sized_constraint(self.tcx());
1940 // (*) binder moved here
1942 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1946 ty::TyProjection(_) | ty::TyParam(_) | ty::TyAnon(..) => None,
1947 ty::TyInfer(ty::TyVar(_)) => Ambiguous,
1949 ty::TyInfer(ty::FreshTy(_))
1950 | ty::TyInfer(ty::FreshIntTy(_))
1951 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1952 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1958 fn copy_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1959 -> BuiltinImplConditions<'tcx>
1961 // NOTE: binder moved to (*)
1962 let self_ty = self.infcx.shallow_resolve(
1963 obligation.predicate.skip_binder().self_ty());
1965 use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1968 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1969 ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1970 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
1971 ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
1972 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
1973 Where(ty::Binder(Vec::new()))
1976 ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) |
1977 ty::TyClosure(..) | ty::TyGenerator(..) |
1978 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
1982 ty::TyArray(element_ty, _) => {
1983 // (*) binder moved here
1984 Where(ty::Binder(vec![element_ty]))
1987 ty::TyTuple(tys, _) => {
1988 // (*) binder moved here
1989 Where(ty::Binder(tys.to_vec()))
1992 ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
1993 // Fallback to whatever user-defined impls exist in this case.
1997 ty::TyInfer(ty::TyVar(_)) => {
1998 // Unbound type variable. Might or might not have
1999 // applicable impls and so forth, depending on what
2000 // those type variables wind up being bound to.
2004 ty::TyInfer(ty::FreshTy(_))
2005 | ty::TyInfer(ty::FreshIntTy(_))
2006 | ty::TyInfer(ty::FreshFloatTy(_)) => {
2007 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2013 /// For default impls, we need to break apart a type into its
2014 /// "constituent types" -- meaning, the types that it contains.
2016 /// Here are some (simple) examples:
2019 /// (i32, u32) -> [i32, u32]
2020 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2021 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2022 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2024 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2034 ty::TyInfer(ty::IntVar(_)) |
2035 ty::TyInfer(ty::FloatVar(_)) |
2043 ty::TyProjection(..) |
2044 ty::TyInfer(ty::TyVar(_)) |
2045 ty::TyInfer(ty::FreshTy(_)) |
2046 ty::TyInfer(ty::FreshIntTy(_)) |
2047 ty::TyInfer(ty::FreshFloatTy(_)) => {
2048 bug!("asked to assemble constituent types of unexpected type: {:?}",
2052 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
2053 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
2057 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
2061 ty::TyTuple(ref tys, _) => {
2062 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2066 ty::TyClosure(def_id, ref substs) => {
2067 // FIXME(#27086). We are invariant w/r/t our
2068 // func_substs, but we don't see them as
2069 // constituent types; this seems RIGHT but also like
2070 // something that a normal type couldn't simulate. Is
2071 // this just a gap with the way that PhantomData and
2072 // OIBIT interact? That is, there is no way to say
2073 // "make me invariant with respect to this TYPE, but
2074 // do not act as though I can reach it"
2075 substs.upvar_tys(def_id, self.tcx()).collect()
2078 ty::TyGenerator(def_id, ref substs, interior) => {
2079 let witness = iter::once(interior.witness);
2080 substs.upvar_tys(def_id, self.tcx()).chain(witness).collect()
2083 // for `PhantomData<T>`, we pass `T`
2084 ty::TyAdt(def, substs) if def.is_phantom_data() => {
2085 substs.types().collect()
2088 ty::TyAdt(def, substs) => {
2090 .map(|f| f.ty(self.tcx(), substs))
2094 ty::TyAnon(def_id, substs) => {
2095 // We can resolve the `impl Trait` to its concrete type,
2096 // which enforces a DAG between the functions requiring
2097 // the auto trait bounds in question.
2098 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2103 fn collect_predicates_for_types(&mut self,
2104 param_env: ty::ParamEnv<'tcx>,
2105 cause: ObligationCause<'tcx>,
2106 recursion_depth: usize,
2107 trait_def_id: DefId,
2108 types: ty::Binder<Vec<Ty<'tcx>>>)
2109 -> Vec<PredicateObligation<'tcx>>
2111 // Because the types were potentially derived from
2112 // higher-ranked obligations they may reference late-bound
2113 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2114 // yield a type like `for<'a> &'a int`. In general, we
2115 // maintain the invariant that we never manipulate bound
2116 // regions, so we have to process these bound regions somehow.
2118 // The strategy is to:
2120 // 1. Instantiate those regions to skolemized regions (e.g.,
2121 // `for<'a> &'a int` becomes `&0 int`.
2122 // 2. Produce something like `&'0 int : Copy`
2123 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2125 types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
2126 let ty: ty::Binder<Ty<'tcx>> = ty::Binder(ty); // <----------/
2128 self.in_snapshot(|this, snapshot| {
2129 let (skol_ty, skol_map) =
2130 this.infcx().skolemize_late_bound_regions(&ty, snapshot);
2131 let Normalized { value: normalized_ty, mut obligations } =
2132 project::normalize_with_depth(this,
2137 let skol_obligation =
2138 this.tcx().predicate_for_trait_def(param_env,
2144 obligations.push(skol_obligation);
2145 this.infcx().plug_leaks(skol_map, snapshot, obligations)
2150 ///////////////////////////////////////////////////////////////////////////
2153 // Confirmation unifies the output type parameters of the trait
2154 // with the values found in the obligation, possibly yielding a
2155 // type error. See `README.md` for more details.
2157 fn confirm_candidate(&mut self,
2158 obligation: &TraitObligation<'tcx>,
2159 candidate: SelectionCandidate<'tcx>)
2160 -> Result<Selection<'tcx>,SelectionError<'tcx>>
2162 debug!("confirm_candidate({:?}, {:?})",
2167 BuiltinCandidate { has_nested } => {
2168 let data = self.confirm_builtin_candidate(obligation, has_nested);
2169 Ok(VtableBuiltin(data))
2172 ParamCandidate(param) => {
2173 let obligations = self.confirm_param_candidate(obligation, param);
2174 Ok(VtableParam(obligations))
2177 DefaultImplCandidate(trait_def_id) => {
2178 let data = self.confirm_default_impl_candidate(obligation, trait_def_id);
2179 Ok(VtableDefaultImpl(data))
2182 ImplCandidate(impl_def_id) => {
2183 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2186 ClosureCandidate => {
2187 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2188 Ok(VtableClosure(vtable_closure))
2191 GeneratorCandidate => {
2192 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2193 Ok(VtableGenerator(vtable_generator))
2196 BuiltinObjectCandidate => {
2197 // This indicates something like `(Trait+Send) :
2198 // Send`. In this case, we know that this holds
2199 // because that's what the object type is telling us,
2200 // and there's really no additional obligations to
2201 // prove and no types in particular to unify etc.
2202 Ok(VtableParam(Vec::new()))
2205 ObjectCandidate => {
2206 let data = self.confirm_object_candidate(obligation);
2207 Ok(VtableObject(data))
2210 FnPointerCandidate => {
2212 self.confirm_fn_pointer_candidate(obligation)?;
2213 Ok(VtableFnPointer(data))
2216 ProjectionCandidate => {
2217 self.confirm_projection_candidate(obligation);
2218 Ok(VtableParam(Vec::new()))
2221 BuiltinUnsizeCandidate => {
2222 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2223 Ok(VtableBuiltin(data))
2228 fn confirm_projection_candidate(&mut self,
2229 obligation: &TraitObligation<'tcx>)
2231 self.in_snapshot(|this, snapshot| {
2233 this.match_projection_obligation_against_definition_bounds(obligation,
2239 fn confirm_param_candidate(&mut self,
2240 obligation: &TraitObligation<'tcx>,
2241 param: ty::PolyTraitRef<'tcx>)
2242 -> Vec<PredicateObligation<'tcx>>
2244 debug!("confirm_param_candidate({:?},{:?})",
2248 // During evaluation, we already checked that this
2249 // where-clause trait-ref could be unified with the obligation
2250 // trait-ref. Repeat that unification now without any
2251 // transactional boundary; it should not fail.
2252 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2253 Ok(obligations) => obligations,
2255 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2262 fn confirm_builtin_candidate(&mut self,
2263 obligation: &TraitObligation<'tcx>,
2265 -> VtableBuiltinData<PredicateObligation<'tcx>>
2267 debug!("confirm_builtin_candidate({:?}, {:?})",
2268 obligation, has_nested);
2270 let obligations = if has_nested {
2271 let trait_def = obligation.predicate.def_id();
2272 let conditions = match trait_def {
2273 _ if Some(trait_def) == self.tcx().lang_items.sized_trait() => {
2274 self.sized_conditions(obligation)
2276 _ if Some(trait_def) == self.tcx().lang_items.copy_trait() => {
2277 self.copy_conditions(obligation)
2279 _ if Some(trait_def) == self.tcx().lang_items.clone_trait() => {
2280 self.copy_conditions(obligation)
2282 _ => bug!("unexpected builtin trait {:?}", trait_def)
2284 let nested = match conditions {
2285 BuiltinImplConditions::Where(nested) => nested,
2286 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2290 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2291 self.collect_predicates_for_types(obligation.param_env,
2293 obligation.recursion_depth+1,
2300 debug!("confirm_builtin_candidate: obligations={:?}",
2303 VtableBuiltinData { nested: obligations }
2306 /// This handles the case where a `impl Foo for ..` impl is being used.
2307 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2309 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2310 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2311 fn confirm_default_impl_candidate(&mut self,
2312 obligation: &TraitObligation<'tcx>,
2313 trait_def_id: DefId)
2314 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2316 debug!("confirm_default_impl_candidate({:?}, {:?})",
2320 // binder is moved below
2321 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2322 let types = self.constituent_types_for_ty(self_ty);
2323 self.vtable_default_impl(obligation, trait_def_id, ty::Binder(types))
2326 /// See `confirm_default_impl_candidate`
2327 fn vtable_default_impl(&mut self,
2328 obligation: &TraitObligation<'tcx>,
2329 trait_def_id: DefId,
2330 nested: ty::Binder<Vec<Ty<'tcx>>>)
2331 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2333 debug!("vtable_default_impl: nested={:?}", nested);
2335 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2336 let mut obligations = self.collect_predicates_for_types(
2337 obligation.param_env,
2339 obligation.recursion_depth+1,
2343 let trait_obligations = self.in_snapshot(|this, snapshot| {
2344 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2345 let (trait_ref, skol_map) =
2346 this.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2347 let cause = obligation.derived_cause(ImplDerivedObligation);
2348 this.impl_or_trait_obligations(cause,
2349 obligation.recursion_depth + 1,
2350 obligation.param_env,
2357 obligations.extend(trait_obligations);
2359 debug!("vtable_default_impl: obligations={:?}", obligations);
2361 VtableDefaultImplData {
2367 fn confirm_impl_candidate(&mut self,
2368 obligation: &TraitObligation<'tcx>,
2370 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2372 debug!("confirm_impl_candidate({:?},{:?})",
2376 // First, create the substitutions by matching the impl again,
2377 // this time not in a probe.
2378 self.in_snapshot(|this, snapshot| {
2379 let (substs, skol_map) =
2380 this.rematch_impl(impl_def_id, obligation,
2382 debug!("confirm_impl_candidate substs={:?}", substs);
2383 let cause = obligation.derived_cause(ImplDerivedObligation);
2384 this.vtable_impl(impl_def_id,
2387 obligation.recursion_depth + 1,
2388 obligation.param_env,
2394 fn vtable_impl(&mut self,
2396 mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2397 cause: ObligationCause<'tcx>,
2398 recursion_depth: usize,
2399 param_env: ty::ParamEnv<'tcx>,
2400 skol_map: infer::SkolemizationMap<'tcx>,
2401 snapshot: &infer::CombinedSnapshot)
2402 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2404 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2410 let mut impl_obligations =
2411 self.impl_or_trait_obligations(cause,
2419 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2423 // Because of RFC447, the impl-trait-ref and obligations
2424 // are sufficient to determine the impl substs, without
2425 // relying on projections in the impl-trait-ref.
2427 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2428 impl_obligations.append(&mut substs.obligations);
2430 VtableImplData { impl_def_id,
2431 substs: substs.value,
2432 nested: impl_obligations }
2435 fn confirm_object_candidate(&mut self,
2436 obligation: &TraitObligation<'tcx>)
2437 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2439 debug!("confirm_object_candidate({:?})",
2442 // FIXME skipping binder here seems wrong -- we should
2443 // probably flatten the binder from the obligation and the
2444 // binder from the object. Have to try to make a broken test
2445 // case that results. -nmatsakis
2446 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2447 let poly_trait_ref = match self_ty.sty {
2448 ty::TyDynamic(ref data, ..) => {
2449 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2452 span_bug!(obligation.cause.span,
2453 "object candidate with non-object");
2457 let mut upcast_trait_ref = None;
2461 let tcx = self.tcx();
2463 // We want to find the first supertrait in the list of
2464 // supertraits that we can unify with, and do that
2465 // unification. We know that there is exactly one in the list
2466 // where we can unify because otherwise select would have
2467 // reported an ambiguity. (When we do find a match, also
2468 // record it for later.)
2470 util::supertraits(tcx, poly_trait_ref)
2474 |this, _| this.match_poly_trait_ref(obligation, t))
2476 Ok(_) => { upcast_trait_ref = Some(t); false }
2481 // Additionally, for each of the nonmatching predicates that
2482 // we pass over, we sum up the set of number of vtable
2483 // entries, so that we can compute the offset for the selected
2486 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2492 upcast_trait_ref: upcast_trait_ref.unwrap(),
2498 fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2499 -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2501 debug!("confirm_fn_pointer_candidate({:?})",
2504 // ok to skip binder; it is reintroduced below
2505 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2506 let sig = self_ty.fn_sig(self.tcx());
2508 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2511 util::TupleArgumentsFlag::Yes)
2512 .map_bound(|(trait_ref, _)| trait_ref);
2514 let Normalized { value: trait_ref, obligations } =
2515 project::normalize_with_depth(self,
2516 obligation.param_env,
2517 obligation.cause.clone(),
2518 obligation.recursion_depth + 1,
2521 self.confirm_poly_trait_refs(obligation.cause.clone(),
2522 obligation.param_env,
2523 obligation.predicate.to_poly_trait_ref(),
2525 Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
2528 fn confirm_generator_candidate(&mut self,
2529 obligation: &TraitObligation<'tcx>)
2530 -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>,
2531 SelectionError<'tcx>>
2533 // ok to skip binder because the substs on generator types never
2534 // touch bound regions, they just capture the in-scope
2535 // type/region parameters
2536 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2537 let (closure_def_id, substs) = match self_ty.sty {
2538 ty::TyGenerator(id, substs, _) => (id, substs),
2539 _ => bug!("closure candidate for non-closure {:?}", obligation)
2542 debug!("confirm_generator_candidate({:?},{:?},{:?})",
2548 self.generator_trait_ref_unnormalized(obligation, closure_def_id, substs);
2552 } = normalize_with_depth(self,
2553 obligation.param_env,
2554 obligation.cause.clone(),
2555 obligation.recursion_depth+1,
2558 debug!("confirm_generator_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2563 self.confirm_poly_trait_refs(obligation.cause.clone(),
2564 obligation.param_env,
2565 obligation.predicate.to_poly_trait_ref(),
2568 Ok(VtableGeneratorData {
2569 closure_def_id: closure_def_id,
2570 substs: substs.clone(),
2575 fn confirm_closure_candidate(&mut self,
2576 obligation: &TraitObligation<'tcx>)
2577 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2578 SelectionError<'tcx>>
2580 debug!("confirm_closure_candidate({:?})", obligation);
2582 let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
2584 None => bug!("closure candidate for non-fn trait {:?}", obligation)
2587 // ok to skip binder because the substs on closure types never
2588 // touch bound regions, they just capture the in-scope
2589 // type/region parameters
2590 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
2591 let (closure_def_id, substs) = match self_ty.sty {
2592 ty::TyClosure(id, substs) => (id, substs),
2593 _ => bug!("closure candidate for non-closure {:?}", obligation)
2597 self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
2601 } = normalize_with_depth(self,
2602 obligation.param_env,
2603 obligation.cause.clone(),
2604 obligation.recursion_depth+1,
2607 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2612 self.confirm_poly_trait_refs(obligation.cause.clone(),
2613 obligation.param_env,
2614 obligation.predicate.to_poly_trait_ref(),
2617 obligations.push(Obligation::new(
2618 obligation.cause.clone(),
2619 obligation.param_env,
2620 ty::Predicate::ClosureKind(closure_def_id, kind)));
2622 Ok(VtableClosureData {
2624 substs: substs.clone(),
2629 /// In the case of closure types and fn pointers,
2630 /// we currently treat the input type parameters on the trait as
2631 /// outputs. This means that when we have a match we have only
2632 /// considered the self type, so we have to go back and make sure
2633 /// to relate the argument types too. This is kind of wrong, but
2634 /// since we control the full set of impls, also not that wrong,
2635 /// and it DOES yield better error messages (since we don't report
2636 /// errors as if there is no applicable impl, but rather report
2637 /// errors are about mismatched argument types.
2639 /// Here is an example. Imagine we have a closure expression
2640 /// and we desugared it so that the type of the expression is
2641 /// `Closure`, and `Closure` expects an int as argument. Then it
2642 /// is "as if" the compiler generated this impl:
2644 /// impl Fn(int) for Closure { ... }
2646 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2647 /// we have matched the self-type `Closure`. At this point we'll
2648 /// compare the `int` to `usize` and generate an error.
2650 /// Note that this checking occurs *after* the impl has selected,
2651 /// because these output type parameters should not affect the
2652 /// selection of the impl. Therefore, if there is a mismatch, we
2653 /// report an error to the user.
2654 fn confirm_poly_trait_refs(&mut self,
2655 obligation_cause: ObligationCause<'tcx>,
2656 obligation_param_env: ty::ParamEnv<'tcx>,
2657 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2658 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2659 -> Result<(), SelectionError<'tcx>>
2661 let obligation_trait_ref = obligation_trait_ref.clone();
2663 .at(&obligation_cause, obligation_param_env)
2664 .sup(obligation_trait_ref, expected_trait_ref)
2665 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2666 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2669 fn confirm_builtin_unsize_candidate(&mut self,
2670 obligation: &TraitObligation<'tcx>,)
2671 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>>
2673 let tcx = self.tcx();
2675 // assemble_candidates_for_unsizing should ensure there are no late bound
2676 // regions here. See the comment there for more details.
2677 let source = self.infcx.shallow_resolve(
2678 tcx.no_late_bound_regions(&obligation.self_ty()).unwrap());
2679 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2680 let target = self.infcx.shallow_resolve(target);
2682 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2685 let mut nested = vec![];
2686 match (&source.sty, &target.sty) {
2687 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2688 (&ty::TyDynamic(ref data_a, r_a), &ty::TyDynamic(ref data_b, r_b)) => {
2689 // See assemble_candidates_for_unsizing for more info.
2690 // Binders reintroduced below in call to mk_existential_predicates.
2691 let principal = data_a.skip_binder().principal();
2692 let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
2693 .chain(data_a.skip_binder().projection_bounds()
2694 .map(|x| ty::ExistentialPredicate::Projection(x)))
2695 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2696 let new_trait = tcx.mk_dynamic(
2697 ty::Binder(tcx.mk_existential_predicates(iter)), r_b);
2698 let InferOk { obligations, .. } =
2699 self.infcx.at(&obligation.cause, obligation.param_env)
2700 .eq(target, new_trait)
2701 .map_err(|_| Unimplemented)?;
2702 self.inferred_obligations.extend(obligations);
2704 // Register one obligation for 'a: 'b.
2705 let cause = ObligationCause::new(obligation.cause.span,
2706 obligation.cause.body_id,
2707 ObjectCastObligation(target));
2708 let outlives = ty::OutlivesPredicate(r_a, r_b);
2709 nested.push(Obligation::with_depth(cause,
2710 obligation.recursion_depth + 1,
2711 obligation.param_env,
2712 ty::Binder(outlives).to_predicate()));
2716 (_, &ty::TyDynamic(ref data, r)) => {
2717 let mut object_dids =
2718 data.auto_traits().chain(data.principal().map(|p| p.def_id()));
2719 if let Some(did) = object_dids.find(|did| {
2720 !tcx.is_object_safe(*did)
2722 return Err(TraitNotObjectSafe(did))
2725 let cause = ObligationCause::new(obligation.cause.span,
2726 obligation.cause.body_id,
2727 ObjectCastObligation(target));
2728 let mut push = |predicate| {
2729 nested.push(Obligation::with_depth(cause.clone(),
2730 obligation.recursion_depth + 1,
2731 obligation.param_env,
2735 // Create obligations:
2736 // - Casting T to Trait
2737 // - For all the various builtin bounds attached to the object cast. (In other
2738 // words, if the object type is Foo+Send, this would create an obligation for the
2740 // - Projection predicates
2741 for predicate in data.iter() {
2742 push(predicate.with_self_ty(tcx, source));
2745 // We can only make objects from sized types.
2746 let tr = ty::TraitRef {
2747 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
2748 substs: tcx.mk_substs_trait(source, &[]),
2750 push(tr.to_predicate());
2752 // If the type is `Foo+'a`, ensures that the type
2753 // being cast to `Foo+'a` outlives `'a`:
2754 let outlives = ty::OutlivesPredicate(source, r);
2755 push(ty::Binder(outlives).to_predicate());
2759 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2760 let InferOk { obligations, .. } =
2761 self.infcx.at(&obligation.cause, obligation.param_env)
2763 .map_err(|_| Unimplemented)?;
2764 self.inferred_obligations.extend(obligations);
2767 // Struct<T> -> Struct<U>.
2768 (&ty::TyAdt(def, substs_a), &ty::TyAdt(_, substs_b)) => {
2771 .map(|f| tcx.type_of(f.did))
2772 .collect::<Vec<_>>();
2774 // The last field of the structure has to exist and contain type parameters.
2775 let field = if let Some(&field) = fields.last() {
2778 return Err(Unimplemented);
2780 let mut ty_params = BitVector::new(substs_a.types().count());
2781 let mut found = false;
2782 for ty in field.walk() {
2783 if let ty::TyParam(p) = ty.sty {
2784 ty_params.insert(p.idx as usize);
2789 return Err(Unimplemented);
2792 // Replace type parameters used in unsizing with
2793 // TyError and ensure they do not affect any other fields.
2794 // This could be checked after type collection for any struct
2795 // with a potentially unsized trailing field.
2796 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2797 if ty_params.contains(i) {
2798 Kind::from(tcx.types.err)
2803 let substs = tcx.mk_substs(params);
2804 for &ty in fields.split_last().unwrap().1 {
2805 if ty.subst(tcx, substs).references_error() {
2806 return Err(Unimplemented);
2810 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2811 let inner_source = field.subst(tcx, substs_a);
2812 let inner_target = field.subst(tcx, substs_b);
2814 // Check that the source struct with the target's
2815 // unsized parameters is equal to the target.
2816 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2817 if ty_params.contains(i) {
2818 Kind::from(substs_b.type_at(i))
2823 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
2824 let InferOk { obligations, .. } =
2825 self.infcx.at(&obligation.cause, obligation.param_env)
2826 .eq(target, new_struct)
2827 .map_err(|_| Unimplemented)?;
2828 self.inferred_obligations.extend(obligations);
2830 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2831 nested.push(tcx.predicate_for_trait_def(
2832 obligation.param_env,
2833 obligation.cause.clone(),
2834 obligation.predicate.def_id(),
2835 obligation.recursion_depth + 1,
2840 // (.., T) -> (.., U).
2841 (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
2842 assert_eq!(tys_a.len(), tys_b.len());
2844 // The last field of the tuple has to exist.
2845 let (a_last, a_mid) = if let Some(x) = tys_a.split_last() {
2848 return Err(Unimplemented);
2850 let b_last = tys_b.last().unwrap();
2852 // Check that the source tuple with the target's
2853 // last element is equal to the target.
2854 let new_tuple = tcx.mk_tup(a_mid.iter().chain(Some(b_last)), false);
2855 let InferOk { obligations, .. } =
2856 self.infcx.at(&obligation.cause, obligation.param_env)
2857 .eq(target, new_tuple)
2858 .map_err(|_| Unimplemented)?;
2859 self.inferred_obligations.extend(obligations);
2861 // Construct the nested T: Unsize<U> predicate.
2862 nested.push(tcx.predicate_for_trait_def(
2863 obligation.param_env,
2864 obligation.cause.clone(),
2865 obligation.predicate.def_id(),
2866 obligation.recursion_depth + 1,
2874 Ok(VtableBuiltinData { nested: nested })
2877 ///////////////////////////////////////////////////////////////////////////
2880 // Matching is a common path used for both evaluation and
2881 // confirmation. It basically unifies types that appear in impls
2882 // and traits. This does affect the surrounding environment;
2883 // therefore, when used during evaluation, match routines must be
2884 // run inside of a `probe()` so that their side-effects are
2887 fn rematch_impl(&mut self,
2889 obligation: &TraitObligation<'tcx>,
2890 snapshot: &infer::CombinedSnapshot)
2891 -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
2892 infer::SkolemizationMap<'tcx>)
2894 match self.match_impl(impl_def_id, obligation, snapshot) {
2895 Ok((substs, skol_map)) => (substs, skol_map),
2897 bug!("Impl {:?} was matchable against {:?} but now is not",
2904 fn match_impl(&mut self,
2906 obligation: &TraitObligation<'tcx>,
2907 snapshot: &infer::CombinedSnapshot)
2908 -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
2909 infer::SkolemizationMap<'tcx>), ()>
2911 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2913 // Before we create the substitutions and everything, first
2914 // consider a "quick reject". This avoids creating more types
2915 // and so forth that we need to.
2916 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2920 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
2921 &obligation.predicate,
2923 let skol_obligation_trait_ref = skol_obligation.trait_ref;
2925 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
2928 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2931 let impl_trait_ref =
2932 project::normalize_with_depth(self,
2933 obligation.param_env,
2934 obligation.cause.clone(),
2935 obligation.recursion_depth + 1,
2938 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
2939 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2943 skol_obligation_trait_ref);
2945 let InferOk { obligations, .. } =
2946 self.infcx.at(&obligation.cause, obligation.param_env)
2947 .eq(skol_obligation_trait_ref, impl_trait_ref.value)
2949 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
2952 self.inferred_obligations.extend(obligations);
2954 if let Err(e) = self.infcx.leak_check(false,
2955 obligation.cause.span,
2958 debug!("match_impl: failed leak check due to `{}`", e);
2962 debug!("match_impl: success impl_substs={:?}", impl_substs);
2965 obligations: impl_trait_ref.obligations
2969 fn fast_reject_trait_refs(&mut self,
2970 obligation: &TraitObligation,
2971 impl_trait_ref: &ty::TraitRef)
2974 // We can avoid creating type variables and doing the full
2975 // substitution if we find that any of the input types, when
2976 // simplified, do not match.
2978 obligation.predicate.skip_binder().input_types()
2979 .zip(impl_trait_ref.input_types())
2980 .any(|(obligation_ty, impl_ty)| {
2981 let simplified_obligation_ty =
2982 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2983 let simplified_impl_ty =
2984 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2986 simplified_obligation_ty.is_some() &&
2987 simplified_impl_ty.is_some() &&
2988 simplified_obligation_ty != simplified_impl_ty
2992 /// Normalize `where_clause_trait_ref` and try to match it against
2993 /// `obligation`. If successful, return any predicates that
2994 /// result from the normalization. Normalization is necessary
2995 /// because where-clauses are stored in the parameter environment
2997 fn match_where_clause_trait_ref(&mut self,
2998 obligation: &TraitObligation<'tcx>,
2999 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
3000 -> Result<Vec<PredicateObligation<'tcx>>,()>
3002 self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
3006 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3007 /// obligation is satisfied.
3008 fn match_poly_trait_ref(&mut self,
3009 obligation: &TraitObligation<'tcx>,
3010 poly_trait_ref: ty::PolyTraitRef<'tcx>)
3013 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3017 self.infcx.at(&obligation.cause, obligation.param_env)
3018 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3019 .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
3023 ///////////////////////////////////////////////////////////////////////////
3026 fn match_fresh_trait_refs(&self,
3027 previous: &ty::PolyTraitRef<'tcx>,
3028 current: &ty::PolyTraitRef<'tcx>)
3031 let mut matcher = ty::_match::Match::new(self.tcx());
3032 matcher.relate(previous, current).is_ok()
3035 fn push_stack<'o,'s:'o>(&mut self,
3036 previous_stack: TraitObligationStackList<'s, 'tcx>,
3037 obligation: &'o TraitObligation<'tcx>)
3038 -> TraitObligationStack<'o, 'tcx>
3040 let fresh_trait_ref =
3041 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
3043 TraitObligationStack {
3046 previous: previous_stack,
3050 fn closure_trait_ref_unnormalized(&mut self,
3051 obligation: &TraitObligation<'tcx>,
3052 closure_def_id: DefId,
3053 substs: ty::ClosureSubsts<'tcx>)
3054 -> ty::PolyTraitRef<'tcx>
3056 let closure_type = self.infcx.fn_sig(closure_def_id)
3057 .subst(self.tcx(), substs.substs);
3058 let ty::Binder((trait_ref, _)) =
3059 self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
3060 obligation.predicate.0.self_ty(), // (1)
3062 util::TupleArgumentsFlag::No);
3063 // (1) Feels icky to skip the binder here, but OTOH we know
3064 // that the self-type is an unboxed closure type and hence is
3065 // in fact unparameterized (or at least does not reference any
3066 // regions bound in the obligation). Still probably some
3067 // refactoring could make this nicer.
3069 ty::Binder(trait_ref)
3072 fn generator_trait_ref_unnormalized(&mut self,
3073 obligation: &TraitObligation<'tcx>,
3074 closure_def_id: DefId,
3075 substs: ty::ClosureSubsts<'tcx>)
3076 -> ty::PolyTraitRef<'tcx>
3078 let gen_sig = self.infcx.generator_sig(closure_def_id).unwrap()
3079 .subst(self.tcx(), substs.substs);
3080 let ty::Binder((trait_ref, ..)) =
3081 self.tcx().generator_trait_ref_and_outputs(obligation.predicate.def_id(),
3082 obligation.predicate.0.self_ty(), // (1)
3084 // (1) Feels icky to skip the binder here, but OTOH we know
3085 // that the self-type is an generator type and hence is
3086 // in fact unparameterized (or at least does not reference any
3087 // regions bound in the obligation). Still probably some
3088 // refactoring could make this nicer.
3090 ty::Binder(trait_ref)
3093 /// Returns the obligations that are implied by instantiating an
3094 /// impl or trait. The obligations are substituted and fully
3095 /// normalized. This is used when confirming an impl or default
3097 fn impl_or_trait_obligations(&mut self,
3098 cause: ObligationCause<'tcx>,
3099 recursion_depth: usize,
3100 param_env: ty::ParamEnv<'tcx>,
3101 def_id: DefId, // of impl or trait
3102 substs: &Substs<'tcx>, // for impl or trait
3103 skol_map: infer::SkolemizationMap<'tcx>,
3104 snapshot: &infer::CombinedSnapshot)
3105 -> Vec<PredicateObligation<'tcx>>
3107 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3108 let tcx = self.tcx();
3110 // To allow for one-pass evaluation of the nested obligation,
3111 // each predicate must be preceded by the obligations required
3113 // for example, if we have:
3114 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3115 // the impl will have the following predicates:
3116 // <V as Iterator>::Item = U,
3117 // U: Iterator, U: Sized,
3118 // V: Iterator, V: Sized,
3119 // <U as Iterator>::Item: Copy
3120 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3121 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3122 // `$1: Copy`, so we must ensure the obligations are emitted in
3124 let predicates = tcx.predicates_of(def_id);
3125 assert_eq!(predicates.parent, None);
3126 let predicates = predicates.predicates.iter().flat_map(|predicate| {
3127 let predicate = normalize_with_depth(self, param_env, cause.clone(), recursion_depth,
3128 &predicate.subst(tcx, substs));
3129 predicate.obligations.into_iter().chain(
3131 cause: cause.clone(),
3134 predicate: predicate.value
3137 self.infcx().plug_leaks(skol_map, snapshot, predicates)
3141 impl<'tcx> TraitObligation<'tcx> {
3142 #[allow(unused_comparisons)]
3143 pub fn derived_cause(&self,
3144 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
3145 -> ObligationCause<'tcx>
3148 * Creates a cause for obligations that are derived from
3149 * `obligation` by a recursive search (e.g., for a builtin
3150 * bound, or eventually a `impl Foo for ..`). If `obligation`
3151 * is itself a derived obligation, this is just a clone, but
3152 * otherwise we create a "derived obligation" cause so as to
3153 * keep track of the original root obligation for error
3157 let obligation = self;
3159 // NOTE(flaper87): As of now, it keeps track of the whole error
3160 // chain. Ideally, we should have a way to configure this either
3161 // by using -Z verbose or just a CLI argument.
3162 if obligation.recursion_depth >= 0 {
3163 let derived_cause = DerivedObligationCause {
3164 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3165 parent_code: Rc::new(obligation.cause.code.clone())
3167 let derived_code = variant(derived_cause);
3168 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3170 obligation.cause.clone()
3175 impl<'tcx> SelectionCache<'tcx> {
3176 pub fn new() -> SelectionCache<'tcx> {
3178 hashmap: RefCell::new(FxHashMap())
3183 impl<'tcx> EvaluationCache<'tcx> {
3184 pub fn new() -> EvaluationCache<'tcx> {
3186 hashmap: RefCell::new(FxHashMap())
3191 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
3192 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
3193 TraitObligationStackList::with(self)
3196 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
3201 #[derive(Copy, Clone)]
3202 struct TraitObligationStackList<'o,'tcx:'o> {
3203 head: Option<&'o TraitObligationStack<'o,'tcx>>
3206 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
3207 fn empty() -> TraitObligationStackList<'o,'tcx> {
3208 TraitObligationStackList { head: None }
3211 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
3212 TraitObligationStackList { head: Some(r) }
3216 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
3217 type Item = &'o TraitObligationStack<'o,'tcx>;
3219 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
3230 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
3231 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3232 write!(f, "TraitObligationStack({:?})", self.obligation)
3237 pub struct WithDepNode<T> {
3238 dep_node: DepNodeIndex,
3242 impl<T: Clone> WithDepNode<T> {
3243 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
3244 WithDepNode { dep_node, cached_value }
3247 pub fn get(&self, tcx: TyCtxt) -> T {
3248 tcx.dep_graph.read_index(self.dep_node);
3249 self.cached_value.clone()