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