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