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