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