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