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