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