]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/select.rs
move projection mode into parameter environment
[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) -> ty::ParamEnv<'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.param_env().reveal
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().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                     // If there are *STILL* multiple candidates, give up
948                     // and report ambiguity.
949                     if i > 1 {
950                         debug!("multiple matches, ambig");
951                         return Ok(None);
952                     }
953                 }
954             }
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 predicates_of = self.tcx().predicates_of(def_id);
1226         let bounds = predicates_of.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         // micro-optimization: filter out predicates relating to different
1304         // traits.
1305         let matching_bounds =
1306             all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1307
1308         let matching_bounds =
1309             matching_bounds.filter(
1310                 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1311
1312         let param_candidates =
1313             matching_bounds.map(|bound| ParamCandidate(bound));
1314
1315         candidates.vec.extend(param_candidates);
1316
1317         Ok(())
1318     }
1319
1320     fn evaluate_where_clause<'o>(&mut self,
1321                                  stack: &TraitObligationStack<'o, 'tcx>,
1322                                  where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1323                                  -> EvaluationResult
1324     {
1325         self.probe(move |this, _| {
1326             match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1327                 Ok(obligations) => {
1328                     this.evaluate_predicates_recursively(stack.list(), obligations.iter())
1329                 }
1330                 Err(()) => EvaluatedToErr
1331             }
1332         })
1333     }
1334
1335     /// Check for the artificial impl that the compiler will create for an obligation like `X :
1336     /// FnMut<..>` where `X` is a closure type.
1337     ///
1338     /// Note: the type parameters on a closure candidate are modeled as *output* type
1339     /// parameters and hence do not affect whether this trait is a match or not. They will be
1340     /// unified during the confirmation step.
1341     fn assemble_closure_candidates(&mut self,
1342                                    obligation: &TraitObligation<'tcx>,
1343                                    candidates: &mut SelectionCandidateSet<'tcx>)
1344                                    -> Result<(),SelectionError<'tcx>>
1345     {
1346         let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1347             Some(k) => k,
1348             None => { return Ok(()); }
1349         };
1350
1351         // ok to skip binder because the substs on closure types never
1352         // touch bound regions, they just capture the in-scope
1353         // type/region parameters
1354         let self_ty = *obligation.self_ty().skip_binder();
1355         let (closure_def_id, substs) = match self_ty.sty {
1356             ty::TyClosure(id, substs) => (id, substs),
1357             ty::TyInfer(ty::TyVar(_)) => {
1358                 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1359                 candidates.ambiguous = true;
1360                 return Ok(());
1361             }
1362             _ => { return Ok(()); }
1363         };
1364
1365         debug!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1366                self_ty,
1367                kind,
1368                obligation);
1369
1370         match self.infcx.closure_kind(closure_def_id) {
1371             Some(closure_kind) => {
1372                 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1373                 if closure_kind.extends(kind) {
1374                     candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1375                 }
1376             }
1377             None => {
1378                 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1379                 candidates.vec.push(ClosureCandidate(closure_def_id, substs, kind));
1380             }
1381         }
1382
1383         Ok(())
1384     }
1385
1386     /// Implement one of the `Fn()` family for a fn pointer.
1387     fn assemble_fn_pointer_candidates(&mut self,
1388                                       obligation: &TraitObligation<'tcx>,
1389                                       candidates: &mut SelectionCandidateSet<'tcx>)
1390                                       -> Result<(),SelectionError<'tcx>>
1391     {
1392         // We provide impl of all fn traits for fn pointers.
1393         if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
1394             return Ok(());
1395         }
1396
1397         // ok to skip binder because what we are inspecting doesn't involve bound regions
1398         let self_ty = *obligation.self_ty().skip_binder();
1399         match self_ty.sty {
1400             ty::TyInfer(ty::TyVar(_)) => {
1401                 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1402                 candidates.ambiguous = true; // could wind up being a fn() type
1403             }
1404
1405             // provide an impl, but only for suitable `fn` pointers
1406             ty::TyFnDef(.., ty::Binder(ty::FnSig {
1407                 unsafety: hir::Unsafety::Normal,
1408                 abi: Abi::Rust,
1409                 variadic: false,
1410                 ..
1411             })) |
1412             ty::TyFnPtr(ty::Binder(ty::FnSig {
1413                 unsafety: hir::Unsafety::Normal,
1414                 abi: Abi::Rust,
1415                 variadic: false,
1416                 ..
1417             })) => {
1418                 candidates.vec.push(FnPointerCandidate);
1419             }
1420
1421             _ => { }
1422         }
1423
1424         Ok(())
1425     }
1426
1427     /// Search for impls that might apply to `obligation`.
1428     fn assemble_candidates_from_impls(&mut self,
1429                                       obligation: &TraitObligation<'tcx>,
1430                                       candidates: &mut SelectionCandidateSet<'tcx>)
1431                                       -> Result<(), SelectionError<'tcx>>
1432     {
1433         debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1434
1435         let def = self.tcx().trait_def(obligation.predicate.def_id());
1436
1437         def.for_each_relevant_impl(
1438             self.tcx(),
1439             obligation.predicate.0.trait_ref.self_ty(),
1440             |impl_def_id| {
1441                 self.probe(|this, snapshot| { /* [1] */
1442                     match this.match_impl(impl_def_id, obligation, snapshot) {
1443                         Ok(skol_map) => {
1444                             candidates.vec.push(ImplCandidate(impl_def_id));
1445
1446                             // NB: we can safely drop the skol map
1447                             // since we are in a probe [1]
1448                             mem::drop(skol_map);
1449                         }
1450                         Err(_) => { }
1451                     }
1452                 });
1453             }
1454         );
1455
1456         Ok(())
1457     }
1458
1459     fn assemble_candidates_from_default_impls(&mut self,
1460                                               obligation: &TraitObligation<'tcx>,
1461                                               candidates: &mut SelectionCandidateSet<'tcx>)
1462                                               -> Result<(), SelectionError<'tcx>>
1463     {
1464         // OK to skip binder here because the tests we do below do not involve bound regions
1465         let self_ty = *obligation.self_ty().skip_binder();
1466         debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty);
1467
1468         let def_id = obligation.predicate.def_id();
1469
1470         if self.tcx().trait_has_default_impl(def_id) {
1471             match self_ty.sty {
1472                 ty::TyDynamic(..) => {
1473                     // For object types, we don't know what the closed
1474                     // over types are. This means we conservatively
1475                     // say nothing; a candidate may be added by
1476                     // `assemble_candidates_from_object_ty`.
1477                 }
1478                 ty::TyParam(..) |
1479                 ty::TyProjection(..) => {
1480                     // In these cases, we don't know what the actual
1481                     // type is.  Therefore, we cannot break it down
1482                     // into its constituent types. So we don't
1483                     // consider the `..` impl but instead just add no
1484                     // candidates: this means that typeck will only
1485                     // succeed if there is another reason to believe
1486                     // that this obligation holds. That could be a
1487                     // where-clause or, in the case of an object type,
1488                     // it could be that the object type lists the
1489                     // trait (e.g. `Foo+Send : Send`). See
1490                     // `compile-fail/typeck-default-trait-impl-send-param.rs`
1491                     // for an example of a test case that exercises
1492                     // this path.
1493                 }
1494                 ty::TyInfer(ty::TyVar(_)) => {
1495                     // the defaulted impl might apply, we don't know
1496                     candidates.ambiguous = true;
1497                 }
1498                 _ => {
1499                     candidates.vec.push(DefaultImplCandidate(def_id.clone()))
1500                 }
1501             }
1502         }
1503
1504         Ok(())
1505     }
1506
1507     /// Search for impls that might apply to `obligation`.
1508     fn assemble_candidates_from_object_ty(&mut self,
1509                                           obligation: &TraitObligation<'tcx>,
1510                                           candidates: &mut SelectionCandidateSet<'tcx>)
1511     {
1512         debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1513                obligation.self_ty().skip_binder());
1514
1515         // Object-safety candidates are only applicable to object-safe
1516         // traits. Including this check is useful because it helps
1517         // inference in cases of traits like `BorrowFrom`, which are
1518         // not object-safe, and which rely on being able to infer the
1519         // self-type from one of the other inputs. Without this check,
1520         // these cases wind up being considered ambiguous due to a
1521         // (spurious) ambiguity introduced here.
1522         let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1523         if !self.tcx().is_object_safe(predicate_trait_ref.def_id()) {
1524             return;
1525         }
1526
1527         self.probe(|this, _snapshot| {
1528             // the code below doesn't care about regions, and the
1529             // self-ty here doesn't escape this probe, so just erase
1530             // any LBR.
1531             let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
1532             let poly_trait_ref = match self_ty.sty {
1533                 ty::TyDynamic(ref data, ..) => {
1534                     if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
1535                         debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1536                                     pushing candidate");
1537                         candidates.vec.push(BuiltinObjectCandidate);
1538                         return;
1539                     }
1540
1541                     match data.principal() {
1542                         Some(p) => p.with_self_ty(this.tcx(), self_ty),
1543                         None => return,
1544                     }
1545                 }
1546                 ty::TyInfer(ty::TyVar(_)) => {
1547                     debug!("assemble_candidates_from_object_ty: ambiguous");
1548                     candidates.ambiguous = true; // could wind up being an object type
1549                     return;
1550                 }
1551                 _ => {
1552                     return;
1553                 }
1554             };
1555
1556             debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1557                    poly_trait_ref);
1558
1559             // Count only those upcast versions that match the trait-ref
1560             // we are looking for. Specifically, do not only check for the
1561             // correct trait, but also the correct type parameters.
1562             // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1563             // but `Foo` is declared as `trait Foo : Bar<u32>`.
1564             let upcast_trait_refs =
1565                 util::supertraits(this.tcx(), poly_trait_ref)
1566                 .filter(|upcast_trait_ref| {
1567                     this.probe(|this, _| {
1568                         let upcast_trait_ref = upcast_trait_ref.clone();
1569                         this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1570                     })
1571                 })
1572                 .count();
1573
1574             if upcast_trait_refs > 1 {
1575                 // can be upcast in many ways; need more type information
1576                 candidates.ambiguous = true;
1577             } else if upcast_trait_refs == 1 {
1578                 candidates.vec.push(ObjectCandidate);
1579             }
1580         })
1581     }
1582
1583     /// Search for unsizing that might apply to `obligation`.
1584     fn assemble_candidates_for_unsizing(&mut self,
1585                                         obligation: &TraitObligation<'tcx>,
1586                                         candidates: &mut SelectionCandidateSet<'tcx>) {
1587         // We currently never consider higher-ranked obligations e.g.
1588         // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1589         // because they are a priori invalid, and we could potentially add support
1590         // for them later, it's just that there isn't really a strong need for it.
1591         // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1592         // impl, and those are generally applied to concrete types.
1593         //
1594         // That said, one might try to write a fn with a where clause like
1595         //     for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1596         // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1597         // Still, you'd be more likely to write that where clause as
1598         //     T: Trait
1599         // so it seems ok if we (conservatively) fail to accept that `Unsize`
1600         // obligation above. Should be possible to extend this in the future.
1601         let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) {
1602             Some(t) => t,
1603             None => {
1604                 // Don't add any candidates if there are bound regions.
1605                 return;
1606             }
1607         };
1608         let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
1609
1610         debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1611                source, target);
1612
1613         let may_apply = match (&source.sty, &target.sty) {
1614             // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1615             (&ty::TyDynamic(ref data_a, ..), &ty::TyDynamic(ref data_b, ..)) => {
1616                 // Upcasts permit two things:
1617                 //
1618                 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1619                 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1620                 //
1621                 // Note that neither of these changes requires any
1622                 // change at runtime.  Eventually this will be
1623                 // generalized.
1624                 //
1625                 // We always upcast when we can because of reason
1626                 // #2 (region bounds).
1627                 match (data_a.principal(), data_b.principal()) {
1628                     (Some(a), Some(b)) => a.def_id() == b.def_id() &&
1629                         data_b.auto_traits()
1630                             // All of a's auto traits need to be in b's auto traits.
1631                             .all(|b| data_a.auto_traits().any(|a| a == b)),
1632                     _ => false
1633                 }
1634             }
1635
1636             // T -> Trait.
1637             (_, &ty::TyDynamic(..)) => true,
1638
1639             // Ambiguous handling is below T -> Trait, because inference
1640             // variables can still implement Unsize<Trait> and nested
1641             // obligations will have the final say (likely deferred).
1642             (&ty::TyInfer(ty::TyVar(_)), _) |
1643             (_, &ty::TyInfer(ty::TyVar(_))) => {
1644                 debug!("assemble_candidates_for_unsizing: ambiguous");
1645                 candidates.ambiguous = true;
1646                 false
1647             }
1648
1649             // [T; n] -> [T].
1650             (&ty::TyArray(..), &ty::TySlice(_)) => true,
1651
1652             // Struct<T> -> Struct<U>.
1653             (&ty::TyAdt(def_id_a, _), &ty::TyAdt(def_id_b, _)) if def_id_a.is_struct() => {
1654                 def_id_a == def_id_b
1655             }
1656
1657             _ => false
1658         };
1659
1660         if may_apply {
1661             candidates.vec.push(BuiltinUnsizeCandidate);
1662         }
1663     }
1664
1665     ///////////////////////////////////////////////////////////////////////////
1666     // WINNOW
1667     //
1668     // Winnowing is the process of attempting to resolve ambiguity by
1669     // probing further. During the winnowing process, we unify all
1670     // type variables (ignoring skolemization) and then we also
1671     // attempt to evaluate recursive bounds to see if they are
1672     // satisfied.
1673
1674     /// Returns true if `candidate_i` should be dropped in favor of
1675     /// `candidate_j`.  Generally speaking we will drop duplicate
1676     /// candidates and prefer where-clause candidates.
1677     /// Returns true if `victim` should be dropped in favor of
1678     /// `other`.  Generally speaking we will drop duplicate
1679     /// candidates and prefer where-clause candidates.
1680     ///
1681     /// See the comment for "SelectionCandidate" for more details.
1682     fn candidate_should_be_dropped_in_favor_of<'o>(
1683         &mut self,
1684         victim: &EvaluatedCandidate<'tcx>,
1685         other: &EvaluatedCandidate<'tcx>)
1686         -> bool
1687     {
1688         if victim.candidate == other.candidate {
1689             return true;
1690         }
1691
1692         match other.candidate {
1693             ObjectCandidate |
1694             ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
1695                 DefaultImplCandidate(..) => {
1696                     bug!(
1697                         "default implementations shouldn't be recorded \
1698                          when there are other valid candidates");
1699                 }
1700                 ImplCandidate(..) |
1701                 ClosureCandidate(..) |
1702                 FnPointerCandidate |
1703                 BuiltinObjectCandidate |
1704                 BuiltinUnsizeCandidate |
1705                 BuiltinCandidate { .. } => {
1706                     // We have a where-clause so don't go around looking
1707                     // for impls.
1708                     true
1709                 }
1710                 ObjectCandidate |
1711                 ProjectionCandidate => {
1712                     // Arbitrarily give param candidates priority
1713                     // over projection and object candidates.
1714                     true
1715                 },
1716                 ParamCandidate(..) => false,
1717             },
1718             ImplCandidate(other_def) => {
1719                 // See if we can toss out `victim` based on specialization.
1720                 // This requires us to know *for sure* that the `other` impl applies
1721                 // i.e. EvaluatedToOk:
1722                 if other.evaluation == EvaluatedToOk {
1723                     if let ImplCandidate(victim_def) = victim.candidate {
1724                         let tcx = self.tcx().global_tcx();
1725                         return traits::specializes(tcx, other_def, victim_def) ||
1726                             tcx.impls_are_allowed_to_overlap(other_def, victim_def);
1727                     }
1728                 }
1729
1730                 false
1731             },
1732             _ => false
1733         }
1734     }
1735
1736     ///////////////////////////////////////////////////////////////////////////
1737     // BUILTIN BOUNDS
1738     //
1739     // These cover the traits that are built-in to the language
1740     // itself.  This includes `Copy` and `Sized` for sure. For the
1741     // moment, it also includes `Send` / `Sync` and a few others, but
1742     // those will hopefully change to library-defined traits in the
1743     // future.
1744
1745     // HACK: if this returns an error, selection exits without considering
1746     // other impls.
1747     fn assemble_builtin_bound_candidates<'o>(&mut self,
1748                                              conditions: BuiltinImplConditions<'tcx>,
1749                                              candidates: &mut SelectionCandidateSet<'tcx>)
1750                                              -> Result<(),SelectionError<'tcx>>
1751     {
1752         match conditions {
1753             BuiltinImplConditions::Where(nested) => {
1754                 debug!("builtin_bound: nested={:?}", nested);
1755                 candidates.vec.push(BuiltinCandidate {
1756                     has_nested: nested.skip_binder().len() > 0
1757                 });
1758                 Ok(())
1759             }
1760             BuiltinImplConditions::None => { Ok(()) }
1761             BuiltinImplConditions::Ambiguous => {
1762                 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1763                 Ok(candidates.ambiguous = true)
1764             }
1765             BuiltinImplConditions::Never => { Err(Unimplemented) }
1766         }
1767     }
1768
1769     fn sized_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1770                      -> BuiltinImplConditions<'tcx>
1771     {
1772         use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1773
1774         // NOTE: binder moved to (*)
1775         let self_ty = self.infcx.shallow_resolve(
1776             obligation.predicate.skip_binder().self_ty());
1777
1778         match self_ty.sty {
1779             ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1780             ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1781             ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyRawPtr(..) |
1782             ty::TyChar | ty::TyRef(..) |
1783             ty::TyArray(..) | ty::TyClosure(..) | ty::TyNever |
1784             ty::TyError => {
1785                 // safe for everything
1786                 Where(ty::Binder(Vec::new()))
1787             }
1788
1789             ty::TyStr | ty::TySlice(_) | ty::TyDynamic(..) => Never,
1790
1791             ty::TyTuple(tys, _) => {
1792                 Where(ty::Binder(tys.last().into_iter().cloned().collect()))
1793             }
1794
1795             ty::TyAdt(def, substs) => {
1796                 let sized_crit = def.sized_constraint(self.tcx());
1797                 // (*) binder moved here
1798                 Where(ty::Binder(
1799                     sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1800                 ))
1801             }
1802
1803             ty::TyProjection(_) | ty::TyParam(_) | ty::TyAnon(..) => None,
1804             ty::TyInfer(ty::TyVar(_)) => Ambiguous,
1805
1806             ty::TyInfer(ty::FreshTy(_))
1807             | ty::TyInfer(ty::FreshIntTy(_))
1808             | ty::TyInfer(ty::FreshFloatTy(_)) => {
1809                 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1810                      self_ty);
1811             }
1812         }
1813     }
1814
1815     fn copy_conditions(&mut self, obligation: &TraitObligation<'tcx>)
1816                      -> BuiltinImplConditions<'tcx>
1817     {
1818         // NOTE: binder moved to (*)
1819         let self_ty = self.infcx.shallow_resolve(
1820             obligation.predicate.skip_binder().self_ty());
1821
1822         use self::BuiltinImplConditions::{Ambiguous, None, Never, Where};
1823
1824         match self_ty.sty {
1825             ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) |
1826             ty::TyUint(_) | ty::TyInt(_) | ty::TyBool | ty::TyFloat(_) |
1827             ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
1828             ty::TyRawPtr(..) | ty::TyError | ty::TyNever |
1829             ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
1830                 Where(ty::Binder(Vec::new()))
1831             }
1832
1833             ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) |
1834             ty::TyClosure(..) |
1835             ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
1836                 Never
1837             }
1838
1839             ty::TyArray(element_ty, _) => {
1840                 // (*) binder moved here
1841                 Where(ty::Binder(vec![element_ty]))
1842             }
1843
1844             ty::TyTuple(tys, _) => {
1845                 // (*) binder moved here
1846                 Where(ty::Binder(tys.to_vec()))
1847             }
1848
1849             ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
1850                 // Fallback to whatever user-defined impls exist in this case.
1851                 None
1852             }
1853
1854             ty::TyInfer(ty::TyVar(_)) => {
1855                 // Unbound type variable. Might or might not have
1856                 // applicable impls and so forth, depending on what
1857                 // those type variables wind up being bound to.
1858                 Ambiguous
1859             }
1860
1861             ty::TyInfer(ty::FreshTy(_))
1862             | ty::TyInfer(ty::FreshIntTy(_))
1863             | ty::TyInfer(ty::FreshFloatTy(_)) => {
1864                 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1865                      self_ty);
1866             }
1867         }
1868     }
1869
1870     /// For default impls, we need to break apart a type into its
1871     /// "constituent types" -- meaning, the types that it contains.
1872     ///
1873     /// Here are some (simple) examples:
1874     ///
1875     /// ```
1876     /// (i32, u32) -> [i32, u32]
1877     /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1878     /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1879     /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1880     /// ```
1881     fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
1882         match t.sty {
1883             ty::TyUint(_) |
1884             ty::TyInt(_) |
1885             ty::TyBool |
1886             ty::TyFloat(_) |
1887             ty::TyFnDef(..) |
1888             ty::TyFnPtr(_) |
1889             ty::TyStr |
1890             ty::TyError |
1891             ty::TyInfer(ty::IntVar(_)) |
1892             ty::TyInfer(ty::FloatVar(_)) |
1893             ty::TyNever |
1894             ty::TyChar => {
1895                 Vec::new()
1896             }
1897
1898             ty::TyDynamic(..) |
1899             ty::TyParam(..) |
1900             ty::TyProjection(..) |
1901             ty::TyInfer(ty::TyVar(_)) |
1902             ty::TyInfer(ty::FreshTy(_)) |
1903             ty::TyInfer(ty::FreshIntTy(_)) |
1904             ty::TyInfer(ty::FreshFloatTy(_)) => {
1905                 bug!("asked to assemble constituent types of unexpected type: {:?}",
1906                      t);
1907             }
1908
1909             ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
1910             ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
1911                 vec![element_ty]
1912             },
1913
1914             ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
1915                 vec![element_ty]
1916             }
1917
1918             ty::TyTuple(ref tys, _) => {
1919                 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1920                 tys.to_vec()
1921             }
1922
1923             ty::TyClosure(def_id, ref substs) => {
1924                 // FIXME(#27086). We are invariant w/r/t our
1925                 // func_substs, but we don't see them as
1926                 // constituent types; this seems RIGHT but also like
1927                 // something that a normal type couldn't simulate. Is
1928                 // this just a gap with the way that PhantomData and
1929                 // OIBIT interact? That is, there is no way to say
1930                 // "make me invariant with respect to this TYPE, but
1931                 // do not act as though I can reach it"
1932                 substs.upvar_tys(def_id, self.tcx()).collect()
1933             }
1934
1935             // for `PhantomData<T>`, we pass `T`
1936             ty::TyAdt(def, substs) if def.is_phantom_data() => {
1937                 substs.types().collect()
1938             }
1939
1940             ty::TyAdt(def, substs) => {
1941                 def.all_fields()
1942                     .map(|f| f.ty(self.tcx(), substs))
1943                     .collect()
1944             }
1945
1946             ty::TyAnon(def_id, substs) => {
1947                 // We can resolve the `impl Trait` to its concrete type,
1948                 // which enforces a DAG between the functions requiring
1949                 // the auto trait bounds in question.
1950                 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
1951             }
1952         }
1953     }
1954
1955     fn collect_predicates_for_types(&mut self,
1956                                     cause: ObligationCause<'tcx>,
1957                                     recursion_depth: usize,
1958                                     trait_def_id: DefId,
1959                                     types: ty::Binder<Vec<Ty<'tcx>>>)
1960                                     -> Vec<PredicateObligation<'tcx>>
1961     {
1962         // Because the types were potentially derived from
1963         // higher-ranked obligations they may reference late-bound
1964         // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1965         // yield a type like `for<'a> &'a int`. In general, we
1966         // maintain the invariant that we never manipulate bound
1967         // regions, so we have to process these bound regions somehow.
1968         //
1969         // The strategy is to:
1970         //
1971         // 1. Instantiate those regions to skolemized regions (e.g.,
1972         //    `for<'a> &'a int` becomes `&0 int`.
1973         // 2. Produce something like `&'0 int : Copy`
1974         // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1975
1976         types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
1977             let ty: ty::Binder<Ty<'tcx>> = ty::Binder(ty); // <----------/
1978
1979             self.in_snapshot(|this, snapshot| {
1980                 let (skol_ty, skol_map) =
1981                     this.infcx().skolemize_late_bound_regions(&ty, snapshot);
1982                 let Normalized { value: normalized_ty, mut obligations } =
1983                     project::normalize_with_depth(this,
1984                                                   cause.clone(),
1985                                                   recursion_depth,
1986                                                   &skol_ty);
1987                 let skol_obligation =
1988                     this.tcx().predicate_for_trait_def(
1989                                                   cause.clone(),
1990                                                   trait_def_id,
1991                                                   recursion_depth,
1992                                                   normalized_ty,
1993                                                   &[]);
1994                 obligations.push(skol_obligation);
1995                 this.infcx().plug_leaks(skol_map, snapshot, obligations)
1996             })
1997         }).collect()
1998     }
1999
2000     ///////////////////////////////////////////////////////////////////////////
2001     // CONFIRMATION
2002     //
2003     // Confirmation unifies the output type parameters of the trait
2004     // with the values found in the obligation, possibly yielding a
2005     // type error.  See `README.md` for more details.
2006
2007     fn confirm_candidate(&mut self,
2008                          obligation: &TraitObligation<'tcx>,
2009                          candidate: SelectionCandidate<'tcx>)
2010                          -> Result<Selection<'tcx>,SelectionError<'tcx>>
2011     {
2012         debug!("confirm_candidate({:?}, {:?})",
2013                obligation,
2014                candidate);
2015
2016         match candidate {
2017             BuiltinCandidate { has_nested } => {
2018                 Ok(VtableBuiltin(
2019                     self.confirm_builtin_candidate(obligation, has_nested)))
2020             }
2021
2022             ParamCandidate(param) => {
2023                 let obligations = self.confirm_param_candidate(obligation, param);
2024                 Ok(VtableParam(obligations))
2025             }
2026
2027             DefaultImplCandidate(trait_def_id) => {
2028                 let data = self.confirm_default_impl_candidate(obligation, trait_def_id);
2029                 Ok(VtableDefaultImpl(data))
2030             }
2031
2032             ImplCandidate(impl_def_id) => {
2033                 Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
2034             }
2035
2036             ClosureCandidate(closure_def_id, substs, kind) => {
2037                 let vtable_closure =
2038                     self.confirm_closure_candidate(obligation, closure_def_id, substs, kind)?;
2039                 Ok(VtableClosure(vtable_closure))
2040             }
2041
2042             BuiltinObjectCandidate => {
2043                 // This indicates something like `(Trait+Send) :
2044                 // Send`. In this case, we know that this holds
2045                 // because that's what the object type is telling us,
2046                 // and there's really no additional obligations to
2047                 // prove and no types in particular to unify etc.
2048                 Ok(VtableParam(Vec::new()))
2049             }
2050
2051             ObjectCandidate => {
2052                 let data = self.confirm_object_candidate(obligation);
2053                 Ok(VtableObject(data))
2054             }
2055
2056             FnPointerCandidate => {
2057                 let data =
2058                     self.confirm_fn_pointer_candidate(obligation)?;
2059                 Ok(VtableFnPointer(data))
2060             }
2061
2062             ProjectionCandidate => {
2063                 self.confirm_projection_candidate(obligation);
2064                 Ok(VtableParam(Vec::new()))
2065             }
2066
2067             BuiltinUnsizeCandidate => {
2068                 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2069                 Ok(VtableBuiltin(data))
2070             }
2071         }
2072     }
2073
2074     fn confirm_projection_candidate(&mut self,
2075                                     obligation: &TraitObligation<'tcx>)
2076     {
2077         self.in_snapshot(|this, snapshot| {
2078             let result =
2079                 this.match_projection_obligation_against_definition_bounds(obligation,
2080                                                                            snapshot);
2081             assert!(result);
2082         })
2083     }
2084
2085     fn confirm_param_candidate(&mut self,
2086                                obligation: &TraitObligation<'tcx>,
2087                                param: ty::PolyTraitRef<'tcx>)
2088                                -> Vec<PredicateObligation<'tcx>>
2089     {
2090         debug!("confirm_param_candidate({:?},{:?})",
2091                obligation,
2092                param);
2093
2094         // During evaluation, we already checked that this
2095         // where-clause trait-ref could be unified with the obligation
2096         // trait-ref. Repeat that unification now without any
2097         // transactional boundary; it should not fail.
2098         match self.match_where_clause_trait_ref(obligation, param.clone()) {
2099             Ok(obligations) => obligations,
2100             Err(()) => {
2101                 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2102                      param,
2103                      obligation);
2104             }
2105         }
2106     }
2107
2108     fn confirm_builtin_candidate(&mut self,
2109                                  obligation: &TraitObligation<'tcx>,
2110                                  has_nested: bool)
2111                                  -> VtableBuiltinData<PredicateObligation<'tcx>>
2112     {
2113         debug!("confirm_builtin_candidate({:?}, {:?})",
2114                obligation, has_nested);
2115
2116         let obligations = if has_nested {
2117             let trait_def = obligation.predicate.def_id();
2118             let conditions = match trait_def {
2119                 _ if Some(trait_def) == self.tcx().lang_items.sized_trait() => {
2120                     self.sized_conditions(obligation)
2121                 }
2122                 _ if Some(trait_def) == self.tcx().lang_items.copy_trait() => {
2123                     self.copy_conditions(obligation)
2124                 }
2125                 _ => bug!("unexpected builtin trait {:?}", trait_def)
2126             };
2127             let nested = match conditions {
2128                 BuiltinImplConditions::Where(nested) => nested,
2129                 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
2130                           obligation)
2131             };
2132
2133             let cause = obligation.derived_cause(BuiltinDerivedObligation);
2134             self.collect_predicates_for_types(cause,
2135                                               obligation.recursion_depth+1,
2136                                               trait_def,
2137                                               nested)
2138         } else {
2139             vec![]
2140         };
2141
2142         debug!("confirm_builtin_candidate: obligations={:?}",
2143                obligations);
2144         VtableBuiltinData { nested: obligations }
2145     }
2146
2147     /// This handles the case where a `impl Foo for ..` impl is being used.
2148     /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2149     ///
2150     /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2151     /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2152     fn confirm_default_impl_candidate(&mut self,
2153                                       obligation: &TraitObligation<'tcx>,
2154                                       trait_def_id: DefId)
2155                                       -> VtableDefaultImplData<PredicateObligation<'tcx>>
2156     {
2157         debug!("confirm_default_impl_candidate({:?}, {:?})",
2158                obligation,
2159                trait_def_id);
2160
2161         // binder is moved below
2162         let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2163         let types = self.constituent_types_for_ty(self_ty);
2164         self.vtable_default_impl(obligation, trait_def_id, ty::Binder(types))
2165     }
2166
2167     /// See `confirm_default_impl_candidate`
2168     fn vtable_default_impl(&mut self,
2169                            obligation: &TraitObligation<'tcx>,
2170                            trait_def_id: DefId,
2171                            nested: ty::Binder<Vec<Ty<'tcx>>>)
2172                            -> VtableDefaultImplData<PredicateObligation<'tcx>>
2173     {
2174         debug!("vtable_default_impl: nested={:?}", nested);
2175
2176         let cause = obligation.derived_cause(BuiltinDerivedObligation);
2177         let mut obligations = self.collect_predicates_for_types(
2178             cause,
2179             obligation.recursion_depth+1,
2180             trait_def_id,
2181             nested);
2182
2183         let trait_obligations = self.in_snapshot(|this, snapshot| {
2184             let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2185             let (trait_ref, skol_map) =
2186                 this.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2187             let cause = obligation.derived_cause(ImplDerivedObligation);
2188             this.impl_or_trait_obligations(cause,
2189                                            obligation.recursion_depth + 1,
2190                                            trait_def_id,
2191                                            &trait_ref.substs,
2192                                            skol_map,
2193                                            snapshot)
2194         });
2195
2196         obligations.extend(trait_obligations);
2197
2198         debug!("vtable_default_impl: obligations={:?}", obligations);
2199
2200         VtableDefaultImplData {
2201             trait_def_id: trait_def_id,
2202             nested: obligations
2203         }
2204     }
2205
2206     fn confirm_impl_candidate(&mut self,
2207                               obligation: &TraitObligation<'tcx>,
2208                               impl_def_id: DefId)
2209                               -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2210     {
2211         debug!("confirm_impl_candidate({:?},{:?})",
2212                obligation,
2213                impl_def_id);
2214
2215         // First, create the substitutions by matching the impl again,
2216         // this time not in a probe.
2217         self.in_snapshot(|this, snapshot| {
2218             let (substs, skol_map) =
2219                 this.rematch_impl(impl_def_id, obligation,
2220                                   snapshot);
2221             debug!("confirm_impl_candidate substs={:?}", substs);
2222             let cause = obligation.derived_cause(ImplDerivedObligation);
2223             this.vtable_impl(impl_def_id, substs, cause,
2224                              obligation.recursion_depth + 1,
2225                              skol_map, snapshot)
2226         })
2227     }
2228
2229     fn vtable_impl(&mut self,
2230                    impl_def_id: DefId,
2231                    mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
2232                    cause: ObligationCause<'tcx>,
2233                    recursion_depth: usize,
2234                    skol_map: infer::SkolemizationMap<'tcx>,
2235                    snapshot: &infer::CombinedSnapshot)
2236                    -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2237     {
2238         debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2239                impl_def_id,
2240                substs,
2241                recursion_depth,
2242                skol_map);
2243
2244         let mut impl_obligations =
2245             self.impl_or_trait_obligations(cause,
2246                                            recursion_depth,
2247                                            impl_def_id,
2248                                            &substs.value,
2249                                            skol_map,
2250                                            snapshot);
2251
2252         debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2253                impl_def_id,
2254                impl_obligations);
2255
2256         // Because of RFC447, the impl-trait-ref and obligations
2257         // are sufficient to determine the impl substs, without
2258         // relying on projections in the impl-trait-ref.
2259         //
2260         // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2261         impl_obligations.append(&mut substs.obligations);
2262
2263         VtableImplData { impl_def_id: impl_def_id,
2264                          substs: substs.value,
2265                          nested: impl_obligations }
2266     }
2267
2268     fn confirm_object_candidate(&mut self,
2269                                 obligation: &TraitObligation<'tcx>)
2270                                 -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
2271     {
2272         debug!("confirm_object_candidate({:?})",
2273                obligation);
2274
2275         // FIXME skipping binder here seems wrong -- we should
2276         // probably flatten the binder from the obligation and the
2277         // binder from the object. Have to try to make a broken test
2278         // case that results. -nmatsakis
2279         let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2280         let poly_trait_ref = match self_ty.sty {
2281             ty::TyDynamic(ref data, ..) => {
2282                 data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
2283             }
2284             _ => {
2285                 span_bug!(obligation.cause.span,
2286                           "object candidate with non-object");
2287             }
2288         };
2289
2290         let mut upcast_trait_ref = None;
2291         let vtable_base;
2292
2293         {
2294             let tcx = self.tcx();
2295
2296             // We want to find the first supertrait in the list of
2297             // supertraits that we can unify with, and do that
2298             // unification. We know that there is exactly one in the list
2299             // where we can unify because otherwise select would have
2300             // reported an ambiguity. (When we do find a match, also
2301             // record it for later.)
2302             let nonmatching =
2303                 util::supertraits(tcx, poly_trait_ref)
2304                 .take_while(|&t| {
2305                     match
2306                         self.commit_if_ok(
2307                             |this, _| this.match_poly_trait_ref(obligation, t))
2308                     {
2309                         Ok(_) => { upcast_trait_ref = Some(t); false }
2310                         Err(_) => { true }
2311                     }
2312                 });
2313
2314             // Additionally, for each of the nonmatching predicates that
2315             // we pass over, we sum up the set of number of vtable
2316             // entries, so that we can compute the offset for the selected
2317             // trait.
2318             vtable_base =
2319                 nonmatching.map(|t| tcx.count_own_vtable_entries(t))
2320                            .sum();
2321
2322         }
2323
2324         VtableObjectData {
2325             upcast_trait_ref: upcast_trait_ref.unwrap(),
2326             vtable_base: vtable_base,
2327             nested: vec![]
2328         }
2329     }
2330
2331     fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
2332         -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
2333     {
2334         debug!("confirm_fn_pointer_candidate({:?})",
2335                obligation);
2336
2337         // ok to skip binder; it is reintroduced below
2338         let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2339         let sig = self_ty.fn_sig();
2340         let trait_ref =
2341             self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2342                                                          self_ty,
2343                                                          sig,
2344                                                          util::TupleArgumentsFlag::Yes)
2345             .map_bound(|(trait_ref, _)| trait_ref);
2346
2347         self.confirm_poly_trait_refs(obligation.cause.clone(),
2348                                      obligation.predicate.to_poly_trait_ref(),
2349                                      trait_ref)?;
2350         Ok(VtableFnPointerData { fn_ty: self_ty, nested: vec![] })
2351     }
2352
2353     fn confirm_closure_candidate(&mut self,
2354                                  obligation: &TraitObligation<'tcx>,
2355                                  closure_def_id: DefId,
2356                                  substs: ty::ClosureSubsts<'tcx>,
2357                                  kind: ty::ClosureKind)
2358                                  -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2359                                            SelectionError<'tcx>>
2360     {
2361         debug!("confirm_closure_candidate({:?},{:?},{:?})",
2362                obligation,
2363                closure_def_id,
2364                substs);
2365
2366         let Normalized {
2367             value: trait_ref,
2368             mut obligations
2369         } = self.closure_trait_ref(obligation, closure_def_id, substs);
2370
2371         debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2372                closure_def_id,
2373                trait_ref,
2374                obligations);
2375
2376         self.confirm_poly_trait_refs(obligation.cause.clone(),
2377                                      obligation.predicate.to_poly_trait_ref(),
2378                                      trait_ref)?;
2379
2380         obligations.push(Obligation::new(
2381                 obligation.cause.clone(),
2382                 ty::Predicate::ClosureKind(closure_def_id, kind)));
2383
2384         Ok(VtableClosureData {
2385             closure_def_id: closure_def_id,
2386             substs: substs.clone(),
2387             nested: obligations
2388         })
2389     }
2390
2391     /// In the case of closure types and fn pointers,
2392     /// we currently treat the input type parameters on the trait as
2393     /// outputs. This means that when we have a match we have only
2394     /// considered the self type, so we have to go back and make sure
2395     /// to relate the argument types too.  This is kind of wrong, but
2396     /// since we control the full set of impls, also not that wrong,
2397     /// and it DOES yield better error messages (since we don't report
2398     /// errors as if there is no applicable impl, but rather report
2399     /// errors are about mismatched argument types.
2400     ///
2401     /// Here is an example. Imagine we have a closure expression
2402     /// and we desugared it so that the type of the expression is
2403     /// `Closure`, and `Closure` expects an int as argument. Then it
2404     /// is "as if" the compiler generated this impl:
2405     ///
2406     ///     impl Fn(int) for Closure { ... }
2407     ///
2408     /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2409     /// we have matched the self-type `Closure`. At this point we'll
2410     /// compare the `int` to `usize` and generate an error.
2411     ///
2412     /// Note that this checking occurs *after* the impl has selected,
2413     /// because these output type parameters should not affect the
2414     /// selection of the impl. Therefore, if there is a mismatch, we
2415     /// report an error to the user.
2416     fn confirm_poly_trait_refs(&mut self,
2417                                obligation_cause: ObligationCause<'tcx>,
2418                                obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2419                                expected_trait_ref: ty::PolyTraitRef<'tcx>)
2420                                -> Result<(), SelectionError<'tcx>>
2421     {
2422         let obligation_trait_ref = obligation_trait_ref.clone();
2423         self.infcx.sub_poly_trait_refs(false,
2424                                        obligation_cause.clone(),
2425                                        expected_trait_ref.clone(),
2426                                        obligation_trait_ref.clone())
2427             .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2428             .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2429     }
2430
2431     fn confirm_builtin_unsize_candidate(&mut self,
2432                                         obligation: &TraitObligation<'tcx>,)
2433                                         -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2434                                                   SelectionError<'tcx>> {
2435         let tcx = self.tcx();
2436
2437         // assemble_candidates_for_unsizing should ensure there are no late bound
2438         // regions here. See the comment there for more details.
2439         let source = self.infcx.shallow_resolve(
2440             tcx.no_late_bound_regions(&obligation.self_ty()).unwrap());
2441         let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
2442         let target = self.infcx.shallow_resolve(target);
2443
2444         debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2445                source, target);
2446
2447         let mut nested = vec![];
2448         match (&source.sty, &target.sty) {
2449             // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2450             (&ty::TyDynamic(ref data_a, r_a), &ty::TyDynamic(ref data_b, r_b)) => {
2451                 // See assemble_candidates_for_unsizing for more info.
2452                 // Binders reintroduced below in call to mk_existential_predicates.
2453                 let principal = data_a.skip_binder().principal();
2454                 let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
2455                     .chain(data_a.skip_binder().projection_bounds()
2456                            .map(|x| ty::ExistentialPredicate::Projection(x)))
2457                     .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
2458                 let new_trait = tcx.mk_dynamic(
2459                     ty::Binder(tcx.mk_existential_predicates(iter)), r_b);
2460                 let InferOk { obligations, .. } =
2461                     self.infcx.eq_types(false, &obligation.cause, new_trait, target)
2462                     .map_err(|_| Unimplemented)?;
2463                 self.inferred_obligations.extend(obligations);
2464
2465                 // Register one obligation for 'a: 'b.
2466                 let cause = ObligationCause::new(obligation.cause.span,
2467                                                  obligation.cause.body_id,
2468                                                  ObjectCastObligation(target));
2469                 let outlives = ty::OutlivesPredicate(r_a, r_b);
2470                 nested.push(Obligation::with_depth(cause,
2471                                                    obligation.recursion_depth + 1,
2472                                                    ty::Binder(outlives).to_predicate()));
2473             }
2474
2475             // T -> Trait.
2476             (_, &ty::TyDynamic(ref data, r)) => {
2477                 let mut object_dids =
2478                     data.auto_traits().chain(data.principal().map(|p| p.def_id()));
2479                 if let Some(did) = object_dids.find(|did| {
2480                     !tcx.is_object_safe(*did)
2481                 }) {
2482                     return Err(TraitNotObjectSafe(did))
2483                 }
2484
2485                 let cause = ObligationCause::new(obligation.cause.span,
2486                                                  obligation.cause.body_id,
2487                                                  ObjectCastObligation(target));
2488                 let mut push = |predicate| {
2489                     nested.push(Obligation::with_depth(cause.clone(),
2490                                                        obligation.recursion_depth + 1,
2491                                                        predicate));
2492                 };
2493
2494                 // Create obligations:
2495                 //  - Casting T to Trait
2496                 //  - For all the various builtin bounds attached to the object cast. (In other
2497                 //  words, if the object type is Foo+Send, this would create an obligation for the
2498                 //  Send check.)
2499                 //  - Projection predicates
2500                 for predicate in data.iter() {
2501                     push(predicate.with_self_ty(tcx, source));
2502                 }
2503
2504                 // We can only make objects from sized types.
2505                 let tr = ty::TraitRef {
2506                     def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
2507                     substs: tcx.mk_substs_trait(source, &[]),
2508                 };
2509                 push(tr.to_predicate());
2510
2511                 // If the type is `Foo+'a`, ensures that the type
2512                 // being cast to `Foo+'a` outlives `'a`:
2513                 let outlives = ty::OutlivesPredicate(source, r);
2514                 push(ty::Binder(outlives).to_predicate());
2515             }
2516
2517             // [T; n] -> [T].
2518             (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2519                 let InferOk { obligations, .. } =
2520                     self.infcx.eq_types(false, &obligation.cause, a, b)
2521                     .map_err(|_| Unimplemented)?;
2522                 self.inferred_obligations.extend(obligations);
2523             }
2524
2525             // Struct<T> -> Struct<U>.
2526             (&ty::TyAdt(def, substs_a), &ty::TyAdt(_, substs_b)) => {
2527                 let fields = def
2528                     .all_fields()
2529                     .map(|f| tcx.type_of(f.did))
2530                     .collect::<Vec<_>>();
2531
2532                 // The last field of the structure has to exist and contain type parameters.
2533                 let field = if let Some(&field) = fields.last() {
2534                     field
2535                 } else {
2536                     return Err(Unimplemented);
2537                 };
2538                 let mut ty_params = BitVector::new(substs_a.types().count());
2539                 let mut found = false;
2540                 for ty in field.walk() {
2541                     if let ty::TyParam(p) = ty.sty {
2542                         ty_params.insert(p.idx as usize);
2543                         found = true;
2544                     }
2545                 }
2546                 if !found {
2547                     return Err(Unimplemented);
2548                 }
2549
2550                 // Replace type parameters used in unsizing with
2551                 // TyError and ensure they do not affect any other fields.
2552                 // This could be checked after type collection for any struct
2553                 // with a potentially unsized trailing field.
2554                 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2555                     if ty_params.contains(i) {
2556                         Kind::from(tcx.types.err)
2557                     } else {
2558                         k
2559                     }
2560                 });
2561                 let substs = tcx.mk_substs(params);
2562                 for &ty in fields.split_last().unwrap().1 {
2563                     if ty.subst(tcx, substs).references_error() {
2564                         return Err(Unimplemented);
2565                     }
2566                 }
2567
2568                 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2569                 let inner_source = field.subst(tcx, substs_a);
2570                 let inner_target = field.subst(tcx, substs_b);
2571
2572                 // Check that the source structure with the target's
2573                 // type parameters is a subtype of the target.
2574                 let params = substs_a.iter().enumerate().map(|(i, &k)| {
2575                     if ty_params.contains(i) {
2576                         Kind::from(substs_b.type_at(i))
2577                     } else {
2578                         k
2579                     }
2580                 });
2581                 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
2582                 let InferOk { obligations, .. } =
2583                     self.infcx.eq_types(false, &obligation.cause, new_struct, target)
2584                     .map_err(|_| Unimplemented)?;
2585                 self.inferred_obligations.extend(obligations);
2586
2587                 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2588                 nested.push(tcx.predicate_for_trait_def(
2589                     obligation.cause.clone(),
2590                     obligation.predicate.def_id(),
2591                     obligation.recursion_depth + 1,
2592                     inner_source,
2593                     &[inner_target]));
2594             }
2595
2596             _ => bug!()
2597         };
2598
2599         Ok(VtableBuiltinData { nested: nested })
2600     }
2601
2602     ///////////////////////////////////////////////////////////////////////////
2603     // Matching
2604     //
2605     // Matching is a common path used for both evaluation and
2606     // confirmation.  It basically unifies types that appear in impls
2607     // and traits. This does affect the surrounding environment;
2608     // therefore, when used during evaluation, match routines must be
2609     // run inside of a `probe()` so that their side-effects are
2610     // contained.
2611
2612     fn rematch_impl(&mut self,
2613                     impl_def_id: DefId,
2614                     obligation: &TraitObligation<'tcx>,
2615                     snapshot: &infer::CombinedSnapshot)
2616                     -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
2617                         infer::SkolemizationMap<'tcx>)
2618     {
2619         match self.match_impl(impl_def_id, obligation, snapshot) {
2620             Ok((substs, skol_map)) => (substs, skol_map),
2621             Err(()) => {
2622                 bug!("Impl {:?} was matchable against {:?} but now is not",
2623                      impl_def_id,
2624                      obligation);
2625             }
2626         }
2627     }
2628
2629     fn match_impl(&mut self,
2630                   impl_def_id: DefId,
2631                   obligation: &TraitObligation<'tcx>,
2632                   snapshot: &infer::CombinedSnapshot)
2633                   -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
2634                              infer::SkolemizationMap<'tcx>), ()>
2635     {
2636         let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2637
2638         // Before we create the substitutions and everything, first
2639         // consider a "quick reject". This avoids creating more types
2640         // and so forth that we need to.
2641         if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2642             return Err(());
2643         }
2644
2645         let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
2646             &obligation.predicate,
2647             snapshot);
2648         let skol_obligation_trait_ref = skol_obligation.trait_ref;
2649
2650         let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
2651                                                            impl_def_id);
2652
2653         let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2654                                                   impl_substs);
2655
2656         let impl_trait_ref =
2657             project::normalize_with_depth(self,
2658                                           obligation.cause.clone(),
2659                                           obligation.recursion_depth + 1,
2660                                           &impl_trait_ref);
2661
2662         debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
2663                impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2664                impl_def_id,
2665                obligation,
2666                impl_trait_ref,
2667                skol_obligation_trait_ref);
2668
2669         let InferOk { obligations, .. } =
2670             self.infcx.eq_trait_refs(false,
2671                                      &obligation.cause,
2672                                      impl_trait_ref.value.clone(),
2673                                      skol_obligation_trait_ref)
2674             .map_err(|e| {
2675                 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
2676                 ()
2677             })?;
2678         self.inferred_obligations.extend(obligations);
2679
2680         if let Err(e) = self.infcx.leak_check(false,
2681                                               obligation.cause.span,
2682                                               &skol_map,
2683                                               snapshot) {
2684             debug!("match_impl: failed leak check due to `{}`", e);
2685             return Err(());
2686         }
2687
2688         debug!("match_impl: success impl_substs={:?}", impl_substs);
2689         Ok((Normalized {
2690             value: impl_substs,
2691             obligations: impl_trait_ref.obligations
2692         }, skol_map))
2693     }
2694
2695     fn fast_reject_trait_refs(&mut self,
2696                               obligation: &TraitObligation,
2697                               impl_trait_ref: &ty::TraitRef)
2698                               -> bool
2699     {
2700         // We can avoid creating type variables and doing the full
2701         // substitution if we find that any of the input types, when
2702         // simplified, do not match.
2703
2704         obligation.predicate.skip_binder().input_types()
2705             .zip(impl_trait_ref.input_types())
2706             .any(|(obligation_ty, impl_ty)| {
2707                 let simplified_obligation_ty =
2708                     fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2709                 let simplified_impl_ty =
2710                     fast_reject::simplify_type(self.tcx(), impl_ty, false);
2711
2712                 simplified_obligation_ty.is_some() &&
2713                     simplified_impl_ty.is_some() &&
2714                     simplified_obligation_ty != simplified_impl_ty
2715             })
2716     }
2717
2718     /// Normalize `where_clause_trait_ref` and try to match it against
2719     /// `obligation`.  If successful, return any predicates that
2720     /// result from the normalization. Normalization is necessary
2721     /// because where-clauses are stored in the parameter environment
2722     /// unnormalized.
2723     fn match_where_clause_trait_ref(&mut self,
2724                                     obligation: &TraitObligation<'tcx>,
2725                                     where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2726                                     -> Result<Vec<PredicateObligation<'tcx>>,()>
2727     {
2728         self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
2729         Ok(Vec::new())
2730     }
2731
2732     /// Returns `Ok` if `poly_trait_ref` being true implies that the
2733     /// obligation is satisfied.
2734     fn match_poly_trait_ref(&mut self,
2735                             obligation: &TraitObligation<'tcx>,
2736                             poly_trait_ref: ty::PolyTraitRef<'tcx>)
2737                             -> Result<(),()>
2738     {
2739         debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2740                obligation,
2741                poly_trait_ref);
2742
2743         self.infcx.sub_poly_trait_refs(false,
2744                                        obligation.cause.clone(),
2745                                        poly_trait_ref,
2746                                        obligation.predicate.to_poly_trait_ref())
2747             .map(|InferOk { obligations, .. }| self.inferred_obligations.extend(obligations))
2748             .map_err(|_| ())
2749     }
2750
2751     ///////////////////////////////////////////////////////////////////////////
2752     // Miscellany
2753
2754     fn match_fresh_trait_refs(&self,
2755                               previous: &ty::PolyTraitRef<'tcx>,
2756                               current: &ty::PolyTraitRef<'tcx>)
2757                               -> bool
2758     {
2759         let mut matcher = ty::_match::Match::new(self.tcx());
2760         matcher.relate(previous, current).is_ok()
2761     }
2762
2763     fn push_stack<'o,'s:'o>(&mut self,
2764                             previous_stack: TraitObligationStackList<'s, 'tcx>,
2765                             obligation: &'o TraitObligation<'tcx>)
2766                             -> TraitObligationStack<'o, 'tcx>
2767     {
2768         let fresh_trait_ref =
2769             obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2770
2771         TraitObligationStack {
2772             obligation: obligation,
2773             fresh_trait_ref: fresh_trait_ref,
2774             previous: previous_stack,
2775         }
2776     }
2777
2778     fn closure_trait_ref_unnormalized(&mut self,
2779                                       obligation: &TraitObligation<'tcx>,
2780                                       closure_def_id: DefId,
2781                                       substs: ty::ClosureSubsts<'tcx>)
2782                                       -> ty::PolyTraitRef<'tcx>
2783     {
2784         let closure_type = self.infcx.closure_type(closure_def_id)
2785             .subst(self.tcx(), substs.substs);
2786         let ty::Binder((trait_ref, _)) =
2787             self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
2788                                                          obligation.predicate.0.self_ty(), // (1)
2789                                                          closure_type,
2790                                                          util::TupleArgumentsFlag::No);
2791         // (1) Feels icky to skip the binder here, but OTOH we know
2792         // that the self-type is an unboxed closure type and hence is
2793         // in fact unparameterized (or at least does not reference any
2794         // regions bound in the obligation). Still probably some
2795         // refactoring could make this nicer.
2796
2797         ty::Binder(trait_ref)
2798     }
2799
2800     fn closure_trait_ref(&mut self,
2801                          obligation: &TraitObligation<'tcx>,
2802                          closure_def_id: DefId,
2803                          substs: ty::ClosureSubsts<'tcx>)
2804                          -> Normalized<'tcx, ty::PolyTraitRef<'tcx>>
2805     {
2806         let trait_ref = self.closure_trait_ref_unnormalized(
2807             obligation, closure_def_id, substs);
2808
2809         // A closure signature can contain associated types which
2810         // must be normalized.
2811         normalize_with_depth(self,
2812                              obligation.cause.clone(),
2813                              obligation.recursion_depth+1,
2814                              &trait_ref)
2815     }
2816
2817     /// Returns the obligations that are implied by instantiating an
2818     /// impl or trait. The obligations are substituted and fully
2819     /// normalized. This is used when confirming an impl or default
2820     /// impl.
2821     fn impl_or_trait_obligations(&mut self,
2822                                  cause: ObligationCause<'tcx>,
2823                                  recursion_depth: usize,
2824                                  def_id: DefId, // of impl or trait
2825                                  substs: &Substs<'tcx>, // for impl or trait
2826                                  skol_map: infer::SkolemizationMap<'tcx>,
2827                                  snapshot: &infer::CombinedSnapshot)
2828                                  -> Vec<PredicateObligation<'tcx>>
2829     {
2830         debug!("impl_or_trait_obligations(def_id={:?})", def_id);
2831         let tcx = self.tcx();
2832
2833         // To allow for one-pass evaluation of the nested obligation,
2834         // each predicate must be preceded by the obligations required
2835         // to normalize it.
2836         // for example, if we have:
2837         //    impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
2838         // the impl will have the following predicates:
2839         //    <V as Iterator>::Item = U,
2840         //    U: Iterator, U: Sized,
2841         //    V: Iterator, V: Sized,
2842         //    <U as Iterator>::Item: Copy
2843         // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2844         // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2845         // `$1: Copy`, so we must ensure the obligations are emitted in
2846         // that order.
2847         let predicates = tcx.predicates_of(def_id);
2848         assert_eq!(predicates.parent, None);
2849         let predicates = predicates.predicates.iter().flat_map(|predicate| {
2850             let predicate = normalize_with_depth(self, cause.clone(), recursion_depth,
2851                                                  &predicate.subst(tcx, substs));
2852             predicate.obligations.into_iter().chain(
2853                 Some(Obligation {
2854                     cause: cause.clone(),
2855                     recursion_depth: recursion_depth,
2856                     predicate: predicate.value
2857                 }))
2858         }).collect();
2859         self.infcx().plug_leaks(skol_map, snapshot, predicates)
2860     }
2861 }
2862
2863 impl<'tcx> TraitObligation<'tcx> {
2864     #[allow(unused_comparisons)]
2865     pub fn derived_cause(&self,
2866                         variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
2867                         -> ObligationCause<'tcx>
2868     {
2869         /*!
2870          * Creates a cause for obligations that are derived from
2871          * `obligation` by a recursive search (e.g., for a builtin
2872          * bound, or eventually a `impl Foo for ..`). If `obligation`
2873          * is itself a derived obligation, this is just a clone, but
2874          * otherwise we create a "derived obligation" cause so as to
2875          * keep track of the original root obligation for error
2876          * reporting.
2877          */
2878
2879         let obligation = self;
2880
2881         // NOTE(flaper87): As of now, it keeps track of the whole error
2882         // chain. Ideally, we should have a way to configure this either
2883         // by using -Z verbose or just a CLI argument.
2884         if obligation.recursion_depth >= 0 {
2885             let derived_cause = DerivedObligationCause {
2886                 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2887                 parent_code: Rc::new(obligation.cause.code.clone())
2888             };
2889             let derived_code = variant(derived_cause);
2890             ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2891         } else {
2892             obligation.cause.clone()
2893         }
2894     }
2895 }
2896
2897 impl<'tcx> SelectionCache<'tcx> {
2898     pub fn new() -> SelectionCache<'tcx> {
2899         SelectionCache {
2900             hashmap: RefCell::new(FxHashMap())
2901         }
2902     }
2903 }
2904
2905 impl<'tcx> EvaluationCache<'tcx> {
2906     pub fn new() -> EvaluationCache<'tcx> {
2907         EvaluationCache {
2908             hashmap: RefCell::new(FxHashMap())
2909         }
2910     }
2911 }
2912
2913 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
2914     fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
2915         TraitObligationStackList::with(self)
2916     }
2917
2918     fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
2919         self.list()
2920     }
2921 }
2922
2923 #[derive(Copy, Clone)]
2924 struct TraitObligationStackList<'o,'tcx:'o> {
2925     head: Option<&'o TraitObligationStack<'o,'tcx>>
2926 }
2927
2928 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
2929     fn empty() -> TraitObligationStackList<'o,'tcx> {
2930         TraitObligationStackList { head: None }
2931     }
2932
2933     fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
2934         TraitObligationStackList { head: Some(r) }
2935     }
2936 }
2937
2938 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
2939     type Item = &'o TraitObligationStack<'o,'tcx>;
2940
2941     fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
2942         match self.head {
2943             Some(o) => {
2944                 *self = o.previous;
2945                 Some(o)
2946             }
2947             None => None
2948         }
2949     }
2950 }
2951
2952 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
2953     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2954         write!(f, "TraitObligationStack({:?})", self.obligation)
2955     }
2956 }
2957
2958 impl EvaluationResult {
2959     fn may_apply(&self) -> bool {
2960         match *self {
2961             EvaluatedToOk |
2962             EvaluatedToAmbig |
2963             EvaluatedToUnknown => true,
2964
2965             EvaluatedToErr => false
2966         }
2967     }
2968 }