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