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