]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/select.rs
c690bebed8c00f09404b1780fd688d53b62b6425
[rust.git] / src / librustc / traits / select.rs
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.
4 //
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.
10
11 //! See `README.md` for high-level documentation
12
13 use self::SelectionCandidate::*;
14 use self::EvaluationResult::*;
15
16 use super::coherence;
17 use super::DerivedObligationCause;
18 use super::project;
19 use super::project::{normalize_with_depth, Normalized};
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;
25 use super::Selection;
26 use super::SelectionResult;
27 use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure,
28             VtableFnPointer, VtableObject, VtableDefaultImpl};
29 use super::{VtableImplData, VtableObjectData, VtableBuiltinData,
30             VtableClosureData, VtableDefaultImplData, VtableFnPointerData};
31 use super::util;
32
33 use dep_graph::{DepNodeIndex, DepKind};
34 use hir::def_id::DefId;
35 use infer;
36 use infer::{InferCtxt, InferOk, TypeFreshener};
37 use ty::subst::{Kind, Subst, Substs};
38 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
39 use traits;
40 use ty::fast_reject;
41 use ty::relate::TypeRelation;
42 use middle::lang_items;
43
44 use rustc_data_structures::bitvec::BitVector;
45 use rustc_data_structures::snapshot_vec::{SnapshotVecDelegate, SnapshotVec};
46 use std::cell::RefCell;
47 use std::cmp;
48 use std::fmt;
49 use std::marker::PhantomData;
50 use std::mem;
51 use std::rc::Rc;
52 use syntax::abi::Abi;
53 use hir;
54 use lint;
55 use util::nodemap::FxHashMap;
56
57 struct InferredObligationsSnapshotVecDelegate<'tcx> {
58     phantom: PhantomData<&'tcx i32>,
59 }
60 impl<'tcx> SnapshotVecDelegate for InferredObligationsSnapshotVecDelegate<'tcx> {
61     type Value = PredicateObligation<'tcx>;
62     type Undo = ();
63     fn reverse(_: &mut Vec<Self::Value>, _: Self::Undo) {}
64 }
65
66 pub struct SelectionContext<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
67     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
68
69     /// Freshener used specifically for skolemizing entries on the
70     /// obligation stack. This ensures that all entries on the stack
71     /// at one time will have the same set of skolemized entries,
72     /// which is important for checking for trait bounds that
73     /// recursively require themselves.
74     freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
75
76     /// If true, indicates that the evaluation should be conservative
77     /// and consider the possibility of types outside this crate.
78     /// This comes up primarily when resolving ambiguity. Imagine
79     /// there is some trait reference `$0 : Bar` where `$0` is an
80     /// inference variable. If `intercrate` is true, then we can never
81     /// say for sure that this reference is not implemented, even if
82     /// there are *no impls at all for `Bar`*, because `$0` could be
83     /// bound to some type that in a downstream crate that implements
84     /// `Bar`. This is the suitable mode for coherence. Elsewhere,
85     /// though, we set this to false, because we are only interested
86     /// in types that the user could actually have written --- in
87     /// other words, we consider `$0 : Bar` to be unimplemented if
88     /// there is no type that the user could *actually name* that
89     /// would satisfy it. This avoids crippling inference, basically.
90     intercrate: bool,
91
92     inferred_obligations: SnapshotVec<InferredObligationsSnapshotVecDelegate<'tcx>>,
93 }
94
95 // A stack that walks back up the stack frame.
96 struct TraitObligationStack<'prev, 'tcx: 'prev> {
97     obligation: &'prev TraitObligation<'tcx>,
98
99     /// Trait ref from `obligation` but skolemized with the
100     /// selection-context's freshener. Used to check for recursion.
101     fresh_trait_ref: ty::PolyTraitRef<'tcx>,
102
103     previous: TraitObligationStackList<'prev, 'tcx>,
104 }
105
106 #[derive(Clone)]
107 pub struct SelectionCache<'tcx> {
108     hashmap: RefCell<FxHashMap<ty::TraitRef<'tcx>,
109                                WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>>,
110 }
111
112 /// The selection process begins by considering all impls, where
113 /// clauses, and so forth that might resolve an obligation.  Sometimes
114 /// we'll be able to say definitively that (e.g.) an impl does not
115 /// apply to the obligation: perhaps it is defined for `usize` but the
116 /// obligation is for `int`. In that case, we drop the impl out of the
117 /// list.  But the other cases are considered *candidates*.
118 ///
119 /// For selection to succeed, there must be exactly one matching
120 /// candidate. If the obligation is fully known, this is guaranteed
121 /// by coherence. However, if the obligation contains type parameters
122 /// or variables, there may be multiple such impls.
123 ///
124 /// It is not a real problem if multiple matching impls exist because
125 /// of type variables - it just means the obligation isn't sufficiently
126 /// elaborated. In that case we report an ambiguity, and the caller can
127 /// try again after more type information has been gathered or report a
128 /// "type annotations required" error.
129 ///
130 /// However, with type parameters, this can be a real problem - type
131 /// parameters don't unify with regular types, but they *can* unify
132 /// with variables from blanket impls, and (unless we know its bounds
133 /// will always be satisfied) picking the blanket impl will be wrong
134 /// for at least *some* substitutions. To make this concrete, if we have
135 ///
136 ///    trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
137 ///    impl<T: fmt::Debug> AsDebug for T {
138 ///        type Out = T;
139 ///        fn debug(self) -> fmt::Debug { self }
140 ///    }
141 ///    fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
142 ///
143 /// we can't just use the impl to resolve the <T as AsDebug> obligation
144 /// - a type from another crate (that doesn't implement fmt::Debug) could
145 /// implement AsDebug.
146 ///
147 /// Because where-clauses match the type exactly, multiple clauses can
148 /// only match if there are unresolved variables, and we can mostly just
149 /// report this ambiguity in that case. This is still a problem - we can't
150 /// *do anything* with ambiguities that involve only regions. This is issue
151 /// #21974.
152 ///
153 /// If a single where-clause matches and there are no inference
154 /// variables left, then it definitely matches and we can just select
155 /// it.
156 ///
157 /// In fact, we even select the where-clause when the obligation contains
158 /// inference variables. The can lead to inference making "leaps of logic",
159 /// for example in this situation:
160 ///
161 ///    pub trait Foo<T> { fn foo(&self) -> T; }
162 ///    impl<T> Foo<()> for T { fn foo(&self) { } }
163 ///    impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
164 ///
165 ///    pub fn foo<T>(t: T) where T: Foo<bool> {
166 ///       println!("{:?}", <T as Foo<_>>::foo(&t));
167 ///    }
168 ///    fn main() { foo(false); }
169 ///
170 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
171 /// impl and the where-clause. We select the where-clause and unify $0=bool,
172 /// so the program prints "false". However, if the where-clause is omitted,
173 /// the blanket impl is selected, we unify $0=(), and the program prints
174 /// "()".
175 ///
176 /// Exactly the same issues apply to projection and object candidates, except
177 /// that we can have both a projection candidate and a where-clause candidate
178 /// for the same obligation. In that case either would do (except that
179 /// different "leaps of logic" would occur if inference variables are
180 /// present), and we just pick the where-clause. This is, for example,
181 /// required for associated types to work in default impls, as the bounds
182 /// are visible both as projection bounds and as where-clauses from the
183 /// parameter environment.
184 #[derive(PartialEq,Eq,Debug,Clone)]
185 enum SelectionCandidate<'tcx> {
186     BuiltinCandidate { has_nested: bool },
187     ParamCandidate(ty::PolyTraitRef<'tcx>),
188     ImplCandidate(DefId),
189     DefaultImplCandidate(DefId),
190
191     /// This is a trait matching with a projected type as `Self`, and
192     /// we found an applicable bound in the trait definition.
193     ProjectionCandidate,
194
195     /// Implementation of a `Fn`-family trait by one of the anonymous types
196     /// generated for a `||` expression. The ty::ClosureKind informs the
197     /// confirmation step what ClosureKind obligation to emit.
198     ClosureCandidate(/* closure */ DefId, ty::ClosureSubsts<'tcx>, ty::ClosureKind),
199
200     /// Implementation of a `Fn`-family trait by one of the anonymous
201     /// types generated for a fn pointer type (e.g., `fn(int)->int`)
202     FnPointerCandidate,
203
204     ObjectCandidate,
205
206     BuiltinObjectCandidate,
207
208     BuiltinUnsizeCandidate,
209 }
210
211 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
212     type Lifted = SelectionCandidate<'tcx>;
213     fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
214         Some(match *self {
215             BuiltinCandidate { has_nested } => {
216                 BuiltinCandidate {
217                     has_nested,
218                 }
219             }
220             ImplCandidate(def_id) => ImplCandidate(def_id),
221             DefaultImplCandidate(def_id) => DefaultImplCandidate(def_id),
222             ProjectionCandidate => ProjectionCandidate,
223             FnPointerCandidate => FnPointerCandidate,
224             ObjectCandidate => ObjectCandidate,
225             BuiltinObjectCandidate => BuiltinObjectCandidate,
226             BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
227
228             ParamCandidate(ref trait_ref) => {
229                 return tcx.lift(trait_ref).map(ParamCandidate);
230             }
231             ClosureCandidate(def_id, ref substs, kind) => {
232                 return tcx.lift(substs).map(|substs| {
233                     ClosureCandidate(def_id, substs, kind)
234                 });
235             }
236         })
237     }
238 }
239
240 struct SelectionCandidateSet<'tcx> {
241     // a list of candidates that definitely apply to the current
242     // obligation (meaning: types unify).
243     vec: Vec<SelectionCandidate<'tcx>>,
244
245     // if this is true, then there were candidates that might or might
246     // not have applied, but we couldn't tell. This occurs when some
247     // of the input types are type variables, in which case there are
248     // various "builtin" rules that might or might not trigger.
249     ambiguous: bool,
250 }
251
252 #[derive(PartialEq,Eq,Debug,Clone)]
253 struct EvaluatedCandidate<'tcx> {
254     candidate: SelectionCandidate<'tcx>,
255     evaluation: EvaluationResult,
256 }
257
258 /// When does the builtin impl for `T: Trait` apply?
259 enum BuiltinImplConditions<'tcx> {
260     /// The impl is conditional on T1,T2,.. : Trait
261     Where(ty::Binder<Vec<Ty<'tcx>>>),
262     /// There is no built-in impl. There may be some other
263     /// candidate (a where-clause or user-defined impl).
264     None,
265     /// There is *no* impl for this, builtin or not. Ignore
266     /// all where-clauses.
267     Never,
268     /// It is unknown whether there is an impl.
269     Ambiguous
270 }
271
272 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
273 /// The result of trait evaluation. The order is important
274 /// here as the evaluation of a list is the maximum of the
275 /// evaluations.
276 ///
277 /// The evaluation results are ordered:
278 ///     - `EvaluatedToOk` implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
279 ///     - `EvaluatedToErr` implies `EvaluatedToRecur`
280 ///     - the "union" of evaluation results is equal to their maximum -
281 ///     all the "potential success" candidates can potentially succeed,
282 ///     so they are no-ops when unioned with a definite error, and within
283 ///     the categories it's easy to see that the unions are correct.
284 enum EvaluationResult {
285     /// Evaluation successful
286     EvaluatedToOk,
287     /// Evaluation is known to be ambiguous - it *might* hold for some
288     /// assignment of inference variables, but it might not.
289     ///
290     /// While this has the same meaning as `EvaluatedToUnknown` - we can't
291     /// know whether this obligation holds or not - it is the result we
292     /// would get with an empty stack, and therefore is cacheable.
293     EvaluatedToAmbig,
294     /// Evaluation failed because of recursion involving inference
295     /// variables. We are somewhat imprecise there, so we don't actually
296     /// know the real result.
297     ///
298     /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
299     EvaluatedToUnknown,
300     /// Evaluation failed because we encountered an obligation we are already
301     /// trying to prove on this branch.
302     ///
303     /// We know this branch can't be a part of a minimal proof-tree for
304     /// the "root" of our cycle, because then we could cut out the recursion
305     /// and maintain a valid proof tree. However, this does not mean
306     /// that all the obligations on this branch do not hold - it's possible
307     /// that we entered this branch "speculatively", and that there
308     /// might be some other way to prove this obligation that does not
309     /// go through this cycle - so we can't cache this as a failure.
310     ///
311     /// For example, suppose we have this:
312     ///
313     /// ```rust,ignore (pseudo-Rust)
314     ///     pub trait Trait { fn xyz(); }
315     ///     // This impl is "useless", but we can still have
316     ///     // an `impl Trait for SomeUnsizedType` somewhere.
317     ///     impl<T: Trait + Sized> Trait for T { fn xyz() {} }
318     ///
319     ///     pub fn foo<T: Trait + ?Sized>() {
320     ///         <T as Trait>::xyz();
321     ///     }
322     /// ```
323     ///
324     /// When checking `foo`, we have to prove `T: Trait`. This basically
325     /// translates into this:
326     ///
327     ///     (T: Trait + Sized â†’_\impl T: Trait), T: Trait âŠ¢ T: Trait
328     ///
329     /// When we try to prove it, we first go the first option, which
330     /// recurses. This shows us that the impl is "useless" - it won't
331     /// tell us that `T: Trait` unless it already implemented `Trait`
332     /// by some other means. However, that does not prevent `T: Trait`
333     /// does not hold, because of the bound (which can indeed be satisfied
334     /// by `SomeUnsizedType` from another crate).
335     ///
336     /// FIXME: when an `EvaluatedToRecur` goes past its parent root, we
337     /// ought to convert it to an `EvaluatedToErr`, because we know
338     /// there definitely isn't a proof tree for that obligation. Not
339     /// doing so is still sound - there isn't any proof tree, so the
340     /// branch still can't be a part of a minimal one - but does not
341     /// re-enable caching.
342     EvaluatedToRecur,
343     /// Evaluation failed
344     EvaluatedToErr,
345 }
346
347 impl EvaluationResult {
348     fn may_apply(self) -> bool {
349         match self {
350             EvaluatedToOk |
351             EvaluatedToAmbig |
352             EvaluatedToUnknown => true,
353
354             EvaluatedToErr |
355             EvaluatedToRecur => false
356         }
357     }
358
359     fn is_stack_dependent(self) -> bool {
360         match self {
361             EvaluatedToUnknown |
362             EvaluatedToRecur => true,
363
364             EvaluatedToOk |
365             EvaluatedToAmbig |
366             EvaluatedToErr => false,
367         }
368     }
369 }
370
371 #[derive(Clone)]
372 pub struct EvaluationCache<'tcx> {
373     hashmap: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>
374 }
375
376 impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
377     pub fn new(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
378         SelectionContext {
379             infcx,
380             freshener: infcx.freshener(),
381             intercrate: false,
382             inferred_obligations: SnapshotVec::new(),
383         }
384     }
385
386     pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>) -> SelectionContext<'cx, 'gcx, 'tcx> {
387         SelectionContext {
388             infcx,
389             freshener: infcx.freshener(),
390             intercrate: true,
391             inferred_obligations: SnapshotVec::new(),
392         }
393     }
394
395     pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
396         self.infcx
397     }
398
399     pub fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
400         self.infcx.tcx
401     }
402
403     pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'gcx, 'tcx> {
404         self.infcx
405     }
406
407     /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
408     /// context's self.
409     fn in_snapshot<R, F>(&mut self, f: F) -> R
410         where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
411     {
412         // The irrefutable nature of the operation means we don't need to snapshot the
413         // inferred_obligations vector.
414         self.infcx.in_snapshot(|snapshot| f(self, snapshot))
415     }
416
417     /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
418     /// retained.
419     fn probe<R, F>(&mut self, f: F) -> R
420         where F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> R
421     {
422         let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
423         let result = self.infcx.probe(|snapshot| f(self, snapshot));
424         self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
425         result
426     }
427
428     /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
429     /// the transaction fails and s.t. old obligations are retained.
430     fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E> where
431         F: FnOnce(&mut Self, &infer::CombinedSnapshot) -> Result<T, E>
432     {
433         let inferred_obligations_snapshot = self.inferred_obligations.start_snapshot();
434         match self.infcx.commit_if_ok(|snapshot| f(self, snapshot)) {
435             Ok(ok) => {
436                 self.inferred_obligations.commit(inferred_obligations_snapshot);
437                 Ok(ok)
438             },
439             Err(err) => {
440                 self.inferred_obligations.rollback_to(inferred_obligations_snapshot);
441                 Err(err)
442             }
443         }
444     }
445
446
447     ///////////////////////////////////////////////////////////////////////////
448     // Selection
449     //
450     // The selection phase tries to identify *how* an obligation will
451     // be resolved. For example, it will identify which impl or
452     // parameter bound is to be used. The process can be inconclusive
453     // if the self type in the obligation is not fully inferred. Selection
454     // can result in an error in one of two ways:
455     //
456     // 1. If no applicable impl or parameter bound can be found.
457     // 2. If the output type parameters in the obligation do not match
458     //    those specified by the impl/bound. For example, if the obligation
459     //    is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
460     //    `impl<T> Iterable<T> for Vec<T>`, than an error would result.
461
462     /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
463     /// type environment by performing unification.
464     pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
465                   -> SelectionResult<'tcx, Selection<'tcx>> {
466         debug!("select({:?})", obligation);
467         assert!(!obligation.predicate.has_escaping_regions());
468
469         let tcx = self.tcx();
470
471         let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
472         let ret = match self.candidate_from_obligation(&stack)? {
473             None => None,
474             Some(candidate) => {
475                 let mut candidate = self.confirm_candidate(obligation, candidate)?;
476                 let inferred_obligations = (*self.inferred_obligations).into_iter().cloned();
477                 candidate.nested_obligations_mut().extend(inferred_obligations);
478                 Some(candidate)
479             },
480         };
481
482         // Test whether this is a `()` which was produced by defaulting a
483         // diverging type variable with `!` disabled. If so, we may need
484         // to raise a warning.
485         if obligation.predicate.skip_binder().self_ty().is_defaulted_unit() {
486             let mut raise_warning = true;
487             // Don't raise a warning if the trait is implemented for ! and only
488             // permits a trivial implementation for !. This stops us warning
489             // about (for example) `(): Clone` becoming `!: Clone` because such
490             // a switch can't cause code to stop compiling or execute
491             // differently.
492             let mut never_obligation = obligation.clone();
493             let def_id = never_obligation.predicate.skip_binder().trait_ref.def_id;
494             never_obligation.predicate = never_obligation.predicate.map_bound(|mut trait_pred| {
495                 // Swap out () with ! so we can check if the trait is impld for !
496                 {
497                     let mut trait_ref = &mut trait_pred.trait_ref;
498                     let unit_substs = trait_ref.substs;
499                     let mut never_substs = Vec::with_capacity(unit_substs.len());
500                     never_substs.push(From::from(tcx.types.never));
501                     never_substs.extend(&unit_substs[1..]);
502                     trait_ref.substs = tcx.intern_substs(&never_substs);
503                 }
504                 trait_pred
505             });
506             if let Ok(Some(..)) = self.select(&never_obligation) {
507                 if !tcx.trait_relevant_for_never(def_id) {
508                     // The trait is also implemented for ! and the resulting
509                     // implementation cannot actually be invoked in any way.
510                     raise_warning = false;
511                 }
512             }
513
514             if raise_warning {
515                 tcx.sess.add_lint(lint::builtin::RESOLVE_TRAIT_ON_DEFAULTED_UNIT,
516                                   obligation.cause.body_id,
517                                   obligation.cause.span,
518                                   format!("code relies on type inference rules which are likely \
519                                            to change"));
520             }
521         }
522         Ok(ret)
523     }
524
525     ///////////////////////////////////////////////////////////////////////////
526     // EVALUATION
527     //
528     // Tests whether an obligation can be selected or whether an impl
529     // can be applied to particular types. It skips the "confirmation"
530     // step and hence completely ignores output type parameters.
531     //
532     // The result is "true" if the obligation *may* hold and "false" if
533     // we can be sure it does not.
534
535     /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
536     pub fn evaluate_obligation(&mut self,
537                                obligation: &PredicateObligation<'tcx>)
538                                -> bool
539     {
540         debug!("evaluate_obligation({:?})",
541                obligation);
542
543         self.probe(|this, _| {
544             this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
545                 .may_apply()
546         })
547     }
548
549     /// Evaluates whether the obligation `obligation` can be satisfied,
550     /// and returns `false` if not certain. However, this is not entirely
551     /// accurate if inference variables are involved.
552     pub fn evaluate_obligation_conservatively(&mut self,
553                                               obligation: &PredicateObligation<'tcx>)
554                                               -> bool
555     {
556         debug!("evaluate_obligation_conservatively({:?})",
557                obligation);
558
559         self.probe(|this, _| {
560             this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
561                 == EvaluatedToOk
562         })
563     }
564
565     /// Evaluates the predicates in `predicates` recursively. Note that
566     /// this applies projections in the predicates, and therefore
567     /// is run within an inference probe.
568     fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
569                                                 stack: TraitObligationStackList<'o, 'tcx>,
570                                                 predicates: I)
571                                                 -> EvaluationResult
572         where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
573     {
574         let mut result = EvaluatedToOk;
575         for obligation in predicates {
576             let eval = self.evaluate_predicate_recursively(stack, obligation);
577             debug!("evaluate_predicate_recursively({:?}) = {:?}",
578                    obligation, eval);
579             if let EvaluatedToErr = eval {
580                 // fast-path - EvaluatedToErr is the top of the lattice,
581                 // so we don't need to look on the other predicates.
582                 return EvaluatedToErr;
583             } else {
584                 result = cmp::max(result, eval);
585             }
586         }
587         result
588     }
589
590     fn evaluate_predicate_recursively<'o>(&mut self,
591                                           previous_stack: TraitObligationStackList<'o, 'tcx>,
592                                           obligation: &PredicateObligation<'tcx>)
593                                            -> EvaluationResult
594     {
595         debug!("evaluate_predicate_recursively({:?})",
596                obligation);
597
598         match obligation.predicate {
599             ty::Predicate::Trait(ref t) => {
600                 assert!(!t.has_escaping_regions());
601                 let obligation = obligation.with(t.clone());
602                 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
603             }
604
605             ty::Predicate::Equate(ref p) => {
606                 // does this code ever run?
607                 match self.infcx.equality_predicate(&obligation.cause, obligation.param_env, p) {
608                     Ok(InferOk { obligations, .. }) => {
609                         self.inferred_obligations.extend(obligations);
610                         EvaluatedToOk
611                     },
612                     Err(_) => EvaluatedToErr
613                 }
614             }
615
616             ty::Predicate::Subtype(ref p) => {
617                 // does this code ever run?
618                 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
619                     Some(Ok(InferOk { obligations, .. })) => {
620                         self.inferred_obligations.extend(obligations);
621                         EvaluatedToOk
622                     },
623                     Some(Err(_)) => EvaluatedToErr,
624                     None => EvaluatedToAmbig,
625                 }
626             }
627
628             ty::Predicate::WellFormed(ty) => {
629                 match ty::wf::obligations(self.infcx,
630                                           obligation.param_env,
631                                           obligation.cause.body_id,
632                                           ty, obligation.cause.span) {
633                     Some(obligations) =>
634                         self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
635                     None =>
636                         EvaluatedToAmbig,
637                 }
638             }
639
640             ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
641                 // we do not consider region relationships when
642                 // evaluating trait matches
643                 EvaluatedToOk
644             }
645
646             ty::Predicate::ObjectSafe(trait_def_id) => {
647                 if self.tcx().is_object_safe(trait_def_id) {
648                     EvaluatedToOk
649                 } else {
650                     EvaluatedToErr
651                 }
652             }
653
654             ty::Predicate::Projection(ref data) => {
655                 let project_obligation = obligation.with(data.clone());
656                 match project::poly_project_and_unify_type(self, &project_obligation) {
657                     Ok(Some(subobligations)) => {
658                         self.evaluate_predicates_recursively(previous_stack,
659                                                              subobligations.iter())
660                     }
661                     Ok(None) => {
662                         EvaluatedToAmbig
663                     }
664                     Err(_) => {
665                         EvaluatedToErr
666                     }
667                 }
668             }
669
670             ty::Predicate::ClosureKind(closure_def_id, kind) => {
671                 match self.infcx.closure_kind(closure_def_id) {
672                     Some(closure_kind) => {
673                         if closure_kind.extends(kind) {
674                             EvaluatedToOk
675                         } else {
676                             EvaluatedToErr
677                         }
678                     }
679                     None => {
680                         EvaluatedToAmbig
681                     }
682                 }
683             }
684         }
685     }
686
687     fn evaluate_trait_predicate_recursively<'o>(&mut self,
688                                                 previous_stack: TraitObligationStackList<'o, 'tcx>,
689                                                 mut obligation: TraitObligation<'tcx>)
690                                                 -> EvaluationResult
691     {
692         debug!("evaluate_trait_predicate_recursively({:?})",
693                obligation);
694
695         if !self.intercrate && obligation.is_global() {
696             // If a param env is consistent, global obligations do not depend on its particular
697             // value in order to work, so we can clear out the param env and get better
698             // caching. (If the current param env is inconsistent, we don't care what happens).
699             debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
700             obligation.param_env = ty::ParamEnv::empty(obligation.param_env.reveal);
701         }
702
703         let stack = self.push_stack(previous_stack, &obligation);
704         let fresh_trait_ref = stack.fresh_trait_ref;
705         if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
706             debug!("CACHE HIT: EVAL({:?})={:?}",
707                    fresh_trait_ref,
708                    result);
709             return result;
710         }
711
712         let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
713
714         debug!("CACHE MISS: EVAL({:?})={:?}",
715                fresh_trait_ref,
716                result);
717         self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
718
719         result
720     }
721
722     fn evaluate_stack<'o>(&mut self,
723                           stack: &TraitObligationStack<'o, 'tcx>)
724                           -> EvaluationResult
725     {
726         // In intercrate mode, whenever any of the types are unbound,
727         // there can always be an impl. Even if there are no impls in
728         // this crate, perhaps the type would be unified with
729         // something from another crate that does provide an impl.
730         //
731         // In intra mode, we must still be conservative. The reason is
732         // that we want to avoid cycles. Imagine an impl like:
733         //
734         //     impl<T:Eq> Eq for Vec<T>
735         //
736         // and a trait reference like `$0 : Eq` where `$0` is an
737         // unbound variable. When we evaluate this trait-reference, we
738         // will unify `$0` with `Vec<$1>` (for some fresh variable
739         // `$1`), on the condition that `$1 : Eq`. We will then wind
740         // up with many candidates (since that are other `Eq` impls
741         // that apply) and try to winnow things down. This results in
742         // a recursive evaluation that `$1 : Eq` -- as you can
743         // imagine, this is just where we started. To avoid that, we
744         // check for unbound variables and return an ambiguous (hence possible)
745         // match if we've seen this trait before.
746         //
747         // This suffices to allow chains like `FnMut` implemented in
748         // terms of `Fn` etc, but we could probably make this more
749         // precise still.
750         let unbound_input_types = stack.fresh_trait_ref.input_types().any(|ty| ty.is_fresh());
751         if unbound_input_types && self.intercrate {
752             debug!("evaluate_stack({:?}) --> unbound argument, intercrate -->  ambiguous",
753                    stack.fresh_trait_ref);
754             return EvaluatedToAmbig;
755         }
756         if unbound_input_types &&
757               stack.iter().skip(1).any(
758                   |prev| stack.obligation.param_env == prev.obligation.param_env &&
759                       self.match_fresh_trait_refs(&stack.fresh_trait_ref,
760                                                   &prev.fresh_trait_ref))
761         {
762             debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
763                    stack.fresh_trait_ref);
764             return EvaluatedToUnknown;
765         }
766
767         // If there is any previous entry on the stack that precisely
768         // matches this obligation, then we can assume that the
769         // obligation is satisfied for now (still all other conditions
770         // must be met of course). One obvious case this comes up is
771         // marker traits like `Send`. Think of a linked list:
772         //
773         //    struct List<T> { data: T, next: Option<Box<List<T>>> {
774         //
775         // `Box<List<T>>` will be `Send` if `T` is `Send` and
776         // `Option<Box<List<T>>>` is `Send`, and in turn
777         // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
778         // `Send`.
779         //
780         // Note that we do this comparison using the `fresh_trait_ref`
781         // fields. Because these have all been skolemized using
782         // `self.freshener`, we can be sure that (a) this will not
783         // affect the inferencer state and (b) that if we see two
784         // skolemized types with the same index, they refer to the
785         // same unbound type variable.
786         if let Some(rec_index) =
787             stack.iter()
788             .skip(1) // skip top-most frame
789             .position(|prev| stack.obligation.param_env == prev.obligation.param_env &&
790                       stack.fresh_trait_ref == prev.fresh_trait_ref)
791         {
792             debug!("evaluate_stack({:?}) --> recursive",
793                    stack.fresh_trait_ref);
794             let cycle = stack.iter().skip(1).take(rec_index+1);
795             let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
796             if self.coinductive_match(cycle) {
797                 debug!("evaluate_stack({:?}) --> recursive, coinductive",
798                        stack.fresh_trait_ref);
799                 return EvaluatedToOk;
800             } else {
801                 debug!("evaluate_stack({:?}) --> recursive, inductive",
802                        stack.fresh_trait_ref);
803                 return EvaluatedToRecur;
804             }
805         }
806
807         match self.candidate_from_obligation(stack) {
808             Ok(Some(c)) => self.evaluate_candidate(stack, &c),
809             Ok(None) => EvaluatedToAmbig,
810             Err(..) => EvaluatedToErr
811         }
812     }
813
814     /// For defaulted traits, we use a co-inductive strategy to solve, so
815     /// that recursion is ok. This routine returns true if the top of the
816     /// stack (`cycle[0]`):
817     /// - is a defaulted trait, and
818     /// - it also appears in the backtrace at some position `X`; and,
819     /// - all the predicates at positions `X..` between `X` an the top are
820     ///   also defaulted traits.
821     pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
822         where I: Iterator<Item=ty::Predicate<'tcx>>
823     {
824         let mut cycle = cycle;
825         cycle.all(|predicate| self.coinductive_predicate(predicate))
826     }
827
828     fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
829         let result = match predicate {
830             ty::Predicate::Trait(ref data) => {
831                 self.tcx().trait_has_default_impl(data.def_id())
832             }
833             _ => {
834                 false
835             }
836         };
837         debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
838         result
839     }
840
841     /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
842     /// obligations are met. Returns true if `candidate` remains viable after this further
843     /// scrutiny.
844     fn evaluate_candidate<'o>(&mut self,
845                               stack: &TraitObligationStack<'o, 'tcx>,
846                               candidate: &SelectionCandidate<'tcx>)
847                               -> EvaluationResult
848     {
849         debug!("evaluate_candidate: depth={} candidate={:?}",
850                stack.obligation.recursion_depth, candidate);
851         let result = self.probe(|this, _| {
852             let candidate = (*candidate).clone();
853             match this.confirm_candidate(stack.obligation, candidate) {
854                 Ok(selection) => {
855                     this.evaluate_predicates_recursively(
856                         stack.list(),
857                         selection.nested_obligations().iter())
858                 }
859                 Err(..) => EvaluatedToErr
860             }
861         });
862         debug!("evaluate_candidate: depth={} result={:?}",
863                stack.obligation.recursion_depth, result);
864         result
865     }
866
867     fn check_evaluation_cache(&self,
868                               param_env: ty::ParamEnv<'tcx>,
869                               trait_ref: ty::PolyTraitRef<'tcx>)
870                               -> Option<EvaluationResult>
871     {
872         let tcx = self.tcx();
873         if self.can_use_global_caches(param_env) {
874             let cache = tcx.evaluation_cache.hashmap.borrow();
875             if let Some(cached) = cache.get(&trait_ref) {
876                 return Some(cached.get(tcx));
877             }
878         }
879         self.infcx.evaluation_cache.hashmap
880                                    .borrow()
881                                    .get(&trait_ref)
882                                    .map(|v| v.get(tcx))
883     }
884
885     fn insert_evaluation_cache(&mut self,
886                                param_env: ty::ParamEnv<'tcx>,
887                                trait_ref: ty::PolyTraitRef<'tcx>,
888                                dep_node: DepNodeIndex,
889                                result: EvaluationResult)
890     {
891         // Avoid caching results that depend on more than just the trait-ref:
892         // The stack can create recursion, and closure signatures
893         // being yet uninferred can create "spurious" EvaluatedToAmbig
894         // and EvaluatedToOk.
895         if result.is_stack_dependent() ||
896             ((result == EvaluatedToAmbig || result == EvaluatedToOk)
897              && trait_ref.has_closure_types())
898         {
899             return;
900         }
901
902         if self.can_use_global_caches(param_env) {
903             let mut cache = self.tcx().evaluation_cache.hashmap.borrow_mut();
904             if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
905                 cache.insert(trait_ref, WithDepNode::new(dep_node, result));
906                 return;
907             }
908         }
909
910         self.infcx.evaluation_cache.hashmap
911                                    .borrow_mut()
912                                    .insert(trait_ref, WithDepNode::new(dep_node, result));
913     }
914
915     ///////////////////////////////////////////////////////////////////////////
916     // CANDIDATE ASSEMBLY
917     //
918     // The selection process begins by examining all in-scope impls,
919     // caller obligations, and so forth and assembling a list of
920     // candidates. See `README.md` and the `Candidate` type for more
921     // details.
922
923     fn candidate_from_obligation<'o>(&mut self,
924                                      stack: &TraitObligationStack<'o, 'tcx>)
925                                      -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
926     {
927         // Watch out for overflow. This intentionally bypasses (and does
928         // not update) the cache.
929         let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
930         if stack.obligation.recursion_depth >= recursion_limit {
931             self.infcx().report_overflow_error(&stack.obligation, true);
932         }
933
934         // Check the cache. Note that we skolemize the trait-ref
935         // separately rather than using `stack.fresh_trait_ref` -- this
936         // is because we want the unbound variables to be replaced
937         // with fresh skolemized types starting from index 0.
938         let cache_fresh_trait_pred =
939             self.infcx.freshen(stack.obligation.predicate.clone());
940         debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
941                cache_fresh_trait_pred,
942                stack);
943         assert!(!stack.obligation.predicate.has_escaping_regions());
944
945         if let Some(c) = self.check_candidate_cache(stack.obligation.param_env,
946                                                     &cache_fresh_trait_pred) {
947             debug!("CACHE HIT: SELECT({:?})={:?}",
948                    cache_fresh_trait_pred,
949                    c);
950             return c;
951         }
952
953         // If no match, compute result and insert into cache.
954         let (candidate, dep_node) = self.in_task(|this| {
955             this.candidate_from_obligation_no_cache(stack)
956         });
957
958         if self.should_update_candidate_cache(&cache_fresh_trait_pred, &candidate) {
959             debug!("CACHE MISS: SELECT({:?})={:?}",
960                    cache_fresh_trait_pred, candidate);
961             self.insert_candidate_cache(stack.obligation.param_env,
962                                         cache_fresh_trait_pred,
963                                         dep_node,
964                                         candidate.clone());
965         }
966
967         candidate
968     }
969
970     fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
971         where OP: FnOnce(&mut Self) -> R
972     {
973         let (result, dep_node) = self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, || {
974             op(self)
975         });
976         self.tcx().dep_graph.read_index(dep_node);
977         (result, dep_node)
978     }
979
980     // Treat negative impls as unimplemented
981     fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
982                              -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
983         if let ImplCandidate(def_id) = candidate {
984             if self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative {
985                 return Err(Unimplemented)
986             }
987         }
988         Ok(Some(candidate))
989     }
990
991     fn candidate_from_obligation_no_cache<'o>(&mut self,
992                                               stack: &TraitObligationStack<'o, 'tcx>)
993                                               -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
994     {
995         if stack.obligation.predicate.references_error() {
996             // If we encounter a `TyError`, we generally prefer the
997             // most "optimistic" result in response -- that is, the
998             // one least likely to report downstream errors. But
999             // because this routine is shared by coherence and by
1000             // trait selection, there isn't an obvious "right" choice
1001             // here in that respect, so we opt to just return
1002             // ambiguity and let the upstream clients sort it out.
1003             return Ok(None);
1004         }
1005
1006         if !self.is_knowable(stack) {
1007             debug!("coherence stage: not knowable");
1008             return Ok(None);
1009         }
1010
1011         let candidate_set = self.assemble_candidates(stack)?;
1012
1013         if candidate_set.ambiguous {
1014             debug!("candidate set contains ambig");
1015             return Ok(None);
1016         }
1017
1018         let mut candidates = candidate_set.vec;
1019
1020         debug!("assembled {} candidates for {:?}: {:?}",
1021                candidates.len(),
1022                stack,
1023                candidates);
1024
1025         // At this point, we know that each of the entries in the
1026         // candidate set is *individually* applicable. Now we have to
1027         // figure out if they contain mutual incompatibilities. This
1028         // frequently arises if we have an unconstrained input type --
1029         // for example, we are looking for $0:Eq where $0 is some
1030         // unconstrained type variable. In that case, we'll get a
1031         // candidate which assumes $0 == int, one that assumes $0 ==
1032         // usize, etc. This spells an ambiguity.
1033
1034         // If there is more than one candidate, first winnow them down
1035         // by considering extra conditions (nested obligations and so
1036         // forth). We don't winnow if there is exactly one
1037         // candidate. This is a relatively minor distinction but it
1038         // can lead to better inference and error-reporting. An
1039         // example would be if there was an impl:
1040         //
1041         //     impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1042         //
1043         // and we were to see some code `foo.push_clone()` where `boo`
1044         // is a `Vec<Bar>` and `Bar` does not implement `Clone`.  If
1045         // we were to winnow, we'd wind up with zero candidates.
1046         // Instead, we select the right impl now but report `Bar does
1047         // not implement Clone`.
1048         if candidates.len() == 1 {
1049             return self.filter_negative_impls(candidates.pop().unwrap());
1050         }
1051
1052         // Winnow, but record the exact outcome of evaluation, which
1053         // is needed for specialization.
1054         let mut candidates: Vec<_> = candidates.into_iter().filter_map(|c| {
1055             let eval = self.evaluate_candidate(stack, &c);
1056             if eval.may_apply() {
1057                 Some(EvaluatedCandidate {
1058                     candidate: c,
1059                     evaluation: eval,
1060                 })
1061             } else {
1062                 None
1063             }
1064         }).collect();
1065
1066         // If there are STILL multiple candidate, we can further
1067         // reduce the list by dropping duplicates -- including
1068         // resolving specializations.
1069         if candidates.len() > 1 {
1070             let mut i = 0;
1071             while i < candidates.len() {
1072                 let is_dup =
1073                     (0..candidates.len())
1074                     .filter(|&j| i != j)
1075                     .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
1076                                                                           &candidates[j]));
1077                 if is_dup {
1078                     debug!("Dropping candidate #{}/{}: {:?}",
1079                            i, candidates.len(), candidates[i]);
1080                     candidates.swap_remove(i);
1081                 } else {
1082                     debug!("Retaining candidate #{}/{}: {:?}",
1083                            i, candidates.len(), candidates[i]);
1084                     i += 1;
1085
1086                     // If there are *STILL* multiple candidates, give up
1087                     // and report ambiguity.
1088                     if i > 1 {
1089                         debug!("multiple matches, ambig");
1090                         return Ok(None);
1091                     }
1092                 }
1093             }
1094         }
1095
1096         // If there are *NO* candidates, then there are no impls --
1097         // that we know of, anyway. Note that in the case where there
1098         // are unbound type variables within the obligation, it might
1099         // be the case that you could still satisfy the obligation
1100         // from another crate by instantiating the type variables with
1101         // a type from another crate that does have an impl. This case
1102         // is checked for in `evaluate_stack` (and hence users
1103         // who might care about this case, like coherence, should use
1104         // that function).
1105         if candidates.is_empty() {
1106             return Err(Unimplemented);
1107         }
1108
1109         // Just one candidate left.
1110         self.filter_negative_impls(candidates.pop().unwrap().candidate)
1111     }
1112
1113     fn is_knowable<'o>(&mut self,
1114                        stack: &TraitObligationStack<'o, 'tcx>)
1115                        -> bool
1116     {
1117         debug!("is_knowable(intercrate={})", self.intercrate);
1118
1119         if !self.intercrate {
1120             return true;
1121         }
1122
1123         let obligation = &stack.obligation;
1124         let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1125
1126         // ok to skip binder because of the nature of the
1127         // trait-ref-is-knowable check, which does not care about
1128         // bound regions
1129         let trait_ref = &predicate.skip_binder().trait_ref;
1130
1131         coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1132     }
1133
1134     /// Returns true if the global caches can be used.
1135     /// Do note that if the type itself is not in the
1136     /// global tcx, the local caches will be used.
1137     fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1138         // If there are any where-clauses in scope, then we always use
1139         // a cache local to this particular scope. Otherwise, we
1140         // switch to a global cache. We used to try and draw
1141         // finer-grained distinctions, but that led to a serious of
1142         // annoying and weird bugs like #22019 and #18290. This simple
1143         // rule seems to be pretty clearly safe and also still retains
1144         // a very high hit rate (~95% when compiling rustc).
1145         if !param_env.caller_bounds.is_empty() {
1146             return false;
1147         }
1148
1149         // Avoid using the master cache during coherence and just rely
1150         // on the local cache. This effectively disables caching
1151         // during coherence. It is really just a simplification to
1152         // avoid us having to fear that coherence results "pollute"
1153         // the master cache. Since coherence executes pretty quickly,
1154         // it's not worth going to more trouble to increase the
1155         // hit-rate I don't think.
1156         if self.intercrate {
1157             return false;
1158         }
1159
1160         // Otherwise, we can use the global cache.
1161         true
1162     }
1163
1164     fn check_candidate_cache(&mut self,
1165                              param_env: ty::ParamEnv<'tcx>,
1166                              cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
1167                              -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
1168     {
1169         let tcx = self.tcx();
1170         let trait_ref = &cache_fresh_trait_pred.0.trait_ref;
1171         if self.can_use_global_caches(param_env) {
1172             let cache = tcx.selection_cache.hashmap.borrow();
1173             if let Some(cached) = cache.get(&trait_ref) {
1174                 return Some(cached.get(tcx));
1175             }
1176         }
1177         self.infcx.selection_cache.hashmap
1178                                   .borrow()
1179                                   .get(trait_ref)
1180                                   .map(|v| v.get(tcx))
1181     }
1182
1183     fn insert_candidate_cache(&mut self,
1184                               param_env: ty::ParamEnv<'tcx>,
1185                               cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1186                               dep_node: DepNodeIndex,
1187                               candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1188     {
1189         let tcx = self.tcx();
1190         let trait_ref = cache_fresh_trait_pred.0.trait_ref;
1191         if self.can_use_global_caches(param_env) {
1192             let mut cache = tcx.selection_cache.hashmap.borrow_mut();
1193             if let Some(trait_ref) = tcx.lift_to_global(&trait_ref) {
1194                 if let Some(candidate) = tcx.lift_to_global(&candidate) {
1195                     cache.insert(trait_ref, WithDepNode::new(dep_node, candidate));
1196                     return;
1197                 }
1198             }
1199         }
1200
1201         self.infcx.selection_cache.hashmap
1202                                   .borrow_mut()
1203                                   .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1204     }
1205
1206     fn should_update_candidate_cache(&mut self,
1207                                      cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1208                                      candidate: &SelectionResult<'tcx, SelectionCandidate<'tcx>>)
1209                                      -> bool
1210     {
1211         // In general, it's a good idea to cache results, even
1212         // ambiguous ones, to save us some trouble later. But we have
1213         // to be careful not to cache results that could be
1214         // invalidated later by advances in inference. Normally, this
1215         // is not an issue, because any inference variables whose
1216         // types are not yet bound are "freshened" in the cache key,
1217         // which means that if we later get the same request once that
1218         // type variable IS bound, we'll have a different cache key.
1219         // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
1220         // not yet known, we may cache the result as `None`. But if
1221         // later `_#0t` is bound to `Bar`, then when we freshen we'll
1222         // have `Vec<Bar> : Foo` as the cache key.
1223         //
1224         // HOWEVER, it CAN happen that we get an ambiguity result in
1225         // one particular case around closures where the cache key
1226         // would not change. That is when the precise types of the
1227         // upvars that a closure references have not yet been figured
1228         // out (i.e., because it is not yet known if they are captured
1229         // by ref, and if by ref, what kind of ref). In these cases,
1230         // when matching a builtin bound, we will yield back an
1231         // ambiguous result. But the *cache key* is just the closure type,
1232         // it doesn't capture the state of the upvar computation.
1233         //
1234         // To avoid this trap, just don't cache ambiguous results if
1235         // the self-type contains no inference byproducts (that really
1236         // shouldn't happen in other circumstances anyway, given
1237         // coherence).
1238
1239         match *candidate {
1240             Ok(Some(_)) | Err(_) => true,
1241             Ok(None) => cache_fresh_trait_pred.has_infer_types()
1242         }
1243     }
1244
1245     fn assemble_candidates<'o>(&mut self,
1246                                stack: &TraitObligationStack<'o, 'tcx>)
1247                                -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
1248     {
1249         let TraitObligationStack { obligation, .. } = *stack;
1250         let ref obligation = Obligation {
1251             param_env: obligation.param_env,
1252             cause: obligation.cause.clone(),
1253             recursion_depth: obligation.recursion_depth,
1254             predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
1255         };
1256
1257         if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1258             // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
1259             //
1260             // This is somewhat problematic, as the current scheme can't really
1261             // handle it turning to be a projection. This does end up as truly
1262             // ambiguous in most cases anyway.
1263             //
1264             // Until this is fixed, take the fast path out - this also improves
1265             // performance by preventing assemble_candidates_from_impls from
1266             // matching every impl for this trait.
1267             return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1268         }
1269
1270         let mut candidates = SelectionCandidateSet {
1271             vec: Vec::new(),
1272             ambiguous: false
1273         };
1274
1275         // Other bounds. Consider both in-scope bounds from fn decl
1276         // and applicable impls. There is a certain set of precedence rules here.
1277
1278         let def_id = obligation.predicate.def_id();
1279         if self.tcx().lang_items.copy_trait() == Some(def_id) {
1280             debug!("obligation self ty is {:?}",
1281                    obligation.predicate.0.self_ty());
1282
1283             // User-defined copy impls are permitted, but only for
1284             // structs and enums.
1285             self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1286
1287             // For other types, we'll use the builtin rules.
1288             let copy_conditions = self.copy_conditions(obligation);
1289             self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1290         } else if self.tcx().lang_items.sized_trait() == Some(def_id) {
1291             // Sized is never implementable by end-users, it is
1292             // always automatically computed.
1293             let sized_conditions = self.sized_conditions(obligation);
1294             self.assemble_builtin_bound_candidates(sized_conditions,
1295                                                    &mut candidates)?;
1296          } else if self.tcx().lang_items.unsize_trait() == Some(def_id) {
1297              self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1298          } else {
1299              self.assemble_closure_candidates(obligation, &mut candidates)?;
1300              self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1301              self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1302              self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1303         }
1304
1305         self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1306         self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1307         // Default implementations have lower priority, so we only
1308         // consider triggering a default if there is no other impl that can apply.
1309         if candidates.vec.is_empty() {
1310             self.assemble_candidates_from_default_impls(obligation, &mut candidates)?;
1311         }
1312         debug!("candidate list size: {}", candidates.vec.len());
1313         Ok(candidates)
1314     }
1315
1316     fn assemble_candidates_from_projected_tys(&mut self,
1317                                               obligation: &TraitObligation<'tcx>,
1318                                               candidates: &mut SelectionCandidateSet<'tcx>)
1319     {
1320         debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1321
1322         // FIXME(#20297) -- just examining the self-type is very simplistic
1323
1324         // before we go into the whole skolemization thing, just
1325         // quickly check if the self-type is a projection at all.
1326         match obligation.predicate.0.trait_ref.self_ty().sty {
1327             ty::TyProjection(_) | ty::TyAnon(..) => {}
1328             ty::TyInfer(ty::TyVar(_)) => {
1329                 span_bug!(obligation.cause.span,
1330                     "Self=_ should have been handled by assemble_candidates");
1331             }
1332             _ => return
1333         }
1334
1335         let result = self.probe(|this, snapshot| {
1336             this.match_projection_obligation_against_definition_bounds(obligation,
1337                                                                        snapshot)
1338         });
1339
1340         if result {
1341             candidates.vec.push(ProjectionCandidate);
1342         }
1343     }
1344
1345     fn match_projection_obligation_against_definition_bounds(
1346         &mut self,
1347         obligation: &TraitObligation<'tcx>,
1348         snapshot: &infer::CombinedSnapshot)
1349         -> bool
1350     {
1351         let poly_trait_predicate =
1352             self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1353         let (skol_trait_predicate, skol_map) =
1354             self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1355         debug!("match_projection_obligation_against_definition_bounds: \
1356                 skol_trait_predicate={:?} skol_map={:?}",
1357                skol_trait_predicate,
1358                skol_map);
1359
1360         let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
1361             ty::TyProjection(ref data) =>
1362                 (data.trait_ref(self.tcx()).def_id, data.substs),
1363             ty::TyAnon(def_id, substs) => (def_id, substs),
1364             _ => {
1365                 span_bug!(
1366                     obligation.cause.span,
1367                     "match_projection_obligation_against_definition_bounds() called \
1368                      but self-ty not a projection: {:?}",
1369                     skol_trait_predicate.trait_ref.self_ty());
1370             }
1371         };
1372         debug!("match_projection_obligation_against_definition_bounds: \
1373                 def_id={:?}, substs={:?}",
1374                def_id, substs);
1375
1376         let predicates_of = self.tcx().predicates_of(def_id);
1377         let bounds = predicates_of.instantiate(self.tcx(), substs);
1378         debug!("match_projection_obligation_against_definition_bounds: \
1379                 bounds={:?}",
1380                bounds);
1381
1382         let matching_bound =
1383             util::elaborate_predicates(self.tcx(), bounds.predicates)
1384             .filter_to_traits()
1385             .find(
1386                 |bound| self.probe(
1387                     |this, _| this.match_projection(obligation,
1388                                                     bound.clone(),
1389                                                     skol_trait_predicate.trait_ref.clone(),
1390                                                     &skol_map,
1391                                                     snapshot)));
1392
1393         debug!("match_projection_obligation_against_definition_bounds: \
1394                 matching_bound={:?}",
1395                matching_bound);
1396         match matching_bound {
1397             None => false,
1398             Some(bound) => {
1399                 // Repeat the successful match, if any, this time outside of a probe.
1400                 let result = self.match_projection(obligation,
1401                                                    bound,
1402                                                    skol_trait_predicate.trait_ref.clone(),
1403                                                    &skol_map,
1404                                                    snapshot);
1405
1406                 self.infcx.pop_skolemized(skol_map, snapshot);
1407
1408                 assert!(result);
1409                 true
1410             }
1411         }
1412     }
1413
1414     fn match_projection(&mut self,
1415                         obligation: &TraitObligation<'tcx>,
1416                         trait_bound: ty::PolyTraitRef<'tcx>,
1417                         skol_trait_ref: ty::TraitRef<'tcx>,
1418                         skol_map: &infer::SkolemizationMap<'tcx>,
1419                         snapshot: &infer::CombinedSnapshot)
1420                         -> bool
1421     {
1422         assert!(!skol_trait_ref.has_escaping_regions());
1423         match self.infcx.at(&obligation.cause, obligation.param_env)
1424                         .sup(ty::Binder(skol_trait_ref), trait_bound) {
1425             Ok(InferOk { obligations, .. }) => {
1426                 self.inferred_obligations.extend(obligations);
1427             }
1428             Err(_) => { return false; }
1429         }
1430
1431         self.infcx.leak_check(false, obligation.cause.span, skol_map, snapshot).is_ok()
1432     }
1433
1434     /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1435     /// supplied to find out whether it is listed among them.
1436     ///
1437     /// Never affects inference environment.
1438     fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1439                                                   stack: &TraitObligationStack<'o, 'tcx>,
1440                                                   candidates: &mut SelectionCandidateSet<'tcx>)
1441                                                   -> Result<(),SelectionError<'tcx>>
1442     {
1443         debug!("assemble_candidates_from_caller_bounds({:?})",
1444                stack.obligation);
1445
1446         let all_bounds =
1447             stack.obligation.param_env.caller_bounds
1448                                       .iter()
1449                                       .filter_map(|o| o.to_opt_poly_trait_ref());
1450
1451         // micro-optimization: filter out predicates relating to different
1452         // traits.
1453         let matching_bounds =
1454             all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1455
1456         let matching_bounds =
1457             matching_bounds.filter(
1458                 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1459
1460         let param_candidates =
1461             matching_bounds.map(|bound| ParamCandidate(bound));
1462
1463         candidates.vec.extend(param_candidates);
1464
1465         Ok(())
1466     }
1467
1468     fn evaluate_where_clause<'o>(&mut self,
1469                                  stack: &TraitObligationStack<'o, 'tcx>,
1470                                  where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1471                                  -> EvaluationResult
1472     {
1473         self.probe(move |this, _| {
1474             match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1475                 Ok(obligations) => {
1476                     this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1477                 }
1478                 Err(()) => EvaluatedToErr
1479             }
1480         })
1481     }
1482
1483     /// Check for the artificial impl that the compiler will create for an obligation like `X :
1484     /// FnMut<..>` where `X` is a closure type.
1485     ///
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>>
1493     {
1494         let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1495             Some(k) => k,
1496             None => { return Ok(()); }
1497         };
1498
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         let self_ty = *obligation.self_ty().skip_binder();
1503         let (closure_def_id, substs) = match self_ty.sty {
1504             ty::TyClosure(id, substs) => (id, substs),
1505             ty::TyInfer(ty::TyVar(_)) => {
1506                 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1507                 candidates.ambiguous = true;
1508                 return Ok(());
1509             }
1510             _ => { return Ok(()); }
1511         };
1512
1513         debug!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1514                self_ty,
1515                kind,
1516                obligation);
1517
1518         match self.infcx.closure_kind(closure_def_id) {
1519             Some(closure_kind) => {
1520                 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1521                 if closure_kind.extends(kind) {
1522                     candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1523                 }
1524             }
1525             None => {
1526                 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1527                 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1528             }
1529         }
1530
1531         Ok(())
1532     }
1533
1534     /// Implement one of the `Fn()` family for a fn pointer.
1535     fn assemble_fn_pointer_candidates(&mut self,
1536                                       obligation: &TraitObligation<'tcx>,
1537                                       candidates: &mut SelectionCandidateSet<'tcx>)
1538                                       -> Result<(),SelectionError<'tcx>>
1539     {
1540         // We provide impl of all fn traits for fn pointers.
1541         if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
1542             return Ok(());
1543         }
1544
1545         // ok to skip binder because what we are inspecting doesn't involve bound regions
1546         let self_ty = *obligation.self_ty().skip_binder();
1547         match self_ty.sty {
1548             ty::TyInfer(ty::TyVar(_)) => {
1549                 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1550                 candidates.ambiguous = true; // could wind up being a fn() type
1551             }
1552
1553             // provide an impl, but only for suitable `fn` pointers
1554             ty::TyFnDef(..) | ty::TyFnPtr(_) => {
1555                 if let ty::Binder(ty::FnSig {
1556                     unsafety: hir::Unsafety::Normal,
1557                     abi: Abi::Rust,
1558                     variadic: false,
1559                     ..
1560                 }) = self_ty.fn_sig(self.tcx()) {
1561                     candidates.vec.push(FnPointerCandidate);
1562                 }
1563             }
1564
1565             _ => { }
1566         }
1567
1568         Ok(())
1569     }
1570
1571     /// Search for impls that might apply to `obligation`.
1572     fn assemble_candidates_from_impls(&mut self,
1573                                       obligation: &TraitObligation<'tcx>,
1574                                       candidates: &mut SelectionCandidateSet<'tcx>)
1575                                       -> Result<(), SelectionError<'tcx>>
1576     {
1577         debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1578
1579         let def = self.tcx().trait_def(obligation.predicate.def_id());
1580
1581         def.for_each_relevant_impl(
1582             self.tcx(),
1583             obligation.predicate.0.trait_ref.self_ty(),
1584             |impl_def_id| {
1585                 self.probe(|this, snapshot| { /* [1] */
1586                     match this.match_impl(impl_def_id, obligation, snapshot) {
1587                         Ok(skol_map) => {
1588                             candidates.vec.push(ImplCandidate(impl_def_id));
1589
1590                             // NB: we can safely drop the skol map
1591                             // since we are in a probe [1]
1592                             mem::drop(skol_map);
1593                         }
1594                         Err(_) => { }
1595                     }
1596                 });
1597             }
1598         );
1599
1600         Ok(())
1601     }
1602
1603     fn assemble_candidates_from_default_impls(&mut self,
1604                                               obligation: &TraitObligation<'tcx>,
1605                                               candidates: &mut SelectionCandidateSet<'tcx>)
1606                                               -> Result<(), SelectionError<'tcx>>
1607     {
1608         // OK to skip binder here because the tests we do below do not involve bound regions
1609         let self_ty = *obligation.self_ty().skip_binder();
1610         debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty);
1611
1612         let def_id = obligation.predicate.def_id();
1613
1614         if self.tcx().trait_has_default_impl(def_id) {
1615             match self_ty.sty {
1616                 ty::TyDynamic(..) => {
1617                     // For object types, we don't know what the closed
1618                     // over types are. This means we conservatively
1619                     // say nothing; a candidate may be added by
1620                     // `assemble_candidates_from_object_ty`.
1621                 }
1622                 ty::TyParam(..) |
1623                 ty::TyProjection(..) => {
1624                     // In these cases, we don't know what the actual
1625                     // type is.  Therefore, we cannot break it down
1626                     // into its constituent types. So we don't
1627                     // consider the `..` impl but instead just add no
1628                     // candidates: this means that typeck will only
1629                     // succeed if there is another reason to believe
1630                     // that this obligation holds. That could be a
1631                     // where-clause or, in the case of an object type,
1632                     // it could be that the object type lists the
1633                     // trait (e.g. `Foo+Send : Send`). See
1634                     // `compile-fail/typeck-default-trait-impl-send-param.rs`
1635                     // for an example of a test case that exercises
1636                     // this path.
1637                 }
1638                 ty::TyInfer(ty::TyVar(_)) => {
1639                     // the defaulted impl might apply, we don't know
1640                     candidates.ambiguous = true;
1641                 }
1642                 _ => {
1643                     candidates.vec.push(DefaultImplCandidate(def_id.clone()))
1644                 }
1645             }
1646         }
1647
1648         Ok(())
1649     }
1650
1651     /// Search for impls that might apply to `obligation`.
1652     fn assemble_candidates_from_object_ty(&mut self,
1653                                           obligation: &TraitObligation<'tcx>,
1654                                           candidates: &mut SelectionCandidateSet<'tcx>)
1655     {
1656         debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1657                obligation.self_ty().skip_binder());
1658
1659         // Object-safety candidates are only applicable to object-safe
1660         // traits. Including this check is useful because it helps
1661         // inference in cases of traits like `BorrowFrom`, which are
1662         // not object-safe, and which rely on being able to infer the
1663         // self-type from one of the other inputs. Without this check,
1664         // these cases wind up being considered ambiguous due to a
1665         // (spurious) ambiguity introduced here.
1666         let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1667         if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1668             return;
1669         }
1670
1671         self.probe(|this, _snapshot| {
1672             // the code below doesn't care about regions, and the
1673             // self-ty here doesn't escape this probe, so just erase
1674             // any LBR.
1675             let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1676             let poly_trait_ref = match self_ty.sty {
1677                 ty::TyDynamic(ref data, ..) => {
1678                     if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1679                         debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1680                                     pushing candidate");
1681                         candidates.vec.push(BuiltinObjectCandidate);
1682                         return;
1683                     }
1684
1685                     match data.principal() {
1686                         Some(p) => p.with_self_ty(this.tcx(), self_ty),
1687                         None => return,
1688                     }
1689                 }
1690                 ty::TyInfer(ty::TyVar(_)) => {
1691                     debug!("assemble_candidates_from_object_ty: ambiguous");
1692                     candidates.ambiguous = true; // could wind up being an object type
1693                     return;
1694                 }
1695                 _ => {
1696                     return;
1697                 }
1698             };
1699
1700             debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1701                    poly_trait_ref);
1702
1703             // Count only those upcast versions that match the trait-ref
1704             // we are looking for. Specifically, do not only check for the
1705             // correct trait, but also the correct type parameters.
1706             // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1707             // but `Foo` is declared as `trait Foo : Bar<u32>`.
1708             let upcast_trait_refs =
1709                 util::supertraits(this.tcx(), poly_trait_ref)
1710                 .filter(|upcast_trait_ref| {
1711                     this.probe(|this, _| {
1712                         let upcast_trait_ref = upcast_trait_ref.clone();
1713                         this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1714                     })
1715                 })
1716                 .count();
1717
1718             if upcast_trait_refs > 1 {
1719                 // can be upcast in many ways; need more type information
1720                 candidates.ambiguous = true;
1721             } else if upcast_trait_refs == 1 {
1722                 candidates.vec.push(ObjectCandidate);
1723             }
1724         })
1725     }
1726
1727     /// Search for unsizing that might apply to `obligation`.
1728     fn assemble_candidates_for_unsizing(&mut self,
1729                                         obligation: &TraitObligation<'tcx>,
1730                                         candidates: &mut SelectionCandidateSet<'tcx>) {
1731         // We currently never consider higher-ranked obligations e.g.
1732         // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1733         // because they are a priori invalid, and we could potentially add support
1734         // for them later, it's just that there isn't really a strong need for it.
1735         // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1736         // impl, and those are generally applied to concrete types.
1737         //
1738         // That said, one might try to write a fn with a where clause like
1739         //     for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1740         // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1741         // Still, you'd be more likely to write that where clause as
1742         //     T: Trait
1743         // so it seems ok if we (conservatively) fail to accept that `Unsize`
1744         // obligation above. Should be possible to extend this in the future.
1745         let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) {
1746             Some(t) => t,
1747             None => {
1748                 // Don't add any candidates if there are bound regions.
1749                 return;
1750             }
1751         };
1752         let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1753
1754         debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1755                source, target);
1756
1757         let may_apply = match (&source.sty, &target.sty) {
1758             // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1759             (&ty::TyDynamic(ref data_a, ..), &ty::TyDynamic(ref data_b, ..)) => {
1760                 // Upcasts permit two things:
1761                 //
1762                 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1763                 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1764                 //
1765                 // Note that neither of these changes requires any
1766                 // change at runtime.  Eventually this will be
1767                 // generalized.
1768                 //
1769                 // We always upcast when we can because of reason
1770                 // #2 (region bounds).
1771                 match (data_a.principal(), data_b.principal()) {
1772                     (Some(a), Some(b)) => a.def_id() == b.def_id() &&
1773                         data_b.auto_traits()
1774                             // All of a's auto traits need to be in b's auto traits.
1775                             .all(|b| data_a.auto_traits().any(|a| a == b)),
1776                     _ => false
1777                 }
1778             }
1779
1780             // T -> Trait.
1781             (_, &ty::TyDynamic(..)) => true,
1782
1783             // Ambiguous handling is below T -> Trait, because inference
1784             // variables can still implement Unsize<Trait> and nested
1785             // obligations will have the final say (likely deferred).
1786             (&ty::TyInfer(ty::TyVar(_)), _) |
1787             (_, &ty::TyInfer(ty::TyVar(_))) => {
1788                 debug!("assemble_candidates_for_unsizing: ambiguous");
1789                 candidates.ambiguous = true;
1790                 false
1791             }
1792
1793             // [T; n] -> [T].
1794             (&ty::TyArray(..), &ty::TySlice(_)) => true,
1795
1796             // Struct<T> -> Struct<U>.
1797             (&ty::TyAdt(def_id_a, _), &ty::TyAdt(def_id_b, _)) if def_id_a.is_struct() => {
1798                 def_id_a == def_id_b
1799             }
1800
1801             // (.., T) -> (.., U).
1802             (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
1803                 tys_a.len() == tys_b.len()
1804             }
1805
1806             _ => false
1807         };
1808
1809         if may_apply {
1810             candidates.vec.push(BuiltinUnsizeCandidate);
1811         }
1812     }
1813
1814     ///////////////////////////////////////////////////////////////////////////
1815     // WINNOW
1816     //
1817     // Winnowing is the process of attempting to resolve ambiguity by
1818     // probing further. During the winnowing process, we unify all
1819     // type variables (ignoring skolemization) and then we also
1820     // attempt to evaluate recursive bounds to see if they are
1821     // satisfied.
1822
1823     /// Returns true if `candidate_i` should be dropped in favor of
1824     /// `candidate_j`.  Generally speaking we will drop duplicate
1825     /// candidates and prefer where-clause candidates.
1826     /// Returns true if `victim` should be dropped in favor of
1827     /// `other`.  Generally speaking we will drop duplicate
1828     /// candidates and prefer where-clause candidates.
1829     ///
1830     /// See the comment for "SelectionCandidate" for more details.
1831     fn candidate_should_be_dropped_in_favor_of<'o>(
1832         &mut self,
1833         victim: &EvaluatedCandidate<'tcx>,
1834         other: &EvaluatedCandidate<'tcx>)
1835         -> bool
1836     {
1837         if victim.candidate == other.candidate {
1838             return true;
1839         }
1840
1841         match other.candidate {
1842             ObjectCandidate |
1843             ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
1844                 DefaultImplCandidate(..) => {
1845                     bug!(
1846                         "default implementations shouldn't be recorded \
1847                          when there are other valid candidates");
1848                 }
1849                 ImplCandidate(..) |
1850                 ClosureCandidate(..) |
1851                 FnPointerCandidate |
1852                 BuiltinObjectCandidate |
1853                 BuiltinUnsizeCandidate |
1854                 BuiltinCandidate { .. } => {
1855                     // We have a where-clause so don't go around looking
1856                     // for impls.
1857                     true
1858                 }
1859                 ObjectCandidate |
1860                 ProjectionCandidate => {
1861                     // Arbitrarily give param candidates priority
1862                     // over projection and object candidates.
1863                     true
1864                 },
1865                 ParamCandidate(..) => false,
1866             },
1867             ImplCandidate(other_def) => {
1868                 // See if we can toss out `victim` based on specialization.
1869                 // This requires us to know *for sure* that the `other` impl applies
1870                 // i.e. EvaluatedToOk:
1871                 if other.evaluation == EvaluatedToOk {
1872                     if let ImplCandidate(victim_def) = victim.candidate {
1873                         let tcx = self.tcx().global_tcx();
1874                         return traits::specializes(tcx, other_def, victim_def) ||
1875                             tcx.impls_are_allowed_to_overlap(other_def, victim_def);
1876                     }
1877                 }
1878
1879                 false
1880             },
1881             _ => false
1882         }
1883     }
1884
1885     ///////////////////////////////////////////////////////////////////////////
1886     // BUILTIN BOUNDS
1887     //
1888     // These cover the traits that are built-in to the language
1889     // itself.  This includes `Copy` and `Sized` for sure. For the
1890     // moment, it also includes `Send` / `Sync` and a few others, but
1891     // those will hopefully change to library-defined traits in the
1892     // future.
1893
1894     // HACK: if this returns an error, selection exits without considering
1895     // other impls.
1896     fn assemble_builtin_bound_candidates<'o>(&mut self,
1897                                              conditions: BuiltinImplConditions<'tcx>,
1898                                              candidates: &mut SelectionCandidateSet<'tcx>)
1899                                              -> Result<(),SelectionError<'tcx>>
1900     {
1901         match conditions {
1902             BuiltinImplConditions::Where(nested) => {
1903                 debug!("builtin_bound: nested={:?}", nested);
1904                 candidates.vec.push(BuiltinCandidate {
1905                     has_nested: nested.skip_binder().len() > 0
1906                 });
1907                 Ok(())
1908             }
1909             BuiltinImplConditions::None => { Ok(()) }
1910             BuiltinImplConditions::Ambiguous => {
1911                 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1912                 Ok(candidates.ambiguous = true)
1913             }
1914             BuiltinImplConditions::Never => { Err(Unimplemented) }
1915         }
1916     }
1917
1918     fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1919                      -> BuiltinImplConditions<'tcx>
1920     {
1921         use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1922
1923         // NOTE: binder moved to (*)
1924         let self_ty = self.infcx.shallow_resolve(
1925             obligation.predicate.skip_binder().self_ty());
1926
1927         match self_ty.sty {
1928             ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1929             ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1930             ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyRawPtr(..) |
1931             ty::TyChar | ty::TyRef(..) |
1932             ty::TyArray(..) | ty::TyClosure(..) | ty::TyNever |
1933             ty::TyError => {
1934                 // safe for everything
1935                 Where(ty::Binder(Vec::new()))
1936             }
1937
1938             ty::TyStr | ty::TySlice(_) | ty::TyDynamic(..) => Never,
1939
1940             ty::TyTuple(tys, _) => {
1941                 Where(ty::Binder(tys.last().into_iter().cloned().collect()))
1942             }
1943
1944             ty::TyAdt(def, substs) => {
1945                 let sized_crit = def.sized_constraint(self.tcx());
1946                 // (*) binder moved here
1947                 Where(ty::Binder(
1948                     sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1949                 ))
1950             }
1951
1952             ty::TyProjection(_) | ty::TyParam(_) | ty::TyAnon(..) => None,
1953             ty::TyInfer(ty::TyVar(_)) => Ambiguous,
1954
1955             ty::TyInfer(ty::FreshTy(_))
1956             | ty::TyInfer(ty::FreshIntTy(_))
1957             | ty::TyInfer(ty::FreshFloatTy(_)) => {
1958                 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1959                      self_ty);
1960             }
1961         }
1962     }
1963
1964     fn copy_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1965                      -> BuiltinImplConditions<'tcx>
1966     {
1967         // NOTE: binder moved to (*)
1968         let self_ty = self.infcx.shallow_resolve(
1969             obligation.predicate.skip_binder().self_ty());
1970
1971         use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1972
1973         match self_ty.sty {
1974             ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1975             ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1976             ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
1977             ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
1978             ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
1979                 Where(ty::Binder(Vec::new()))
1980             }
1981
1982             ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) |
1983             ty::TyClosure(..) |
1984             ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
1985                 Never
1986             }
1987
1988             ty::TyArray(element_ty, _) => {
1989                 // (*) binder moved here
1990                 Where(ty::Binder(vec![element_ty]))
1991             }
1992
1993             ty::TyTuple(tys, _) => {
1994                 // (*) binder moved here
1995                 Where(ty::Binder(tys.to_vec()))
1996             }
1997
1998             ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
1999                 // Fallback to whatever user-defined impls exist in this case.
2000                 None
2001             }
2002
2003             ty::TyInfer(ty::TyVar(_)) => {
2004                 // Unbound type variable. Might or might not have
2005                 // applicable impls and so forth, depending on what
2006                 // those type variables wind up being bound to.
2007                 Ambiguous
2008             }
2009
2010             ty::TyInfer(ty::FreshTy(_))
2011             | ty::TyInfer(ty::FreshIntTy(_))
2012             | ty::TyInfer(ty::FreshFloatTy(_)) => {
2013                 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
2014                      self_ty);
2015             }
2016         }
2017     }
2018
2019     /// For default impls, we need to break apart a type into its
2020     /// "constituent types" -- meaning, the types that it contains.
2021     ///
2022     /// Here are some (simple) examples:
2023     ///
2024     /// ```
2025     /// (i32, u32) -> [i32, u32]
2026     /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2027     /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2028     /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2029     /// ```
2030     fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2031         match t.sty {
2032             ty::TyUint(_) |
2033             ty::TyInt(_) |
2034             ty::TyBool |
2035             ty::TyFloat(_) |
2036             ty::TyFnDef(..) |
2037             ty::TyFnPtr(_) |
2038             ty::TyStr |
2039             ty::TyError |
2040             ty::TyInfer(ty::IntVar(_)) |
2041             ty::TyInfer(ty::FloatVar(_)) |
2042             ty::TyNever |
2043             ty::TyChar => {
2044                 Vec::new()
2045             }
2046
2047             ty::TyDynamic(..) |
2048             ty::TyParam(..) |
2049             ty::TyProjection(..) |
2050             ty::TyInfer(ty::TyVar(_)) |
2051             ty::TyInfer(ty::FreshTy(_)) |
2052             ty::TyInfer(ty::FreshIntTy(_)) |
2053             ty::TyInfer(ty::FreshFloatTy(_)) => {
2054                 bug!("asked to assemble constituent types of unexpected type: {:?}",
2055                      t);
2056             }
2057
2058             ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
2059             ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
2060                 vec![element_ty]
2061             },
2062
2063             ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
2064                 vec![element_ty]
2065             }
2066
2067             ty::TyTuple(ref tys, _) => {
2068                 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2069                 tys.to_vec()
2070             }
2071
2072             ty::TyClosure(def_id, ref substs) => {
2073                 // FIXME(#27086). We are invariant w/r/t our
2074                 // func_substs, but we don't see them as
2075                 // constituent types; this seems RIGHT but also like
2076                 // something that a normal type couldn't simulate. Is
2077                 // this just a gap with the way that PhantomData and
2078                 // OIBIT interact? That is, there is no way to say
2079                 // "make me invariant with respect to this TYPE, but
2080                 // do not act as though I can reach it"
2081                 substs.upvar_tys(def_id, self.tcx()).collect()
2082             }
2083
2084             // for `PhantomData<T>`, we pass `T`
2085             ty::TyAdt(def, substs) if def.is_phantom_data() => {
2086                 substs.types().collect()
2087             }
2088
2089             ty::TyAdt(def, substs) => {
2090                 def.all_fields()
2091                     .map(|f| f.ty(self.tcx(), substs))
2092                     .collect()
2093             }
2094
2095             ty::TyAnon(def_id, substs) => {
2096                 // We can resolve the `impl Trait` to its concrete type,
2097                 // which enforces a DAG between the functions requiring
2098                 // the auto trait bounds in question.
2099                 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2100             }
2101         }
2102     }
2103
2104     fn collect_predicates_for_types(&mut self,
2105                                     param_env: ty::ParamEnv<'tcx>,
2106                                     cause: ObligationCause<'tcx>,
2107                                     recursion_depth: usize,
2108                                     trait_def_id: DefId,
2109                                     types: ty::Binder<Vec<Ty<'tcx>>>)
2110                                     -> Vec<PredicateObligation<'tcx>>
2111     {
2112         // Because the types were potentially derived from
2113         // higher-ranked obligations they may reference late-bound
2114         // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2115         // yield a type like `for<'a> &'a int`. In general, we
2116         // maintain the invariant that we never manipulate bound
2117         // regions, so we have to process these bound regions somehow.
2118         //
2119         // The strategy is to:
2120         //
2121         // 1. Instantiate those regions to skolemized regions (e.g.,
2122         //    `for<'a> &'a int` becomes `&0 int`.
2123         // 2. Produce something like `&'0 int : Copy`
2124         // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2125
2126         types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
2127             let ty: ty::Binder<Ty<'tcx>> = ty::Binder(ty); // <----------/
2128
2129             self.in_snapshot(|this, snapshot| {
2130                 let (skol_ty, skol_map) =
2131                     this.infcx().skolemize_late_bound_regions(&ty, snapshot);
2132                 let Normalized { value: normalized_ty, mut obligations } =
2133                     project::normalize_with_depth(this,
2134                                                   param_env,
2135                                                   cause.clone(),
2136                                                   recursion_depth,
2137                                                   &skol_ty);
2138                 let skol_obligation =
2139                     this.tcx().predicate_for_trait_def(param_env,
2140                                                        cause.clone(),
2141                                                        trait_def_id,
2142                                                        recursion_depth,
2143                                                        normalized_ty,
2144                                                        &[]);
2145                 obligations.push(skol_obligation);
2146                 this.infcx().plug_leaks(skol_map, snapshot, obligations)
2147             })
2148         }).collect()
2149     }
2150
2151     ///////////////////////////////////////////////////////////////////////////
2152     // CONFIRMATION
2153     //
2154     // Confirmation unifies the output type parameters of the trait
2155     // with the values found in the obligation, possibly yielding a
2156     // type error.  See `README.md` for more details.
2157
2158     fn confirm_candidate(&mut self,
2159                          obligation: &TraitObligation<'tcx>,
2160                          candidate: SelectionCandidate<'tcx>)
2161                          -> Result<Selection<'tcx>,SelectionError<'tcx>>
2162     {
2163         debug!("confirm_candidate({:?}, {:?})",
2164                obligation,
2165                candidate);
2166
2167         match candidate {
2168             BuiltinCandidate { has_nested } => {
2169                 Ok(VtableBuiltin(
2170                     self.confirm_builtin_candidate(obligation, has_nested)))
2171             }
2172
2173             ParamCandidate(param) => {
2174                 let obligations = self.confirm_param_candidate(obligation, param);
2175                 Ok(VtableParam(obligations))
2176             }
2177
2178             DefaultImplCandidate(trait_def_id) => {
2179                 let data = self.confirm_default_impl_candidate(obligation, trait_def_id);
2180                 Ok(VtableDefaultImpl(data))
2181             }
2182
2183             ImplCandidate(impl_def_id) => {
2184                 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2185             }
2186
2187             ClosureCandidate(closure_def_id, substs, kind) => {
2188                 let vtable_closure =
2189                     self.confirm_closure_candidate(obligation, closure_def_id, substs, kind)?;
2190                 Ok(VtableClosure(vtable_closure))
2191             }
2192
2193             BuiltinObjectCandidate => {
2194                 // This indicates something like `(Trait+Send) :
2195                 // Send`. In this case, we know that this holds
2196                 // because that's what the object type is telling us,
2197                 // and there's really no additional obligations to
2198                 // prove and no types in particular to unify etc.
2199                 Ok(VtableParam(Vec::new()))
2200             }
2201
2202             ObjectCandidate => {
2203                 let data = self.confirm_object_candidate(obligation);
2204                 Ok(VtableObject(data))
2205             }
2206
2207             FnPointerCandidate => {
2208                 let data =
2209                     self.confirm_fn_pointer_candidate(obligation)?;
2210                 Ok(VtableFnPointer(data))
2211             }
2212
2213             ProjectionCandidate => {
2214                 self.confirm_projection_candidate(obligation);
2215                 Ok(VtableParam(Vec::new()))
2216             }
2217
2218             BuiltinUnsizeCandidate => {
2219                 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2220                 Ok(VtableBuiltin(data))
2221             }
2222         }
2223     }
2224
2225     fn confirm_projection_candidate(&mut self,
2226                                     obligation: &TraitObligation<'tcx>)
2227     {
2228         self.in_snapshot(|this, snapshot| {
2229             let result =
2230                 this.match_projection_obligation_against_definition_bounds(obligation,
2231                                                                            snapshot);
2232             assert!(result);
2233         })
2234     }
2235
2236     fn confirm_param_candidate(&mut self,
2237                                obligation: &TraitObligation<'tcx>,
2238                                param: ty::PolyTraitRef<'tcx>)
2239                                -> Vec<PredicateObligation<'tcx>>
2240     {
2241         debug!("confirm_param_candidate({:?},{:?})",
2242                obligation,
2243                param);
2244
2245         // During evaluation, we already checked that this
2246         // where-clause trait-ref could be unified with the obligation
2247         // trait-ref. Repeat that unification now without any
2248         // transactional boundary; it should not fail.
2249         match self.match_where_clause_trait_ref(obligation, param.clone()) {
2250             Ok(obligations) => obligations,
2251             Err(()) => {
2252                 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2253                      param,
2254                      obligation);
2255             }
2256         }
2257     }
2258
2259     fn confirm_builtin_candidate(&mut self,
2260                                  obligation: &TraitObligation<'tcx>,
2261                                  has_nested: bool)
2262                                  -> VtableBuiltinData<PredicateObligation<'tcx>>
2263     {
2264         debug!("confirm_builtin_candidate({:?}, {:?})",
2265                obligation, has_nested);
2266
2267         let obligations = if has_nested {
2268             let trait_def = obligation.predicate.def_id();
2269             let conditions = match trait_def {
2270                 _ if Some(trait_def) == self.tcx().lang_items.sized_trait() => {
2271                     self.sized_conditions(obligation)
2272                 }
2273                 _ if Some(trait_def) == self.tcx().lang_items.copy_trait() => {
2274                     self.copy_conditions(obligation)
2275                 }
2276                 _ => bug!("unexpected builtin trait {:?}", trait_def)
2277             };
2278             let nested = match conditions {
2279                 BuiltinImplConditions::Where(nested) => nested,
2280                 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2281                           obligation)
2282             };
2283
2284             let cause = obligation.derived_cause(BuiltinDerivedObligation);
2285             self.collect_predicates_for_types(obligation.param_env,
2286                                               cause,
2287                                               obligation.recursion_depth+1,
2288                                               trait_def,
2289                                               nested)
2290         } else {
2291             vec![]
2292         };
2293
2294         debug!("confirm_builtin_candidate: obligations={:?}",
2295                obligations);
2296         VtableBuiltinData { nested: obligations }
2297     }
2298
2299     /// This handles the case where a `impl Foo for ..` impl is being used.
2300     /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2301     ///
2302     /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2303     /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2304     fn confirm_default_impl_candidate(&mut self,
2305                                       obligation: &TraitObligation<'tcx>,
2306                                       trait_def_id: DefId)
2307                                       -> VtableDefaultImplData<PredicateObligation<'tcx>>
2308     {
2309         debug!("confirm_default_impl_candidate({:?}, {:?})",
2310                obligation,
2311                trait_def_id);
2312
2313         // binder is moved below
2314         let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2315         let types = self.constituent_types_for_ty(self_ty);
2316         self.vtable_default_impl(obligation, trait_def_id, ty::Binder(types))
2317     }
2318
2319     /// See `confirm_default_impl_candidate`
2320     fn vtable_default_impl(&mut self,
2321                            obligation: &TraitObligation<'tcx>,
2322                            trait_def_id: DefId,
2323                            nested: ty::Binder<Vec<Ty<'tcx>>>)
2324                            -> VtableDefaultImplData<PredicateObligation<'tcx>>
2325     {
2326         debug!("vtable_default_impl: nested={:?}", nested);
2327
2328         let cause = obligation.derived_cause(BuiltinDerivedObligation);
2329         let mut obligations = self.collect_predicates_for_types(
2330             obligation.param_env,
2331             cause,
2332             obligation.recursion_depth+1,
2333             trait_def_id,
2334             nested);
2335
2336         let trait_obligations = self.in_snapshot(|this, snapshot| {
2337             let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2338             let (trait_ref, skol_map) =
2339                 this.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2340             let cause = obligation.derived_cause(ImplDerivedObligation);
2341             this.impl_or_trait_obligations(cause,
2342                                            obligation.recursion_depth + 1,
2343                                            obligation.param_env,
2344                                            trait_def_id,
2345                                            &trait_ref.substs,
2346                                            skol_map,
2347                                            snapshot)
2348         });
2349
2350         obligations.extend(trait_obligations);
2351
2352         debug!("vtable_default_impl: obligations={:?}", obligations);
2353
2354         VtableDefaultImplData {
2355             trait_def_id,
2356             nested: obligations
2357         }
2358     }
2359
2360     fn confirm_impl_candidate(&mut self,
2361                               obligation: &TraitObligation<'tcx>,
2362                               impl_def_id: DefId)
2363                               -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2364     {
2365         debug!("confirm_impl_candidate({:?},{:?})",
2366                obligation,
2367                impl_def_id);
2368
2369         // First, create the substitutions by matching the impl again,
2370         // this time not in a probe.
2371         self.in_snapshot(|this, snapshot| {
2372             let (substs, skol_map) =
2373                 this.rematch_impl(impl_def_id, obligation,
2374                                   snapshot);
2375             debug!("confirm_impl_candidate substs={:?}", substs);
2376             let cause = obligation.derived_cause(ImplDerivedObligation);
2377             this.vtable_impl(impl_def_id,
2378                              substs,
2379                              cause,
2380                              obligation.recursion_depth + 1,
2381                              obligation.param_env,
2382                              skol_map,
2383                              snapshot)
2384         })
2385     }
2386
2387     fn vtable_impl(&mut self,
2388                    impl_def_id: DefId,
2389                    mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2390                    cause: ObligationCause<'tcx>,
2391                    recursion_depth: usize,
2392                    param_env: ty::ParamEnv<'tcx>,
2393                    skol_map: infer::SkolemizationMap<'tcx>,
2394                    snapshot: &infer::CombinedSnapshot)
2395                    -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2396     {
2397         debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2398                impl_def_id,
2399                substs,
2400                recursion_depth,
2401                skol_map);
2402
2403         let mut impl_obligations =
2404             self.impl_or_trait_obligations(cause,
2405                                            recursion_depth,
2406                                            param_env,
2407                                            impl_def_id,
2408                                            &substs.value,
2409                                            skol_map,
2410                                            snapshot);
2411
2412         debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2413                impl_def_id,
2414                impl_obligations);
2415
2416         // Because of RFC447, the impl-trait-ref and obligations
2417         // are sufficient to determine the impl substs, without
2418         // relying on projections in the impl-trait-ref.
2419         //
2420         // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2421         impl_obligations.append(&mut substs.obligations);
2422
2423         VtableImplData { impl_def_id,
2424                          substs: substs.value,
2425                          nested: impl_obligations }
2426     }
2427
2428     fn confirm_object_candidate(&mut self,
2429                                 obligation: &TraitObligation<'tcx>)
2430                                 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2431     {
2432         debug!("confirm_object_candidate({:?})",
2433                obligation);
2434
2435         // FIXME skipping binder here seems wrong -- we should
2436         // probably flatten the binder from the obligation and the
2437         // binder from the object. Have to try to make a broken test
2438         // case that results. -nmatsakis
2439         let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2440         let poly_trait_ref = match self_ty.sty {
2441             ty::TyDynamic(ref data, ..) => {
2442                 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2443             }
2444             _ => {
2445                 span_bug!(obligation.cause.span,
2446                           "object candidate with non-object");
2447             }
2448         };
2449
2450         let mut upcast_trait_ref = None;
2451         let vtable_base;
2452
2453         {
2454             let tcx = self.tcx();
2455
2456             // We want to find the first supertrait in the list of
2457             // supertraits that we can unify with, and do that
2458             // unification. We know that there is exactly one in the list
2459             // where we can unify because otherwise select would have
2460             // reported an ambiguity. (When we do find a match, also
2461             // record it for later.)
2462             let nonmatching =
2463                 util::supertraits(tcx, poly_trait_ref)
2464                 .take_while(|&t| {
2465                     match
2466                         self.commit_if_ok(
2467                             |this, _| this.match_poly_trait_ref(obligation, t))
2468                     {
2469                         Ok(_) => { upcast_trait_ref = Some(t); false }
2470                         Err(_) => { true }
2471                     }
2472                 });
2473
2474             // Additionally, for each of the nonmatching predicates that
2475             // we pass over, we sum up the set of number of vtable
2476             // entries, so that we can compute the offset for the selected
2477             // trait.
2478             vtable_base =
2479                 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2480                            .sum();
2481
2482         }
2483
2484         VtableObjectData {
2485             upcast_trait_ref: upcast_trait_ref.unwrap(),
2486             vtable_base,
2487             nested: vec![]
2488         }
2489     }
2490
2491     fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2492         -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2493     {
2494         debug!("confirm_fn_pointer_candidate({:?})",
2495                obligation);
2496
2497         // ok to skip binder; it is reintroduced below
2498         let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2499         let sig = self_ty.fn_sig(self.tcx());
2500         let trait_ref =
2501             self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2502                                                          self_ty,
2503                                                          sig,
2504                                                          util::TupleArgumentsFlag::Yes)
2505             .map_bound(|(trait_ref, _)| trait_ref);
2506
2507         let Normalized { value: trait_ref, obligations } =
2508             project::normalize_with_depth(self,
2509                                           obligation.param_env,
2510                                           obligation.cause.clone(),
2511                                           obligation.recursion_depth + 1,
2512                                           &trait_ref);
2513
2514         self.confirm_poly_trait_refs(obligation.cause.clone(),
2515                                      obligation.param_env,
2516                                      obligation.predicate.to_poly_trait_ref(),
2517                                      trait_ref)?;
2518         Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
2519     }
2520
2521     fn confirm_closure_candidate(&mut self,
2522                                  obligation: &TraitObligation<'tcx>,
2523                                  closure_def_id: DefId,
2524                                  substs: ty::ClosureSubsts<'tcx>,
2525                                  kind: ty::ClosureKind)
2526                                  -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2527                                            SelectionError<'tcx>>
2528     {
2529         debug!("confirm_closure_candidate({:?},{:?},{:?})",
2530                obligation,
2531                closure_def_id,
2532                substs);
2533
2534         let Normalized {
2535             value: trait_ref,
2536             mut obligations
2537         } = self.closure_trait_ref(obligation, closure_def_id, substs);
2538
2539         debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2540                closure_def_id,
2541                trait_ref,
2542                obligations);
2543
2544         self.confirm_poly_trait_refs(obligation.cause.clone(),
2545                                      obligation.param_env,
2546                                      obligation.predicate.to_poly_trait_ref(),
2547                                      trait_ref)?;
2548
2549         obligations.push(Obligation::new(
2550             obligation.cause.clone(),
2551             obligation.param_env,
2552             ty::Predicate::ClosureKind(closure_def_id, kind)));
2553
2554         Ok(VtableClosureData {
2555             closure_def_id,
2556             substs: substs.clone(),
2557             nested: obligations
2558         })
2559     }
2560
2561     /// In the case of closure types and fn pointers,
2562     /// we currently treat the input type parameters on the trait as
2563     /// outputs. This means that when we have a match we have only
2564     /// considered the self type, so we have to go back and make sure
2565     /// to relate the argument types too.  This is kind of wrong, but
2566     /// since we control the full set of impls, also not that wrong,
2567     /// and it DOES yield better error messages (since we don't report
2568     /// errors as if there is no applicable impl, but rather report
2569     /// errors are about mismatched argument types.
2570     ///
2571     /// Here is an example. Imagine we have a closure expression
2572     /// and we desugared it so that the type of the expression is
2573     /// `Closure`, and `Closure` expects an int as argument. Then it
2574     /// is "as if" the compiler generated this impl:
2575     ///
2576     ///     impl Fn(int) for Closure { ... }
2577     ///
2578     /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2579     /// we have matched the self-type `Closure`. At this point we'll
2580     /// compare the `int` to `usize` and generate an error.
2581     ///
2582     /// Note that this checking occurs *after* the impl has selected,
2583     /// because these output type parameters should not affect the
2584     /// selection of the impl. Therefore, if there is a mismatch, we
2585     /// report an error to the user.
2586     fn confirm_poly_trait_refs(&mut self,
2587                                obligation_cause: ObligationCause<'tcx>,
2588                                obligation_param_env: ty::ParamEnv<'tcx>,
2589                                obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2590                                expected_trait_ref: ty::PolyTraitRef<'tcx>)
2591                                -> Result<(), SelectionError<'tcx>>
2592     {
2593         let obligation_trait_ref = obligation_trait_ref.clone();
2594         self.infcx
2595             .at(&obligation_cause, obligation_param_env)
2596             .sup(obligation_trait_ref, expected_trait_ref)
2597             .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2598             .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2599     }
2600
2601     fn confirm_builtin_unsize_candidate(&mut self,
2602                                         obligation: &TraitObligation<'tcx>,)
2603                                         -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2604                                                   SelectionError<'tcx>> {
2605         let tcx = self.tcx();
2606
2607         // assemble_candidates_for_unsizing should ensure there are no late bound
2608         // regions here. See the comment there for more details.
2609         let source = self.infcx.shallow_resolve(
2610             tcx.no_late_bound_regions(&obligation.self_ty()).unwrap());
2611         let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2612         let target = self.infcx.shallow_resolve(target);
2613
2614         debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2615                source, target);
2616
2617         let mut nested = vec![];
2618         match (&source.sty, &target.sty) {
2619             // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2620             (&ty::TyDynamic(ref data_a, r_a), &ty::TyDynamic(ref data_b, r_b)) => {
2621                 // See assemble_candidates_for_unsizing for more info.
2622                 // Binders reintroduced below in call to mk_existential_predicates.
2623                 let principal = data_a.skip_binder().principal();
2624                 let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
2625                     .chain(data_a.skip_binder().projection_bounds()
2626                            .map(|x| ty::ExistentialPredicate::Projection(x)))
2627                     .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2628                 let new_trait = tcx.mk_dynamic(
2629                     ty::Binder(tcx.mk_existential_predicates(iter)), r_b);
2630                 let InferOk { obligations, .. } =
2631                     self.infcx.at(&obligation.cause, obligation.param_env)
2632                               .eq(target, new_trait)
2633                               .map_err(|_| Unimplemented)?;
2634                 self.inferred_obligations.extend(obligations);
2635
2636                 // Register one obligation for 'a: 'b.
2637                 let cause = ObligationCause::new(obligation.cause.span,
2638                                                  obligation.cause.body_id,
2639                                                  ObjectCastObligation(target));
2640                 let outlives = ty::OutlivesPredicate(r_a, r_b);
2641                 nested.push(Obligation::with_depth(cause,
2642                                                    obligation.recursion_depth + 1,
2643                                                    obligation.param_env,
2644                                                    ty::Binder(outlives).to_predicate()));
2645             }
2646
2647             // T -> Trait.
2648             (_, &ty::TyDynamic(ref data, r)) => {
2649                 let mut object_dids =
2650                     data.auto_traits().chain(data.principal().map(|p| p.def_id()));
2651                 if let Some(did) = object_dids.find(|did| {
2652                     !tcx.is_object_safe(*did)
2653                 }) {
2654                     return Err(TraitNotObjectSafe(did))
2655                 }
2656
2657                 let cause = ObligationCause::new(obligation.cause.span,
2658                                                  obligation.cause.body_id,
2659                                                  ObjectCastObligation(target));
2660                 let mut push = |predicate| {
2661                     nested.push(Obligation::with_depth(cause.clone(),
2662                                                        obligation.recursion_depth + 1,
2663                                                        obligation.param_env,
2664                                                        predicate));
2665                 };
2666
2667                 // Create obligations:
2668                 //  - Casting T to Trait
2669                 //  - For all the various builtin bounds attached to the object cast. (In other
2670                 //  words, if the object type is Foo+Send, this would create an obligation for the
2671                 //  Send check.)
2672                 //  - Projection predicates
2673                 for predicate in data.iter() {
2674                     push(predicate.with_self_ty(tcx, source));
2675                 }
2676
2677                 // We can only make objects from sized types.
2678                 let tr = ty::TraitRef {
2679                     def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
2680                     substs: tcx.mk_substs_trait(source, &[]),
2681                 };
2682                 push(tr.to_predicate());
2683
2684                 // If the type is `Foo+'a`, ensures that the type
2685                 // being cast to `Foo+'a` outlives `'a`:
2686                 let outlives = ty::OutlivesPredicate(source, r);
2687                 push(ty::Binder(outlives).to_predicate());
2688             }
2689
2690             // [T; n] -> [T].
2691             (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2692                 let InferOk { obligations, .. } =
2693                     self.infcx.at(&obligation.cause, obligation.param_env)
2694                               .eq(b, a)
2695                               .map_err(|_| Unimplemented)?;
2696                 self.inferred_obligations.extend(obligations);
2697             }
2698
2699             // Struct<T> -> Struct<U>.
2700             (&ty::TyAdt(def, substs_a), &ty::TyAdt(_, substs_b)) => {
2701                 let fields = def
2702                     .all_fields()
2703                     .map(|f| tcx.type_of(f.did))
2704                     .collect::<Vec<_>>();
2705
2706                 // The last field of the structure has to exist and contain type parameters.
2707                 let field = if let Some(&field) = fields.last() {
2708                     field
2709                 } else {
2710                     return Err(Unimplemented);
2711                 };
2712                 let mut ty_params = BitVector::new(substs_a.types().count());
2713                 let mut found = false;
2714                 for ty in field.walk() {
2715                     if let ty::TyParam(p) = ty.sty {
2716                         ty_params.insert(p.idx as usize);
2717                         found = true;
2718                     }
2719                 }
2720                 if !found {
2721                     return Err(Unimplemented);
2722                 }
2723
2724                 // Replace type parameters used in unsizing with
2725                 // TyError and ensure they do not affect any other fields.
2726                 // This could be checked after type collection for any struct
2727                 // with a potentially unsized trailing field.
2728                 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2729                     if ty_params.contains(i) {
2730                         Kind::from(tcx.types.err)
2731                     } else {
2732                         k
2733                     }
2734                 });
2735                 let substs = tcx.mk_substs(params);
2736                 for &ty in fields.split_last().unwrap().1 {
2737                     if ty.subst(tcx, substs).references_error() {
2738                         return Err(Unimplemented);
2739                     }
2740                 }
2741
2742                 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2743                 let inner_source = field.subst(tcx, substs_a);
2744                 let inner_target = field.subst(tcx, substs_b);
2745
2746                 // Check that the source struct with the target's
2747                 // unsized parameters is equal to the target.
2748                 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2749                     if ty_params.contains(i) {
2750                         Kind::from(substs_b.type_at(i))
2751                     } else {
2752                         k
2753                     }
2754                 });
2755                 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
2756                 let InferOk { obligations, .. } =
2757                     self.infcx.at(&obligation.cause, obligation.param_env)
2758                               .eq(target, new_struct)
2759                               .map_err(|_| Unimplemented)?;
2760                 self.inferred_obligations.extend(obligations);
2761
2762                 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2763                 nested.push(tcx.predicate_for_trait_def(
2764                     obligation.param_env,
2765                     obligation.cause.clone(),
2766                     obligation.predicate.def_id(),
2767                     obligation.recursion_depth + 1,
2768                     inner_source,
2769                     &[inner_target]));
2770             }
2771
2772             // (.., T) -> (.., U).
2773             (&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
2774                 assert_eq!(tys_a.len(), tys_b.len());
2775
2776                 // The last field of the tuple has to exist.
2777                 let (a_last, a_mid) = if let Some(x) = tys_a.split_last() {
2778                     x
2779                 } else {
2780                     return Err(Unimplemented);
2781                 };
2782                 let b_last = tys_b.last().unwrap();
2783
2784                 // Check that the source tuple with the target's
2785                 // last element is equal to the target.
2786                 let new_tuple = tcx.mk_tup(a_mid.iter().chain(Some(b_last)), false);
2787                 let InferOk { obligations, .. } =
2788                     self.infcx.at(&obligation.cause, obligation.param_env)
2789                               .eq(target, new_tuple)
2790                               .map_err(|_| Unimplemented)?;
2791                 self.inferred_obligations.extend(obligations);
2792
2793                 // Construct the nested T: Unsize<U> predicate.
2794                 nested.push(tcx.predicate_for_trait_def(
2795                     obligation.param_env,
2796                     obligation.cause.clone(),
2797                     obligation.predicate.def_id(),
2798                     obligation.recursion_depth + 1,
2799                     a_last,
2800                     &[b_last]));
2801             }
2802
2803             _ => bug!()
2804         };
2805
2806         Ok(VtableBuiltinData { nested: nested })
2807     }
2808
2809     ///////////////////////////////////////////////////////////////////////////
2810     // Matching
2811     //
2812     // Matching is a common path used for both evaluation and
2813     // confirmation.  It basically unifies types that appear in impls
2814     // and traits. This does affect the surrounding environment;
2815     // therefore, when used during evaluation, match routines must be
2816     // run inside of a `probe()` so that their side-effects are
2817     // contained.
2818
2819     fn rematch_impl(&mut self,
2820                     impl_def_id: DefId,
2821                     obligation: &TraitObligation<'tcx>,
2822                     snapshot: &infer::CombinedSnapshot)
2823                     -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
2824                         infer::SkolemizationMap<'tcx>)
2825     {
2826         match self.match_impl(impl_def_id, obligation, snapshot) {
2827             Ok((substs, skol_map)) => (substs, skol_map),
2828             Err(()) => {
2829                 bug!("Impl {:?} was matchable against {:?} but now is not",
2830                      impl_def_id,
2831                      obligation);
2832             }
2833         }
2834     }
2835
2836     fn match_impl(&mut self,
2837                   impl_def_id: DefId,
2838                   obligation: &TraitObligation<'tcx>,
2839                   snapshot: &infer::CombinedSnapshot)
2840                   -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
2841                              infer::SkolemizationMap<'tcx>), ()>
2842     {
2843         let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2844
2845         // Before we create the substitutions and everything, first
2846         // consider a "quick reject". This avoids creating more types
2847         // and so forth that we need to.
2848         if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2849             return Err(());
2850         }
2851
2852         let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
2853             &obligation.predicate,
2854             snapshot);
2855         let skol_obligation_trait_ref = skol_obligation.trait_ref;
2856
2857         let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
2858                                                            impl_def_id);
2859
2860         let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2861                                                   impl_substs);
2862
2863         let impl_trait_ref =
2864             project::normalize_with_depth(self,
2865                                           obligation.param_env,
2866                                           obligation.cause.clone(),
2867                                           obligation.recursion_depth + 1,
2868                                           &impl_trait_ref);
2869
2870         debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
2871                impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2872                impl_def_id,
2873                obligation,
2874                impl_trait_ref,
2875                skol_obligation_trait_ref);
2876
2877         let InferOk { obligations, .. } =
2878             self.infcx.at(&obligation.cause, obligation.param_env)
2879                       .eq(skol_obligation_trait_ref, impl_trait_ref.value)
2880                       .map_err(|e| {
2881                           debug!("match_impl: failed eq_trait_refs due to `{}`", e);
2882                           ()
2883                       })?;
2884         self.inferred_obligations.extend(obligations);
2885
2886         if let Err(e) = self.infcx.leak_check(false,
2887                                               obligation.cause.span,
2888                                               &skol_map,
2889                                               snapshot) {
2890             debug!("match_impl: failed leak check due to `{}`", e);
2891             return Err(());
2892         }
2893
2894         debug!("match_impl: success impl_substs={:?}", impl_substs);
2895         Ok((Normalized {
2896             value: impl_substs,
2897             obligations: impl_trait_ref.obligations
2898         }, skol_map))
2899     }
2900
2901     fn fast_reject_trait_refs(&mut self,
2902                               obligation: &TraitObligation,
2903                               impl_trait_ref: &ty::TraitRef)
2904                               -> bool
2905     {
2906         // We can avoid creating type variables and doing the full
2907         // substitution if we find that any of the input types, when
2908         // simplified, do not match.
2909
2910         obligation.predicate.skip_binder().input_types()
2911             .zip(impl_trait_ref.input_types())
2912             .any(|(obligation_ty, impl_ty)| {
2913                 let simplified_obligation_ty =
2914                     fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2915                 let simplified_impl_ty =
2916                     fast_reject::simplify_type(self.tcx(), impl_ty, false);
2917
2918                 simplified_obligation_ty.is_some() &&
2919                     simplified_impl_ty.is_some() &&
2920                     simplified_obligation_ty != simplified_impl_ty
2921             })
2922     }
2923
2924     /// Normalize `where_clause_trait_ref` and try to match it against
2925     /// `obligation`.  If successful, return any predicates that
2926     /// result from the normalization. Normalization is necessary
2927     /// because where-clauses are stored in the parameter environment
2928     /// unnormalized.
2929     fn match_where_clause_trait_ref(&mut self,
2930                                     obligation: &TraitObligation<'tcx>,
2931                                     where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2932                                     -> Result<Vec<PredicateObligation<'tcx>>,()>
2933     {
2934         self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
2935         Ok(Vec::new())
2936     }
2937
2938     /// Returns `Ok` if `poly_trait_ref` being true implies that the
2939     /// obligation is satisfied.
2940     fn match_poly_trait_ref(&mut self,
2941                             obligation: &TraitObligation<'tcx>,
2942                             poly_trait_ref: ty::PolyTraitRef<'tcx>)
2943                             -> Result<(),()>
2944     {
2945         debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2946                obligation,
2947                poly_trait_ref);
2948
2949         self.infcx.at(&obligation.cause, obligation.param_env)
2950                   .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2951                   .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2952                   .map_err(|_| ())
2953     }
2954
2955     ///////////////////////////////////////////////////////////////////////////
2956     // Miscellany
2957
2958     fn match_fresh_trait_refs(&self,
2959                               previous: &ty::PolyTraitRef<'tcx>,
2960                               current: &ty::PolyTraitRef<'tcx>)
2961                               -> bool
2962     {
2963         let mut matcher = ty::_match::Match::new(self.tcx());
2964         matcher.relate(previous, current).is_ok()
2965     }
2966
2967     fn push_stack<'o,'s:'o>(&mut self,
2968                             previous_stack: TraitObligationStackList<'s, 'tcx>,
2969                             obligation: &'o TraitObligation<'tcx>)
2970                             -> TraitObligationStack<'o, 'tcx>
2971     {
2972         let fresh_trait_ref =
2973             obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2974
2975         TraitObligationStack {
2976             obligation,
2977             fresh_trait_ref,
2978             previous: previous_stack,
2979         }
2980     }
2981
2982     fn closure_trait_ref_unnormalized(&mut self,
2983                                       obligation: &TraitObligation<'tcx>,
2984                                       closure_def_id: DefId,
2985                                       substs: ty::ClosureSubsts<'tcx>)
2986                                       -> ty::PolyTraitRef<'tcx>
2987     {
2988         let closure_type = self.infcx.fn_sig(closure_def_id)
2989             .subst(self.tcx(), substs.substs);
2990         let ty::Binder((trait_ref, _)) =
2991             self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2992                                                          obligation.predicate.0.self_ty(), // (1)
2993                                                          closure_type,
2994                                                          util::TupleArgumentsFlag::No);
2995         // (1) Feels icky to skip the binder here, but OTOH we know
2996         // that the self-type is an unboxed closure type and hence is
2997         // in fact unparameterized (or at least does not reference any
2998         // regions bound in the obligation). Still probably some
2999         // refactoring could make this nicer.
3000
3001         ty::Binder(trait_ref)
3002     }
3003
3004     fn closure_trait_ref(&mut self,
3005                          obligation: &TraitObligation<'tcx>,
3006                          closure_def_id: DefId,
3007                          substs: ty::ClosureSubsts<'tcx>)
3008                          -> Normalized<'tcx, ty::PolyTraitRef<'tcx>>
3009     {
3010         let trait_ref = self.closure_trait_ref_unnormalized(
3011             obligation, closure_def_id, substs);
3012
3013         // A closure signature can contain associated types which
3014         // must be normalized.
3015         normalize_with_depth(self,
3016                              obligation.param_env,
3017                              obligation.cause.clone(),
3018                              obligation.recursion_depth+1,
3019                              &trait_ref)
3020     }
3021
3022     /// Returns the obligations that are implied by instantiating an
3023     /// impl or trait. The obligations are substituted and fully
3024     /// normalized. This is used when confirming an impl or default
3025     /// impl.
3026     fn impl_or_trait_obligations(&mut self,
3027                                  cause: ObligationCause<'tcx>,
3028                                  recursion_depth: usize,
3029                                  param_env: ty::ParamEnv<'tcx>,
3030                                  def_id: DefId, // of impl or trait
3031                                  substs: &Substs<'tcx>, // for impl or trait
3032                                  skol_map: infer::SkolemizationMap<'tcx>,
3033                                  snapshot: &infer::CombinedSnapshot)
3034                                  -> Vec<PredicateObligation<'tcx>>
3035     {
3036         debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3037         let tcx = self.tcx();
3038
3039         // To allow for one-pass evaluation of the nested obligation,
3040         // each predicate must be preceded by the obligations required
3041         // to normalize it.
3042         // for example, if we have:
3043         //    impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3044         // the impl will have the following predicates:
3045         //    <V as Iterator>::Item = U,
3046         //    U: Iterator, U: Sized,
3047         //    V: Iterator, V: Sized,
3048         //    <U as Iterator>::Item: Copy
3049         // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3050         // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3051         // `$1: Copy`, so we must ensure the obligations are emitted in
3052         // that order.
3053         let predicates = tcx.predicates_of(def_id);
3054         assert_eq!(predicates.parent, None);
3055         let predicates = predicates.predicates.iter().flat_map(|predicate| {
3056             let predicate = normalize_with_depth(self, param_env, cause.clone(), recursion_depth,
3057                                                  &predicate.subst(tcx, substs));
3058             predicate.obligations.into_iter().chain(
3059                 Some(Obligation {
3060                     cause: cause.clone(),
3061                     recursion_depth,
3062                     param_env,
3063                     predicate: predicate.value
3064                 }))
3065         }).collect();
3066         self.infcx().plug_leaks(skol_map, snapshot, predicates)
3067     }
3068 }
3069
3070 impl<'tcx> TraitObligation<'tcx> {
3071     #[allow(unused_comparisons)]
3072     pub fn derived_cause(&self,
3073                         variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
3074                         -> ObligationCause<'tcx>
3075     {
3076         /*!
3077          * Creates a cause for obligations that are derived from
3078          * `obligation` by a recursive search (e.g., for a builtin
3079          * bound, or eventually a `impl Foo for ..`). If `obligation`
3080          * is itself a derived obligation, this is just a clone, but
3081          * otherwise we create a "derived obligation" cause so as to
3082          * keep track of the original root obligation for error
3083          * reporting.
3084          */
3085
3086         let obligation = self;
3087
3088         // NOTE(flaper87): As of now, it keeps track of the whole error
3089         // chain. Ideally, we should have a way to configure this either
3090         // by using -Z verbose or just a CLI argument.
3091         if obligation.recursion_depth >= 0 {
3092             let derived_cause = DerivedObligationCause {
3093                 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3094                 parent_code: Rc::new(obligation.cause.code.clone())
3095             };
3096             let derived_code = variant(derived_cause);
3097             ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
3098         } else {
3099             obligation.cause.clone()
3100         }
3101     }
3102 }
3103
3104 impl<'tcx> SelectionCache<'tcx> {
3105     pub fn new() -> SelectionCache<'tcx> {
3106         SelectionCache {
3107             hashmap: RefCell::new(FxHashMap())
3108         }
3109     }
3110 }
3111
3112 impl<'tcx> EvaluationCache<'tcx> {
3113     pub fn new() -> EvaluationCache<'tcx> {
3114         EvaluationCache {
3115             hashmap: RefCell::new(FxHashMap())
3116         }
3117     }
3118 }
3119
3120 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
3121     fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
3122         TraitObligationStackList::with(self)
3123     }
3124
3125     fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
3126         self.list()
3127     }
3128 }
3129
3130 #[derive(Copy, Clone)]
3131 struct TraitObligationStackList<'o,'tcx:'o> {
3132     head: Option<&'o TraitObligationStack<'o,'tcx>>
3133 }
3134
3135 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
3136     fn empty() -> TraitObligationStackList<'o,'tcx> {
3137         TraitObligationStackList { head: None }
3138     }
3139
3140     fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
3141         TraitObligationStackList { head: Some(r) }
3142     }
3143 }
3144
3145 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
3146     type Item = &'o TraitObligationStack<'o,'tcx>;
3147
3148     fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
3149         match self.head {
3150             Some(o) => {
3151                 *self = o.previous;
3152                 Some(o)
3153             }
3154             None => None
3155         }
3156     }
3157 }
3158
3159 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
3160     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3161         write!(f, "TraitObligationStack({:?})", self.obligation)
3162     }
3163 }
3164
3165 #[derive(Clone)]
3166 pub struct WithDepNode<T> {
3167     dep_node: DepNodeIndex,
3168     cached_value: T
3169 }
3170
3171 impl<T: Clone> WithDepNode<T> {
3172     pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
3173         WithDepNode { dep_node, cached_value }
3174     }
3175
3176     pub fn get(&self, tcx: TyCtxt) -> T {
3177         tcx.dep_graph.read_index(self.dep_node);
3178         self.cached_value.clone()
3179     }
3180 }