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