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