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