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