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