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