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