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