]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/select.rs
Rollup merge of #64296 - KodrAus:chore/iter_order_by, r=Centril
[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
1330     fn filter_negative_impls(
1331         &self,
1332         candidate: SelectionCandidate<'tcx>,
1333     ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1334         if let ImplCandidate(def_id) = candidate {
1335             if !self.allow_negative_impls
1336                 && self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative
1337             {
1338                 return Err(Unimplemented);
1339             }
1340         }
1341         Ok(Some(candidate))
1342     }
1343
1344     fn candidate_from_obligation_no_cache<'o>(
1345         &mut self,
1346         stack: &TraitObligationStack<'o, 'tcx>,
1347     ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1348         if stack.obligation.predicate.references_error() {
1349             // If we encounter a `Error`, we generally prefer the
1350             // most "optimistic" result in response -- that is, the
1351             // one least likely to report downstream errors. But
1352             // because this routine is shared by coherence and by
1353             // trait selection, there isn't an obvious "right" choice
1354             // here in that respect, so we opt to just return
1355             // ambiguity and let the upstream clients sort it out.
1356             return Ok(None);
1357         }
1358
1359         if let Some(conflict) = self.is_knowable(stack) {
1360             debug!("coherence stage: not knowable");
1361             if self.intercrate_ambiguity_causes.is_some() {
1362                 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1363                 // Heuristics: show the diagnostics when there are no candidates in crate.
1364                 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1365                     let mut no_candidates_apply = true;
1366                     {
1367                         let evaluated_candidates = candidate_set
1368                             .vec
1369                             .iter()
1370                             .map(|c| self.evaluate_candidate(stack, &c));
1371
1372                         for ec in evaluated_candidates {
1373                             match ec {
1374                                 Ok(c) => {
1375                                     if c.may_apply() {
1376                                         no_candidates_apply = false;
1377                                         break;
1378                                     }
1379                                 }
1380                                 Err(e) => return Err(e.into()),
1381                             }
1382                         }
1383                     }
1384
1385                     if !candidate_set.ambiguous && no_candidates_apply {
1386                         let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1387                         let self_ty = trait_ref.self_ty();
1388                         let trait_desc = trait_ref.to_string();
1389                         let self_desc = if self_ty.has_concrete_skeleton() {
1390                             Some(self_ty.to_string())
1391                         } else {
1392                             None
1393                         };
1394                         let cause = if let Conflict::Upstream = conflict {
1395                             IntercrateAmbiguityCause::UpstreamCrateUpdate {
1396                                 trait_desc,
1397                                 self_desc,
1398                             }
1399                         } else {
1400                             IntercrateAmbiguityCause::DownstreamCrate {
1401                                 trait_desc,
1402                                 self_desc,
1403                             }
1404                         };
1405                         debug!("evaluate_stack: pushing cause = {:?}", cause);
1406                         self.intercrate_ambiguity_causes
1407                             .as_mut()
1408                             .unwrap()
1409                             .push(cause);
1410                     }
1411                 }
1412             }
1413             return Ok(None);
1414         }
1415
1416         let candidate_set = self.assemble_candidates(stack)?;
1417
1418         if candidate_set.ambiguous {
1419             debug!("candidate set contains ambig");
1420             return Ok(None);
1421         }
1422
1423         let mut candidates = candidate_set.vec;
1424
1425         debug!(
1426             "assembled {} candidates for {:?}: {:?}",
1427             candidates.len(),
1428             stack,
1429             candidates
1430         );
1431
1432         // At this point, we know that each of the entries in the
1433         // candidate set is *individually* applicable. Now we have to
1434         // figure out if they contain mutual incompatibilities. This
1435         // frequently arises if we have an unconstrained input type --
1436         // for example, we are looking for $0:Eq where $0 is some
1437         // unconstrained type variable. In that case, we'll get a
1438         // candidate which assumes $0 == int, one that assumes $0 ==
1439         // usize, etc. This spells an ambiguity.
1440
1441         // If there is more than one candidate, first winnow them down
1442         // by considering extra conditions (nested obligations and so
1443         // forth). We don't winnow if there is exactly one
1444         // candidate. This is a relatively minor distinction but it
1445         // can lead to better inference and error-reporting. An
1446         // example would be if there was an impl:
1447         //
1448         //     impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1449         //
1450         // and we were to see some code `foo.push_clone()` where `boo`
1451         // is a `Vec<Bar>` and `Bar` does not implement `Clone`.  If
1452         // we were to winnow, we'd wind up with zero candidates.
1453         // Instead, we select the right impl now but report `Bar does
1454         // not implement Clone`.
1455         if candidates.len() == 1 {
1456             return self.filter_negative_impls(candidates.pop().unwrap());
1457         }
1458
1459         // Winnow, but record the exact outcome of evaluation, which
1460         // is needed for specialization. Propagate overflow if it occurs.
1461         let mut candidates = candidates
1462             .into_iter()
1463             .map(|c| match self.evaluate_candidate(stack, &c) {
1464                 Ok(eval) if eval.may_apply() => Ok(Some(EvaluatedCandidate {
1465                     candidate: c,
1466                     evaluation: eval,
1467                 })),
1468                 Ok(_) => Ok(None),
1469                 Err(OverflowError) => Err(Overflow),
1470             })
1471             .flat_map(Result::transpose)
1472             .collect::<Result<Vec<_>, _>>()?;
1473
1474         debug!(
1475             "winnowed to {} candidates for {:?}: {:?}",
1476             candidates.len(),
1477             stack,
1478             candidates
1479         );
1480
1481         // If there are STILL multiple candidates, we can further
1482         // reduce the list by dropping duplicates -- including
1483         // resolving specializations.
1484         if candidates.len() > 1 {
1485             let mut i = 0;
1486             while i < candidates.len() {
1487                 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1488                     self.candidate_should_be_dropped_in_favor_of(&candidates[i], &candidates[j])
1489                 });
1490                 if is_dup {
1491                     debug!(
1492                         "Dropping candidate #{}/{}: {:?}",
1493                         i,
1494                         candidates.len(),
1495                         candidates[i]
1496                     );
1497                     candidates.swap_remove(i);
1498                 } else {
1499                     debug!(
1500                         "Retaining candidate #{}/{}: {:?}",
1501                         i,
1502                         candidates.len(),
1503                         candidates[i]
1504                     );
1505                     i += 1;
1506
1507                     // If there are *STILL* multiple candidates, give up
1508                     // and report ambiguity.
1509                     if i > 1 {
1510                         debug!("multiple matches, ambig");
1511                         return Ok(None);
1512                     }
1513                 }
1514             }
1515         }
1516
1517         // If there are *NO* candidates, then there are no impls --
1518         // that we know of, anyway. Note that in the case where there
1519         // are unbound type variables within the obligation, it might
1520         // be the case that you could still satisfy the obligation
1521         // from another crate by instantiating the type variables with
1522         // a type from another crate that does have an impl. This case
1523         // is checked for in `evaluate_stack` (and hence users
1524         // who might care about this case, like coherence, should use
1525         // that function).
1526         if candidates.is_empty() {
1527             return Err(Unimplemented);
1528         }
1529
1530         // Just one candidate left.
1531         self.filter_negative_impls(candidates.pop().unwrap().candidate)
1532     }
1533
1534     fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1535         debug!("is_knowable(intercrate={:?})", self.intercrate);
1536
1537         if !self.intercrate.is_some() {
1538             return None;
1539         }
1540
1541         let obligation = &stack.obligation;
1542         let predicate = self.infcx()
1543             .resolve_vars_if_possible(&obligation.predicate);
1544
1545         // Okay to skip binder because of the nature of the
1546         // trait-ref-is-knowable check, which does not care about
1547         // bound regions.
1548         let trait_ref = predicate.skip_binder().trait_ref;
1549
1550         let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1551         if let (
1552             Some(Conflict::Downstream {
1553                 used_to_be_broken: true,
1554             }),
1555             Some(IntercrateMode::Issue43355),
1556         ) = (result, self.intercrate)
1557         {
1558             debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1559             None
1560         } else {
1561             result
1562         }
1563     }
1564
1565     /// Returns `true` if the global caches can be used.
1566     /// Do note that if the type itself is not in the
1567     /// global tcx, the local caches will be used.
1568     fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1569         // If there are any where-clauses in scope, then we always use
1570         // a cache local to this particular scope. Otherwise, we
1571         // switch to a global cache. We used to try and draw
1572         // finer-grained distinctions, but that led to a serious of
1573         // annoying and weird bugs like #22019 and #18290. This simple
1574         // rule seems to be pretty clearly safe and also still retains
1575         // a very high hit rate (~95% when compiling rustc).
1576         if !param_env.caller_bounds.is_empty() {
1577             return false;
1578         }
1579
1580         // Avoid using the master cache during coherence and just rely
1581         // on the local cache. This effectively disables caching
1582         // during coherence. It is really just a simplification to
1583         // avoid us having to fear that coherence results "pollute"
1584         // the master cache. Since coherence executes pretty quickly,
1585         // it's not worth going to more trouble to increase the
1586         // hit-rate I don't think.
1587         if self.intercrate.is_some() {
1588             return false;
1589         }
1590
1591         // Otherwise, we can use the global cache.
1592         true
1593     }
1594
1595     fn check_candidate_cache(
1596         &mut self,
1597         param_env: ty::ParamEnv<'tcx>,
1598         cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1599     ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1600         let tcx = self.tcx();
1601         let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1602         if self.can_use_global_caches(param_env) {
1603             let cache = tcx.selection_cache.hashmap.borrow();
1604             if let Some(cached) = cache.get(&trait_ref) {
1605                 return Some(cached.get(tcx));
1606             }
1607         }
1608         self.infcx
1609             .selection_cache
1610             .hashmap
1611             .borrow()
1612             .get(trait_ref)
1613             .map(|v| v.get(tcx))
1614     }
1615
1616     /// Determines whether can we safely cache the result
1617     /// of selecting an obligation. This is almost always 'true',
1618     /// except when dealing with certain ParamCandidates.
1619     ///
1620     /// Ordinarily, a ParamCandidate will contain no inference variables,
1621     /// since it was usually produced directly from a DefId. However,
1622     /// certain cases (currently only librustdoc's blanket impl finder),
1623     /// a ParamEnv may be explicitly constructed with inference types.
1624     /// When this is the case, we do *not* want to cache the resulting selection
1625     /// candidate. This is due to the fact that it might not always be possible
1626     /// to equate the obligation's trait ref and the candidate's trait ref,
1627     /// if more constraints end up getting added to an inference variable.
1628     ///
1629     /// Because of this, we always want to re-run the full selection
1630     /// process for our obligation the next time we see it, since
1631     /// we might end up picking a different SelectionCandidate (or none at all)
1632     fn can_cache_candidate(&self,
1633         result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>
1634      ) -> bool {
1635         match result {
1636             Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => {
1637                 !trait_ref.skip_binder().input_types().any(|t| t.walk().any(|t_| t_.is_ty_infer()))
1638             },
1639             _ => true
1640         }
1641     }
1642
1643     fn insert_candidate_cache(
1644         &mut self,
1645         param_env: ty::ParamEnv<'tcx>,
1646         cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1647         dep_node: DepNodeIndex,
1648         candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1649     ) {
1650         let tcx = self.tcx();
1651         let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1652
1653         if !self.can_cache_candidate(&candidate) {
1654             debug!("insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1655                     candidate is not cacheable", trait_ref, candidate);
1656             return;
1657
1658         }
1659
1660         if self.can_use_global_caches(param_env) {
1661             if let Err(Overflow) = candidate {
1662                 // Don't cache overflow globally; we only produce this
1663                 // in certain modes.
1664             } else if !trait_ref.has_local_value() {
1665                 if !candidate.has_local_value() {
1666                     debug!(
1667                         "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1668                         trait_ref, candidate,
1669                     );
1670                     // This may overwrite the cache with the same value
1671                     tcx.selection_cache
1672                         .hashmap
1673                         .borrow_mut()
1674                         .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1675                     return;
1676                 }
1677             }
1678         }
1679
1680         debug!(
1681             "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1682             trait_ref, candidate,
1683         );
1684         self.infcx
1685             .selection_cache
1686             .hashmap
1687             .borrow_mut()
1688             .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1689     }
1690
1691     fn assemble_candidates<'o>(
1692         &mut self,
1693         stack: &TraitObligationStack<'o, 'tcx>,
1694     ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1695         let TraitObligationStack { obligation, .. } = *stack;
1696         let ref obligation = Obligation {
1697             param_env: obligation.param_env,
1698             cause: obligation.cause.clone(),
1699             recursion_depth: obligation.recursion_depth,
1700             predicate: self.infcx()
1701                 .resolve_vars_if_possible(&obligation.predicate),
1702         };
1703
1704         if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1705             // Self is a type variable (e.g., `_: AsRef<str>`).
1706             //
1707             // This is somewhat problematic, as the current scheme can't really
1708             // handle it turning to be a projection. This does end up as truly
1709             // ambiguous in most cases anyway.
1710             //
1711             // Take the fast path out - this also improves
1712             // performance by preventing assemble_candidates_from_impls from
1713             // matching every impl for this trait.
1714             return Ok(SelectionCandidateSet {
1715                 vec: vec![],
1716                 ambiguous: true,
1717             });
1718         }
1719
1720         let mut candidates = SelectionCandidateSet {
1721             vec: Vec::new(),
1722             ambiguous: false,
1723         };
1724
1725         self.assemble_candidates_for_trait_alias(obligation, &mut candidates)?;
1726
1727         // Other bounds. Consider both in-scope bounds from fn decl
1728         // and applicable impls. There is a certain set of precedence rules here.
1729         let def_id = obligation.predicate.def_id();
1730         let lang_items = self.tcx().lang_items();
1731
1732         if lang_items.copy_trait() == Some(def_id) {
1733             debug!(
1734                 "obligation self ty is {:?}",
1735                 obligation.predicate.skip_binder().self_ty()
1736             );
1737
1738             // User-defined copy impls are permitted, but only for
1739             // structs and enums.
1740             self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1741
1742             // For other types, we'll use the builtin rules.
1743             let copy_conditions = self.copy_clone_conditions(obligation);
1744             self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1745         } else if lang_items.sized_trait() == Some(def_id) {
1746             // Sized is never implementable by end-users, it is
1747             // always automatically computed.
1748             let sized_conditions = self.sized_conditions(obligation);
1749             self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1750         } else if lang_items.unsize_trait() == Some(def_id) {
1751             self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1752         } else {
1753             if lang_items.clone_trait() == Some(def_id) {
1754                 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
1755                 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1756                 // types have builtin support for `Clone`.
1757                 let clone_conditions = self.copy_clone_conditions(obligation);
1758                 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1759             }
1760
1761             self.assemble_generator_candidates(obligation, &mut candidates)?;
1762             self.assemble_closure_candidates(obligation, &mut candidates)?;
1763             self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1764             self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1765             self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1766         }
1767
1768         self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1769         self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1770         // Auto implementations have lower priority, so we only
1771         // consider triggering a default if there is no other impl that can apply.
1772         if candidates.vec.is_empty() {
1773             self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1774         }
1775         debug!("candidate list size: {}", candidates.vec.len());
1776         Ok(candidates)
1777     }
1778
1779     fn assemble_candidates_from_projected_tys(
1780         &mut self,
1781         obligation: &TraitObligation<'tcx>,
1782         candidates: &mut SelectionCandidateSet<'tcx>,
1783     ) {
1784         debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1785
1786         // before we go into the whole placeholder thing, just
1787         // quickly check if the self-type is a projection at all.
1788         match obligation.predicate.skip_binder().trait_ref.self_ty().sty {
1789             ty::Projection(_) | ty::Opaque(..) => {}
1790             ty::Infer(ty::TyVar(_)) => {
1791                 span_bug!(
1792                     obligation.cause.span,
1793                     "Self=_ should have been handled by assemble_candidates"
1794                 );
1795             }
1796             _ => return,
1797         }
1798
1799         let result = self.infcx.probe(|snapshot| {
1800             self.match_projection_obligation_against_definition_bounds(
1801                 obligation,
1802                 snapshot,
1803             )
1804         });
1805
1806         if result {
1807             candidates.vec.push(ProjectionCandidate);
1808         }
1809     }
1810
1811     fn match_projection_obligation_against_definition_bounds(
1812         &mut self,
1813         obligation: &TraitObligation<'tcx>,
1814         snapshot: &CombinedSnapshot<'_, 'tcx>,
1815     ) -> bool {
1816         let poly_trait_predicate = self.infcx()
1817             .resolve_vars_if_possible(&obligation.predicate);
1818         let (placeholder_trait_predicate, placeholder_map) = self.infcx()
1819             .replace_bound_vars_with_placeholders(&poly_trait_predicate);
1820         debug!(
1821             "match_projection_obligation_against_definition_bounds: \
1822              placeholder_trait_predicate={:?}",
1823             placeholder_trait_predicate,
1824         );
1825
1826         let (def_id, substs) = match placeholder_trait_predicate.trait_ref.self_ty().sty {
1827             ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1828             ty::Opaque(def_id, substs) => (def_id, substs),
1829             _ => {
1830                 span_bug!(
1831                     obligation.cause.span,
1832                     "match_projection_obligation_against_definition_bounds() called \
1833                      but self-ty is not a projection: {:?}",
1834                     placeholder_trait_predicate.trait_ref.self_ty()
1835                 );
1836             }
1837         };
1838         debug!(
1839             "match_projection_obligation_against_definition_bounds: \
1840              def_id={:?}, substs={:?}",
1841             def_id, substs
1842         );
1843
1844         let predicates_of = self.tcx().predicates_of(def_id);
1845         let bounds = predicates_of.instantiate(self.tcx(), substs);
1846         debug!(
1847             "match_projection_obligation_against_definition_bounds: \
1848              bounds={:?}",
1849             bounds
1850         );
1851
1852         let elaborated_predicates = util::elaborate_predicates(self.tcx(), bounds.predicates);
1853         let matching_bound = elaborated_predicates
1854             .filter_to_traits()
1855             .find(|bound| {
1856                 self.infcx.probe(|_| {
1857                     self.match_projection(
1858                         obligation,
1859                         bound.clone(),
1860                         placeholder_trait_predicate.trait_ref.clone(),
1861                         &placeholder_map,
1862                         snapshot,
1863                     )
1864                 })
1865             });
1866
1867         debug!(
1868             "match_projection_obligation_against_definition_bounds: \
1869              matching_bound={:?}",
1870             matching_bound
1871         );
1872         match matching_bound {
1873             None => false,
1874             Some(bound) => {
1875                 // Repeat the successful match, if any, this time outside of a probe.
1876                 let result = self.match_projection(
1877                     obligation,
1878                     bound,
1879                     placeholder_trait_predicate.trait_ref.clone(),
1880                     &placeholder_map,
1881                     snapshot,
1882                 );
1883
1884                 assert!(result);
1885                 true
1886             }
1887         }
1888     }
1889
1890     fn match_projection(
1891         &mut self,
1892         obligation: &TraitObligation<'tcx>,
1893         trait_bound: ty::PolyTraitRef<'tcx>,
1894         placeholder_trait_ref: ty::TraitRef<'tcx>,
1895         placeholder_map: &PlaceholderMap<'tcx>,
1896         snapshot: &CombinedSnapshot<'_, 'tcx>,
1897     ) -> bool {
1898         debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1899         self.infcx
1900             .at(&obligation.cause, obligation.param_env)
1901             .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1902             .is_ok()
1903             &&
1904             self.infcx.leak_check(false, placeholder_map, snapshot).is_ok()
1905     }
1906
1907     /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1908     /// supplied to find out whether it is listed among them.
1909     ///
1910     /// Never affects inference environment.
1911     fn assemble_candidates_from_caller_bounds<'o>(
1912         &mut self,
1913         stack: &TraitObligationStack<'o, 'tcx>,
1914         candidates: &mut SelectionCandidateSet<'tcx>,
1915     ) -> Result<(), SelectionError<'tcx>> {
1916         debug!(
1917             "assemble_candidates_from_caller_bounds({:?})",
1918             stack.obligation
1919         );
1920
1921         let all_bounds = stack
1922             .obligation
1923             .param_env
1924             .caller_bounds
1925             .iter()
1926             .filter_map(|o| o.to_opt_poly_trait_ref());
1927
1928         // Micro-optimization: filter out predicates relating to different traits.
1929         let matching_bounds =
1930             all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1931
1932         // Keep only those bounds which may apply, and propagate overflow if it occurs.
1933         let mut param_candidates = vec![];
1934         for bound in matching_bounds {
1935             let wc = self.evaluate_where_clause(stack, bound.clone())?;
1936             if wc.may_apply() {
1937                 param_candidates.push(ParamCandidate(bound));
1938             }
1939         }
1940
1941         candidates.vec.extend(param_candidates);
1942
1943         Ok(())
1944     }
1945
1946     fn evaluate_where_clause<'o>(
1947         &mut self,
1948         stack: &TraitObligationStack<'o, 'tcx>,
1949         where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1950     ) -> Result<EvaluationResult, OverflowError> {
1951         self.evaluation_probe(|this| {
1952             match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1953                 Ok(obligations) => {
1954                     this.evaluate_predicates_recursively(stack.list(), obligations.into_iter())
1955                 }
1956                 Err(()) => Ok(EvaluatedToErr),
1957             }
1958         })
1959     }
1960
1961     fn assemble_generator_candidates(
1962         &mut self,
1963         obligation: &TraitObligation<'tcx>,
1964         candidates: &mut SelectionCandidateSet<'tcx>,
1965     ) -> Result<(), SelectionError<'tcx>> {
1966         if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1967             return Ok(());
1968         }
1969
1970         // Okay to skip binder because the substs on generator types never
1971         // touch bound regions, they just capture the in-scope
1972         // type/region parameters.
1973         let self_ty = *obligation.self_ty().skip_binder();
1974         match self_ty.sty {
1975             ty::Generator(..) => {
1976                 debug!(
1977                     "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1978                     self_ty, obligation
1979                 );
1980
1981                 candidates.vec.push(GeneratorCandidate);
1982             }
1983             ty::Infer(ty::TyVar(_)) => {
1984                 debug!("assemble_generator_candidates: ambiguous self-type");
1985                 candidates.ambiguous = true;
1986             }
1987             _ => {}
1988         }
1989
1990         Ok(())
1991     }
1992
1993     /// Checks for the artificial impl that the compiler will create for an obligation like `X :
1994     /// FnMut<..>` where `X` is a closure type.
1995     ///
1996     /// Note: the type parameters on a closure candidate are modeled as *output* type
1997     /// parameters and hence do not affect whether this trait is a match or not. They will be
1998     /// unified during the confirmation step.
1999     fn assemble_closure_candidates(
2000         &mut self,
2001         obligation: &TraitObligation<'tcx>,
2002         candidates: &mut SelectionCandidateSet<'tcx>,
2003     ) -> Result<(), SelectionError<'tcx>> {
2004         let kind = match self.tcx()
2005             .lang_items()
2006             .fn_trait_kind(obligation.predicate.def_id())
2007         {
2008             Some(k) => k,
2009             None => {
2010                 return Ok(());
2011             }
2012         };
2013
2014         // Okay to skip binder because the substs on closure types never
2015         // touch bound regions, they just capture the in-scope
2016         // type/region parameters
2017         match obligation.self_ty().skip_binder().sty {
2018             ty::Closure(closure_def_id, closure_substs) => {
2019                 debug!(
2020                     "assemble_unboxed_candidates: kind={:?} obligation={:?}",
2021                     kind, obligation
2022                 );
2023                 match self.infcx.closure_kind(closure_def_id, closure_substs) {
2024                     Some(closure_kind) => {
2025                         debug!(
2026                             "assemble_unboxed_candidates: closure_kind = {:?}",
2027                             closure_kind
2028                         );
2029                         if closure_kind.extends(kind) {
2030                             candidates.vec.push(ClosureCandidate);
2031                         }
2032                     }
2033                     None => {
2034                         debug!("assemble_unboxed_candidates: closure_kind not yet known");
2035                         candidates.vec.push(ClosureCandidate);
2036                     }
2037                 }
2038             }
2039             ty::Infer(ty::TyVar(_)) => {
2040                 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
2041                 candidates.ambiguous = true;
2042             }
2043             _ => {}
2044         }
2045
2046         Ok(())
2047     }
2048
2049     /// Implement one of the `Fn()` family for a fn pointer.
2050     fn assemble_fn_pointer_candidates(
2051         &mut self,
2052         obligation: &TraitObligation<'tcx>,
2053         candidates: &mut SelectionCandidateSet<'tcx>,
2054     ) -> Result<(), SelectionError<'tcx>> {
2055         // We provide impl of all fn traits for fn pointers.
2056         if self.tcx()
2057             .lang_items()
2058             .fn_trait_kind(obligation.predicate.def_id())
2059             .is_none()
2060         {
2061             return Ok(());
2062         }
2063
2064         // Okay to skip binder because what we are inspecting doesn't involve bound regions
2065         let self_ty = *obligation.self_ty().skip_binder();
2066         match self_ty.sty {
2067             ty::Infer(ty::TyVar(_)) => {
2068                 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
2069                 candidates.ambiguous = true; // could wind up being a fn() type
2070             }
2071             // provide an impl, but only for suitable `fn` pointers
2072             ty::FnDef(..) | ty::FnPtr(_) => {
2073                 if let ty::FnSig {
2074                     unsafety: hir::Unsafety::Normal,
2075                     abi: Abi::Rust,
2076                     c_variadic: false,
2077                     ..
2078                 } = self_ty.fn_sig(self.tcx()).skip_binder()
2079                 {
2080                     candidates.vec.push(FnPointerCandidate);
2081                 }
2082             }
2083             _ => {}
2084         }
2085
2086         Ok(())
2087     }
2088
2089     /// Search for impls that might apply to `obligation`.
2090     fn assemble_candidates_from_impls(
2091         &mut self,
2092         obligation: &TraitObligation<'tcx>,
2093         candidates: &mut SelectionCandidateSet<'tcx>,
2094     ) -> Result<(), SelectionError<'tcx>> {
2095         debug!(
2096             "assemble_candidates_from_impls(obligation={:?})",
2097             obligation
2098         );
2099
2100         self.tcx().for_each_relevant_impl(
2101             obligation.predicate.def_id(),
2102             obligation.predicate.skip_binder().trait_ref.self_ty(),
2103             |impl_def_id| {
2104                 self.infcx.probe(|snapshot| {
2105                     if let Ok(_substs) = self.match_impl(impl_def_id, obligation, snapshot)
2106                     {
2107                         candidates.vec.push(ImplCandidate(impl_def_id));
2108                     }
2109                 });
2110             },
2111         );
2112
2113         Ok(())
2114     }
2115
2116     fn assemble_candidates_from_auto_impls(
2117         &mut self,
2118         obligation: &TraitObligation<'tcx>,
2119         candidates: &mut SelectionCandidateSet<'tcx>,
2120     ) -> Result<(), SelectionError<'tcx>> {
2121         // Okay to skip binder here because the tests we do below do not involve bound regions.
2122         let self_ty = *obligation.self_ty().skip_binder();
2123         debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
2124
2125         let def_id = obligation.predicate.def_id();
2126
2127         if self.tcx().trait_is_auto(def_id) {
2128             match self_ty.sty {
2129                 ty::Dynamic(..) => {
2130                     // For object types, we don't know what the closed
2131                     // over types are. This means we conservatively
2132                     // say nothing; a candidate may be added by
2133                     // `assemble_candidates_from_object_ty`.
2134                 }
2135                 ty::Foreign(..) => {
2136                     // Since the contents of foreign types is unknown,
2137                     // we don't add any `..` impl. Default traits could
2138                     // still be provided by a manual implementation for
2139                     // this trait and type.
2140                 }
2141                 ty::Param(..) | ty::Projection(..) => {
2142                     // In these cases, we don't know what the actual
2143                     // type is.  Therefore, we cannot break it down
2144                     // into its constituent types. So we don't
2145                     // consider the `..` impl but instead just add no
2146                     // candidates: this means that typeck will only
2147                     // succeed if there is another reason to believe
2148                     // that this obligation holds. That could be a
2149                     // where-clause or, in the case of an object type,
2150                     // it could be that the object type lists the
2151                     // trait (e.g., `Foo+Send : Send`). See
2152                     // `compile-fail/typeck-default-trait-impl-send-param.rs`
2153                     // for an example of a test case that exercises
2154                     // this path.
2155                 }
2156                 ty::Infer(ty::TyVar(_)) => {
2157                     // the auto impl might apply, we don't know
2158                     candidates.ambiguous = true;
2159                 }
2160                 ty::Generator(_, _, movability)
2161                     if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
2162                 {
2163                     match movability {
2164                         hir::GeneratorMovability::Static => {
2165                             // Immovable generators are never `Unpin`, so
2166                             // suppress the normal auto-impl candidate for it.
2167                         }
2168                         hir::GeneratorMovability::Movable => {
2169                             // Movable generators are always `Unpin`, so add an
2170                             // unconditional builtin candidate.
2171                             candidates.vec.push(BuiltinCandidate {
2172                                 has_nested: false,
2173                             });
2174                         }
2175                     }
2176                 }
2177
2178                 _ => candidates.vec.push(AutoImplCandidate(def_id.clone())),
2179             }
2180         }
2181
2182         Ok(())
2183     }
2184
2185     /// Search for impls that might apply to `obligation`.
2186     fn assemble_candidates_from_object_ty(
2187         &mut self,
2188         obligation: &TraitObligation<'tcx>,
2189         candidates: &mut SelectionCandidateSet<'tcx>,
2190     ) {
2191         debug!(
2192             "assemble_candidates_from_object_ty(self_ty={:?})",
2193             obligation.self_ty().skip_binder()
2194         );
2195
2196         self.infcx.probe(|_snapshot| {
2197             // The code below doesn't care about regions, and the
2198             // self-ty here doesn't escape this probe, so just erase
2199             // any LBR.
2200             let self_ty = self.tcx().erase_late_bound_regions(&obligation.self_ty());
2201             let poly_trait_ref = match self_ty.sty {
2202                 ty::Dynamic(ref data, ..) => {
2203                     if data.auto_traits()
2204                         .any(|did| did == obligation.predicate.def_id())
2205                     {
2206                         debug!(
2207                             "assemble_candidates_from_object_ty: matched builtin bound, \
2208                              pushing candidate"
2209                         );
2210                         candidates.vec.push(BuiltinObjectCandidate);
2211                         return;
2212                     }
2213
2214                     if let Some(principal) = data.principal() {
2215                         principal.with_self_ty(self.tcx(), self_ty)
2216                     } else {
2217                         // Only auto-trait bounds exist.
2218                         return;
2219                     }
2220                 }
2221                 ty::Infer(ty::TyVar(_)) => {
2222                     debug!("assemble_candidates_from_object_ty: ambiguous");
2223                     candidates.ambiguous = true; // could wind up being an object type
2224                     return;
2225                 }
2226                 _ => return,
2227             };
2228
2229             debug!(
2230                 "assemble_candidates_from_object_ty: poly_trait_ref={:?}",
2231                 poly_trait_ref
2232             );
2233
2234             // Count only those upcast versions that match the trait-ref
2235             // we are looking for. Specifically, do not only check for the
2236             // correct trait, but also the correct type parameters.
2237             // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
2238             // but `Foo` is declared as `trait Foo : Bar<u32>`.
2239             let upcast_trait_refs = util::supertraits(self.tcx(), poly_trait_ref)
2240                 .filter(|upcast_trait_ref| {
2241                     self.infcx.probe(|_| {
2242                         let upcast_trait_ref = upcast_trait_ref.clone();
2243                         self.match_poly_trait_ref(obligation, upcast_trait_ref)
2244                             .is_ok()
2245                     })
2246                 })
2247                 .count();
2248
2249             if upcast_trait_refs > 1 {
2250                 // Can be upcast in many ways; need more type information.
2251                 candidates.ambiguous = true;
2252             } else if upcast_trait_refs == 1 {
2253                 candidates.vec.push(ObjectCandidate);
2254             }
2255         })
2256     }
2257
2258     /// Search for unsizing that might apply to `obligation`.
2259     fn assemble_candidates_for_unsizing(
2260         &mut self,
2261         obligation: &TraitObligation<'tcx>,
2262         candidates: &mut SelectionCandidateSet<'tcx>,
2263     ) {
2264         // We currently never consider higher-ranked obligations e.g.
2265         // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
2266         // because they are a priori invalid, and we could potentially add support
2267         // for them later, it's just that there isn't really a strong need for it.
2268         // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
2269         // impl, and those are generally applied to concrete types.
2270         //
2271         // That said, one might try to write a fn with a where clause like
2272         //     for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
2273         // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
2274         // Still, you'd be more likely to write that where clause as
2275         //     T: Trait
2276         // so it seems ok if we (conservatively) fail to accept that `Unsize`
2277         // obligation above. Should be possible to extend this in the future.
2278         let source = match obligation.self_ty().no_bound_vars() {
2279             Some(t) => t,
2280             None => {
2281                 // Don't add any candidates if there are bound regions.
2282                 return;
2283             }
2284         };
2285         let target = obligation
2286             .predicate
2287             .skip_binder()
2288             .trait_ref
2289             .substs
2290             .type_at(1);
2291
2292         debug!(
2293             "assemble_candidates_for_unsizing(source={:?}, target={:?})",
2294             source, target
2295         );
2296
2297         let may_apply = match (&source.sty, &target.sty) {
2298             // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2299             (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
2300                 // Upcasts permit two things:
2301                 //
2302                 // 1. Dropping builtin bounds, e.g., `Foo+Send` to `Foo`
2303                 // 2. Tightening the region bound, e.g., `Foo+'a` to `Foo+'b` if `'a : 'b`
2304                 //
2305                 // Note that neither of these changes requires any
2306                 // change at runtime.  Eventually this will be
2307                 // generalized.
2308                 //
2309                 // We always upcast when we can because of reason
2310                 // #2 (region bounds).
2311                 data_a.principal_def_id() == data_b.principal_def_id()
2312                     && data_b.auto_traits()
2313                     // All of a's auto traits need to be in b's auto traits.
2314                     .all(|b| data_a.auto_traits().any(|a| a == b))
2315             }
2316
2317             // T -> Trait.
2318             (_, &ty::Dynamic(..)) => true,
2319
2320             // Ambiguous handling is below T -> Trait, because inference
2321             // variables can still implement Unsize<Trait> and nested
2322             // obligations will have the final say (likely deferred).
2323             (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
2324                 debug!("assemble_candidates_for_unsizing: ambiguous");
2325                 candidates.ambiguous = true;
2326                 false
2327             }
2328
2329             // [T; n] -> [T].
2330             (&ty::Array(..), &ty::Slice(_)) => true,
2331
2332             // Struct<T> -> Struct<U>.
2333             (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
2334                 def_id_a == def_id_b
2335             }
2336
2337             // (.., T) -> (.., U).
2338             (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
2339
2340             _ => false,
2341         };
2342
2343         if may_apply {
2344             candidates.vec.push(BuiltinUnsizeCandidate);
2345         }
2346     }
2347
2348     fn assemble_candidates_for_trait_alias(
2349         &mut self,
2350         obligation: &TraitObligation<'tcx>,
2351         candidates: &mut SelectionCandidateSet<'tcx>,
2352     ) -> Result<(), SelectionError<'tcx>> {
2353         // Okay to skip binder here because the tests we do below do not involve bound regions.
2354         let self_ty = *obligation.self_ty().skip_binder();
2355         debug!("assemble_candidates_for_trait_alias(self_ty={:?})", self_ty);
2356
2357         let def_id = obligation.predicate.def_id();
2358
2359         if self.tcx().is_trait_alias(def_id) {
2360             candidates.vec.push(TraitAliasCandidate(def_id.clone()));
2361         }
2362
2363         Ok(())
2364     }
2365
2366     ///////////////////////////////////////////////////////////////////////////
2367     // WINNOW
2368     //
2369     // Winnowing is the process of attempting to resolve ambiguity by
2370     // probing further. During the winnowing process, we unify all
2371     // type variables and then we also attempt to evaluate recursive
2372     // bounds to see if they are satisfied.
2373
2374     /// Returns `true` if `victim` should be dropped in favor of
2375     /// `other`. Generally speaking we will drop duplicate
2376     /// candidates and prefer where-clause candidates.
2377     ///
2378     /// See the comment for "SelectionCandidate" for more details.
2379     fn candidate_should_be_dropped_in_favor_of(
2380         &mut self,
2381         victim: &EvaluatedCandidate<'tcx>,
2382         other: &EvaluatedCandidate<'tcx>,
2383     ) -> bool {
2384         if victim.candidate == other.candidate {
2385             return true;
2386         }
2387
2388         // Check if a bound would previously have been removed when normalizing
2389         // the param_env so that it can be given the lowest priority. See
2390         // #50825 for the motivation for this.
2391         let is_global =
2392             |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
2393
2394         match other.candidate {
2395             // Prefer BuiltinCandidate { has_nested: false } to anything else.
2396             // This is a fix for #53123 and prevents winnowing from accidentally extending the
2397             // lifetime of a variable.
2398             BuiltinCandidate { has_nested: false } => true,
2399             ParamCandidate(ref cand) => match victim.candidate {
2400                 AutoImplCandidate(..) => {
2401                     bug!(
2402                         "default implementations shouldn't be recorded \
2403                          when there are other valid candidates"
2404                     );
2405                 }
2406                 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2407                 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2408                 // lifetime of a variable.
2409                 BuiltinCandidate { has_nested: false } => false,
2410                 ImplCandidate(..)
2411                 | ClosureCandidate
2412                 | GeneratorCandidate
2413                 | FnPointerCandidate
2414                 | BuiltinObjectCandidate
2415                 | BuiltinUnsizeCandidate
2416                 | BuiltinCandidate { .. }
2417                 | TraitAliasCandidate(..) => {
2418                     // Global bounds from the where clause should be ignored
2419                     // here (see issue #50825). Otherwise, we have a where
2420                     // clause so don't go around looking for impls.
2421                     !is_global(cand)
2422                 }
2423                 ObjectCandidate | ProjectionCandidate => {
2424                     // Arbitrarily give param candidates priority
2425                     // over projection and object candidates.
2426                     !is_global(cand)
2427                 }
2428                 ParamCandidate(..) => false,
2429             },
2430             ObjectCandidate | ProjectionCandidate => match victim.candidate {
2431                 AutoImplCandidate(..) => {
2432                     bug!(
2433                         "default implementations shouldn't be recorded \
2434                          when there are other valid candidates"
2435                     );
2436                 }
2437                 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2438                 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2439                 // lifetime of a variable.
2440                 BuiltinCandidate { has_nested: false } => false,
2441                 ImplCandidate(..)
2442                 | ClosureCandidate
2443                 | GeneratorCandidate
2444                 | FnPointerCandidate
2445                 | BuiltinObjectCandidate
2446                 | BuiltinUnsizeCandidate
2447                 | BuiltinCandidate { .. }
2448                 | TraitAliasCandidate(..) => true,
2449                 ObjectCandidate | ProjectionCandidate => {
2450                     // Arbitrarily give param candidates priority
2451                     // over projection and object candidates.
2452                     true
2453                 }
2454                 ParamCandidate(ref cand) => is_global(cand),
2455             },
2456             ImplCandidate(other_def) => {
2457                 // See if we can toss out `victim` based on specialization.
2458                 // This requires us to know *for sure* that the `other` impl applies
2459                 // i.e., EvaluatedToOk:
2460                 if other.evaluation.must_apply_modulo_regions() {
2461                     match victim.candidate {
2462                         ImplCandidate(victim_def) => {
2463                             let tcx = self.tcx().global_tcx();
2464                             return tcx.specializes((other_def, victim_def))
2465                                 || tcx.impls_are_allowed_to_overlap(
2466                                     other_def, victim_def).is_some();
2467                         }
2468                         ParamCandidate(ref cand) => {
2469                             // Prefer the impl to a global where clause candidate.
2470                             return is_global(cand);
2471                         }
2472                         _ => (),
2473                     }
2474                 }
2475
2476                 false
2477             }
2478             ClosureCandidate
2479             | GeneratorCandidate
2480             | FnPointerCandidate
2481             | BuiltinObjectCandidate
2482             | BuiltinUnsizeCandidate
2483             | BuiltinCandidate { has_nested: true } => {
2484                 match victim.candidate {
2485                     ParamCandidate(ref cand) => {
2486                         // Prefer these to a global where-clause bound
2487                         // (see issue #50825)
2488                         is_global(cand) && other.evaluation.must_apply_modulo_regions()
2489                     }
2490                     _ => false,
2491                 }
2492             }
2493             _ => false,
2494         }
2495     }
2496
2497     ///////////////////////////////////////////////////////////////////////////
2498     // BUILTIN BOUNDS
2499     //
2500     // These cover the traits that are built-in to the language
2501     // itself: `Copy`, `Clone` and `Sized`.
2502
2503     fn assemble_builtin_bound_candidates(
2504         &mut self,
2505         conditions: BuiltinImplConditions<'tcx>,
2506         candidates: &mut SelectionCandidateSet<'tcx>,
2507     ) -> Result<(), SelectionError<'tcx>> {
2508         match conditions {
2509             BuiltinImplConditions::Where(nested) => {
2510                 debug!("builtin_bound: nested={:?}", nested);
2511                 candidates.vec.push(BuiltinCandidate {
2512                     has_nested: nested.skip_binder().len() > 0,
2513                 });
2514             }
2515             BuiltinImplConditions::None => {}
2516             BuiltinImplConditions::Ambiguous => {
2517                 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2518                 candidates.ambiguous = true;
2519             }
2520         }
2521
2522         Ok(())
2523     }
2524
2525     fn sized_conditions(
2526         &mut self,
2527         obligation: &TraitObligation<'tcx>,
2528     ) -> BuiltinImplConditions<'tcx> {
2529         use self::BuiltinImplConditions::{Ambiguous, None, Where};
2530
2531         // NOTE: binder moved to (*)
2532         let self_ty = self.infcx
2533             .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2534
2535         match self_ty.sty {
2536             ty::Infer(ty::IntVar(_))
2537             | ty::Infer(ty::FloatVar(_))
2538             | ty::Uint(_)
2539             | ty::Int(_)
2540             | ty::Bool
2541             | ty::Float(_)
2542             | ty::FnDef(..)
2543             | ty::FnPtr(_)
2544             | ty::RawPtr(..)
2545             | ty::Char
2546             | ty::Ref(..)
2547             | ty::Generator(..)
2548             | ty::GeneratorWitness(..)
2549             | ty::Array(..)
2550             | ty::Closure(..)
2551             | ty::Never
2552             | ty::Error => {
2553                 // safe for everything
2554                 Where(ty::Binder::dummy(Vec::new()))
2555             }
2556
2557             ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2558
2559             ty::Tuple(tys) => {
2560                 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
2561             }
2562
2563             ty::Adt(def, substs) => {
2564                 let sized_crit = def.sized_constraint(self.tcx());
2565                 // (*) binder moved here
2566                 Where(ty::Binder::bind(
2567                     sized_crit
2568                         .iter()
2569                         .map(|ty| ty.subst(self.tcx(), substs))
2570                         .collect(),
2571                 ))
2572             }
2573
2574             ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2575             ty::Infer(ty::TyVar(_)) => Ambiguous,
2576
2577             ty::UnnormalizedProjection(..)
2578             | ty::Placeholder(..)
2579             | ty::Bound(..)
2580             | ty::Infer(ty::FreshTy(_))
2581             | ty::Infer(ty::FreshIntTy(_))
2582             | ty::Infer(ty::FreshFloatTy(_)) => {
2583                 bug!(
2584                     "asked to assemble builtin bounds of unexpected type: {:?}",
2585                     self_ty
2586                 );
2587             }
2588         }
2589     }
2590
2591     fn copy_clone_conditions(
2592         &mut self,
2593         obligation: &TraitObligation<'tcx>,
2594     ) -> BuiltinImplConditions<'tcx> {
2595         // NOTE: binder moved to (*)
2596         let self_ty = self.infcx
2597             .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2598
2599         use self::BuiltinImplConditions::{Ambiguous, None, Where};
2600
2601         match self_ty.sty {
2602             ty::Infer(ty::IntVar(_))
2603             | ty::Infer(ty::FloatVar(_))
2604             | ty::FnDef(..)
2605             | ty::FnPtr(_)
2606             | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2607
2608             ty::Uint(_)
2609             | ty::Int(_)
2610             | ty::Bool
2611             | ty::Float(_)
2612             | ty::Char
2613             | ty::RawPtr(..)
2614             | ty::Never
2615             | ty::Ref(_, _, hir::MutImmutable) => {
2616                 // Implementations provided in libcore
2617                 None
2618             }
2619
2620             ty::Dynamic(..)
2621             | ty::Str
2622             | ty::Slice(..)
2623             | ty::Generator(..)
2624             | ty::GeneratorWitness(..)
2625             | ty::Foreign(..)
2626             | ty::Ref(_, _, hir::MutMutable) => None,
2627
2628             ty::Array(element_ty, _) => {
2629                 // (*) binder moved here
2630                 Where(ty::Binder::bind(vec![element_ty]))
2631             }
2632
2633             ty::Tuple(tys) => {
2634                 // (*) binder moved here
2635                 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
2636             }
2637
2638             ty::Closure(def_id, substs) => {
2639                 // (*) binder moved here
2640                 Where(ty::Binder::bind(
2641                     substs.upvar_tys(def_id, self.tcx()).collect(),
2642                 ))
2643             }
2644
2645             ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2646                 // Fallback to whatever user-defined impls exist in this case.
2647                 None
2648             }
2649
2650             ty::Infer(ty::TyVar(_)) => {
2651                 // Unbound type variable. Might or might not have
2652                 // applicable impls and so forth, depending on what
2653                 // those type variables wind up being bound to.
2654                 Ambiguous
2655             }
2656
2657             ty::UnnormalizedProjection(..)
2658             | ty::Placeholder(..)
2659             | ty::Bound(..)
2660             | ty::Infer(ty::FreshTy(_))
2661             | ty::Infer(ty::FreshIntTy(_))
2662             | ty::Infer(ty::FreshFloatTy(_)) => {
2663                 bug!(
2664                     "asked to assemble builtin bounds of unexpected type: {:?}",
2665                     self_ty
2666                 );
2667             }
2668         }
2669     }
2670
2671     /// For default impls, we need to break apart a type into its
2672     /// "constituent types" -- meaning, the types that it contains.
2673     ///
2674     /// Here are some (simple) examples:
2675     ///
2676     /// ```
2677     /// (i32, u32) -> [i32, u32]
2678     /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2679     /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2680     /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2681     /// ```
2682     fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2683         match t.sty {
2684             ty::Uint(_)
2685             | ty::Int(_)
2686             | ty::Bool
2687             | ty::Float(_)
2688             | ty::FnDef(..)
2689             | ty::FnPtr(_)
2690             | ty::Str
2691             | ty::Error
2692             | ty::Infer(ty::IntVar(_))
2693             | ty::Infer(ty::FloatVar(_))
2694             | ty::Never
2695             | ty::Char => Vec::new(),
2696
2697             ty::UnnormalizedProjection(..)
2698             | ty::Placeholder(..)
2699             | ty::Dynamic(..)
2700             | ty::Param(..)
2701             | ty::Foreign(..)
2702             | ty::Projection(..)
2703             | ty::Bound(..)
2704             | ty::Infer(ty::TyVar(_))
2705             | ty::Infer(ty::FreshTy(_))
2706             | ty::Infer(ty::FreshIntTy(_))
2707             | ty::Infer(ty::FreshFloatTy(_)) => {
2708                 bug!(
2709                     "asked to assemble constituent types of unexpected type: {:?}",
2710                     t
2711                 );
2712             }
2713
2714             ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2715                 vec![element_ty]
2716             }
2717
2718             ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2719
2720             ty::Tuple(ref tys) => {
2721                 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2722                 tys.iter().map(|k| k.expect_ty()).collect()
2723             }
2724
2725             ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, self.tcx()).collect(),
2726
2727             ty::Generator(def_id, ref substs, _) => {
2728                 let witness = substs.witness(def_id, self.tcx());
2729                 substs
2730                     .upvar_tys(def_id, self.tcx())
2731                     .chain(iter::once(witness))
2732                     .collect()
2733             }
2734
2735             ty::GeneratorWitness(types) => {
2736                 // This is sound because no regions in the witness can refer to
2737                 // the binder outside the witness. So we'll effectivly reuse
2738                 // the implicit binder around the witness.
2739                 types.skip_binder().to_vec()
2740             }
2741
2742             // for `PhantomData<T>`, we pass `T`
2743             ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2744
2745             ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2746
2747             ty::Opaque(def_id, substs) => {
2748                 // We can resolve the `impl Trait` to its concrete type,
2749                 // which enforces a DAG between the functions requiring
2750                 // the auto trait bounds in question.
2751                 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2752             }
2753         }
2754     }
2755
2756     fn collect_predicates_for_types(
2757         &mut self,
2758         param_env: ty::ParamEnv<'tcx>,
2759         cause: ObligationCause<'tcx>,
2760         recursion_depth: usize,
2761         trait_def_id: DefId,
2762         types: ty::Binder<Vec<Ty<'tcx>>>,
2763     ) -> Vec<PredicateObligation<'tcx>> {
2764         // Because the types were potentially derived from
2765         // higher-ranked obligations they may reference late-bound
2766         // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2767         // yield a type like `for<'a> &'a int`. In general, we
2768         // maintain the invariant that we never manipulate bound
2769         // regions, so we have to process these bound regions somehow.
2770         //
2771         // The strategy is to:
2772         //
2773         // 1. Instantiate those regions to placeholder regions (e.g.,
2774         //    `for<'a> &'a int` becomes `&0 int`.
2775         // 2. Produce something like `&'0 int : Copy`
2776         // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2777
2778         types
2779             .skip_binder()
2780             .into_iter()
2781             .flat_map(|ty| {
2782                 // binder moved -\
2783                 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2784
2785                 self.infcx.in_snapshot(|_| {
2786                     let (skol_ty, _) = self.infcx
2787                         .replace_bound_vars_with_placeholders(&ty);
2788                     let Normalized {
2789                         value: normalized_ty,
2790                         mut obligations,
2791                     } = project::normalize_with_depth(
2792                         self,
2793                         param_env,
2794                         cause.clone(),
2795                         recursion_depth,
2796                         &skol_ty,
2797                     );
2798                     let skol_obligation = self.tcx().predicate_for_trait_def(
2799                         param_env,
2800                         cause.clone(),
2801                         trait_def_id,
2802                         recursion_depth,
2803                         normalized_ty,
2804                         &[],
2805                     );
2806                     obligations.push(skol_obligation);
2807                     obligations
2808                 })
2809             })
2810             .collect()
2811     }
2812
2813     ///////////////////////////////////////////////////////////////////////////
2814     // CONFIRMATION
2815     //
2816     // Confirmation unifies the output type parameters of the trait
2817     // with the values found in the obligation, possibly yielding a
2818     // type error.  See the [rustc guide] for more details.
2819     //
2820     // [rustc guide]:
2821     // https://rust-lang.github.io/rustc-guide/traits/resolution.html#confirmation
2822
2823     fn confirm_candidate(
2824         &mut self,
2825         obligation: &TraitObligation<'tcx>,
2826         candidate: SelectionCandidate<'tcx>,
2827     ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2828         debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2829
2830         match candidate {
2831             BuiltinCandidate { has_nested } => {
2832                 let data = self.confirm_builtin_candidate(obligation, has_nested);
2833                 Ok(VtableBuiltin(data))
2834             }
2835
2836             ParamCandidate(param) => {
2837                 let obligations = self.confirm_param_candidate(obligation, param);
2838                 Ok(VtableParam(obligations))
2839             }
2840
2841             ImplCandidate(impl_def_id) => Ok(VtableImpl(self.confirm_impl_candidate(
2842                 obligation,
2843                 impl_def_id,
2844             ))),
2845
2846             AutoImplCandidate(trait_def_id) => {
2847                 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2848                 Ok(VtableAutoImpl(data))
2849             }
2850
2851             ProjectionCandidate => {
2852                 self.confirm_projection_candidate(obligation);
2853                 Ok(VtableParam(Vec::new()))
2854             }
2855
2856             ClosureCandidate => {
2857                 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2858                 Ok(VtableClosure(vtable_closure))
2859             }
2860
2861             GeneratorCandidate => {
2862                 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2863                 Ok(VtableGenerator(vtable_generator))
2864             }
2865
2866             FnPointerCandidate => {
2867                 let data = self.confirm_fn_pointer_candidate(obligation)?;
2868                 Ok(VtableFnPointer(data))
2869             }
2870
2871             TraitAliasCandidate(alias_def_id) => {
2872                 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
2873                 Ok(VtableTraitAlias(data))
2874             }
2875
2876             ObjectCandidate => {
2877                 let data = self.confirm_object_candidate(obligation);
2878                 Ok(VtableObject(data))
2879             }
2880
2881             BuiltinObjectCandidate => {
2882                 // This indicates something like `(Trait+Send) :
2883                 // Send`. In this case, we know that this holds
2884                 // because that's what the object type is telling us,
2885                 // and there's really no additional obligations to
2886                 // prove and no types in particular to unify etc.
2887                 Ok(VtableParam(Vec::new()))
2888             }
2889
2890             BuiltinUnsizeCandidate => {
2891                 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2892                 Ok(VtableBuiltin(data))
2893             }
2894         }
2895     }
2896
2897     fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2898         self.infcx.in_snapshot(|snapshot| {
2899             let result =
2900                 self.match_projection_obligation_against_definition_bounds(
2901                     obligation,
2902                     snapshot,
2903                 );
2904             assert!(result);
2905         })
2906     }
2907
2908     fn confirm_param_candidate(
2909         &mut self,
2910         obligation: &TraitObligation<'tcx>,
2911         param: ty::PolyTraitRef<'tcx>,
2912     ) -> Vec<PredicateObligation<'tcx>> {
2913         debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2914
2915         // During evaluation, we already checked that this
2916         // where-clause trait-ref could be unified with the obligation
2917         // trait-ref. Repeat that unification now without any
2918         // transactional boundary; it should not fail.
2919         match self.match_where_clause_trait_ref(obligation, param.clone()) {
2920             Ok(obligations) => obligations,
2921             Err(()) => {
2922                 bug!(
2923                     "Where clause `{:?}` was applicable to `{:?}` but now is not",
2924                     param,
2925                     obligation
2926                 );
2927             }
2928         }
2929     }
2930
2931     fn confirm_builtin_candidate(
2932         &mut self,
2933         obligation: &TraitObligation<'tcx>,
2934         has_nested: bool,
2935     ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2936         debug!(
2937             "confirm_builtin_candidate({:?}, {:?})",
2938             obligation, has_nested
2939         );
2940
2941         let lang_items = self.tcx().lang_items();
2942         let obligations = if has_nested {
2943             let trait_def = obligation.predicate.def_id();
2944             let conditions = if Some(trait_def) == lang_items.sized_trait() {
2945                 self.sized_conditions(obligation)
2946             } else if Some(trait_def) == lang_items.copy_trait() {
2947                 self.copy_clone_conditions(obligation)
2948             } else if Some(trait_def) == lang_items.clone_trait() {
2949                 self.copy_clone_conditions(obligation)
2950             } else {
2951                 bug!("unexpected builtin trait {:?}", trait_def)
2952             };
2953             let nested = match conditions {
2954                 BuiltinImplConditions::Where(nested) => nested,
2955                 _ => bug!(
2956                     "obligation {:?} had matched a builtin impl but now doesn't",
2957                     obligation
2958                 ),
2959             };
2960
2961             let cause = obligation.derived_cause(BuiltinDerivedObligation);
2962             self.collect_predicates_for_types(
2963                 obligation.param_env,
2964                 cause,
2965                 obligation.recursion_depth + 1,
2966                 trait_def,
2967                 nested,
2968             )
2969         } else {
2970             vec![]
2971         };
2972
2973         debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2974
2975         VtableBuiltinData {
2976             nested: obligations,
2977         }
2978     }
2979
2980     /// This handles the case where a `auto trait Foo` impl is being used.
2981     /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2982     ///
2983     /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2984     /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2985     fn confirm_auto_impl_candidate(
2986         &mut self,
2987         obligation: &TraitObligation<'tcx>,
2988         trait_def_id: DefId,
2989     ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2990         debug!(
2991             "confirm_auto_impl_candidate({:?}, {:?})",
2992             obligation, trait_def_id
2993         );
2994
2995         let types = obligation.predicate.map_bound(|inner| {
2996             let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2997             self.constituent_types_for_ty(self_ty)
2998         });
2999         self.vtable_auto_impl(obligation, trait_def_id, types)
3000     }
3001
3002     /// See `confirm_auto_impl_candidate`.
3003     fn vtable_auto_impl(
3004         &mut self,
3005         obligation: &TraitObligation<'tcx>,
3006         trait_def_id: DefId,
3007         nested: ty::Binder<Vec<Ty<'tcx>>>,
3008     ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
3009         debug!("vtable_auto_impl: nested={:?}", nested);
3010
3011         let cause = obligation.derived_cause(BuiltinDerivedObligation);
3012         let mut obligations = self.collect_predicates_for_types(
3013             obligation.param_env,
3014             cause,
3015             obligation.recursion_depth + 1,
3016             trait_def_id,
3017             nested,
3018         );
3019
3020         let trait_obligations: Vec<PredicateObligation<'_>> = self.infcx.in_snapshot(|_| {
3021             let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
3022             let (trait_ref, _) = self.infcx
3023                 .replace_bound_vars_with_placeholders(&poly_trait_ref);
3024             let cause = obligation.derived_cause(ImplDerivedObligation);
3025             self.impl_or_trait_obligations(
3026                 cause,
3027                 obligation.recursion_depth + 1,
3028                 obligation.param_env,
3029                 trait_def_id,
3030                 &trait_ref.substs,
3031             )
3032         });
3033
3034         // Adds the predicates from the trait.  Note that this contains a `Self: Trait`
3035         // predicate as usual.  It won't have any effect since auto traits are coinductive.
3036         obligations.extend(trait_obligations);
3037
3038         debug!("vtable_auto_impl: obligations={:?}", obligations);
3039
3040         VtableAutoImplData {
3041             trait_def_id,
3042             nested: obligations,
3043         }
3044     }
3045
3046     fn confirm_impl_candidate(
3047         &mut self,
3048         obligation: &TraitObligation<'tcx>,
3049         impl_def_id: DefId,
3050     ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
3051         debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
3052
3053         // First, create the substitutions by matching the impl again,
3054         // this time not in a probe.
3055         self.infcx.in_snapshot(|snapshot| {
3056             let substs = self.rematch_impl(impl_def_id, obligation, snapshot);
3057             debug!("confirm_impl_candidate: substs={:?}", substs);
3058             let cause = obligation.derived_cause(ImplDerivedObligation);
3059             self.vtable_impl(
3060                 impl_def_id,
3061                 substs,
3062                 cause,
3063                 obligation.recursion_depth + 1,
3064                 obligation.param_env,
3065             )
3066         })
3067     }
3068
3069     fn vtable_impl(
3070         &mut self,
3071         impl_def_id: DefId,
3072         mut substs: Normalized<'tcx, SubstsRef<'tcx>>,
3073         cause: ObligationCause<'tcx>,
3074         recursion_depth: usize,
3075         param_env: ty::ParamEnv<'tcx>,
3076     ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
3077         debug!(
3078             "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={})",
3079             impl_def_id, substs, recursion_depth,
3080         );
3081
3082         let mut impl_obligations = self.impl_or_trait_obligations(
3083             cause,
3084             recursion_depth,
3085             param_env,
3086             impl_def_id,
3087             &substs.value,
3088         );
3089
3090         debug!(
3091             "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
3092             impl_def_id, impl_obligations
3093         );
3094
3095         // Because of RFC447, the impl-trait-ref and obligations
3096         // are sufficient to determine the impl substs, without
3097         // relying on projections in the impl-trait-ref.
3098         //
3099         // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
3100         impl_obligations.append(&mut substs.obligations);
3101
3102         VtableImplData {
3103             impl_def_id,
3104             substs: substs.value,
3105             nested: impl_obligations,
3106         }
3107     }
3108
3109     fn confirm_object_candidate(
3110         &mut self,
3111         obligation: &TraitObligation<'tcx>,
3112     ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
3113         debug!("confirm_object_candidate({:?})", obligation);
3114
3115         // FIXME(nmatsakis) skipping binder here seems wrong -- we should
3116         // probably flatten the binder from the obligation and the binder
3117         // from the object. Have to try to make a broken test case that
3118         // results.
3119         let self_ty = self.infcx
3120             .shallow_resolve(*obligation.self_ty().skip_binder());
3121         let poly_trait_ref = match self_ty.sty {
3122             ty::Dynamic(ref data, ..) =>
3123                 data.principal().unwrap_or_else(|| {
3124                     span_bug!(obligation.cause.span, "object candidate with no principal")
3125                 }).with_self_ty(self.tcx(), self_ty),
3126             _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
3127         };
3128
3129         let mut upcast_trait_ref = None;
3130         let mut nested = vec![];
3131         let vtable_base;
3132
3133         {
3134             let tcx = self.tcx();
3135
3136             // We want to find the first supertrait in the list of
3137             // supertraits that we can unify with, and do that
3138             // unification. We know that there is exactly one in the list
3139             // where we can unify because otherwise select would have
3140             // reported an ambiguity. (When we do find a match, also
3141             // record it for later.)
3142             let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(
3143                 |&t| match self.infcx.commit_if_ok(|_| self.match_poly_trait_ref(obligation, t)) {
3144                     Ok(obligations) => {
3145                         upcast_trait_ref = Some(t);
3146                         nested.extend(obligations);
3147                         false
3148                     }
3149                     Err(_) => true,
3150                 },
3151             );
3152
3153             // Additionally, for each of the nonmatching predicates that
3154             // we pass over, we sum up the set of number of vtable
3155             // entries, so that we can compute the offset for the selected
3156             // trait.
3157             vtable_base = nonmatching.map(|t| tcx.count_own_vtable_entries(t)).sum();
3158         }
3159
3160         VtableObjectData {
3161             upcast_trait_ref: upcast_trait_ref.unwrap(),
3162             vtable_base,
3163             nested,
3164         }
3165     }
3166
3167     fn confirm_fn_pointer_candidate(
3168         &mut self,
3169         obligation: &TraitObligation<'tcx>,
3170     ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3171         debug!("confirm_fn_pointer_candidate({:?})", obligation);
3172
3173         // Okay to skip binder; it is reintroduced below.
3174         let self_ty = self.infcx
3175             .shallow_resolve(*obligation.self_ty().skip_binder());
3176         let sig = self_ty.fn_sig(self.tcx());
3177         let trait_ref = self.tcx()
3178             .closure_trait_ref_and_return_type(
3179                 obligation.predicate.def_id(),
3180                 self_ty,
3181                 sig,
3182                 util::TupleArgumentsFlag::Yes,
3183             )
3184             .map_bound(|(trait_ref, _)| trait_ref);
3185
3186         let Normalized {
3187             value: trait_ref,
3188             obligations,
3189         } = project::normalize_with_depth(
3190             self,
3191             obligation.param_env,
3192             obligation.cause.clone(),
3193             obligation.recursion_depth + 1,
3194             &trait_ref,
3195         );
3196
3197         self.confirm_poly_trait_refs(
3198             obligation.cause.clone(),
3199             obligation.param_env,
3200             obligation.predicate.to_poly_trait_ref(),
3201             trait_ref,
3202         )?;
3203         Ok(VtableFnPointerData {
3204             fn_ty: self_ty,
3205             nested: obligations,
3206         })
3207     }
3208
3209     fn confirm_trait_alias_candidate(
3210         &mut self,
3211         obligation: &TraitObligation<'tcx>,
3212         alias_def_id: DefId,
3213     ) -> VtableTraitAliasData<'tcx, PredicateObligation<'tcx>> {
3214         debug!(
3215             "confirm_trait_alias_candidate({:?}, {:?})",
3216             obligation, alias_def_id
3217         );
3218
3219         self.infcx.in_snapshot(|_| {
3220             let (predicate, _) = self.infcx()
3221                 .replace_bound_vars_with_placeholders(&obligation.predicate);
3222             let trait_ref = predicate.trait_ref;
3223             let trait_def_id = trait_ref.def_id;
3224             let substs = trait_ref.substs;
3225
3226             let trait_obligations = self.impl_or_trait_obligations(
3227                 obligation.cause.clone(),
3228                 obligation.recursion_depth,
3229                 obligation.param_env,
3230                 trait_def_id,
3231                 &substs,
3232             );
3233
3234             debug!(
3235                 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
3236                 trait_def_id, trait_obligations
3237             );
3238
3239             VtableTraitAliasData {
3240                 alias_def_id,
3241                 substs: substs,
3242                 nested: trait_obligations,
3243             }
3244         })
3245     }
3246
3247     fn confirm_generator_candidate(
3248         &mut self,
3249         obligation: &TraitObligation<'tcx>,
3250     ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3251         // Okay to skip binder because the substs on generator types never
3252         // touch bound regions, they just capture the in-scope
3253         // type/region parameters.
3254         let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3255         let (generator_def_id, substs) = match self_ty.sty {
3256             ty::Generator(id, substs, _) => (id, substs),
3257             _ => bug!("closure candidate for non-closure {:?}", obligation),
3258         };
3259
3260         debug!(
3261             "confirm_generator_candidate({:?},{:?},{:?})",
3262             obligation, generator_def_id, substs
3263         );
3264
3265         let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
3266         let Normalized {
3267             value: trait_ref,
3268             mut obligations,
3269         } = normalize_with_depth(
3270             self,
3271             obligation.param_env,
3272             obligation.cause.clone(),
3273             obligation.recursion_depth + 1,
3274             &trait_ref,
3275         );
3276
3277         debug!(
3278             "confirm_generator_candidate(generator_def_id={:?}, \
3279              trait_ref={:?}, obligations={:?})",
3280             generator_def_id, trait_ref, obligations
3281         );
3282
3283         obligations.extend(self.confirm_poly_trait_refs(
3284             obligation.cause.clone(),
3285             obligation.param_env,
3286             obligation.predicate.to_poly_trait_ref(),
3287             trait_ref,
3288         )?);
3289
3290         Ok(VtableGeneratorData {
3291             generator_def_id: generator_def_id,
3292             substs: substs.clone(),
3293             nested: obligations,
3294         })
3295     }
3296
3297     fn confirm_closure_candidate(
3298         &mut self,
3299         obligation: &TraitObligation<'tcx>,
3300     ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3301         debug!("confirm_closure_candidate({:?})", obligation);
3302
3303         let kind = self.tcx()
3304             .lang_items()
3305             .fn_trait_kind(obligation.predicate.def_id())
3306             .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
3307
3308         // Okay to skip binder because the substs on closure types never
3309         // touch bound regions, they just capture the in-scope
3310         // type/region parameters.
3311         let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3312         let (closure_def_id, substs) = match self_ty.sty {
3313             ty::Closure(id, substs) => (id, substs),
3314             _ => bug!("closure candidate for non-closure {:?}", obligation),
3315         };
3316
3317         let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
3318         let Normalized {
3319             value: trait_ref,
3320             mut obligations,
3321         } = normalize_with_depth(
3322             self,
3323             obligation.param_env,
3324             obligation.cause.clone(),
3325             obligation.recursion_depth + 1,
3326             &trait_ref,
3327         );
3328
3329         debug!(
3330             "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
3331             closure_def_id, trait_ref, obligations
3332         );
3333
3334         obligations.extend(self.confirm_poly_trait_refs(
3335             obligation.cause.clone(),
3336             obligation.param_env,
3337             obligation.predicate.to_poly_trait_ref(),
3338             trait_ref,
3339         )?);
3340
3341         // FIXME: chalk
3342         if !self.tcx().sess.opts.debugging_opts.chalk {
3343             obligations.push(Obligation::new(
3344                 obligation.cause.clone(),
3345                 obligation.param_env,
3346                 ty::Predicate::ClosureKind(closure_def_id, substs, kind),
3347             ));
3348         }
3349
3350         Ok(VtableClosureData {
3351             closure_def_id,
3352             substs: substs.clone(),
3353             nested: obligations,
3354         })
3355     }
3356
3357     /// In the case of closure types and fn pointers,
3358     /// we currently treat the input type parameters on the trait as
3359     /// outputs. This means that when we have a match we have only
3360     /// considered the self type, so we have to go back and make sure
3361     /// to relate the argument types too. This is kind of wrong, but
3362     /// since we control the full set of impls, also not that wrong,
3363     /// and it DOES yield better error messages (since we don't report
3364     /// errors as if there is no applicable impl, but rather report
3365     /// errors are about mismatched argument types.
3366     ///
3367     /// Here is an example. Imagine we have a closure expression
3368     /// and we desugared it so that the type of the expression is
3369     /// `Closure`, and `Closure` expects an int as argument. Then it
3370     /// is "as if" the compiler generated this impl:
3371     ///
3372     ///     impl Fn(int) for Closure { ... }
3373     ///
3374     /// Now imagine our obligation is `Fn(usize) for Closure`. So far
3375     /// we have matched the self type `Closure`. At this point we'll
3376     /// compare the `int` to `usize` and generate an error.
3377     ///
3378     /// Note that this checking occurs *after* the impl has selected,
3379     /// because these output type parameters should not affect the
3380     /// selection of the impl. Therefore, if there is a mismatch, we
3381     /// report an error to the user.
3382     fn confirm_poly_trait_refs(
3383         &mut self,
3384         obligation_cause: ObligationCause<'tcx>,
3385         obligation_param_env: ty::ParamEnv<'tcx>,
3386         obligation_trait_ref: ty::PolyTraitRef<'tcx>,
3387         expected_trait_ref: ty::PolyTraitRef<'tcx>,
3388     ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3389         let obligation_trait_ref = obligation_trait_ref.clone();
3390         self.infcx
3391             .at(&obligation_cause, obligation_param_env)
3392             .sup(obligation_trait_ref, expected_trait_ref)
3393             .map(|InferOk { obligations, .. }| obligations)
3394             .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
3395     }
3396
3397     fn confirm_builtin_unsize_candidate(
3398         &mut self,
3399         obligation: &TraitObligation<'tcx>,
3400     ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3401         let tcx = self.tcx();
3402
3403         // assemble_candidates_for_unsizing should ensure there are no late bound
3404         // regions here. See the comment there for more details.
3405         let source = self.infcx
3406             .shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
3407         let target = obligation
3408             .predicate
3409             .skip_binder()
3410             .trait_ref
3411             .substs
3412             .type_at(1);
3413         let target = self.infcx.shallow_resolve(target);
3414
3415         debug!(
3416             "confirm_builtin_unsize_candidate(source={:?}, target={:?})",
3417             source, target
3418         );
3419
3420         let mut nested = vec![];
3421         match (&source.sty, &target.sty) {
3422             // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
3423             (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
3424                 // See assemble_candidates_for_unsizing for more info.
3425                 let existential_predicates = data_a.map_bound(|data_a| {
3426                     let iter =
3427                         data_a.principal().map(|x| ty::ExistentialPredicate::Trait(x))
3428                         .into_iter().chain(
3429                             data_a
3430                                 .projection_bounds()
3431                                 .map(|x| ty::ExistentialPredicate::Projection(x)),
3432                         )
3433                         .chain(
3434                             data_b
3435                                 .auto_traits()
3436                                 .map(ty::ExistentialPredicate::AutoTrait),
3437                         );
3438                     tcx.mk_existential_predicates(iter)
3439                 });
3440                 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
3441
3442                 // Require that the traits involved in this upcast are **equal**;
3443                 // only the **lifetime bound** is changed.
3444                 //
3445                 // FIXME: This condition is arguably too strong -- it
3446                 // would suffice for the source trait to be a
3447                 // *subtype* of the target trait. In particular
3448                 // changing from something like `for<'a, 'b> Foo<'a,
3449                 // 'b>` to `for<'a> Foo<'a, 'a>` should be
3450                 // permitted. And, indeed, in the in commit
3451                 // 904a0bde93f0348f69914ee90b1f8b6e4e0d7cbc, this
3452                 // condition was loosened. However, when the leak check was added
3453                 // back, using subtype here actually guies the coercion code in
3454                 // such a way that it accepts `old-lub-glb-object.rs`. This is probably
3455                 // a good thing, but I've modified this to `.eq` because I want
3456                 // to continue rejecting that test (as we have done for quite some time)
3457                 // before we are firmly comfortable with what our behavior
3458                 // should be there. -nikomatsakis
3459                 let InferOk { obligations, .. } = self.infcx
3460                     .at(&obligation.cause, obligation.param_env)
3461                     .eq(target, source_trait) // FIXME -- see below
3462                     .map_err(|_| Unimplemented)?;
3463                 nested.extend(obligations);
3464
3465                 // Register one obligation for 'a: 'b.
3466                 let cause = ObligationCause::new(
3467                     obligation.cause.span,
3468                     obligation.cause.body_id,
3469                     ObjectCastObligation(target),
3470                 );
3471                 let outlives = ty::OutlivesPredicate(r_a, r_b);
3472                 nested.push(Obligation::with_depth(
3473                     cause,
3474                     obligation.recursion_depth + 1,
3475                     obligation.param_env,
3476                     ty::Binder::bind(outlives).to_predicate(),
3477                 ));
3478             }
3479
3480             // T -> Trait.
3481             (_, &ty::Dynamic(ref data, r)) => {
3482                 let mut object_dids = data.auto_traits()
3483                     .chain(data.principal_def_id());
3484                 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3485                     return Err(TraitNotObjectSafe(did));
3486                 }
3487
3488                 let cause = ObligationCause::new(
3489                     obligation.cause.span,
3490                     obligation.cause.body_id,
3491                     ObjectCastObligation(target),
3492                 );
3493
3494                 let predicate_to_obligation = |predicate| {
3495                     Obligation::with_depth(
3496                         cause.clone(),
3497                         obligation.recursion_depth + 1,
3498                         obligation.param_env,
3499                         predicate,
3500                     )
3501                 };
3502
3503                 // Create obligations:
3504                 //  - Casting T to Trait
3505                 //  - For all the various builtin bounds attached to the object cast. (In other
3506                 //  words, if the object type is Foo+Send, this would create an obligation for the
3507                 //  Send check.)
3508                 //  - Projection predicates
3509                 nested.extend(
3510                     data.iter()
3511                         .map(|d| predicate_to_obligation(d.with_self_ty(tcx, source))),
3512                 );
3513
3514                 // We can only make objects from sized types.
3515                 let tr = ty::TraitRef {
3516                     def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
3517                     substs: tcx.mk_substs_trait(source, &[]),
3518                 };
3519                 nested.push(predicate_to_obligation(tr.to_predicate()));
3520
3521                 // If the type is `Foo+'a`, ensures that the type
3522                 // being cast to `Foo+'a` outlives `'a`:
3523                 let outlives = ty::OutlivesPredicate(source, r);
3524                 nested.push(predicate_to_obligation(
3525                     ty::Binder::dummy(outlives).to_predicate(),
3526                 ));
3527             }
3528
3529             // [T; n] -> [T].
3530             (&ty::Array(a, _), &ty::Slice(b)) => {
3531                 let InferOk { obligations, .. } = self.infcx
3532                     .at(&obligation.cause, obligation.param_env)
3533                     .eq(b, a)
3534                     .map_err(|_| Unimplemented)?;
3535                 nested.extend(obligations);
3536             }
3537
3538             // Struct<T> -> Struct<U>.
3539             (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3540                 let fields = def.all_fields()
3541                     .map(|f| tcx.type_of(f.did))
3542                     .collect::<Vec<_>>();
3543
3544                 // The last field of the structure has to exist and contain type parameters.
3545                 let field = if let Some(&field) = fields.last() {
3546                     field
3547                 } else {
3548                     return Err(Unimplemented);
3549                 };
3550                 let mut ty_params = GrowableBitSet::new_empty();
3551                 let mut found = false;
3552                 for ty in field.walk() {
3553                     if let ty::Param(p) = ty.sty {
3554                         ty_params.insert(p.index as usize);
3555                         found = true;
3556                     }
3557                 }
3558                 if !found {
3559                     return Err(Unimplemented);
3560                 }
3561
3562                 // Replace type parameters used in unsizing with
3563                 // Error and ensure they do not affect any other fields.
3564                 // This could be checked after type collection for any struct
3565                 // with a potentially unsized trailing field.
3566                 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3567                     if ty_params.contains(i) {
3568                         tcx.types.err.into()
3569                     } else {
3570                         k
3571                     }
3572                 });
3573                 let substs = tcx.mk_substs(params);
3574                 for &ty in fields.split_last().unwrap().1 {
3575                     if ty.subst(tcx, substs).references_error() {
3576                         return Err(Unimplemented);
3577                     }
3578                 }
3579
3580                 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
3581                 let inner_source = field.subst(tcx, substs_a);
3582                 let inner_target = field.subst(tcx, substs_b);
3583
3584                 // Check that the source struct with the target's
3585                 // unsized parameters is equal to the target.
3586                 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3587                     if ty_params.contains(i) {
3588                         substs_b.type_at(i).into()
3589                     } else {
3590                         k
3591                     }
3592                 });
3593                 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3594                 let InferOk { obligations, .. } = self.infcx
3595                     .at(&obligation.cause, obligation.param_env)
3596                     .eq(target, new_struct)
3597                     .map_err(|_| Unimplemented)?;
3598                 nested.extend(obligations);
3599
3600                 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
3601                 nested.push(tcx.predicate_for_trait_def(
3602                     obligation.param_env,
3603                     obligation.cause.clone(),
3604                     obligation.predicate.def_id(),
3605                     obligation.recursion_depth + 1,
3606                     inner_source,
3607                     &[inner_target.into()],
3608                 ));
3609             }
3610
3611             // (.., T) -> (.., U).
3612             (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3613                 assert_eq!(tys_a.len(), tys_b.len());
3614
3615                 // The last field of the tuple has to exist.
3616                 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3617                     x
3618                 } else {
3619                     return Err(Unimplemented);
3620                 };
3621                 let &b_last = tys_b.last().unwrap();
3622
3623                 // Check that the source tuple with the target's
3624                 // last element is equal to the target.
3625                 let new_tuple = tcx.mk_tup(
3626                     a_mid.iter().map(|k| k.expect_ty()).chain(iter::once(b_last.expect_ty())),
3627                 );
3628                 let InferOk { obligations, .. } = self.infcx
3629                     .at(&obligation.cause, obligation.param_env)
3630                     .eq(target, new_tuple)
3631                     .map_err(|_| Unimplemented)?;
3632                 nested.extend(obligations);
3633
3634                 // Construct the nested T: Unsize<U> predicate.
3635                 nested.push(tcx.predicate_for_trait_def(
3636                     obligation.param_env,
3637                     obligation.cause.clone(),
3638                     obligation.predicate.def_id(),
3639                     obligation.recursion_depth + 1,
3640                     a_last.expect_ty(),
3641                     &[b_last.into()],
3642                 ));
3643             }
3644
3645             _ => bug!(),
3646         };
3647
3648         Ok(VtableBuiltinData { nested })
3649     }
3650
3651     ///////////////////////////////////////////////////////////////////////////
3652     // Matching
3653     //
3654     // Matching is a common path used for both evaluation and
3655     // confirmation.  It basically unifies types that appear in impls
3656     // and traits. This does affect the surrounding environment;
3657     // therefore, when used during evaluation, match routines must be
3658     // run inside of a `probe()` so that their side-effects are
3659     // contained.
3660
3661     fn rematch_impl(
3662         &mut self,
3663         impl_def_id: DefId,
3664         obligation: &TraitObligation<'tcx>,
3665         snapshot: &CombinedSnapshot<'_, 'tcx>,
3666     ) -> Normalized<'tcx, SubstsRef<'tcx>> {
3667         match self.match_impl(impl_def_id, obligation, snapshot) {
3668             Ok(substs) => substs,
3669             Err(()) => {
3670                 bug!(
3671                     "Impl {:?} was matchable against {:?} but now is not",
3672                     impl_def_id,
3673                     obligation
3674                 );
3675             }
3676         }
3677     }
3678
3679     fn match_impl(
3680         &mut self,
3681         impl_def_id: DefId,
3682         obligation: &TraitObligation<'tcx>,
3683         snapshot: &CombinedSnapshot<'_, 'tcx>,
3684     ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
3685         let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3686
3687         // Before we create the substitutions and everything, first
3688         // consider a "quick reject". This avoids creating more types
3689         // and so forth that we need to.
3690         if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3691             return Err(());
3692         }
3693
3694         let (skol_obligation, placeholder_map) = self.infcx()
3695             .replace_bound_vars_with_placeholders(&obligation.predicate);
3696         let skol_obligation_trait_ref = skol_obligation.trait_ref;
3697
3698         let impl_substs = self.infcx
3699             .fresh_substs_for_item(obligation.cause.span, impl_def_id);
3700
3701         let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3702
3703         let Normalized {
3704             value: impl_trait_ref,
3705             obligations: mut nested_obligations,
3706         } = project::normalize_with_depth(
3707             self,
3708             obligation.param_env,
3709             obligation.cause.clone(),
3710             obligation.recursion_depth + 1,
3711             &impl_trait_ref,
3712         );
3713
3714         debug!(
3715             "match_impl(impl_def_id={:?}, obligation={:?}, \
3716              impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3717             impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3718         );
3719
3720         let InferOk { obligations, .. } = self.infcx
3721             .at(&obligation.cause, obligation.param_env)
3722             .eq(skol_obligation_trait_ref, impl_trait_ref)
3723             .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3724         nested_obligations.extend(obligations);
3725
3726         if let Err(e) = self.infcx.leak_check(false, &placeholder_map, snapshot) {
3727             debug!("match_impl: failed leak check due to `{}`", e);
3728             return Err(());
3729         }
3730
3731         debug!("match_impl: success impl_substs={:?}", impl_substs);
3732         Ok(Normalized {
3733             value: impl_substs,
3734             obligations: nested_obligations,
3735         })
3736     }
3737
3738     fn fast_reject_trait_refs(
3739         &mut self,
3740         obligation: &TraitObligation<'_>,
3741         impl_trait_ref: &ty::TraitRef<'_>,
3742     ) -> bool {
3743         // We can avoid creating type variables and doing the full
3744         // substitution if we find that any of the input types, when
3745         // simplified, do not match.
3746
3747         obligation
3748             .predicate
3749             .skip_binder()
3750             .input_types()
3751             .zip(impl_trait_ref.input_types())
3752             .any(|(obligation_ty, impl_ty)| {
3753                 let simplified_obligation_ty =
3754                     fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3755                 let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
3756
3757                 simplified_obligation_ty.is_some()
3758                     && simplified_impl_ty.is_some()
3759                     && simplified_obligation_ty != simplified_impl_ty
3760             })
3761     }
3762
3763     /// Normalize `where_clause_trait_ref` and try to match it against
3764     /// `obligation`. If successful, return any predicates that
3765     /// result from the normalization. Normalization is necessary
3766     /// because where-clauses are stored in the parameter environment
3767     /// unnormalized.
3768     fn match_where_clause_trait_ref(
3769         &mut self,
3770         obligation: &TraitObligation<'tcx>,
3771         where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3772     ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3773         self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3774     }
3775
3776     /// Returns `Ok` if `poly_trait_ref` being true implies that the
3777     /// obligation is satisfied.
3778     fn match_poly_trait_ref(
3779         &mut self,
3780         obligation: &TraitObligation<'tcx>,
3781         poly_trait_ref: ty::PolyTraitRef<'tcx>,
3782     ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3783         debug!(
3784             "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3785             obligation, poly_trait_ref
3786         );
3787
3788         self.infcx
3789             .at(&obligation.cause, obligation.param_env)
3790             .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3791             .map(|InferOk { obligations, .. }| obligations)
3792             .map_err(|_| ())
3793     }
3794
3795     ///////////////////////////////////////////////////////////////////////////
3796     // Miscellany
3797
3798     fn match_fresh_trait_refs(
3799         &self,
3800         previous: &ty::PolyTraitRef<'tcx>,
3801         current: &ty::PolyTraitRef<'tcx>,
3802         param_env: ty::ParamEnv<'tcx>,
3803     ) -> bool {
3804         let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
3805         matcher.relate(previous, current).is_ok()
3806     }
3807
3808     fn push_stack<'o>(
3809         &mut self,
3810         previous_stack: TraitObligationStackList<'o, 'tcx>,
3811         obligation: &'o TraitObligation<'tcx>,
3812     ) -> TraitObligationStack<'o, 'tcx> {
3813         let fresh_trait_ref = obligation
3814             .predicate
3815             .to_poly_trait_ref()
3816             .fold_with(&mut self.freshener);
3817
3818         let dfn = previous_stack.cache.next_dfn();
3819         let depth = previous_stack.depth() + 1;
3820         TraitObligationStack {
3821             obligation,
3822             fresh_trait_ref,
3823             reached_depth: Cell::new(depth),
3824             previous: previous_stack,
3825             dfn,
3826             depth,
3827         }
3828     }
3829
3830     fn closure_trait_ref_unnormalized(
3831         &mut self,
3832         obligation: &TraitObligation<'tcx>,
3833         closure_def_id: DefId,
3834         substs: ty::ClosureSubsts<'tcx>,
3835     ) -> ty::PolyTraitRef<'tcx> {
3836         debug!(
3837             "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})",
3838             obligation, closure_def_id, substs,
3839         );
3840         let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3841
3842         debug!(
3843             "closure_trait_ref_unnormalized: closure_type = {:?}",
3844             closure_type
3845         );
3846
3847         // (1) Feels icky to skip the binder here, but OTOH we know
3848         // that the self-type is an unboxed closure type and hence is
3849         // in fact unparameterized (or at least does not reference any
3850         // regions bound in the obligation). Still probably some
3851         // refactoring could make this nicer.
3852         self.tcx()
3853             .closure_trait_ref_and_return_type(
3854                 obligation.predicate.def_id(),
3855                 obligation.predicate.skip_binder().self_ty(), // (1)
3856                 closure_type,
3857                 util::TupleArgumentsFlag::No,
3858             )
3859             .map_bound(|(trait_ref, _)| trait_ref)
3860     }
3861
3862     fn generator_trait_ref_unnormalized(
3863         &mut self,
3864         obligation: &TraitObligation<'tcx>,
3865         closure_def_id: DefId,
3866         substs: ty::GeneratorSubsts<'tcx>,
3867     ) -> ty::PolyTraitRef<'tcx> {
3868         let gen_sig = substs.poly_sig(closure_def_id, self.tcx());
3869
3870         // (1) Feels icky to skip the binder here, but OTOH we know
3871         // that the self-type is an generator type and hence is
3872         // in fact unparameterized (or at least does not reference any
3873         // regions bound in the obligation). Still probably some
3874         // refactoring could make this nicer.
3875
3876         self.tcx()
3877             .generator_trait_ref_and_outputs(
3878                 obligation.predicate.def_id(),
3879                 obligation.predicate.skip_binder().self_ty(), // (1)
3880                 gen_sig,
3881             )
3882             .map_bound(|(trait_ref, ..)| trait_ref)
3883     }
3884
3885     /// Returns the obligations that are implied by instantiating an
3886     /// impl or trait. The obligations are substituted and fully
3887     /// normalized. This is used when confirming an impl or default
3888     /// impl.
3889     fn impl_or_trait_obligations(
3890         &mut self,
3891         cause: ObligationCause<'tcx>,
3892         recursion_depth: usize,
3893         param_env: ty::ParamEnv<'tcx>,
3894         def_id: DefId,         // of impl or trait
3895         substs: SubstsRef<'tcx>,  // for impl or trait
3896     ) -> Vec<PredicateObligation<'tcx>> {
3897         debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3898         let tcx = self.tcx();
3899
3900         // To allow for one-pass evaluation of the nested obligation,
3901         // each predicate must be preceded by the obligations required
3902         // to normalize it.
3903         // for example, if we have:
3904         //    impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
3905         // the impl will have the following predicates:
3906         //    <V as Iterator>::Item = U,
3907         //    U: Iterator, U: Sized,
3908         //    V: Iterator, V: Sized,
3909         //    <U as Iterator>::Item: Copy
3910         // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3911         // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3912         // `$1: Copy`, so we must ensure the obligations are emitted in
3913         // that order.
3914         let predicates = tcx.predicates_of(def_id);
3915         assert_eq!(predicates.parent, None);
3916         let mut predicates: Vec<_> = predicates
3917             .predicates
3918             .iter()
3919             .flat_map(|(predicate, _)| {
3920                 let predicate = normalize_with_depth(
3921                     self,
3922                     param_env,
3923                     cause.clone(),
3924                     recursion_depth,
3925                     &predicate.subst(tcx, substs),
3926                 );
3927                 predicate.obligations.into_iter().chain(Some(Obligation {
3928                     cause: cause.clone(),
3929                     recursion_depth,
3930                     param_env,
3931                     predicate: predicate.value,
3932                 }))
3933             })
3934             .collect();
3935
3936         // We are performing deduplication here to avoid exponential blowups
3937         // (#38528) from happening, but the real cause of the duplication is
3938         // unknown. What we know is that the deduplication avoids exponential
3939         // amount of predicates being propagated when processing deeply nested
3940         // types.
3941         //
3942         // This code is hot enough that it's worth avoiding the allocation
3943         // required for the FxHashSet when possible. Special-casing lengths 0,
3944         // 1 and 2 covers roughly 75--80% of the cases.
3945         if predicates.len() <= 1 {
3946             // No possibility of duplicates.
3947         } else if predicates.len() == 2 {
3948             // Only two elements. Drop the second if they are equal.
3949             if predicates[0] == predicates[1] {
3950                 predicates.truncate(1);
3951             }
3952         } else {
3953             // Three or more elements. Use a general deduplication process.
3954             let mut seen = FxHashSet::default();
3955             predicates.retain(|i| seen.insert(i.clone()));
3956         }
3957
3958         predicates
3959     }
3960 }
3961
3962 impl<'tcx> TraitObligation<'tcx> {
3963     #[allow(unused_comparisons)]
3964     pub fn derived_cause(
3965         &self,
3966         variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3967     ) -> ObligationCause<'tcx> {
3968         /*!
3969          * Creates a cause for obligations that are derived from
3970          * `obligation` by a recursive search (e.g., for a builtin
3971          * bound, or eventually a `auto trait Foo`). If `obligation`
3972          * is itself a derived obligation, this is just a clone, but
3973          * otherwise we create a "derived obligation" cause so as to
3974          * keep track of the original root obligation for error
3975          * reporting.
3976          */
3977
3978         let obligation = self;
3979
3980         // NOTE(flaper87): As of now, it keeps track of the whole error
3981         // chain. Ideally, we should have a way to configure this either
3982         // by using -Z verbose or just a CLI argument.
3983         if obligation.recursion_depth >= 0 {
3984             let derived_cause = DerivedObligationCause {
3985                 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3986                 parent_code: Rc::new(obligation.cause.code.clone()),
3987             };
3988             let derived_code = variant(derived_cause);
3989             ObligationCause::new(
3990                 obligation.cause.span,
3991                 obligation.cause.body_id,
3992                 derived_code,
3993             )
3994         } else {
3995             obligation.cause.clone()
3996         }
3997     }
3998 }
3999
4000 impl<'tcx> SelectionCache<'tcx> {
4001     /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
4002     pub fn clear(&self) {
4003         *self.hashmap.borrow_mut() = Default::default();
4004     }
4005 }
4006
4007 impl<'tcx> EvaluationCache<'tcx> {
4008     /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
4009     pub fn clear(&self) {
4010         *self.hashmap.borrow_mut() = Default::default();
4011     }
4012 }
4013
4014 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
4015     fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
4016         TraitObligationStackList::with(self)
4017     }
4018
4019     fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
4020         self.previous.cache
4021     }
4022
4023     fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
4024         self.list()
4025     }
4026
4027     /// Indicates that attempting to evaluate this stack entry
4028     /// required accessing something from the stack at depth `reached_depth`.
4029     fn update_reached_depth(&self, reached_depth: usize) {
4030         assert!(
4031             self.depth > reached_depth,
4032             "invoked `update_reached_depth` with something under this stack: \
4033              self.depth={} reached_depth={}",
4034             self.depth,
4035             reached_depth,
4036         );
4037         debug!("update_reached_depth(reached_depth={})", reached_depth);
4038         let mut p = self;
4039         while reached_depth < p.depth {
4040             debug!("update_reached_depth: marking {:?} as cycle participant", p.fresh_trait_ref);
4041             p.reached_depth.set(p.reached_depth.get().min(reached_depth));
4042             p = p.previous.head.unwrap();
4043         }
4044     }
4045 }
4046
4047 /// The "provisional evaluation cache" is used to store intermediate cache results
4048 /// when solving auto traits. Auto traits are unusual in that they can support
4049 /// cycles. So, for example, a "proof tree" like this would be ok:
4050 ///
4051 /// - `Foo<T>: Send` :-
4052 ///   - `Bar<T>: Send` :-
4053 ///     - `Foo<T>: Send` -- cycle, but ok
4054 ///   - `Baz<T>: Send`
4055 ///
4056 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
4057 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
4058 /// For non-auto traits, this cycle would be an error, but for auto traits (because
4059 /// they are coinductive) it is considered ok.
4060 ///
4061 /// However, there is a complication: at the point where we have
4062 /// "proven" `Bar<T>: Send`, we have in fact only proven it
4063 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
4064 /// *under the assumption* that `Foo<T>: Send`. But what if we later
4065 /// find out this assumption is wrong?  Specifically, we could
4066 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
4067 /// `Bar<T>: Send` didn't turn out to be true.
4068 ///
4069 /// In Issue #60010, we found a bug in rustc where it would cache
4070 /// these intermediate results. This was fixed in #60444 by disabling
4071 /// *all* caching for things involved in a cycle -- in our example,
4072 /// that would mean we don't cache that `Bar<T>: Send`.  But this led
4073 /// to large slowdowns.
4074 ///
4075 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
4076 /// first requires proving `Bar<T>: Send` (which is true:
4077 ///
4078 /// - `Foo<T>: Send` :-
4079 ///   - `Bar<T>: Send` :-
4080 ///     - `Foo<T>: Send` -- cycle, but ok
4081 ///   - `Baz<T>: Send`
4082 ///     - `Bar<T>: Send` -- would be nice for this to be a cache hit!
4083 ///     - `*const T: Send` -- but what if we later encounter an error?
4084 ///
4085 /// The *provisional evaluation cache* resolves this issue. It stores
4086 /// cache results that we've proven but which were involved in a cycle
4087 /// in some way. We track the minimal stack depth (i.e., the
4088 /// farthest from the top of the stack) that we are dependent on.
4089 /// The idea is that the cache results within are all valid -- so long as
4090 /// none of the nodes in between the current node and the node at that minimum
4091 /// depth result in an error (in which case the cached results are just thrown away).
4092 ///
4093 /// During evaluation, we consult this provisional cache and rely on
4094 /// it. Accessing a cached value is considered equivalent to accessing
4095 /// a result at `reached_depth`, so it marks the *current* solution as
4096 /// provisional as well. If an error is encountered, we toss out any
4097 /// provisional results added from the subtree that encountered the
4098 /// error.  When we pop the node at `reached_depth` from the stack, we
4099 /// can commit all the things that remain in the provisional cache.
4100 struct ProvisionalEvaluationCache<'tcx> {
4101     /// next "depth first number" to issue -- just a counter
4102     dfn: Cell<usize>,
4103
4104     /// Stores the "coldest" depth (bottom of stack) reached by any of
4105     /// the evaluation entries. The idea here is that all things in the provisional
4106     /// cache are always dependent on *something* that is colder in the stack:
4107     /// therefore, if we add a new entry that is dependent on something *colder still*,
4108     /// we have to modify the depth for all entries at once.
4109     ///
4110     /// Example:
4111     ///
4112     /// Imagine we have a stack `A B C D E` (with `E` being the top of
4113     /// the stack).  We cache something with depth 2, which means that
4114     /// it was dependent on C.  Then we pop E but go on and process a
4115     /// new node F: A B C D F.  Now F adds something to the cache with
4116     /// depth 1, meaning it is dependent on B.  Our original cache
4117     /// entry is also dependent on B, because there is a path from E
4118     /// to C and then from C to F and from F to B.
4119     reached_depth: Cell<usize>,
4120
4121     /// Map from cache key to the provisionally evaluated thing.
4122     /// The cache entries contain the result but also the DFN in which they
4123     /// were added. The DFN is used to clear out values on failure.
4124     ///
4125     /// Imagine we have a stack like:
4126     ///
4127     /// - `A B C` and we add a cache for the result of C (DFN 2)
4128     /// - Then we have a stack `A B D` where `D` has DFN 3
4129     /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
4130     /// - `E` generates various cache entries which have cyclic dependices on `B`
4131     ///   - `A B D E F` and so forth
4132     ///   - the DFN of `F` for example would be 5
4133     /// - then we determine that `E` is in error -- we will then clear
4134     ///   all cache values whose DFN is >= 4 -- in this case, that
4135     ///   means the cached value for `F`.
4136     map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
4137 }
4138
4139 /// A cache value for the provisional cache: contains the depth-first
4140 /// number (DFN) and result.
4141 #[derive(Copy, Clone, Debug)]
4142 struct ProvisionalEvaluation {
4143     from_dfn: usize,
4144     result: EvaluationResult,
4145 }
4146
4147 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
4148     fn default() -> Self {
4149         Self {
4150             dfn: Cell::new(0),
4151             reached_depth: Cell::new(std::usize::MAX),
4152             map: Default::default(),
4153         }
4154     }
4155 }
4156
4157 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
4158     /// Get the next DFN in sequence (basically a counter).
4159     fn next_dfn(&self) -> usize {
4160         let result = self.dfn.get();
4161         self.dfn.set(result + 1);
4162         result
4163     }
4164
4165     /// Check the provisional cache for any result for
4166     /// `fresh_trait_ref`. If there is a hit, then you must consider
4167     /// it an access to the stack slots at depth
4168     /// `self.current_reached_depth()` and above.
4169     fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
4170         debug!(
4171             "get_provisional(fresh_trait_ref={:?}) = {:#?} with reached-depth {}",
4172             fresh_trait_ref,
4173             self.map.borrow().get(&fresh_trait_ref),
4174             self.reached_depth.get(),
4175         );
4176         Some(self.map.borrow().get(&fresh_trait_ref)?.result)
4177     }
4178
4179     /// Current value of the `reached_depth` counter -- all the
4180     /// provisional cache entries are dependent on the item at this
4181     /// depth.
4182     fn current_reached_depth(&self) -> usize {
4183         self.reached_depth.get()
4184     }
4185
4186     /// Insert a provisional result into the cache. The result came
4187     /// from the node with the given DFN. It accessed a minimum depth
4188     /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
4189     /// and resulted in `result`.
4190     fn insert_provisional(
4191         &self,
4192         from_dfn: usize,
4193         reached_depth: usize,
4194         fresh_trait_ref: ty::PolyTraitRef<'tcx>,
4195         result: EvaluationResult,
4196     ) {
4197         debug!(
4198             "insert_provisional(from_dfn={}, reached_depth={}, fresh_trait_ref={:?}, result={:?})",
4199             from_dfn,
4200             reached_depth,
4201             fresh_trait_ref,
4202             result,
4203         );
4204         let r_d = self.reached_depth.get();
4205         self.reached_depth.set(r_d.min(reached_depth));
4206
4207         debug!("insert_provisional: reached_depth={:?}", self.reached_depth.get());
4208
4209         self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
4210     }
4211
4212     /// Invoked when the node with dfn `dfn` does not get a successful
4213     /// result.  This will clear out any provisional cache entries
4214     /// that were added since `dfn` was created. This is because the
4215     /// provisional entries are things which must assume that the
4216     /// things on the stack at the time of their creation succeeded --
4217     /// since the failing node is presently at the top of the stack,
4218     /// these provisional entries must either depend on it or some
4219     /// ancestor of it.
4220     fn on_failure(&self, dfn: usize) {
4221         debug!(
4222             "on_failure(dfn={:?})",
4223             dfn,
4224         );
4225         self.map.borrow_mut().retain(|key, eval| {
4226             if !eval.from_dfn >= dfn {
4227                 debug!("on_failure: removing {:?}", key);
4228                 false
4229             } else {
4230                 true
4231             }
4232         });
4233     }
4234
4235     /// Invoked when the node at depth `depth` completed without
4236     /// depending on anything higher in the stack (if that completion
4237     /// was a failure, then `on_failure` should have been invoked
4238     /// already). The callback `op` will be invoked for each
4239     /// provisional entry that we can now confirm.
4240     fn on_completion(
4241         &self,
4242         depth: usize,
4243         mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
4244     ) {
4245         debug!(
4246             "on_completion(depth={}, reached_depth={})",
4247             depth,
4248             self.reached_depth.get(),
4249         );
4250
4251         if self.reached_depth.get() < depth {
4252             debug!("on_completion: did not yet reach depth to complete");
4253             return;
4254         }
4255
4256         for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
4257             debug!(
4258                 "on_completion: fresh_trait_ref={:?} eval={:?}",
4259                 fresh_trait_ref,
4260                 eval,
4261             );
4262
4263             op(fresh_trait_ref, eval.result);
4264         }
4265
4266         self.reached_depth.set(std::usize::MAX);
4267     }
4268 }
4269
4270 #[derive(Copy, Clone)]
4271 struct TraitObligationStackList<'o, 'tcx> {
4272     cache: &'o ProvisionalEvaluationCache<'tcx>,
4273     head: Option<&'o TraitObligationStack<'o, 'tcx>>,
4274 }
4275
4276 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
4277     fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4278         TraitObligationStackList { cache, head: None }
4279     }
4280
4281     fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4282         TraitObligationStackList { cache: r.cache(), head: Some(r) }
4283     }
4284
4285     fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4286         self.head
4287     }
4288
4289     fn depth(&self) -> usize {
4290         if let Some(head) = self.head {
4291             head.depth
4292         } else {
4293             0
4294         }
4295     }
4296 }
4297
4298 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
4299     type Item = &'o TraitObligationStack<'o, 'tcx>;
4300
4301     fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4302         match self.head {
4303             Some(o) => {
4304                 *self = o.previous;
4305                 Some(o)
4306             }
4307             None => None,
4308         }
4309     }
4310 }
4311
4312 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
4313     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4314         write!(f, "TraitObligationStack({:?})", self.obligation)
4315     }
4316 }
4317
4318 #[derive(Clone, Eq, PartialEq)]
4319 pub struct WithDepNode<T> {
4320     dep_node: DepNodeIndex,
4321     cached_value: T,
4322 }
4323
4324 impl<T: Clone> WithDepNode<T> {
4325     pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
4326         WithDepNode {
4327             dep_node,
4328             cached_value,
4329         }
4330     }
4331
4332     pub fn get(&self, tcx: TyCtxt<'_>) -> T {
4333         tcx.dep_graph.read_index(self.dep_node);
4334         self.cached_value.clone()
4335     }
4336 }