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