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