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