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