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