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