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