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