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