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