Skip to main content

rustc_type_ir/
binder.rs

1use std::fmt;
2use std::hash::Hash;
3use std::marker::PhantomData;
4use std::ops::{ControlFlow, Deref};
5
6use derive_where::derive_where;
7#[cfg(feature = "nightly")]
8use rustc_macros::{Decodable_NoContext, Encodable_NoContext, StableHash, StableHash_NoContext};
9use rustc_type_ir_macros::{
10    GenericTypeVisitable, Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic,
11};
12use tracing::instrument;
13
14use crate::data_structures::SsoHashSet;
15use crate::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable};
16use crate::inherent::*;
17use crate::visit::{Flags, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor};
18use crate::{self as ty, DebruijnIndex, Interner, Region, UniverseIndex, Unnormalized};
19
20/// `Binder` is a binder for higher-ranked lifetimes or types. It is part of the
21/// compiler's representation for things like `for<'a> Fn(&'a isize)`
22/// (which would be represented by the type `PolyTraitRef == Binder<I, TraitRef>`).
23///
24/// See <https://rustc-dev-guide.rust-lang.org/ty_module/instantiating_binders.html>
25/// for more details.
26#[automatically_derived]
impl<I: Interner, T> ::core::fmt::Debug for Binder<I, T> where I: Interner,
    T: ::core::fmt::Debug {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            Binder {
                value: ref __field_value, bound_vars: ref __field_bound_vars }
                => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f, "Binder");
                ::core::fmt::DebugStruct::field(&mut __builder, "value",
                    __field_value);
                ::core::fmt::DebugStruct::field(&mut __builder, "bound_vars",
                    __field_bound_vars);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
        }
    }
}#[derive_where(Clone, Copy, Hash, PartialEq, Debug; I: Interner, T)]
27#[derive(GenericTypeVisitable, const _: () =
    {
        impl<I: Interner, T, J> ::rustc_type_ir::lift::Lift<J> for
            Binder<I, T> where J: Interner, I: ::rustc_type_ir::LiftInto<J>,
            T: ::rustc_type_ir::lift::Lift<J> {
            type Lifted =
                Binder<J, <T as ::rustc_type_ir::lift::Lift<J>>::Lifted>;
            fn lift_to_interner(self, interner: J) -> Self::Lifted {
                match self {
                    Binder { value: __binding_0, bound_vars: __binding_1 } => {
                        Binder {
                            value: __binding_0.lift_to_interner(interner),
                            bound_vars: __binding_1.lift_to_interner(interner),
                        }
                    }
                }
            }
        }
    };Lift_Generic)]
28#[cfg_attr(feature = "nightly", derive(const _: () =
    {
        impl<I: Interner, T> ::rustc_data_structures::stable_hash::StableHash
            for Binder<I, T> where
            T: ::rustc_data_structures::stable_hash::StableHash,
            I::BoundVarKinds: ::rustc_data_structures::stable_hash::StableHash
            {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Binder { value: ref __binding_0, bound_vars: ref __binding_1
                        } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash_NoContext))]
29pub struct Binder<I: Interner, T> {
30    value: T,
31    bound_vars: I::BoundVarKinds,
32}
33
34impl<I: Interner, T: Eq> Eq for Binder<I, T> {}
35
36impl<I: Interner, T> Binder<I, T>
37where
38    T: TypeVisitable<I>,
39{
40    /// Wraps `value` in a binder, asserting that `value` does not
41    /// contain any bound vars that would be bound by the
42    /// binder. This is commonly used to 'inject' a value T into a
43    /// different binding level.
44    #[track_caller]
45    pub fn dummy(value: T) -> Binder<I, T> {
46        if !!value.has_escaping_bound_vars() {
    {
        ::core::panicking::panic_fmt(format_args!("`{0:?}` has escaping bound vars, so it cannot be wrapped in a dummy binder.",
                value));
    }
};assert!(
47            !value.has_escaping_bound_vars(),
48            "`{value:?}` has escaping bound vars, so it cannot be wrapped in a dummy binder."
49        );
50        Binder { value, bound_vars: Default::default() }
51    }
52
53    pub fn bind_with_vars(value: T, bound_vars: I::BoundVarKinds) -> Binder<I, T> {
54        if truecfg!(debug_assertions) {
55            let mut validator = ValidateBoundVars::new(bound_vars);
56            let _ = value.visit_with(&mut validator);
57        }
58        Binder { value, bound_vars }
59    }
60}
61
62impl<I: Interner, T: TypeFoldable<I>> TypeFoldable<I> for Binder<I, T> {
63    fn try_fold_with<F: FallibleTypeFolder<I>>(self, folder: &mut F) -> Result<Self, F::Error> {
64        folder.try_fold_binder(self)
65    }
66
67    fn fold_with<F: TypeFolder<I>>(self, folder: &mut F) -> Self {
68        folder.fold_binder(self)
69    }
70}
71
72impl<I: Interner, T: TypeVisitable<I>> TypeVisitable<I> for Binder<I, T> {
73    fn visit_with<V: TypeVisitor<I>>(&self, visitor: &mut V) -> V::Result {
74        visitor.visit_binder(self)
75    }
76}
77
78impl<I: Interner, T: TypeFoldable<I>> TypeSuperFoldable<I> for Binder<I, T> {
79    fn try_super_fold_with<F: FallibleTypeFolder<I>>(
80        self,
81        folder: &mut F,
82    ) -> Result<Self, F::Error> {
83        self.try_map_bound(|t| t.try_fold_with(folder))
84    }
85
86    fn super_fold_with<F: TypeFolder<I>>(self, folder: &mut F) -> Self {
87        self.map_bound(|t| t.fold_with(folder))
88    }
89}
90
91impl<I: Interner, T: TypeVisitable<I>> TypeSuperVisitable<I> for Binder<I, T> {
92    fn super_visit_with<V: TypeVisitor<I>>(&self, visitor: &mut V) -> V::Result {
93        self.as_ref().skip_binder().visit_with(visitor)
94    }
95}
96
97impl<I: Interner, T> Binder<I, T> {
98    /// Returns the value contained inside of this `for<'a>`. Accessing generic args
99    /// in the returned value is generally incorrect.
100    ///
101    /// Please read <https://rustc-dev-guide.rust-lang.org/ty_module/instantiating_binders.html>
102    /// before using this function. It is usually better to discharge the binder using
103    /// `no_bound_vars` or `instantiate_bound_regions` or something like that.
104    ///
105    /// `skip_binder` is only valid when you are either extracting data that does not reference
106    /// any generic arguments, e.g. a `DefId`, or when you're making sure you only pass the
107    /// value to things which can handle escaping bound vars.
108    ///
109    /// See existing uses of `.skip_binder()` in `rustc_trait_selection::traits::select`
110    /// or `rustc_next_trait_solver` for examples.
111    pub fn skip_binder(self) -> T {
112        self.value
113    }
114
115    pub fn bound_vars(&self) -> I::BoundVarKinds {
116        self.bound_vars
117    }
118
119    pub fn as_ref(&self) -> Binder<I, &T> {
120        Binder { value: &self.value, bound_vars: self.bound_vars }
121    }
122
123    pub fn as_deref(&self) -> Binder<I, &T::Target>
124    where
125        T: Deref,
126    {
127        Binder { value: &self.value, bound_vars: self.bound_vars }
128    }
129
130    pub fn map_bound_ref<F, U: TypeVisitable<I>>(&self, f: F) -> Binder<I, U>
131    where
132        F: FnOnce(&T) -> U,
133    {
134        self.as_ref().map_bound(f)
135    }
136
137    pub fn map_bound<F, U: TypeVisitable<I>>(self, f: F) -> Binder<I, U>
138    where
139        F: FnOnce(T) -> U,
140    {
141        let Binder { value, bound_vars } = self;
142        let value = f(value);
143        if truecfg!(debug_assertions) {
144            let mut validator = ValidateBoundVars::new(bound_vars);
145            let _ = value.visit_with(&mut validator);
146        }
147        Binder { value, bound_vars }
148    }
149
150    pub fn try_map_bound<F, U: TypeVisitable<I>, E>(self, f: F) -> Result<Binder<I, U>, E>
151    where
152        F: FnOnce(T) -> Result<U, E>,
153    {
154        let Binder { value, bound_vars } = self;
155        let value = f(value)?;
156        if truecfg!(debug_assertions) {
157            let mut validator = ValidateBoundVars::new(bound_vars);
158            let _ = value.visit_with(&mut validator);
159        }
160        Ok(Binder { value, bound_vars })
161    }
162
163    /// Wraps a `value` in a binder, using the same bound variables as the
164    /// current `Binder`. This should not be used if the new value *changes*
165    /// the bound variables. Note: the (old or new) value itself does not
166    /// necessarily need to *name* all the bound variables.
167    ///
168    /// This currently doesn't do anything different than `bind`, because we
169    /// don't actually track bound vars. However, semantically, it is different
170    /// because bound vars aren't allowed to change here, whereas they are
171    /// in `bind`. This may be (debug) asserted in the future.
172    pub fn rebind<U>(&self, value: U) -> Binder<I, U>
173    where
174        U: TypeVisitable<I>,
175    {
176        Binder::bind_with_vars(value, self.bound_vars)
177    }
178
179    /// Unwraps and returns the value within, but only if it contains
180    /// no bound vars at all. (In other words, if this binder --
181    /// and indeed any enclosing binder -- doesn't bind anything at
182    /// all.) Otherwise, returns `None`.
183    ///
184    /// (One could imagine having a method that just unwraps a single
185    /// binder, but permits late-bound vars bound by enclosing
186    /// binders, but that would require adjusting the debruijn
187    /// indices, and given the shallow binding structure we often use,
188    /// would not be that useful.)
189    pub fn no_bound_vars(self) -> Option<T>
190    where
191        T: TypeVisitable<I>,
192    {
193        // `self.value` is equivalent to `self.skip_binder()`
194        if self.value.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) }
195    }
196}
197
198impl<I: Interner, T> Binder<I, Option<T>> {
199    pub fn transpose(self) -> Option<Binder<I, T>> {
200        let Binder { value, bound_vars } = self;
201        value.map(|value| Binder { value, bound_vars })
202    }
203}
204
205impl<I: Interner, T: IntoIterator> Binder<I, T> {
206    pub fn iter(self) -> impl Iterator<Item = Binder<I, T::Item>> {
207        let Binder { value, bound_vars } = self;
208        value.into_iter().map(move |value| Binder { value, bound_vars })
209    }
210}
211
212pub struct ValidateBoundVars<I: Interner> {
213    bound_vars: I::BoundVarKinds,
214    binder_index: ty::DebruijnIndex,
215    // We only cache types because any complex const will have to step through
216    // a type at some point anyways. We may encounter the same variable at
217    // different levels of binding, so this can't just be `Ty`.
218    visited: SsoHashSet<(ty::DebruijnIndex, I::Ty)>,
219}
220
221impl<I: Interner> ValidateBoundVars<I> {
222    pub fn new(bound_vars: I::BoundVarKinds) -> Self {
223        ValidateBoundVars {
224            bound_vars,
225            binder_index: ty::INNERMOST,
226            visited: SsoHashSet::default(),
227        }
228    }
229}
230
231impl<I: Interner> TypeVisitor<I> for ValidateBoundVars<I> {
232    type Result = ControlFlow<()>;
233
234    fn visit_binder<T: TypeVisitable<I>>(&mut self, t: &Binder<I, T>) -> Self::Result {
235        self.binder_index.shift_in(1);
236        let result = t.super_visit_with(self);
237        self.binder_index.shift_out(1);
238        result
239    }
240
241    fn visit_ty(&mut self, t: I::Ty) -> Self::Result {
242        if t.outer_exclusive_binder() < self.binder_index
243            || !self.visited.insert((self.binder_index, t))
244        {
245            return ControlFlow::Break(());
246        }
247        match t.kind() {
248            ty::Bound(ty::BoundVarIndexKind::Bound(debruijn), bound_ty)
249                if debruijn == self.binder_index =>
250            {
251                let idx = bound_ty.var().as_usize();
252                if self.bound_vars.len() <= idx {
253                    {
    ::core::panicking::panic_fmt(format_args!("Not enough bound vars: {0:?} not found in {1:?}",
            t, self.bound_vars));
};panic!("Not enough bound vars: {:?} not found in {:?}", t, self.bound_vars);
254                }
255                bound_ty.assert_eq(self.bound_vars.get(idx).unwrap());
256            }
257            _ => {}
258        };
259
260        t.super_visit_with(self)
261    }
262
263    fn visit_const(&mut self, c: I::Const) -> Self::Result {
264        if c.outer_exclusive_binder() < self.binder_index {
265            return ControlFlow::Break(());
266        }
267        match c.kind() {
268            ty::ConstKind::Bound(debruijn, bound_const)
269                if debruijn == ty::BoundVarIndexKind::Bound(self.binder_index) =>
270            {
271                let idx = bound_const.var().as_usize();
272                if self.bound_vars.len() <= idx {
273                    {
    ::core::panicking::panic_fmt(format_args!("Not enough bound vars: {0:?} not found in {1:?}",
            c, self.bound_vars));
};panic!("Not enough bound vars: {:?} not found in {:?}", c, self.bound_vars);
274                }
275                bound_const.assert_eq(self.bound_vars.get(idx).unwrap());
276            }
277            _ => {}
278        };
279
280        c.super_visit_with(self)
281    }
282
283    fn visit_region(&mut self, r: Region<I>) -> Self::Result {
284        match r.kind() {
285            ty::ReBound(index, br) if index == ty::BoundVarIndexKind::Bound(self.binder_index) => {
286                let idx = br.var().as_usize();
287                if self.bound_vars.len() <= idx {
288                    {
    ::core::panicking::panic_fmt(format_args!("Not enough bound vars: {0:?} not found in {1:?}",
            r, self.bound_vars));
};panic!("Not enough bound vars: {:?} not found in {:?}", r, self.bound_vars);
289                }
290                br.assert_eq(self.bound_vars.get(idx).unwrap());
291            }
292
293            _ => (),
294        };
295
296        ControlFlow::Continue(())
297    }
298}
299
300/// Similar to [`Binder`] except that it tracks early bound generics, i.e. `struct Foo<T>(T)`
301/// needs `T` instantiated immediately. This type primarily exists to avoid forgetting to call
302/// `instantiate`.
303///
304/// See <https://rustc-dev-guide.rust-lang.org/ty_module/early_binder.html> for more details.
305#[automatically_derived]
impl<I: Interner, T> ::core::fmt::Debug for EarlyBinder<I, T> where
    I: Interner, T: ::core::fmt::Debug {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            EarlyBinder { value: ref __field_value, _tcx: ref __field__tcx }
                => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f, "EarlyBinder");
                ::core::fmt::DebugStruct::field(&mut __builder, "value",
                    __field_value);
                ::core::fmt::DebugStruct::finish_non_exhaustive(&mut __builder)
            }
        }
    }
}#[derive_where(Clone, Copy, PartialOrd, Ord, PartialEq, Hash, Debug; I: Interner, T)]
306#[derive(GenericTypeVisitable)]
307#[cfg_attr(
308    feature = "nightly",
309    derive(const _: () =
    {
        impl<I: Interner, T, __E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for EarlyBinder<I, T> where
            T: ::rustc_serialize::Encodable<__E>,
            PhantomData<fn() -> I>: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    EarlyBinder { value: ref __binding_0, _tcx: ref __binding_1
                        } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<I: Interner, T, __D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for EarlyBinder<I, T> where
            T: ::rustc_serialize::Decodable<__D>,
            PhantomData<fn() -> I>: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                EarlyBinder {
                    value: ::rustc_serialize::Decodable::decode(__decoder),
                    _tcx: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl<I: Interner, T> ::rustc_data_structures::stable_hash::StableHash
            for EarlyBinder<I, T> where
            T: ::rustc_data_structures::stable_hash::StableHash,
            PhantomData<fn()
                -> I>: ::rustc_data_structures::stable_hash::StableHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    EarlyBinder { value: ref __binding_0, _tcx: ref __binding_1
                        } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash_NoContext)
310)]
311pub struct EarlyBinder<I: Interner, T> {
312    value: T,
313    #[derive_where(skip(Debug))]
314    _tcx: PhantomData<fn() -> I>,
315}
316
317impl<I: Interner, T: Eq> Eq for EarlyBinder<I, T> {}
318
319// FIXME(154045): Recommended as per https://github.com/rust-lang/rust/issues/154045, this is so sad :((
320#[cfg(feature = "nightly")]
321macro_rules! generate { ($( $tt:tt )*) => { $( $tt )* } }
322
323#[cfg(feature = "nightly")]
324generate!(
325    /// For early binders, you should first call `instantiate` before using any visitors.
326    impl<I: Interner, T> !TypeFoldable<I> for ty::EarlyBinder<I, T> {}
327    /// For early binders, you should first call `instantiate` before using any visitors.
328    impl<I: Interner, T> !TypeVisitable<I> for ty::EarlyBinder<I, T> {}
329);
330
331impl<I: Interner, T: TypeFoldable<I>> EarlyBinder<I, T> {
332    pub fn bind(cx: I, value: T) -> EarlyBinder<I, T> {
333        // Instantiation will require normalization.
334        let value = ty::set_aliases_to_non_rigid(cx, value).skip_normalization();
335        EarlyBinder { value, _tcx: PhantomData }
336    }
337}
338
339impl<I: Interner, T: IntoIterator<Item: TypeVisitable<I>> + Clone> EarlyBinder<I, T> {
340    pub fn bind_iter(value: T) -> EarlyBinder<I, T> {
341        #[cfg(debug_assertions)]
342        {
343            value.clone().into_iter().for_each(|v| if !!v.has_rigid_aliases() {
    ::core::panicking::panic("assertion failed: !v.has_rigid_aliases()")
}assert!(!v.has_rigid_aliases()));
344        }
345
346        EarlyBinder { value, _tcx: PhantomData }
347    }
348}
349
350impl<I: Interner, T: TypeVisitable<I>> EarlyBinder<I, T> {
351    pub fn bind_no_rigid_aliases(value: T) -> EarlyBinder<I, T> {
352        if true {
    if !!value.has_rigid_aliases() {
        ::core::panicking::panic("assertion failed: !value.has_rigid_aliases()")
    };
};debug_assert!(!value.has_rigid_aliases());
353        EarlyBinder { value, _tcx: PhantomData }
354    }
355}
356
357impl<I: Interner, T> EarlyBinder<I, T> {
358    /// Use `bind/bind_iter/bind_no_rigid_aliases` instead.
359    /// Don't use this unless you know what you're doing.
360    pub fn bind_unchecked(value: T) -> EarlyBinder<I, T> {
361        EarlyBinder { value, _tcx: PhantomData }
362    }
363}
364
365impl<I: Interner, T> EarlyBinder<I, T> {
366    pub fn as_ref(&self) -> EarlyBinder<I, &T> {
367        EarlyBinder { value: &self.value, _tcx: PhantomData }
368    }
369
370    pub fn map_bound_ref<F, U>(&self, f: F) -> EarlyBinder<I, U>
371    where
372        F: FnOnce(&T) -> U,
373    {
374        self.as_ref().map_bound(f)
375    }
376
377    pub fn map_bound<F, U>(self, f: F) -> EarlyBinder<I, U>
378    where
379        F: FnOnce(T) -> U,
380    {
381        let value = f(self.value);
382        EarlyBinder { value, _tcx: PhantomData }
383    }
384
385    pub fn try_map_bound<F, U, E>(self, f: F) -> Result<EarlyBinder<I, U>, E>
386    where
387        F: FnOnce(T) -> Result<U, E>,
388    {
389        let value = f(self.value)?;
390        Ok(EarlyBinder { value, _tcx: PhantomData })
391    }
392
393    pub fn rebind<U>(&self, value: U) -> EarlyBinder<I, U> {
394        EarlyBinder { value, _tcx: PhantomData }
395    }
396
397    /// Skips the binder and returns the "bound" value. Accessing generic args
398    /// in the returned value is generally incorrect.
399    ///
400    /// Please read <https://rustc-dev-guide.rust-lang.org/ty_module/early_binder.html>
401    /// before using this function.
402    ///
403    /// Only use this to extract data that does not depend on generic parameters, e.g.
404    /// to get the `DefId` of the inner value or the number of arguments ofan `FnSig`,
405    /// or while making sure to only pass the value to functions which are explicitly
406    /// set up to handle these uninstantiated generic parameters.
407    ///
408    /// To skip the binder on `x: &EarlyBinder<I, T>` to obtain `&T`, leverage
409    /// [`EarlyBinder::as_ref`](EarlyBinder::as_ref): `x.as_ref().skip_binder()`.
410    ///
411    /// See also [`Binder::skip_binder`](Binder::skip_binder), which is
412    /// the analogous operation on [`Binder`].
413    pub fn skip_binder(self) -> T {
414        self.value
415    }
416}
417
418impl<I: Interner> EarlyBinder<I, ty::TraitRef<I>> {
419    pub fn def_id(&self) -> I::TraitId {
420        self.value.def_id
421    }
422}
423
424impl<I: Interner, T> EarlyBinder<I, Option<T>> {
425    pub fn transpose(self) -> Option<EarlyBinder<I, T>> {
426        self.value.map(|value| EarlyBinder { value, _tcx: PhantomData })
427    }
428}
429
430impl<I: Interner, Iter: IntoIterator> EarlyBinder<I, Iter>
431where
432    Iter::Item: TypeFoldable<I>,
433{
434    pub fn iter_instantiated<A>(self, cx: I, args: A) -> IterInstantiated<I, Iter, A>
435    where
436        A: SliceLike<Item = I::GenericArg>,
437    {
438        IterInstantiated { it: self.value.into_iter(), cx, args }
439    }
440
441    /// Similar to [`instantiate_identity`](EarlyBinder::instantiate_identity),
442    /// but on an iterator of `TypeFoldable` values.
443    pub fn iter_identity(self) -> impl Iterator<Item = Unnormalized<I, Iter::Item>> {
444        self.value.into_iter().map(Unnormalized::new)
445    }
446}
447
448pub struct IterInstantiated<I: Interner, Iter: IntoIterator, A> {
449    it: Iter::IntoIter,
450    cx: I,
451    args: A,
452}
453
454impl<I: Interner, Iter: IntoIterator, A> Iterator for IterInstantiated<I, Iter, A>
455where
456    Iter::Item: TypeFoldable<I>,
457    A: SliceLike<Item = I::GenericArg>,
458{
459    type Item = Unnormalized<I, Iter::Item>;
460
461    fn next(&mut self) -> Option<Self::Item> {
462        Some(
463            EarlyBinder { value: self.it.next()?, _tcx: PhantomData }
464                .instantiate(self.cx, self.args),
465        )
466    }
467
468    fn size_hint(&self) -> (usize, Option<usize>) {
469        self.it.size_hint()
470    }
471}
472
473impl<I: Interner, Iter: IntoIterator, A> DoubleEndedIterator for IterInstantiated<I, Iter, A>
474where
475    Iter::IntoIter: DoubleEndedIterator,
476    Iter::Item: TypeFoldable<I>,
477    A: SliceLike<Item = I::GenericArg>,
478{
479    fn next_back(&mut self) -> Option<Self::Item> {
480        Some(
481            EarlyBinder { value: self.it.next_back()?, _tcx: PhantomData }
482                .instantiate(self.cx, self.args),
483        )
484    }
485}
486
487impl<I: Interner, Iter: IntoIterator, A> ExactSizeIterator for IterInstantiated<I, Iter, A>
488where
489    Iter::IntoIter: ExactSizeIterator,
490    Iter::Item: TypeFoldable<I>,
491    A: SliceLike<Item = I::GenericArg>,
492{
493}
494
495impl<'s, I: Interner, Iter: IntoIterator> EarlyBinder<I, Iter>
496where
497    Iter::Item: Deref,
498    <Iter::Item as Deref>::Target: Copy + TypeFoldable<I>,
499{
500    pub fn iter_instantiated_copied(
501        self,
502        cx: I,
503        args: &'s [I::GenericArg],
504    ) -> IterInstantiatedCopied<'s, I, Iter> {
505        IterInstantiatedCopied { it: self.value.into_iter(), cx, args }
506    }
507
508    /// Similar to [`instantiate_identity`](EarlyBinder::instantiate_identity),
509    /// but on an iterator of values that deref to a `TypeFoldable`.
510    pub fn iter_identity_copied(self) -> IterIdentityCopied<I, Iter> {
511        IterIdentityCopied { it: self.value.into_iter(), _tcx: PhantomData }
512    }
513}
514
515pub struct IterInstantiatedCopied<'a, I: Interner, Iter: IntoIterator> {
516    it: Iter::IntoIter,
517    cx: I,
518    args: &'a [I::GenericArg],
519}
520
521impl<'a, I: Interner, Iter: IntoIterator<IntoIter: Clone>> Clone
522    for IterInstantiatedCopied<'a, I, Iter>
523{
524    fn clone(&self) -> IterInstantiatedCopied<'a, I, Iter> {
525        IterInstantiatedCopied { it: self.it.clone(), cx: self.cx, args: self.args }
526    }
527}
528
529impl<I: Interner, Iter: IntoIterator> Iterator for IterInstantiatedCopied<'_, I, Iter>
530where
531    Iter::Item: Deref,
532    <Iter::Item as Deref>::Target: Copy + TypeFoldable<I>,
533{
534    type Item = Unnormalized<I, <Iter::Item as Deref>::Target>;
535
536    fn next(&mut self) -> Option<Self::Item> {
537        self.it.next().map(|value| {
538            EarlyBinder { value: *value, _tcx: PhantomData }.instantiate(self.cx, self.args)
539        })
540    }
541
542    fn size_hint(&self) -> (usize, Option<usize>) {
543        self.it.size_hint()
544    }
545}
546
547impl<I: Interner, Iter: IntoIterator> DoubleEndedIterator for IterInstantiatedCopied<'_, I, Iter>
548where
549    Iter::IntoIter: DoubleEndedIterator,
550    Iter::Item: Deref,
551    <Iter::Item as Deref>::Target: Copy + TypeFoldable<I>,
552{
553    fn next_back(&mut self) -> Option<Self::Item> {
554        self.it.next_back().map(|value| {
555            EarlyBinder { value: *value, _tcx: PhantomData }.instantiate(self.cx, self.args)
556        })
557    }
558}
559
560impl<I: Interner, Iter: IntoIterator> ExactSizeIterator for IterInstantiatedCopied<'_, I, Iter>
561where
562    Iter::IntoIter: ExactSizeIterator,
563    Iter::Item: Deref,
564    <Iter::Item as Deref>::Target: Copy + TypeFoldable<I>,
565{
566}
567
568pub struct IterIdentityCopied<I: Interner, Iter: IntoIterator> {
569    it: Iter::IntoIter,
570    _tcx: PhantomData<fn() -> I>,
571}
572
573impl<I: Interner, Iter: IntoIterator<IntoIter: Clone>> Clone for IterIdentityCopied<I, Iter> {
574    fn clone(&self) -> IterIdentityCopied<I, Iter> {
575        IterIdentityCopied { it: self.it.clone(), _tcx: self._tcx }
576    }
577}
578
579impl<I: Interner, Iter: IntoIterator> Iterator for IterIdentityCopied<I, Iter>
580where
581    Iter::Item: Deref,
582    <Iter::Item as Deref>::Target: Copy,
583{
584    type Item = Unnormalized<I, <Iter::Item as Deref>::Target>;
585
586    fn next(&mut self) -> Option<Self::Item> {
587        self.it.next().map(|i| Unnormalized::new(*i))
588    }
589
590    fn size_hint(&self) -> (usize, Option<usize>) {
591        self.it.size_hint()
592    }
593}
594
595impl<I: Interner, Iter: IntoIterator> DoubleEndedIterator for IterIdentityCopied<I, Iter>
596where
597    Iter::IntoIter: DoubleEndedIterator,
598    Iter::Item: Deref,
599    <Iter::Item as Deref>::Target: Copy,
600{
601    fn next_back(&mut self) -> Option<Self::Item> {
602        self.it.next_back().map(|i| Unnormalized::new(*i))
603    }
604}
605
606impl<I: Interner, Iter: IntoIterator> ExactSizeIterator for IterIdentityCopied<I, Iter>
607where
608    Iter::IntoIter: ExactSizeIterator,
609    Iter::Item: Deref,
610    <Iter::Item as Deref>::Target: Copy,
611{
612}
613pub struct EarlyBinderIter<I, T> {
614    t: T,
615    _tcx: PhantomData<I>,
616}
617
618impl<I: Interner, T: IntoIterator> EarlyBinder<I, T> {
619    pub fn transpose_iter(self) -> EarlyBinderIter<I, T::IntoIter> {
620        EarlyBinderIter { t: self.value.into_iter(), _tcx: PhantomData }
621    }
622}
623
624impl<I: Interner, T: Iterator> Iterator for EarlyBinderIter<I, T> {
625    type Item = EarlyBinder<I, T::Item>;
626
627    fn next(&mut self) -> Option<Self::Item> {
628        self.t.next().map(|value| EarlyBinder { value, _tcx: PhantomData })
629    }
630
631    fn size_hint(&self) -> (usize, Option<usize>) {
632        self.t.size_hint()
633    }
634}
635
636impl<I: Interner, T: TypeFoldable<I>> ty::EarlyBinder<I, T> {
637    pub fn instantiate<A>(self, cx: I, args: A) -> Unnormalized<I, T>
638    where
639        A: SliceLike<Item = I::GenericArg>,
640    {
641        // Nothing to fold, so let's avoid visiting things and possibly re-hashing/equating
642        // them when interning. Perf testing found this to be a modest improvement.
643        // See: <https://github.com/rust-lang/rust/pull/142317>
644        if args.is_empty() {
645            if !!self.value.has_param() {
    {
        ::core::panicking::panic_fmt(format_args!("{0:?} has parameters, but no args were provided in instantiate",
                self.value));
    }
};assert!(
646                !self.value.has_param(),
647                "{:?} has parameters, but no args were provided in instantiate",
648                self.value,
649            );
650            return Unnormalized::new(self.value);
651        }
652        let mut folder = ArgFolder { cx, args: args.as_slice(), binders_passed: 0 };
653        Unnormalized::new(self.value.fold_with(&mut folder))
654    }
655
656    /// Makes the identity replacement `T0 => T0, ..., TN => TN`.
657    /// Conceptually, this converts universally bound variables into placeholders
658    /// when inside of a given item.
659    ///
660    /// For example, consider `for<T> fn foo<T>(){ .. }`:
661    /// - Outside of `foo`, `T` is bound (represented by the presence of `EarlyBinder`).
662    /// - Inside of the body of `foo`, we treat `T` as a placeholder by calling
663    /// `instantiate_identity` to discharge the `EarlyBinder`.
664    pub fn instantiate_identity(self) -> Unnormalized<I, T> {
665        // FIXME(#155345): In case the bound value was already normalized, this
666        // is unnecessary. We may want to track explicitly whether `EarlyBinder`
667        // contains something that has been normalized already.
668        // Also do that for other types who have `instantiate_identity` method,
669        // e.g., `GenericClauses` and `ConstConditions`.
670        //
671        // This is annoying, as e.g. `type_of` for opaque types is normalized,
672        // while `type_of` for free type aliases is not.
673        Unnormalized::new(self.value)
674    }
675
676    /// Returns the inner value, but only if it contains no bound vars.
677    pub fn no_bound_vars(self) -> Option<T> {
678        if !self.value.has_param() { Some(self.value) } else { None }
679    }
680}
681
682///////////////////////////////////////////////////////////////////////////
683// The actual instantiation engine itself is a type folder.
684
685struct ArgFolder<'a, I: Interner> {
686    cx: I,
687    args: &'a [I::GenericArg],
688
689    /// Number of region binders we have passed through while doing the instantiation
690    binders_passed: u32,
691}
692
693impl<'a, I: Interner> TypeFolder<I> for ArgFolder<'a, I> {
694    #[inline]
695    fn cx(&self) -> I {
696        self.cx
697    }
698
699    fn fold_binder<T: TypeFoldable<I>>(&mut self, t: ty::Binder<I, T>) -> ty::Binder<I, T> {
700        self.binders_passed += 1;
701        let t = t.super_fold_with(self);
702        self.binders_passed -= 1;
703        t
704    }
705
706    fn fold_region(&mut self, r: Region<I>) -> Region<I> {
707        // Note: This routine only handles regions that are bound on
708        // type declarations and other outer declarations, not those
709        // bound in *fn types*. Region instantiation of the bound
710        // regions that appear in a function signature is done using
711        // the specialized routine `ty::replace_late_regions()`.
712        match r.kind() {
713            ty::ReEarlyParam(data) => {
714                let rk = self.args.get(data.index() as usize).map(|arg| arg.kind());
715                match rk {
716                    Some(ty::GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt),
717                    Some(other) => self.region_param_expected(data, r, other),
718                    None => self.region_param_out_of_range(data, r),
719                }
720            }
721            ty::ReBound(..)
722            | ty::ReLateParam(_)
723            | ty::ReStatic
724            | ty::RePlaceholder(_)
725            | ty::ReErased
726            | ty::ReError(_) => r,
727            ty::ReVar(_) => { ::core::panicking::panic_fmt(format_args!("unexpected region: {0:?}", r)); }panic!("unexpected region: {r:?}"),
728        }
729    }
730
731    fn fold_ty(&mut self, t: I::Ty) -> I::Ty {
732        if !t.has_param() {
733            return t;
734        }
735
736        match t.kind() {
737            ty::Param(p) => self.ty_for_param(p, t),
738            _ => t.super_fold_with(self),
739        }
740    }
741
742    fn fold_const(&mut self, c: I::Const) -> I::Const {
743        if let ty::ConstKind::Param(p) = c.kind() {
744            self.const_for_param(p, c)
745        } else {
746            c.super_fold_with(self)
747        }
748    }
749
750    fn fold_predicate(&mut self, p: I::Predicate) -> I::Predicate {
751        if p.has_param() { p.super_fold_with(self) } else { p }
752    }
753
754    fn fold_clauses(&mut self, c: I::Clauses) -> I::Clauses {
755        if c.has_param() { c.super_fold_with(self) } else { c }
756    }
757}
758
759impl<'a, I: Interner> ArgFolder<'a, I> {
760    fn ty_for_param(&self, p: I::ParamTy, source_ty: I::Ty) -> I::Ty {
761        // Look up the type in the args. It really should be in there.
762        let opt_ty = self.args.get(p.index() as usize).map(|arg| arg.kind());
763        let ty = match opt_ty {
764            Some(ty::GenericArgKind::Type(ty)) => ty,
765            Some(kind) => self.type_param_expected(p, source_ty, kind),
766            None => self.type_param_out_of_range(p, source_ty),
767        };
768
769        self.shift_vars_through_binders(ty)
770    }
771
772    #[cold]
773    #[inline(never)]
774    fn type_param_expected(&self, p: I::ParamTy, ty: I::Ty, kind: ty::GenericArgKind<I>) -> ! {
775        {
    ::core::panicking::panic_fmt(format_args!("expected type for `{0:?}` ({1:?}/{2}) but found {3:?} when instantiating, args={4:?}",
            p, ty, p.index(), kind, self.args));
}panic!(
776            "expected type for `{:?}` ({:?}/{}) but found {:?} when instantiating, args={:?}",
777            p,
778            ty,
779            p.index(),
780            kind,
781            self.args,
782        )
783    }
784
785    #[cold]
786    #[inline(never)]
787    fn type_param_out_of_range(&self, p: I::ParamTy, ty: I::Ty) -> ! {
788        {
    ::core::panicking::panic_fmt(format_args!("type parameter `{0:?}` ({1:?}/{2}) out of range when instantiating, args={3:?}",
            p, ty, p.index(), self.args));
}panic!(
789            "type parameter `{:?}` ({:?}/{}) out of range when instantiating, args={:?}",
790            p,
791            ty,
792            p.index(),
793            self.args,
794        )
795    }
796
797    fn const_for_param(&self, p: I::ParamConst, source_ct: I::Const) -> I::Const {
798        // Look up the const in the args. It really should be in there.
799        let opt_ct = self.args.get(p.index() as usize).map(|arg| arg.kind());
800        let ct = match opt_ct {
801            Some(ty::GenericArgKind::Const(ct)) => ct,
802            Some(kind) => self.const_param_expected(p, source_ct, kind),
803            None => self.const_param_out_of_range(p, source_ct),
804        };
805
806        self.shift_vars_through_binders(ct)
807    }
808
809    #[cold]
810    #[inline(never)]
811    fn const_param_expected(
812        &self,
813        p: I::ParamConst,
814        ct: I::Const,
815        kind: ty::GenericArgKind<I>,
816    ) -> ! {
817        {
    ::core::panicking::panic_fmt(format_args!("expected const for `{0:?}` ({1:?}/{2}) but found {3:?} when instantiating args={4:?}",
            p, ct, p.index(), kind, self.args));
}panic!(
818            "expected const for `{:?}` ({:?}/{}) but found {:?} when instantiating args={:?}",
819            p,
820            ct,
821            p.index(),
822            kind,
823            self.args,
824        )
825    }
826
827    #[cold]
828    #[inline(never)]
829    fn const_param_out_of_range(&self, p: I::ParamConst, ct: I::Const) -> ! {
830        {
    ::core::panicking::panic_fmt(format_args!("const parameter `{0:?}` ({1:?}/{2}) out of range when instantiating args={3:?}",
            p, ct, p.index(), self.args));
}panic!(
831            "const parameter `{:?}` ({:?}/{}) out of range when instantiating args={:?}",
832            p,
833            ct,
834            p.index(),
835            self.args,
836        )
837    }
838
839    #[cold]
840    #[inline(never)]
841    fn region_param_expected(
842        &self,
843        ebr: I::EarlyParamRegion,
844        r: Region<I>,
845        kind: ty::GenericArgKind<I>,
846    ) -> ! {
847        {
    ::core::panicking::panic_fmt(format_args!("expected region for `{0:?}` ({1:?}/{2}) but found {3:?} when instantiating args={4:?}",
            ebr, r, ebr.index(), kind, self.args));
}panic!(
848            "expected region for `{:?}` ({:?}/{}) but found {:?} when instantiating args={:?}",
849            ebr,
850            r,
851            ebr.index(),
852            kind,
853            self.args,
854        )
855    }
856
857    #[cold]
858    #[inline(never)]
859    fn region_param_out_of_range(&self, ebr: I::EarlyParamRegion, r: Region<I>) -> ! {
860        {
    ::core::panicking::panic_fmt(format_args!("region parameter `{0:?}` ({1:?}/{2}) out of range when instantiating args={3:?}",
            ebr, r, ebr.index(), self.args));
}panic!(
861            "region parameter `{:?}` ({:?}/{}) out of range when instantiating args={:?}",
862            ebr,
863            r,
864            ebr.index(),
865            self.args,
866        )
867    }
868
869    /// It is sometimes necessary to adjust the De Bruijn indices during instantiation. This occurs
870    /// when we are instantiating a type with escaping bound vars into a context where we have
871    /// passed through binders. That's quite a mouthful. Let's see an example:
872    ///
873    /// ```
874    /// type Func<A> = fn(A);
875    /// type MetaFunc = for<'a> fn(Func<&'a i32>);
876    /// ```
877    ///
878    /// The type `MetaFunc`, when fully expanded, will be
879    /// ```ignore (illustrative)
880    /// for<'a> fn(fn(&'a i32))
881    /// //      ^~ ^~ ^~~
882    /// //      |  |  |
883    /// //      |  |  DebruijnIndex of 2
884    /// //      Binders
885    /// ```
886    /// Here the `'a` lifetime is bound in the outer function, but appears as an argument of the
887    /// inner one. Therefore, that appearance will have a DebruijnIndex of 2, because we must skip
888    /// over the inner binder (remember that we count De Bruijn indices from 1). However, in the
889    /// definition of `MetaFunc`, the binder is not visible, so the type `&'a i32` will have a
890    /// De Bruijn index of 1. It's only during the instantiation that we can see we must increase the
891    /// depth by 1 to account for the binder that we passed through.
892    ///
893    /// As a second example, consider this twist:
894    ///
895    /// ```
896    /// type FuncTuple<A> = (A,fn(A));
897    /// type MetaFuncTuple = for<'a> fn(FuncTuple<&'a i32>);
898    /// ```
899    ///
900    /// Here the final type will be:
901    /// ```ignore (illustrative)
902    /// for<'a> fn((&'a i32, fn(&'a i32)))
903    /// //          ^~~         ^~~
904    /// //          |           |
905    /// //   DebruijnIndex of 1 |
906    /// //               DebruijnIndex of 2
907    /// ```
908    /// As indicated in the diagram, here the same type `&'a i32` is instantiated once, but in the
909    /// first case we do not increase the De Bruijn index and in the second case we do. The reason
910    /// is that only in the second case have we passed through a fn binder.
911    x;#[instrument(level = "trace", skip(self), fields(binders_passed = self.binders_passed), ret)]
912    fn shift_vars_through_binders<T: TypeFoldable<I>>(&self, val: T) -> T {
913        if self.binders_passed == 0 || !val.has_escaping_bound_vars() {
914            val
915        } else {
916            ty::shift_vars(self.cx, val, self.binders_passed)
917        }
918    }
919
920    fn shift_region_through_binders(&self, region: Region<I>) -> Region<I> {
921        if self.binders_passed == 0 || !region.has_escaping_bound_vars() {
922            region
923        } else {
924            ty::shift_region(self.cx, region, self.binders_passed)
925        }
926    }
927}
928
929/// Okay, we do something fun for `Bound` types/regions/consts:
930/// Specifically, we distinguish between *canonically* bound things and
931/// `for<>` bound things. And, really, it comes down to caching during
932/// canonicalization and instantiation.
933///
934/// To understand why we do this, imagine we have a type `(T, for<> fn(T))`.
935/// If we just tracked canonically bound types with a `DebruijnIndex` (as we
936/// used to), then the canonicalized type would be something like
937/// `for<0> (^0.0, for<> fn(^1.0))` and so we can't cache `T -> ^0.0`,
938/// we have to also factor in binder level. (Of course, we don't cache that
939/// exactly, but rather the entire enclosing type, but the point stands.)
940///
941/// Of course, this is okay because we don't ever nest canonicalization, so
942/// `BoundVarIndexKind::Canonical` is unambiguous. We, alternatively, could
943/// have some sentinel `DebruijinIndex`, but that just seems too scary.
944///
945/// This doesn't seem to have a huge perf swing either way, but in the next
946/// solver, canonicalization is hot and there are some pathological cases where
947/// this is needed (`post-mono-higher-ranked-hang`).
948#[derive(#[automatically_derived]
impl ::core::clone::Clone for BoundVarIndexKind {
    #[inline]
    fn clone(&self) -> BoundVarIndexKind {
        let _: ::core::clone::AssertParamIsClone<DebruijnIndex>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BoundVarIndexKind { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for BoundVarIndexKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            BoundVarIndexKind::Bound(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Bound",
                    &__self_0),
            BoundVarIndexKind::Canonical =>
                ::core::fmt::Formatter::write_str(f, "Canonical"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for BoundVarIndexKind {
    #[inline]
    fn eq(&self, other: &BoundVarIndexKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (BoundVarIndexKind::Bound(__self_0),
                    BoundVarIndexKind::Bound(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for BoundVarIndexKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DebruijnIndex>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for BoundVarIndexKind {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            BoundVarIndexKind::Bound(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash)]
949#[cfg_attr(feature = "nightly", derive(const _: () =
    {
        impl<__E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for BoundVarIndexKind {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        BoundVarIndexKind::Bound(ref __binding_0) => { 0usize }
                        BoundVarIndexKind::Canonical => { 1usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    BoundVarIndexKind::Bound(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    BoundVarIndexKind::Canonical => {}
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<__D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for BoundVarIndexKind {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        BoundVarIndexKind::Bound(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => { BoundVarIndexKind::Canonical }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `BoundVarIndexKind`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            BoundVarIndexKind {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    BoundVarIndexKind::Bound(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    BoundVarIndexKind::Canonical => {}
                }
            }
        }
    };StableHash))]
950#[derive(const _: () =
    {
        impl<I> ::rustc_type_ir::TypeVisitable<I> for BoundVarIndexKind where
            I: Interner {
            fn visit_with<__V: ::rustc_type_ir::TypeVisitor<I>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    BoundVarIndexKind::Bound(ref __binding_0) => {
                        {
                            match ::rustc_type_ir::VisitorResult::branch(::rustc_type_ir::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_type_ir::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    BoundVarIndexKind::Canonical => {}
                }
                <__V::Result as ::rustc_type_ir::VisitorResult>::output()
            }
        }
    };TypeVisitable_Generic, GenericTypeVisitable, const _: () =
    {
        impl<I> ::rustc_type_ir::TypeFoldable<I> for BoundVarIndexKind where
            I: Interner {
            fn try_fold_with<__F: ::rustc_type_ir::FallibleTypeFolder<I>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        BoundVarIndexKind::Bound(__binding_0) => {
                            BoundVarIndexKind::Bound(::rustc_type_ir::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        BoundVarIndexKind::Canonical => {
                            BoundVarIndexKind::Canonical
                        }
                    })
            }
            fn fold_with<__F: ::rustc_type_ir::TypeFolder<I>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    BoundVarIndexKind::Bound(__binding_0) => {
                        BoundVarIndexKind::Bound(::rustc_type_ir::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    BoundVarIndexKind::Canonical => {
                        BoundVarIndexKind::Canonical
                    }
                }
            }
        }
    };TypeFoldable_Generic)]
951pub enum BoundVarIndexKind {
952    Bound(DebruijnIndex),
953    Canonical,
954}
955
956/// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
957/// identified by both a universe, as well as a name residing within that universe. Distinct bound
958/// regions/types/consts within the same universe simply have an unknown relationship to one
959#[automatically_derived]
impl<I: Interner, T> ::core::hash::Hash for Placeholder<I, T> where
    I: Interner, T: ::core::hash::Hash {
    fn hash<__H: ::core::hash::Hasher>(&self, __state: &mut __H) {
        match self {
            Placeholder {
                universe: ref __field_universe,
                bound: ref __field_bound,
                _tcx: ref __field__tcx } => {
                ::core::hash::Hash::hash(__field_universe, __state);
                ::core::hash::Hash::hash(__field_bound, __state);
                ::core::hash::Hash::hash(__field__tcx, __state);
            }
        }
    }
}#[derive_where(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash; I: Interner, T)]
960#[derive(const _: () =
    {
        impl<I: Interner, T> ::rustc_type_ir::TypeVisitable<I> for
            Placeholder<I, T> where I: Interner,
            T: ::rustc_type_ir::TypeVisitable<I> {
            fn visit_with<__V: ::rustc_type_ir::TypeVisitor<I>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    Placeholder {
                        universe: ref __binding_0, bound: ref __binding_1, .. } => {
                        {
                            match ::rustc_type_ir::VisitorResult::branch(::rustc_type_ir::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_type_ir::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_type_ir::VisitorResult::branch(::rustc_type_ir::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_type_ir::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_type_ir::VisitorResult>::output()
            }
        }
    };TypeVisitable_Generic, const _: () =
    {
        impl<I: Interner, T> ::rustc_type_ir::TypeFoldable<I> for
            Placeholder<I, T> where I: Interner,
            T: ::rustc_type_ir::TypeFoldable<I>,
            T: ::rustc_type_ir::TypeFoldable<I> {
            fn try_fold_with<__F: ::rustc_type_ir::FallibleTypeFolder<I>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        Placeholder {
                            universe: __binding_0, bound: __binding_1, _tcx: __binding_2
                            } => {
                            Placeholder {
                                universe: ::rustc_type_ir::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                bound: ::rustc_type_ir::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                _tcx: __binding_2,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_type_ir::TypeFolder<I>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    Placeholder {
                        universe: __binding_0, bound: __binding_1, _tcx: __binding_2
                        } => {
                        Placeholder {
                            universe: ::rustc_type_ir::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            bound: ::rustc_type_ir::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            _tcx: __binding_2,
                        }
                    }
                }
            }
        }
    };TypeFoldable_Generic, GenericTypeVisitable, const _: () =
    {
        impl<I: Interner, T, J> ::rustc_type_ir::lift::Lift<J> for
            Placeholder<I, T> where J: Interner,
            I: ::rustc_type_ir::LiftInto<J>, T: ::rustc_type_ir::lift::Lift<J>
            {
            type Lifted =
                Placeholder<J, <T as ::rustc_type_ir::lift::Lift<J>>::Lifted>;
            fn lift_to_interner(self, interner: J) -> Self::Lifted {
                match self {
                    Placeholder {
                        universe: __binding_0, bound: __binding_1, _tcx: __binding_2
                        } => {
                        Placeholder {
                            universe: __binding_0,
                            bound: __binding_1.lift_to_interner(interner),
                            _tcx: PhantomData,
                        }
                    }
                }
            }
        }
    };Lift_Generic)]
961#[cfg_attr(
962    feature = "nightly",
963    derive(const _: () =
    {
        impl<I: Interner, T, __E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for Placeholder<I, T> where
            T: ::rustc_serialize::Encodable<__E>,
            PhantomData<fn() -> I>: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    Placeholder {
                        universe: ref __binding_0,
                        bound: ref __binding_1,
                        _tcx: ref __binding_2 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                            __encoder);
                    }
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<I: Interner, T, __D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for Placeholder<I, T> where
            T: ::rustc_serialize::Decodable<__D>,
            PhantomData<fn() -> I>: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                Placeholder {
                    universe: ::rustc_serialize::Decodable::decode(__decoder),
                    bound: ::rustc_serialize::Decodable::decode(__decoder),
                    _tcx: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl<I: Interner, T> ::rustc_data_structures::stable_hash::StableHash
            for Placeholder<I, T> where
            T: ::rustc_data_structures::stable_hash::StableHash,
            PhantomData<fn()
                -> I>: ::rustc_data_structures::stable_hash::StableHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Placeholder {
                        universe: ref __binding_0,
                        bound: ref __binding_1,
                        _tcx: ref __binding_2 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash_NoContext)
964)]
965pub struct Placeholder<I: Interner, T> {
966    #[lift(identity)]
967    pub universe: UniverseIndex,
968    pub bound: T,
969    #[type_foldable(identity)]
970    #[type_visitable(ignore)]
971    _tcx: PhantomData<fn() -> I>,
972}
973
974impl<I: Interner, T: fmt::Debug> fmt::Debug for ty::Placeholder<I, T> {
975    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
976        if self.universe == ty::UniverseIndex::ROOT {
977            f.write_fmt(format_args!("!{0:?}", self.bound))write!(f, "!{:?}", self.bound)
978        } else {
979            f.write_fmt(format_args!("!{0}_{1:?}", self.universe.index(), self.bound))write!(f, "!{}_{:?}", self.universe.index(), self.bound)
980        }
981    }
982}
983
984#[automatically_derived]
impl<I: Interner> ::core::hash::Hash for BoundRegionKind<I> where I: Interner
    {
    fn hash<__H: ::core::hash::Hasher>(&self, __state: &mut __H) {
        match self {
            BoundRegionKind::Anon => {
                ::core::hash::Hash::hash(&::core::mem::discriminant(self),
                    __state);
            }
            BoundRegionKind::NamedForPrinting(ref __field_0) => {
                ::core::hash::Hash::hash(&::core::mem::discriminant(self),
                    __state);
                ::core::hash::Hash::hash(__field_0, __state);
            }
            BoundRegionKind::Named(ref __field_0) => {
                ::core::hash::Hash::hash(&::core::mem::discriminant(self),
                    __state);
                ::core::hash::Hash::hash(__field_0, __state);
            }
            BoundRegionKind::ClosureEnv => {
                ::core::hash::Hash::hash(&::core::mem::discriminant(self),
                    __state);
            }
        }
    }
}#[derive_where(Clone, Copy, PartialEq, Eq, Hash; I: Interner)]
985#[derive(const _: () =
    {
        impl<I: Interner, J> ::rustc_type_ir::lift::Lift<J> for
            BoundRegionKind<I> where J: Interner,
            I: ::rustc_type_ir::LiftInto<J> {
            type Lifted = BoundRegionKind<J>;
            fn lift_to_interner(self, interner: J) -> Self::Lifted {
                match self {
                    BoundRegionKind::Anon => { BoundRegionKind::Anon }
                    BoundRegionKind::NamedForPrinting(__binding_0) => {
                        BoundRegionKind::NamedForPrinting(__binding_0.lift_to_interner(interner))
                    }
                    BoundRegionKind::Named(__binding_0) => {
                        BoundRegionKind::Named(__binding_0.lift_to_interner(interner))
                    }
                    BoundRegionKind::ClosureEnv => {
                        BoundRegionKind::ClosureEnv
                    }
                }
            }
        }
    };Lift_Generic, GenericTypeVisitable)]
986#[cfg_attr(
987    feature = "nightly",
988    derive(const _: () =
    {
        impl<I: Interner, __E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for BoundRegionKind<I> where
            I::Symbol: ::rustc_serialize::Encodable<__E>,
            I::DefId: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        BoundRegionKind::Anon => { 0usize }
                        BoundRegionKind::NamedForPrinting(ref __binding_0) => {
                            1usize
                        }
                        BoundRegionKind::Named(ref __binding_0) => { 2usize }
                        BoundRegionKind::ClosureEnv => { 3usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    BoundRegionKind::Anon => {}
                    BoundRegionKind::NamedForPrinting(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    BoundRegionKind::Named(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    BoundRegionKind::ClosureEnv => {}
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<I: Interner, __D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for BoundRegionKind<I> where
            I::Symbol: ::rustc_serialize::Decodable<__D>,
            I::DefId: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { BoundRegionKind::Anon }
                    1usize => {
                        BoundRegionKind::NamedForPrinting(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    2usize => {
                        BoundRegionKind::Named(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    3usize => { BoundRegionKind::ClosureEnv }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `BoundRegionKind`, expected 0..4, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl<I: Interner> ::rustc_data_structures::stable_hash::StableHash for
            BoundRegionKind<I> where
            I::Symbol: ::rustc_data_structures::stable_hash::StableHash,
            I::DefId: ::rustc_data_structures::stable_hash::StableHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    BoundRegionKind::Anon => {}
                    BoundRegionKind::NamedForPrinting(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    BoundRegionKind::Named(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    BoundRegionKind::ClosureEnv => {}
                }
            }
        }
    };StableHash_NoContext)
989)]
990pub enum BoundRegionKind<I: Interner> {
991    /// An anonymous region parameter for a given fn (&T)
992    Anon,
993
994    /// An anonymous region parameter with a `Symbol` name.
995    ///
996    /// Used to give late-bound regions names for things like pretty printing.
997    NamedForPrinting(I::Symbol),
998
999    /// Late-bound regions that appear in the AST.
1000    Named(I::DefId),
1001
1002    /// Anonymous region for the implicit env pointer parameter
1003    /// to a closure
1004    ClosureEnv,
1005}
1006
1007impl<I: Interner> fmt::Debug for ty::BoundRegionKind<I> {
1008    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1009        match *self {
1010            ty::BoundRegionKind::Anon => f.write_fmt(format_args!("BrAnon"))write!(f, "BrAnon"),
1011            ty::BoundRegionKind::NamedForPrinting(name) => {
1012                f.write_fmt(format_args!("BrNamedForPrinting({0:?})", name))write!(f, "BrNamedForPrinting({:?})", name)
1013            }
1014            ty::BoundRegionKind::Named(did) => {
1015                f.write_fmt(format_args!("BrNamed({0:?})", did))write!(f, "BrNamed({did:?})")
1016            }
1017            ty::BoundRegionKind::ClosureEnv => f.write_fmt(format_args!("BrEnv"))write!(f, "BrEnv"),
1018        }
1019    }
1020}
1021
1022impl<I: Interner> BoundRegionKind<I> {
1023    pub fn is_named(&self, tcx: I) -> bool {
1024        self.get_name(tcx).is_some()
1025    }
1026
1027    pub fn get_name(&self, tcx: I) -> Option<I::Symbol> {
1028        match *self {
1029            ty::BoundRegionKind::Named(def_id) => {
1030                let name = tcx.item_name(def_id);
1031                if name.is_kw_underscore_lifetime() { None } else { Some(name) }
1032            }
1033            ty::BoundRegionKind::NamedForPrinting(name) => Some(name),
1034            _ => None,
1035        }
1036    }
1037
1038    pub fn get_id(&self) -> Option<I::DefId> {
1039        match *self {
1040            ty::BoundRegionKind::Named(id) => Some(id),
1041            _ => None,
1042        }
1043    }
1044}
1045
1046#[automatically_derived]
impl<I: Interner> ::core::hash::Hash for BoundTyKind<I> where I: Interner {
    fn hash<__H: ::core::hash::Hasher>(&self, __state: &mut __H) {
        match self {
            BoundTyKind::Anon => {
                ::core::hash::Hash::hash(&::core::mem::discriminant(self),
                    __state);
            }
            BoundTyKind::Param(ref __field_0) => {
                ::core::hash::Hash::hash(&::core::mem::discriminant(self),
                    __state);
                ::core::hash::Hash::hash(__field_0, __state);
            }
        }
    }
}#[derive_where(Clone, Copy, PartialEq, Eq, Debug, Hash; I: Interner)]
1047#[derive(const _: () =
    {
        impl<I: Interner, J> ::rustc_type_ir::lift::Lift<J> for BoundTyKind<I>
            where J: Interner, I: ::rustc_type_ir::LiftInto<J> {
            type Lifted = BoundTyKind<J>;
            fn lift_to_interner(self, interner: J) -> Self::Lifted {
                match self {
                    BoundTyKind::Anon => { BoundTyKind::Anon }
                    BoundTyKind::Param(__binding_0) => {
                        BoundTyKind::Param(__binding_0.lift_to_interner(interner))
                    }
                }
            }
        }
    };Lift_Generic, GenericTypeVisitable)]
1048#[cfg_attr(
1049    feature = "nightly",
1050    derive(const _: () =
    {
        impl<I: Interner, __E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for BoundTyKind<I> where
            I::DefId: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        BoundTyKind::Anon => { 0usize }
                        BoundTyKind::Param(ref __binding_0) => { 1usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    BoundTyKind::Anon => {}
                    BoundTyKind::Param(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<I: Interner, __D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for BoundTyKind<I> where
            I::DefId: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { BoundTyKind::Anon }
                    1usize => {
                        BoundTyKind::Param(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `BoundTyKind`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl<I: Interner> ::rustc_data_structures::stable_hash::StableHash for
            BoundTyKind<I> where
            I::DefId: ::rustc_data_structures::stable_hash::StableHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    BoundTyKind::Anon => {}
                    BoundTyKind::Param(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash_NoContext)
1051)]
1052pub enum BoundTyKind<I: Interner> {
1053    Anon,
1054    Param(I::DefId),
1055}
1056
1057#[automatically_derived]
impl<I: Interner> ::core::hash::Hash for BoundVariableKind<I> where
    I: Interner {
    fn hash<__H: ::core::hash::Hasher>(&self, __state: &mut __H) {
        match self {
            BoundVariableKind::Ty(ref __field_0) => {
                ::core::hash::Hash::hash(&::core::mem::discriminant(self),
                    __state);
                ::core::hash::Hash::hash(__field_0, __state);
            }
            BoundVariableKind::Region(ref __field_0) => {
                ::core::hash::Hash::hash(&::core::mem::discriminant(self),
                    __state);
                ::core::hash::Hash::hash(__field_0, __state);
            }
            BoundVariableKind::Const => {
                ::core::hash::Hash::hash(&::core::mem::discriminant(self),
                    __state);
            }
        }
    }
}#[derive_where(Clone, Copy, PartialEq, Eq, Debug, Hash; I: Interner)]
1058#[derive(const _: () =
    {
        impl<I: Interner, J> ::rustc_type_ir::lift::Lift<J> for
            BoundVariableKind<I> where J: Interner,
            I: ::rustc_type_ir::LiftInto<J> {
            type Lifted = BoundVariableKind<J>;
            fn lift_to_interner(self, interner: J) -> Self::Lifted {
                match self {
                    BoundVariableKind::Ty(__binding_0) => {
                        BoundVariableKind::Ty(__binding_0.lift_to_interner(interner))
                    }
                    BoundVariableKind::Region(__binding_0) => {
                        BoundVariableKind::Region(__binding_0.lift_to_interner(interner))
                    }
                    BoundVariableKind::Const => { BoundVariableKind::Const }
                }
            }
        }
    };Lift_Generic, GenericTypeVisitable)]
1059#[cfg_attr(
1060    feature = "nightly",
1061    derive(const _: () =
    {
        impl<I: Interner, __E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for BoundVariableKind<I> where
            BoundTyKind<I>: ::rustc_serialize::Encodable<__E>,
            BoundRegionKind<I>: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        BoundVariableKind::Ty(ref __binding_0) => { 0usize }
                        BoundVariableKind::Region(ref __binding_0) => { 1usize }
                        BoundVariableKind::Const => { 2usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    BoundVariableKind::Ty(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    BoundVariableKind::Region(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    BoundVariableKind::Const => {}
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<I: Interner, __D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for BoundVariableKind<I> where
            BoundTyKind<I>: ::rustc_serialize::Decodable<__D>,
            BoundRegionKind<I>: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        BoundVariableKind::Ty(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        BoundVariableKind::Region(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    2usize => { BoundVariableKind::Const }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `BoundVariableKind`, expected 0..3, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl<I: Interner> ::rustc_data_structures::stable_hash::StableHash for
            BoundVariableKind<I> where
            BoundTyKind<I>: ::rustc_data_structures::stable_hash::StableHash,
            BoundRegionKind<I>: ::rustc_data_structures::stable_hash::StableHash
            {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    BoundVariableKind::Ty(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    BoundVariableKind::Region(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    BoundVariableKind::Const => {}
                }
            }
        }
    };StableHash_NoContext)
1062)]
1063pub enum BoundVariableKind<I: Interner> {
1064    Ty(BoundTyKind<I>),
1065    Region(BoundRegionKind<I>),
1066    Const,
1067}
1068
1069impl<I: Interner> BoundVariableKind<I> {
1070    pub fn expect_region(self) -> BoundRegionKind<I> {
1071        match self {
1072            BoundVariableKind::Region(lt) => lt,
1073            _ => {
    ::core::panicking::panic_fmt(format_args!("expected a region, but found another kind"));
}panic!("expected a region, but found another kind"),
1074        }
1075    }
1076
1077    pub fn expect_ty(self) -> BoundTyKind<I> {
1078        match self {
1079            BoundVariableKind::Ty(ty) => ty,
1080            _ => {
    ::core::panicking::panic_fmt(format_args!("expected a type, but found another kind"));
}panic!("expected a type, but found another kind"),
1081        }
1082    }
1083
1084    pub fn expect_const(self) {
1085        match self {
1086            BoundVariableKind::Const => (),
1087            _ => {
    ::core::panicking::panic_fmt(format_args!("expected a const, but found another kind"));
}panic!("expected a const, but found another kind"),
1088        }
1089    }
1090}
1091
1092#[automatically_derived]
impl<I: Interner> ::core::hash::Hash for BoundRegion<I> where I: Interner {
    fn hash<__H: ::core::hash::Hasher>(&self, __state: &mut __H) {
        match self {
            BoundRegion { var: ref __field_var, kind: ref __field_kind } => {
                ::core::hash::Hash::hash(__field_var, __state);
                ::core::hash::Hash::hash(__field_kind, __state);
            }
        }
    }
}#[derive_where(Clone, Copy, PartialEq, Eq, Hash; I: Interner)]
1093#[derive(GenericTypeVisitable, const _: () =
    {
        impl<I: Interner, J> ::rustc_type_ir::lift::Lift<J> for BoundRegion<I>
            where J: Interner, I: ::rustc_type_ir::LiftInto<J> {
            type Lifted = BoundRegion<J>;
            fn lift_to_interner(self, interner: J) -> Self::Lifted {
                match self {
                    BoundRegion { var: __binding_0, kind: __binding_1 } => {
                        BoundRegion {
                            var: __binding_0,
                            kind: __binding_1.lift_to_interner(interner),
                        }
                    }
                }
            }
        }
    };Lift_Generic)]
1094#[cfg_attr(
1095    feature = "nightly",
1096    derive(const _: () =
    {
        impl<I: Interner, __E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for BoundRegion<I> where
            BoundRegionKind<I>: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    BoundRegion { var: ref __binding_0, kind: ref __binding_1 }
                        => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<I: Interner> ::rustc_data_structures::stable_hash::StableHash for
            BoundRegion<I> where
            BoundRegionKind<I>: ::rustc_data_structures::stable_hash::StableHash
            {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    BoundRegion { var: ref __binding_0, kind: ref __binding_1 }
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash_NoContext, const _: () =
    {
        impl<I: Interner, __D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for BoundRegion<I> where
            BoundRegionKind<I>: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                BoundRegion {
                    var: ::rustc_serialize::Decodable::decode(__decoder),
                    kind: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable_NoContext)
1097)]
1098pub struct BoundRegion<I: Interner> {
1099    #[lift(identity)]
1100    pub var: ty::BoundVar,
1101    pub kind: BoundRegionKind<I>,
1102}
1103
1104impl<I: Interner> core::fmt::Debug for BoundRegion<I> {
1105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1106        match self.kind {
1107            BoundRegionKind::Anon => f.write_fmt(format_args!("{0:?}", self.var))write!(f, "{:?}", self.var),
1108            BoundRegionKind::ClosureEnv => f.write_fmt(format_args!("{0:?}.Env", self.var))write!(f, "{:?}.Env", self.var),
1109            BoundRegionKind::Named(def) => {
1110                f.write_fmt(format_args!("{0:?}.Named({1:?})", self.var, def))write!(f, "{:?}.Named({:?})", self.var, def)
1111            }
1112            BoundRegionKind::NamedForPrinting(symbol) => {
1113                f.write_fmt(format_args!("{0:?}.NamedAnon({1:?})", self.var, symbol))write!(f, "{:?}.NamedAnon({:?})", self.var, symbol)
1114            }
1115        }
1116    }
1117}
1118
1119impl<I: Interner> BoundRegion<I> {
1120    pub fn var(self) -> ty::BoundVar {
1121        self.var
1122    }
1123
1124    pub fn assert_eq(self, var: BoundVariableKind<I>) {
1125        {
    match (&self.kind, &var.expect_region()) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
}assert_eq!(self.kind, var.expect_region())
1126    }
1127}
1128
1129pub type PlaceholderRegion<I> = ty::Placeholder<I, BoundRegion<I>>;
1130
1131impl<I: Interner> PlaceholderRegion<I> {
1132    pub fn universe(self) -> UniverseIndex {
1133        self.universe
1134    }
1135
1136    pub fn var(self) -> ty::BoundVar {
1137        self.bound.var()
1138    }
1139
1140    pub fn with_updated_universe(self, ui: UniverseIndex) -> Self {
1141        Self { universe: ui, bound: self.bound, _tcx: PhantomData }
1142    }
1143
1144    pub fn new(ui: UniverseIndex, bound: BoundRegion<I>) -> Self {
1145        Self { universe: ui, bound, _tcx: PhantomData }
1146    }
1147
1148    pub fn new_anon(ui: UniverseIndex, var: ty::BoundVar) -> Self {
1149        let bound = BoundRegion { var, kind: BoundRegionKind::Anon };
1150        Self { universe: ui, bound, _tcx: PhantomData }
1151    }
1152}
1153
1154#[automatically_derived]
impl<I: Interner> ::core::hash::Hash for BoundTy<I> where I: Interner {
    fn hash<__H: ::core::hash::Hasher>(&self, __state: &mut __H) {
        match self {
            BoundTy { var: ref __field_var, kind: ref __field_kind } => {
                ::core::hash::Hash::hash(__field_var, __state);
                ::core::hash::Hash::hash(__field_kind, __state);
            }
        }
    }
}#[derive_where(Clone, Copy, PartialEq, Eq, Hash; I: Interner)]
1155#[derive(GenericTypeVisitable, const _: () =
    {
        impl<I: Interner, J> ::rustc_type_ir::lift::Lift<J> for BoundTy<I>
            where J: Interner, I: ::rustc_type_ir::LiftInto<J> {
            type Lifted = BoundTy<J>;
            fn lift_to_interner(self, interner: J) -> Self::Lifted {
                match self {
                    BoundTy { var: __binding_0, kind: __binding_1 } => {
                        BoundTy {
                            var: __binding_0,
                            kind: __binding_1.lift_to_interner(interner),
                        }
                    }
                }
            }
        }
    };Lift_Generic)]
1156#[cfg_attr(
1157    feature = "nightly",
1158    derive(const _: () =
    {
        impl<I: Interner, __E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for BoundTy<I> where
            BoundTyKind<I>: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    BoundTy { var: ref __binding_0, kind: ref __binding_1 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<I: Interner, __D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for BoundTy<I> where
            BoundTyKind<I>: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                BoundTy {
                    var: ::rustc_serialize::Decodable::decode(__decoder),
                    kind: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl<I: Interner> ::rustc_data_structures::stable_hash::StableHash for
            BoundTy<I> where
            BoundTyKind<I>: ::rustc_data_structures::stable_hash::StableHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    BoundTy { var: ref __binding_0, kind: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash_NoContext)
1159)]
1160pub struct BoundTy<I: Interner> {
1161    #[lift(identity)]
1162    pub var: ty::BoundVar,
1163    pub kind: BoundTyKind<I>,
1164}
1165
1166impl<I: Interner> fmt::Debug for ty::BoundTy<I> {
1167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1168        match self.kind {
1169            ty::BoundTyKind::Anon => f.write_fmt(format_args!("{0:?}", self.var))write!(f, "{:?}", self.var),
1170            ty::BoundTyKind::Param(def_id) => f.write_fmt(format_args!("{0:?}", def_id))write!(f, "{def_id:?}"),
1171        }
1172    }
1173}
1174
1175impl<I: Interner> BoundTy<I> {
1176    pub fn var(self) -> ty::BoundVar {
1177        self.var
1178    }
1179
1180    pub fn assert_eq(self, var: BoundVariableKind<I>) {
1181        {
    match (&self.kind, &var.expect_ty()) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
}assert_eq!(self.kind, var.expect_ty())
1182    }
1183}
1184
1185pub type PlaceholderType<I> = ty::Placeholder<I, BoundTy<I>>;
1186
1187impl<I: Interner> PlaceholderType<I> {
1188    pub fn universe(self) -> UniverseIndex {
1189        self.universe
1190    }
1191
1192    pub fn var(self) -> ty::BoundVar {
1193        self.bound.var
1194    }
1195
1196    pub fn with_updated_universe(self, ui: UniverseIndex) -> Self {
1197        Self { universe: ui, bound: self.bound, _tcx: PhantomData }
1198    }
1199
1200    pub fn new(ui: UniverseIndex, bound: BoundTy<I>) -> Self {
1201        Self { universe: ui, bound, _tcx: PhantomData }
1202    }
1203
1204    pub fn new_anon(ui: UniverseIndex, var: ty::BoundVar) -> Self {
1205        let bound = BoundTy { var, kind: BoundTyKind::Anon };
1206        Self { universe: ui, bound, _tcx: PhantomData }
1207    }
1208}
1209
1210#[automatically_derived]
impl<I: Interner> ::core::hash::Hash for BoundConst<I> where I: Interner {
    fn hash<__H: ::core::hash::Hasher>(&self, __state: &mut __H) {
        match self {
            BoundConst { var: ref __field_var, _tcx: ref __field__tcx } => {
                ::core::hash::Hash::hash(__field_var, __state);
                ::core::hash::Hash::hash(__field__tcx, __state);
            }
        }
    }
}#[derive_where(Clone, Copy, PartialEq, Debug, Eq, Hash; I: Interner)]
1211#[derive(GenericTypeVisitable)]
1212#[cfg_attr(
1213    feature = "nightly",
1214    derive(const _: () =
    {
        impl<I: Interner, __E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for BoundConst<I> where
            PhantomData<fn() -> I>: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    BoundConst { var: ref __binding_0, _tcx: ref __binding_1 }
                        => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<I: Interner, __D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for BoundConst<I> where
            PhantomData<fn() -> I>: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                BoundConst {
                    var: ::rustc_serialize::Decodable::decode(__decoder),
                    _tcx: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl<I: Interner> ::rustc_data_structures::stable_hash::StableHash for
            BoundConst<I> where
            PhantomData<fn()
                -> I>: ::rustc_data_structures::stable_hash::StableHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    BoundConst { var: ref __binding_0, _tcx: ref __binding_1 }
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash_NoContext)
1215)]
1216pub struct BoundConst<I: Interner> {
1217    pub var: ty::BoundVar,
1218    #[derive_where(skip(Debug))]
1219    pub _tcx: PhantomData<fn() -> I>,
1220}
1221
1222impl<I: Interner> BoundConst<I> {
1223    pub fn var(self) -> ty::BoundVar {
1224        self.var
1225    }
1226
1227    pub fn assert_eq(self, var: BoundVariableKind<I>) {
1228        var.expect_const()
1229    }
1230
1231    pub fn new(var: ty::BoundVar) -> Self {
1232        Self { var, _tcx: PhantomData }
1233    }
1234}
1235
1236pub type PlaceholderConst<I> = ty::Placeholder<I, BoundConst<I>>;
1237
1238impl<I: Interner> PlaceholderConst<I> {
1239    pub fn universe(self) -> UniverseIndex {
1240        self.universe
1241    }
1242
1243    pub fn var(self) -> ty::BoundVar {
1244        self.bound.var
1245    }
1246
1247    pub fn with_updated_universe(self, ui: UniverseIndex) -> Self {
1248        Self { universe: ui, bound: self.bound, _tcx: PhantomData }
1249    }
1250
1251    pub fn new(ui: UniverseIndex, bound: BoundConst<I>) -> Self {
1252        Self { universe: ui, bound, _tcx: PhantomData }
1253    }
1254
1255    pub fn new_anon(ui: UniverseIndex, var: ty::BoundVar) -> Self {
1256        let bound = BoundConst::new(var);
1257        Self { universe: ui, bound, _tcx: PhantomData }
1258    }
1259
1260    pub fn find_const_ty_from_env(self, env: I::ParamEnv) -> I::Ty {
1261        let mut candidates = env.caller_bounds().iter().filter_map(|clause| {
1262            // `ConstArgHasType` are never desugared to be higher ranked.
1263            match clause.kind().skip_binder() {
1264                ty::ClauseKind::ConstArgHasType(placeholder_ct, ty) => {
1265                    if !!(placeholder_ct, ty).has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !(placeholder_ct, ty).has_escaping_bound_vars()")
};assert!(!(placeholder_ct, ty).has_escaping_bound_vars());
1266
1267                    match placeholder_ct.kind() {
1268                        ty::ConstKind::Placeholder(placeholder_ct) if placeholder_ct == self => {
1269                            Some(ty)
1270                        }
1271                        _ => None,
1272                    }
1273                }
1274                _ => None,
1275            }
1276        });
1277
1278        // N.B. it may be tempting to fix ICEs by making this function return
1279        // `Option<Ty<'tcx>>` instead of `Ty<'tcx>`; however, this is generally
1280        // considered to be a bandaid solution, since it hides more important
1281        // underlying issues with how we construct generics and predicates of
1282        // items. It's advised to fix the underlying issue rather than trying
1283        // to modify this function.
1284        let ty = candidates.next().unwrap_or_else(|| {
1285            {
    ::core::panicking::panic_fmt(format_args!("cannot find `{0:?}` in param-env: {1:#?}",
            self, env));
};panic!("cannot find `{self:?}` in param-env: {env:#?}");
1286        });
1287        if !candidates.next().is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("did not expect duplicate `ConstParamHasTy` for `{0:?}` in param-env: {1:#?}",
                self, env));
    }
};assert!(
1288            candidates.next().is_none(),
1289            "did not expect duplicate `ConstParamHasTy` for `{self:?}` in param-env: {env:#?}"
1290        );
1291        ty
1292    }
1293}