Skip to main content

rustc_middle/ty/
adt.rs

1use std::cell::RefCell;
2use std::hash::{Hash, Hasher};
3use std::ops::Range;
4use std::str;
5
6use rustc_abi::{FIRST_VARIANT, FieldIdx, ReprOptions, VariantIdx};
7use rustc_data_structures::fingerprint::Fingerprint;
8use rustc_data_structures::fx::FxHashMap;
9use rustc_data_structures::intern::Interned;
10use rustc_data_structures::stable_hasher::{HashStable, HashingControls, StableHasher};
11use rustc_errors::ErrorGuaranteed;
12use rustc_hir::def::{CtorKind, DefKind, Res};
13use rustc_hir::def_id::DefId;
14use rustc_hir::{self as hir, LangItem, find_attr};
15use rustc_index::{IndexSlice, IndexVec};
16use rustc_macros::{HashStable, TyDecodable, TyEncodable};
17use rustc_session::DataTypeKind;
18use rustc_span::sym;
19use rustc_type_ir::FieldInfo;
20use rustc_type_ir::solve::AdtDestructorKind;
21use tracing::{debug, info, trace};
22
23use super::{
24    AsyncDestructor, Destructor, FieldDef, GenericPredicates, Ty, TyCtxt, VariantDef, VariantDiscr,
25};
26use crate::ich::StableHashingContext;
27use crate::mir::interpret::ErrorHandled;
28use crate::ty::util::{Discr, IntTypeExt};
29use crate::ty::{self, ConstKind};
30
31#[derive(#[automatically_derived]
impl ::core::clone::Clone for AdtFlags {
    #[inline]
    fn clone(&self) -> AdtFlags {
        let _: ::core::clone::AssertParamIsClone<u16>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AdtFlags { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AdtFlags {
    #[inline]
    fn eq(&self, other: &AdtFlags) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AdtFlags {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u16>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for AdtFlags {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for AdtFlags {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    AdtFlags(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for AdtFlags {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    AdtFlags(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for AdtFlags {
            fn decode(__decoder: &mut __D) -> Self {
                AdtFlags(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };TyDecodable)]
32pub struct AdtFlags(u16);
33impl AdtFlags {
    #[allow(deprecated, non_upper_case_globals,)]
    pub const NO_ADT_FLAGS: Self = Self::from_bits_retain(0);
    #[doc = r" Indicates whether the ADT is an enum."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_ENUM: Self = Self::from_bits_retain(1 << 0);
    #[doc = r" Indicates whether the ADT is a union."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_UNION: Self = Self::from_bits_retain(1 << 1);
    #[doc = r" Indicates whether the ADT is a struct."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_STRUCT: Self = Self::from_bits_retain(1 << 2);
    #[doc = r" Indicates whether the ADT is a struct and has a constructor."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const HAS_CTOR: Self = Self::from_bits_retain(1 << 3);
    #[doc = r" Indicates whether the type is `PhantomData`."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_PHANTOM_DATA: Self = Self::from_bits_retain(1 << 4);
    #[doc = r" Indicates whether the type has a `#[fundamental]` attribute."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_FUNDAMENTAL: Self = Self::from_bits_retain(1 << 5);
    #[doc = r" Indicates whether the type is `Box`."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_BOX: Self = Self::from_bits_retain(1 << 6);
    #[doc = r" Indicates whether the type is `ManuallyDrop`."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_MANUALLY_DROP: Self = Self::from_bits_retain(1 << 7);
    #[doc =
    r" Indicates whether the variant list of this ADT is `#[non_exhaustive]`."]
    #[doc = r" (i.e., this flag is never set unless this ADT is an enum)."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_VARIANT_LIST_NON_EXHAUSTIVE: Self =
        Self::from_bits_retain(1 << 8);
    #[doc = r" Indicates whether the type is `UnsafeCell`."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_UNSAFE_CELL: Self = Self::from_bits_retain(1 << 9);
    #[doc = r" Indicates whether the type is `UnsafePinned`."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_UNSAFE_PINNED: Self = Self::from_bits_retain(1 << 10);
    #[doc = r" Indicates whether the type is `Pin`."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_PIN: Self = Self::from_bits_retain(1 << 11);
    #[doc = r" Indicates whether the type is `#[pin_project]`."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_PIN_PROJECT: Self = Self::from_bits_retain(1 << 12);
    #[doc = r" Indicates whether the type is `FieldRepresentingType`."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_FIELD_REPRESENTING_TYPE: Self =
        Self::from_bits_retain(1 << 13);
}
impl ::bitflags::Flags for AdtFlags {
    const FLAGS: &'static [::bitflags::Flag<AdtFlags>] =
        &[{

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("NO_ADT_FLAGS",
                            AdtFlags::NO_ADT_FLAGS)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_ENUM", AdtFlags::IS_ENUM)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_UNION", AdtFlags::IS_UNION)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_STRUCT", AdtFlags::IS_STRUCT)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("HAS_CTOR", AdtFlags::HAS_CTOR)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_PHANTOM_DATA",
                            AdtFlags::IS_PHANTOM_DATA)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_FUNDAMENTAL",
                            AdtFlags::IS_FUNDAMENTAL)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_BOX", AdtFlags::IS_BOX)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_MANUALLY_DROP",
                            AdtFlags::IS_MANUALLY_DROP)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_VARIANT_LIST_NON_EXHAUSTIVE",
                            AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_UNSAFE_CELL",
                            AdtFlags::IS_UNSAFE_CELL)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_UNSAFE_PINNED",
                            AdtFlags::IS_UNSAFE_PINNED)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_PIN", AdtFlags::IS_PIN)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_PIN_PROJECT",
                            AdtFlags::IS_PIN_PROJECT)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_FIELD_REPRESENTING_TYPE",
                            AdtFlags::IS_FIELD_REPRESENTING_TYPE)
                    }];
    type Bits = u16;
    fn bits(&self) -> u16 { AdtFlags::bits(self) }
    fn from_bits_retain(bits: u16) -> AdtFlags {
        AdtFlags::from_bits_retain(bits)
    }
}
#[allow(dead_code, deprecated, unused_doc_comments, unused_attributes,
unused_mut, unused_imports, non_upper_case_globals, clippy ::
assign_op_pattern, clippy :: iter_without_into_iter,)]
const _: () =
    {
        #[allow(dead_code, deprecated, unused_attributes)]
        impl AdtFlags {
            /// Get a flags value with all bits unset.
            #[inline]
            pub const fn empty() -> Self {
                Self(<u16 as ::bitflags::Bits>::EMPTY)
            }
            /// Get a flags value with all known bits set.
            #[inline]
            pub const fn all() -> Self {
                let mut truncated = <u16 as ::bitflags::Bits>::EMPTY;
                let mut i = 0;
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <AdtFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                let _ = i;
                Self(truncated)
            }
            /// Get the underlying bits value.
            ///
            /// The returned value is exactly the bits set in this flags value.
            #[inline]
            pub const fn bits(&self) -> u16 { self.0 }
            /// Convert from a bits value.
            ///
            /// This method will return `None` if any unknown bits are set.
            #[inline]
            pub const fn from_bits(bits: u16)
                -> ::bitflags::__private::core::option::Option<Self> {
                let truncated = Self::from_bits_truncate(bits).0;
                if truncated == bits {
                    ::bitflags::__private::core::option::Option::Some(Self(bits))
                } else { ::bitflags::__private::core::option::Option::None }
            }
            /// Convert from a bits value, unsetting any unknown bits.
            #[inline]
            pub const fn from_bits_truncate(bits: u16) -> Self {
                Self(bits & Self::all().0)
            }
            /// Convert from a bits value exactly.
            #[inline]
            pub const fn from_bits_retain(bits: u16) -> Self { Self(bits) }
            /// Get a flags value with the bits of a flag with the given name set.
            ///
            /// This method will return `None` if `name` is empty or doesn't
            /// correspond to any named flag.
            #[inline]
            pub fn from_name(name: &str)
                -> ::bitflags::__private::core::option::Option<Self> {
                {
                    if name == "NO_ADT_FLAGS" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::NO_ADT_FLAGS.bits()));
                    }
                };
                ;
                {
                    if name == "IS_ENUM" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_ENUM.bits()));
                    }
                };
                ;
                {
                    if name == "IS_UNION" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_UNION.bits()));
                    }
                };
                ;
                {
                    if name == "IS_STRUCT" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_STRUCT.bits()));
                    }
                };
                ;
                {
                    if name == "HAS_CTOR" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::HAS_CTOR.bits()));
                    }
                };
                ;
                {
                    if name == "IS_PHANTOM_DATA" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_PHANTOM_DATA.bits()));
                    }
                };
                ;
                {
                    if name == "IS_FUNDAMENTAL" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_FUNDAMENTAL.bits()));
                    }
                };
                ;
                {
                    if name == "IS_BOX" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_BOX.bits()));
                    }
                };
                ;
                {
                    if name == "IS_MANUALLY_DROP" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_MANUALLY_DROP.bits()));
                    }
                };
                ;
                {
                    if name == "IS_VARIANT_LIST_NON_EXHAUSTIVE" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE.bits()));
                    }
                };
                ;
                {
                    if name == "IS_UNSAFE_CELL" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_UNSAFE_CELL.bits()));
                    }
                };
                ;
                {
                    if name == "IS_UNSAFE_PINNED" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_UNSAFE_PINNED.bits()));
                    }
                };
                ;
                {
                    if name == "IS_PIN" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_PIN.bits()));
                    }
                };
                ;
                {
                    if name == "IS_PIN_PROJECT" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_PIN_PROJECT.bits()));
                    }
                };
                ;
                {
                    if name == "IS_FIELD_REPRESENTING_TYPE" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_FIELD_REPRESENTING_TYPE.bits()));
                    }
                };
                ;
                let _ = name;
                ::bitflags::__private::core::option::Option::None
            }
            /// Whether all bits in this flags value are unset.
            #[inline]
            pub const fn is_empty(&self) -> bool {
                self.0 == <u16 as ::bitflags::Bits>::EMPTY
            }
            /// Whether all known bits in this flags value are set.
            #[inline]
            pub const fn is_all(&self) -> bool {
                Self::all().0 | self.0 == self.0
            }
            /// Whether any set bits in a source flags value are also set in a target flags value.
            #[inline]
            pub const fn intersects(&self, other: Self) -> bool {
                self.0 & other.0 != <u16 as ::bitflags::Bits>::EMPTY
            }
            /// Whether all set bits in a source flags value are also set in a target flags value.
            #[inline]
            pub const fn contains(&self, other: Self) -> bool {
                self.0 & other.0 == other.0
            }
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            pub fn insert(&mut self, other: Self) {
                *self = Self(self.0).union(other);
            }
            /// The intersection of a source flags value with the complement of a target flags
            /// value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `remove` won't truncate `other`, but the `!` operator will.
            #[inline]
            pub fn remove(&mut self, other: Self) {
                *self = Self(self.0).difference(other);
            }
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            pub fn toggle(&mut self, other: Self) {
                *self = Self(self.0).symmetric_difference(other);
            }
            /// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
            #[inline]
            pub fn set(&mut self, other: Self, value: bool) {
                if value { self.insert(other); } else { self.remove(other); }
            }
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn intersection(self, other: Self) -> Self {
                Self(self.0 & other.0)
            }
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn union(self, other: Self) -> Self {
                Self(self.0 | other.0)
            }
            /// The intersection of a source flags value with the complement of a target flags
            /// value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            #[must_use]
            pub const fn difference(self, other: Self) -> Self {
                Self(self.0 & !other.0)
            }
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn symmetric_difference(self, other: Self) -> Self {
                Self(self.0 ^ other.0)
            }
            /// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
            #[inline]
            #[must_use]
            pub const fn complement(self) -> Self {
                Self::from_bits_truncate(!self.0)
            }
        }
        impl ::bitflags::__private::core::fmt::Binary for AdtFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::Octal for AdtFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::LowerHex for AdtFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::UpperHex for AdtFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::ops::BitOr for AdtFlags {
            type Output = Self;
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            fn bitor(self, other: AdtFlags) -> Self { self.union(other) }
        }
        impl ::bitflags::__private::core::ops::BitOrAssign for AdtFlags {
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            fn bitor_assign(&mut self, other: Self) { self.insert(other); }
        }
        impl ::bitflags::__private::core::ops::BitXor for AdtFlags {
            type Output = Self;
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            fn bitxor(self, other: Self) -> Self {
                self.symmetric_difference(other)
            }
        }
        impl ::bitflags::__private::core::ops::BitXorAssign for AdtFlags {
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
        }
        impl ::bitflags::__private::core::ops::BitAnd for AdtFlags {
            type Output = Self;
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            fn bitand(self, other: Self) -> Self { self.intersection(other) }
        }
        impl ::bitflags::__private::core::ops::BitAndAssign for AdtFlags {
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            fn bitand_assign(&mut self, other: Self) {
                *self =
                    Self::from_bits_retain(self.bits()).intersection(other);
            }
        }
        impl ::bitflags::__private::core::ops::Sub for AdtFlags {
            type Output = Self;
            /// The intersection of a source flags value with the complement of a target flags value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub(self, other: Self) -> Self { self.difference(other) }
        }
        impl ::bitflags::__private::core::ops::SubAssign for AdtFlags {
            /// The intersection of a source flags value with the complement of a target flags value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub_assign(&mut self, other: Self) { self.remove(other); }
        }
        impl ::bitflags::__private::core::ops::Not for AdtFlags {
            type Output = Self;
            /// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
            #[inline]
            fn not(self) -> Self { self.complement() }
        }
        impl ::bitflags::__private::core::iter::Extend<AdtFlags> for AdtFlags
            {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(&mut self, iterator: T) {
                for item in iterator { self.insert(item) }
            }
        }
        impl ::bitflags::__private::core::iter::FromIterator<AdtFlags> for
            AdtFlags {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(iterator: T) -> Self {
                use ::bitflags::__private::core::iter::Extend;
                let mut result = Self::empty();
                result.extend(iterator);
                result
            }
        }
        impl AdtFlags {
            /// Yield a set of contained flags values.
            ///
            /// Each yielded flags value will correspond to a defined named flag. Any unknown bits
            /// will be yielded together as a final flags value.
            #[inline]
            pub const fn iter(&self) -> ::bitflags::iter::Iter<AdtFlags> {
                ::bitflags::iter::Iter::__private_const_new(<AdtFlags as
                        ::bitflags::Flags>::FLAGS,
                    AdtFlags::from_bits_retain(self.bits()),
                    AdtFlags::from_bits_retain(self.bits()))
            }
            /// Yield a set of contained named flags values.
            ///
            /// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
            /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
            #[inline]
            pub const fn iter_names(&self)
                -> ::bitflags::iter::IterNames<AdtFlags> {
                ::bitflags::iter::IterNames::__private_const_new(<AdtFlags as
                        ::bitflags::Flags>::FLAGS,
                    AdtFlags::from_bits_retain(self.bits()),
                    AdtFlags::from_bits_retain(self.bits()))
            }
        }
        impl ::bitflags::__private::core::iter::IntoIterator for AdtFlags {
            type Item = AdtFlags;
            type IntoIter = ::bitflags::iter::Iter<AdtFlags>;
            fn into_iter(self) -> Self::IntoIter { self.iter() }
        }
    };bitflags::bitflags! {
34    impl AdtFlags: u16 {
35        const NO_ADT_FLAGS        = 0;
36        /// Indicates whether the ADT is an enum.
37        const IS_ENUM             = 1 << 0;
38        /// Indicates whether the ADT is a union.
39        const IS_UNION            = 1 << 1;
40        /// Indicates whether the ADT is a struct.
41        const IS_STRUCT           = 1 << 2;
42        /// Indicates whether the ADT is a struct and has a constructor.
43        const HAS_CTOR            = 1 << 3;
44        /// Indicates whether the type is `PhantomData`.
45        const IS_PHANTOM_DATA     = 1 << 4;
46        /// Indicates whether the type has a `#[fundamental]` attribute.
47        const IS_FUNDAMENTAL      = 1 << 5;
48        /// Indicates whether the type is `Box`.
49        const IS_BOX              = 1 << 6;
50        /// Indicates whether the type is `ManuallyDrop`.
51        const IS_MANUALLY_DROP    = 1 << 7;
52        /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
53        /// (i.e., this flag is never set unless this ADT is an enum).
54        const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
55        /// Indicates whether the type is `UnsafeCell`.
56        const IS_UNSAFE_CELL              = 1 << 9;
57        /// Indicates whether the type is `UnsafePinned`.
58        const IS_UNSAFE_PINNED              = 1 << 10;
59        /// Indicates whether the type is `Pin`.
60        const IS_PIN                        = 1 << 11;
61        /// Indicates whether the type is `#[pin_project]`.
62        const IS_PIN_PROJECT                = 1 << 12;
63        /// Indicates whether the type is `FieldRepresentingType`.
64        const IS_FIELD_REPRESENTING_TYPE    = 1 << 13;
65    }
66}
67impl ::std::fmt::Debug for AdtFlags {
    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        ::bitflags::parser::to_writer(self, f)
    }
}rustc_data_structures::external_bitflags_debug! { AdtFlags }
68
69/// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
70///
71/// These are all interned (by `mk_adt_def`) into the global arena.
72///
73/// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
74/// This is slightly wrong because `union`s are not ADTs.
75/// Moreover, Rust only allows recursive data types through indirection.
76///
77/// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
78///
79/// # Recursive types
80///
81/// It may seem impossible to represent recursive types using [`Ty`],
82/// since [`TyKind::Adt`] includes [`AdtDef`], which includes its fields,
83/// creating a cycle. However, `AdtDef` does not actually include the *types*
84/// of its fields; it includes just their [`DefId`]s.
85///
86/// [`TyKind::Adt`]: ty::TyKind::Adt
87///
88/// For example, the following type:
89///
90/// ```
91/// struct S { x: Box<S> }
92/// ```
93///
94/// is essentially represented with [`Ty`] as the following pseudocode:
95///
96/// ```ignore (illustrative)
97/// struct S { x }
98/// ```
99///
100/// where `x` here represents the `DefId` of `S.x`. Then, the `DefId`
101/// can be used with [`TyCtxt::type_of()`] to get the type of the field.
102#[derive(const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for AdtDefData {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    AdtDefData {
                        did: ref __binding_0,
                        variants: ref __binding_1,
                        flags: ref __binding_2,
                        repr: ref __binding_3 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_3,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for AdtDefData {
            fn decode(__decoder: &mut __D) -> Self {
                AdtDefData {
                    did: ::rustc_serialize::Decodable::decode(__decoder),
                    variants: ::rustc_serialize::Decodable::decode(__decoder),
                    flags: ::rustc_serialize::Decodable::decode(__decoder),
                    repr: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable)]
103pub struct AdtDefData {
104    /// The `DefId` of the struct, enum or union item.
105    pub did: DefId,
106    /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
107    variants: IndexVec<VariantIdx, VariantDef>,
108    /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
109    flags: AdtFlags,
110    /// Repr options provided by the user.
111    repr: ReprOptions,
112}
113
114impl PartialEq for AdtDefData {
115    #[inline]
116    fn eq(&self, other: &Self) -> bool {
117        // There should be only one `AdtDefData` for each `def_id`, therefore
118        // it is fine to implement `PartialEq` only based on `def_id`.
119        //
120        // Below, we exhaustively destructure `self` and `other` so that if the
121        // definition of `AdtDefData` changes, a compile-error will be produced,
122        // reminding us to revisit this assumption.
123
124        let Self { did: self_def_id, variants: _, flags: _, repr: _ } = self;
125        let Self { did: other_def_id, variants: _, flags: _, repr: _ } = other;
126
127        let res = self_def_id == other_def_id;
128
129        // Double check that implicit assumption detailed above.
130        if truecfg!(debug_assertions) && res {
131            let deep = self.flags == other.flags
132                && self.repr == other.repr
133                && self.variants == other.variants;
134            if !deep {
    {
        ::core::panicking::panic_fmt(format_args!("AdtDefData for the same def-id has differing data"));
    }
};assert!(deep, "AdtDefData for the same def-id has differing data");
135        }
136
137        res
138    }
139}
140
141impl Eq for AdtDefData {}
142
143/// There should be only one AdtDef for each `did`, therefore
144/// it is fine to implement `Hash` only based on `did`.
145impl Hash for AdtDefData {
146    #[inline]
147    fn hash<H: Hasher>(&self, s: &mut H) {
148        self.did.hash(s)
149    }
150}
151
152impl<'a> HashStable<StableHashingContext<'a>> for AdtDefData {
153    fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
154        const CACHE:
    ::std::thread::LocalKey<RefCell<FxHashMap<(usize, HashingControls),
    Fingerprint>>> =
    {
        #[inline]
        fn __rust_std_internal_init_fn()
            -> RefCell<FxHashMap<(usize, HashingControls), Fingerprint>> {
            Default::default()
        }
        unsafe {
            ::std::thread::LocalKey::new(const {
                        if ::std::mem::needs_drop::<RefCell<FxHashMap<(usize,
                                    HashingControls), Fingerprint>>>() {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::LazyStorage<RefCell<FxHashMap<(usize,
                                        HashingControls), Fingerprint>>, ()> =
                                        ::std::thread::local_impl::LazyStorage::new();
                                    __RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
                                        __rust_std_internal_init_fn)
                                }
                        } else {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::LazyStorage<RefCell<FxHashMap<(usize,
                                        HashingControls), Fingerprint>>, !> =
                                        ::std::thread::local_impl::LazyStorage::new();
                                    __RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
                                        __rust_std_internal_init_fn)
                                }
                        }
                    })
        }
    };thread_local! {
155            static CACHE: RefCell<FxHashMap<(usize, HashingControls), Fingerprint>> = Default::default();
156        }
157
158        let hash: Fingerprint = CACHE.with(|cache| {
159            let addr = self as *const AdtDefData as usize;
160            let hashing_controls = hcx.hashing_controls();
161            *cache.borrow_mut().entry((addr, hashing_controls)).or_insert_with(|| {
162                let ty::AdtDefData { did, ref variants, ref flags, ref repr } = *self;
163
164                let mut hasher = StableHasher::new();
165                did.hash_stable(hcx, &mut hasher);
166                variants.hash_stable(hcx, &mut hasher);
167                flags.hash_stable(hcx, &mut hasher);
168                repr.hash_stable(hcx, &mut hasher);
169
170                hasher.finish()
171            })
172        });
173
174        hash.hash_stable(hcx, hasher);
175    }
176}
177
178#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for AdtDef<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for AdtDef<'tcx> {
    #[inline]
    fn clone(&self) -> AdtDef<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Interned<'tcx, AdtDefData>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for AdtDef<'tcx> {
    #[inline]
    fn eq(&self, other: &AdtDef<'tcx>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for AdtDef<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Interned<'tcx, AdtDefData>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for AdtDef<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, const _: () =
    {
        impl<'tcx, '__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for AdtDef<'tcx> {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    AdtDef(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable)]
179#[rustc_pass_by_value]
180pub struct AdtDef<'tcx>(pub Interned<'tcx, AdtDefData>);
181
182impl<'tcx> AdtDef<'tcx> {
183    #[inline]
184    pub fn did(self) -> DefId {
185        self.0.0.did
186    }
187
188    #[inline]
189    pub fn variants(self) -> &'tcx IndexSlice<VariantIdx, VariantDef> {
190        &self.0.0.variants
191    }
192
193    #[inline]
194    pub fn variant(self, idx: VariantIdx) -> &'tcx VariantDef {
195        &self.0.0.variants[idx]
196    }
197
198    #[inline]
199    pub fn flags(self) -> AdtFlags {
200        self.0.0.flags
201    }
202
203    #[inline]
204    pub fn repr(self) -> ReprOptions {
205        self.0.0.repr
206    }
207
208    pub fn field_representing_type_info(
209        self,
210        tcx: TyCtxt<'tcx>,
211        args: ty::GenericArgsRef<'tcx>,
212    ) -> Option<FieldInfo<TyCtxt<'tcx>>> {
213        if !self.is_field_representing_type() {
214            return None;
215        }
216        let base = args.type_at(0);
217        let variant_idx = match args.const_at(1).kind() {
218            ConstKind::Value(v) => VariantIdx::from_u32(v.to_leaf().to_u32()),
219            _ => return None,
220        };
221        let field_idx = match args.const_at(2).kind() {
222            ConstKind::Value(v) => FieldIdx::from_u32(v.to_leaf().to_u32()),
223            _ => return None,
224        };
225        let (ty, variant, name) = match base.kind() {
226            ty::Adt(base_def, base_args) => {
227                let variant = base_def.variant(variant_idx);
228                let field = &variant.fields[field_idx];
229                (field.ty(tcx, base_args), base_def.is_enum().then_some(variant.name), field.name)
230            }
231            ty::Tuple(tys) => {
232                if variant_idx != FIRST_VARIANT {
233                    crate::util::bug::bug_fmt(format_args!("expected variant of tuple to be FIRST_VARIANT, but found {0:?}",
        variant_idx))bug!("expected variant of tuple to be FIRST_VARIANT, but found {variant_idx:?}")
234                }
235                (
236                    if let Some(ty) = tys.get(field_idx.index()) {
237                        *ty
238                    } else {
239                        crate::util::bug::bug_fmt(format_args!("expected valid tuple index, but got {1:?}, tuple length: {0}",
        tys.len(), field_idx))bug!(
240                            "expected valid tuple index, but got {field_idx:?}, tuple length: {}",
241                            tys.len()
242                        )
243                    },
244                    None,
245                    sym::integer(field_idx.index()),
246                )
247            }
248            _ => ::core::panicking::panic("explicit panic")panic!(),
249        };
250        Some(FieldInfo { base, ty, variant, variant_idx, name, field_idx })
251    }
252}
253
254impl<'tcx> rustc_type_ir::inherent::AdtDef<TyCtxt<'tcx>> for AdtDef<'tcx> {
255    fn def_id(self) -> DefId {
256        self.did()
257    }
258
259    fn is_struct(self) -> bool {
260        self.is_struct()
261    }
262
263    fn is_packed(self) -> bool {
264        self.repr().packed()
265    }
266
267    fn struct_tail_ty(self, interner: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
268        Some(interner.type_of(self.non_enum_variant().tail_opt()?.did))
269    }
270
271    fn is_phantom_data(self) -> bool {
272        self.is_phantom_data()
273    }
274
275    fn is_manually_drop(self) -> bool {
276        self.is_manually_drop()
277    }
278
279    fn field_representing_type_info(
280        self,
281        tcx: TyCtxt<'tcx>,
282        args: ty::GenericArgsRef<'tcx>,
283    ) -> Option<FieldInfo<TyCtxt<'tcx>>> {
284        self.field_representing_type_info(tcx, args)
285    }
286
287    fn all_field_tys(
288        self,
289        tcx: TyCtxt<'tcx>,
290    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = Ty<'tcx>>> {
291        ty::EarlyBinder::bind(
292            self.all_fields().map(move |field| tcx.type_of(field.did).skip_binder()),
293        )
294    }
295
296    fn sizedness_constraint(
297        self,
298        tcx: TyCtxt<'tcx>,
299        sizedness: ty::SizedTraitKind,
300    ) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
301        self.sizedness_constraint(tcx, sizedness)
302    }
303
304    fn is_fundamental(self) -> bool {
305        self.is_fundamental()
306    }
307
308    fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<AdtDestructorKind> {
309        Some(match tcx.constness(self.destructor(tcx)?.did) {
310            hir::Constness::Const => AdtDestructorKind::Const,
311            hir::Constness::NotConst => AdtDestructorKind::NotConst,
312        })
313    }
314}
315
316#[derive(#[automatically_derived]
impl ::core::marker::Copy for AdtKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AdtKind {
    #[inline]
    fn clone(&self) -> AdtKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AdtKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AdtKind::Struct => "Struct",
                AdtKind::Union => "Union",
                AdtKind::Enum => "Enum",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for AdtKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for AdtKind {
    #[inline]
    fn eq(&self, other: &AdtKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for AdtKind {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                ::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
                match *self {
                    AdtKind::Struct => {}
                    AdtKind::Union => {}
                    AdtKind::Enum => {}
                }
            }
        }
    };HashStable, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for AdtKind {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        AdtKind::Struct => { 0usize }
                        AdtKind::Union => { 1usize }
                        AdtKind::Enum => { 2usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    AdtKind::Struct => {}
                    AdtKind::Union => {}
                    AdtKind::Enum => {}
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for AdtKind {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { AdtKind::Struct }
                    1usize => { AdtKind::Union }
                    2usize => { AdtKind::Enum }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `AdtKind`, expected 0..3, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable)]
317pub enum AdtKind {
318    Struct,
319    Union,
320    Enum,
321}
322
323impl From<AdtKind> for DataTypeKind {
324    fn from(val: AdtKind) -> Self {
325        match val {
326            AdtKind::Struct => DataTypeKind::Struct,
327            AdtKind::Union => DataTypeKind::Union,
328            AdtKind::Enum => DataTypeKind::Enum,
329        }
330    }
331}
332
333impl AdtDefData {
334    /// Creates a new `AdtDefData`.
335    pub(super) fn new(
336        tcx: TyCtxt<'_>,
337        did: DefId,
338        kind: AdtKind,
339        variants: IndexVec<VariantIdx, VariantDef>,
340        repr: ReprOptions,
341    ) -> Self {
342        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/adt.rs:342",
                        "rustc_middle::ty::adt", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/adt.rs"),
                        ::tracing_core::__macro_support::Option::Some(342u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::adt"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("AdtDef::new({0:?}, {1:?}, {2:?}, {3:?})",
                                                    did, kind, variants, repr) as &dyn Value))])
            });
    } else { ; }
};debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
343        let mut flags = AdtFlags::NO_ADT_FLAGS;
344
345        if kind == AdtKind::Enum && {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in tcx.get_all_attrs(did) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(NonExhaustive(..)) => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(tcx, did, NonExhaustive(..)) {
346            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/adt.rs:346",
                        "rustc_middle::ty::adt", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/adt.rs"),
                        ::tracing_core::__macro_support::Option::Some(346u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::adt"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("found non-exhaustive variant list for {0:?}",
                                                    did) as &dyn Value))])
            });
    } else { ; }
};debug!("found non-exhaustive variant list for {:?}", did);
347            flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
348        }
349        if {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in tcx.get_all_attrs(did) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(PinV2(..)) => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(tcx, did, PinV2(..)) {
350            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/adt.rs:350",
                        "rustc_middle::ty::adt", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/adt.rs"),
                        ::tracing_core::__macro_support::Option::Some(350u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::adt"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("found pin-project type {0:?}",
                                                    did) as &dyn Value))])
            });
    } else { ; }
};debug!("found pin-project type {:?}", did);
351            flags |= AdtFlags::IS_PIN_PROJECT;
352        }
353
354        flags |= match kind {
355            AdtKind::Enum => AdtFlags::IS_ENUM,
356            AdtKind::Union => AdtFlags::IS_UNION,
357            AdtKind::Struct => AdtFlags::IS_STRUCT,
358        };
359
360        if kind == AdtKind::Struct && variants[FIRST_VARIANT].ctor.is_some() {
361            flags |= AdtFlags::HAS_CTOR;
362        }
363
364        if {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in tcx.get_all_attrs(did) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(Fundamental) => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(tcx, did, Fundamental) {
365            flags |= AdtFlags::IS_FUNDAMENTAL;
366        }
367        if tcx.is_lang_item(did, LangItem::PhantomData) {
368            flags |= AdtFlags::IS_PHANTOM_DATA;
369        }
370        if tcx.is_lang_item(did, LangItem::OwnedBox) {
371            flags |= AdtFlags::IS_BOX;
372        }
373        if tcx.is_lang_item(did, LangItem::ManuallyDrop) {
374            flags |= AdtFlags::IS_MANUALLY_DROP;
375        }
376        if tcx.is_lang_item(did, LangItem::UnsafeCell) {
377            flags |= AdtFlags::IS_UNSAFE_CELL;
378        }
379        if tcx.is_lang_item(did, LangItem::UnsafePinned) {
380            flags |= AdtFlags::IS_UNSAFE_PINNED;
381        }
382        if tcx.is_lang_item(did, LangItem::Pin) {
383            flags |= AdtFlags::IS_PIN;
384        }
385        if tcx.is_lang_item(did, LangItem::FieldRepresentingType) {
386            flags |= AdtFlags::IS_FIELD_REPRESENTING_TYPE;
387        }
388
389        AdtDefData { did, variants, flags, repr }
390    }
391}
392
393impl<'tcx> AdtDef<'tcx> {
394    /// Returns `true` if this is a struct.
395    #[inline]
396    pub fn is_struct(self) -> bool {
397        self.flags().contains(AdtFlags::IS_STRUCT)
398    }
399
400    /// Returns `true` if this is a union.
401    #[inline]
402    pub fn is_union(self) -> bool {
403        self.flags().contains(AdtFlags::IS_UNION)
404    }
405
406    /// Returns `true` if this is an enum.
407    #[inline]
408    pub fn is_enum(self) -> bool {
409        self.flags().contains(AdtFlags::IS_ENUM)
410    }
411
412    /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
413    ///
414    /// Note that this function will return `true` even if the ADT has been
415    /// defined in the crate currently being compiled. If that's not what you
416    /// want, see [`Self::variant_list_has_applicable_non_exhaustive`].
417    #[inline]
418    pub fn is_variant_list_non_exhaustive(self) -> bool {
419        self.flags().contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
420    }
421
422    /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`
423    /// and has been defined in another crate.
424    #[inline]
425    pub fn variant_list_has_applicable_non_exhaustive(self) -> bool {
426        self.is_variant_list_non_exhaustive() && !self.did().is_local()
427    }
428
429    /// Returns the kind of the ADT.
430    #[inline]
431    pub fn adt_kind(self) -> AdtKind {
432        if self.is_enum() {
433            AdtKind::Enum
434        } else if self.is_union() {
435            AdtKind::Union
436        } else {
437            AdtKind::Struct
438        }
439    }
440
441    /// Returns a description of this abstract data type.
442    pub fn descr(self) -> &'static str {
443        match self.adt_kind() {
444            AdtKind::Struct => "struct",
445            AdtKind::Union => "union",
446            AdtKind::Enum => "enum",
447        }
448    }
449
450    /// Returns a description of a variant of this abstract data type.
451    #[inline]
452    pub fn variant_descr(self) -> &'static str {
453        match self.adt_kind() {
454            AdtKind::Struct => "struct",
455            AdtKind::Union => "union",
456            AdtKind::Enum => "variant",
457        }
458    }
459
460    /// If this function returns `true`, it implies that `is_struct` must return `true`.
461    #[inline]
462    pub fn has_ctor(self) -> bool {
463        self.flags().contains(AdtFlags::HAS_CTOR)
464    }
465
466    /// Returns `true` if this type is `#[fundamental]` for the purposes
467    /// of coherence checking.
468    #[inline]
469    pub fn is_fundamental(self) -> bool {
470        self.flags().contains(AdtFlags::IS_FUNDAMENTAL)
471    }
472
473    /// Returns `true` if this is `PhantomData<T>`.
474    #[inline]
475    pub fn is_phantom_data(self) -> bool {
476        self.flags().contains(AdtFlags::IS_PHANTOM_DATA)
477    }
478
479    /// Returns `true` if this is `Box<T>`.
480    #[inline]
481    pub fn is_box(self) -> bool {
482        self.flags().contains(AdtFlags::IS_BOX)
483    }
484
485    /// Returns `true` if this is `UnsafeCell<T>`.
486    #[inline]
487    pub fn is_unsafe_cell(self) -> bool {
488        self.flags().contains(AdtFlags::IS_UNSAFE_CELL)
489    }
490
491    /// Returns `true` if this is `UnsafePinned<T>`.
492    #[inline]
493    pub fn is_unsafe_pinned(self) -> bool {
494        self.flags().contains(AdtFlags::IS_UNSAFE_PINNED)
495    }
496
497    /// Returns `true` if this is `ManuallyDrop<T>`.
498    #[inline]
499    pub fn is_manually_drop(self) -> bool {
500        self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
501    }
502
503    /// Returns `true` if this is `Pin<T>`.
504    #[inline]
505    pub fn is_pin(self) -> bool {
506        self.flags().contains(AdtFlags::IS_PIN)
507    }
508
509    /// Returns `true` is this is `#[pin_v2]` for the purposes
510    /// of structural pinning.
511    #[inline]
512    pub fn is_pin_project(self) -> bool {
513        self.flags().contains(AdtFlags::IS_PIN_PROJECT)
514    }
515
516    pub fn is_field_representing_type(self) -> bool {
517        self.flags().contains(AdtFlags::IS_FIELD_REPRESENTING_TYPE)
518    }
519
520    /// Returns `true` if this type has a destructor.
521    pub fn has_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
522        self.destructor(tcx).is_some()
523    }
524
525    /// Asserts this is a struct or union and returns its unique variant.
526    pub fn non_enum_variant(self) -> &'tcx VariantDef {
527        if !(self.is_struct() || self.is_union()) {
    ::core::panicking::panic("assertion failed: self.is_struct() || self.is_union()")
};assert!(self.is_struct() || self.is_union());
528        self.variant(FIRST_VARIANT)
529    }
530
531    #[inline]
532    pub fn predicates(self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
533        tcx.predicates_of(self.did())
534    }
535
536    /// Returns an iterator over all fields contained
537    /// by this ADT (nested unnamed fields are not expanded).
538    #[inline]
539    pub fn all_fields(self) -> impl Iterator<Item = &'tcx FieldDef> + Clone {
540        self.variants().iter().flat_map(|v| v.fields.iter())
541    }
542
543    /// Whether the ADT lacks fields. Note that this includes uninhabited enums,
544    /// e.g., `enum Void {}` is considered payload free as well.
545    pub fn is_payloadfree(self) -> bool {
546        // Treat the ADT as not payload-free if arbitrary_enum_discriminant is used (#88621).
547        // This would disallow the following kind of enum from being casted into integer.
548        // ```
549        // enum Enum {
550        //    Foo() = 1,
551        //    Bar{} = 2,
552        //    Baz = 3,
553        // }
554        // ```
555        if self.variants().iter().any(|v| {
556            #[allow(non_exhaustive_omitted_patterns)] match v.discr {
    VariantDiscr::Explicit(_) => true,
    _ => false,
}matches!(v.discr, VariantDiscr::Explicit(_)) && v.ctor_kind() != Some(CtorKind::Const)
557        }) {
558            return false;
559        }
560        self.variants().iter().all(|v| v.fields.is_empty())
561    }
562
563    /// Return a `VariantDef` given a variant id.
564    pub fn variant_with_id(self, vid: DefId) -> &'tcx VariantDef {
565        self.variants().iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
566    }
567
568    /// Return a `VariantDef` given a constructor id.
569    pub fn variant_with_ctor_id(self, cid: DefId) -> &'tcx VariantDef {
570        self.variants()
571            .iter()
572            .find(|v| v.ctor_def_id() == Some(cid))
573            .expect("variant_with_ctor_id: unknown variant")
574    }
575
576    /// Return the index of `VariantDef` given a variant id.
577    #[inline]
578    pub fn variant_index_with_id(self, vid: DefId) -> VariantIdx {
579        self.variants()
580            .iter_enumerated()
581            .find(|(_, v)| v.def_id == vid)
582            .expect("variant_index_with_id: unknown variant")
583            .0
584    }
585
586    /// Return the index of `VariantDef` given a constructor id.
587    pub fn variant_index_with_ctor_id(self, cid: DefId) -> VariantIdx {
588        self.variants()
589            .iter_enumerated()
590            .find(|(_, v)| v.ctor_def_id() == Some(cid))
591            .expect("variant_index_with_ctor_id: unknown variant")
592            .0
593    }
594
595    pub fn variant_of_res(self, res: Res) -> &'tcx VariantDef {
596        match res {
597            Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
598            Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
599            Res::Def(DefKind::Struct, _)
600            | Res::Def(DefKind::Union, _)
601            | Res::Def(DefKind::TyAlias, _)
602            | Res::Def(DefKind::AssocTy, _)
603            | Res::SelfTyParam { .. }
604            | Res::SelfTyAlias { .. }
605            | Res::SelfCtor(..) => self.non_enum_variant(),
606            _ => crate::util::bug::bug_fmt(format_args!("unexpected res {0:?} in variant_of_res",
        res))bug!("unexpected res {:?} in variant_of_res", res),
607        }
608    }
609
610    #[inline]
611    pub fn eval_explicit_discr(
612        self,
613        tcx: TyCtxt<'tcx>,
614        expr_did: DefId,
615    ) -> Result<Discr<'tcx>, ErrorGuaranteed> {
616        if !self.is_enum() {
    ::core::panicking::panic("assertion failed: self.is_enum()")
};assert!(self.is_enum());
617
618        let repr_type = self.repr().discr_type();
619        match tcx.const_eval_poly(expr_did) {
620            Ok(val) => {
621                let typing_env = ty::TypingEnv::post_analysis(tcx, expr_did);
622                let ty = repr_type.to_ty(tcx);
623                if let Some(b) = val.try_to_bits_for_ty(tcx, typing_env, ty) {
624                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/adt.rs:624",
                        "rustc_middle::ty::adt", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/adt.rs"),
                        ::tracing_core::__macro_support::Option::Some(624u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::adt"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("discriminants: {0} ({1:?})",
                                                    b, repr_type) as &dyn Value))])
            });
    } else { ; }
};trace!("discriminants: {} ({:?})", b, repr_type);
625                    Ok(Discr { val: b, ty })
626                } else {
627                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/adt.rs:627",
                        "rustc_middle::ty::adt", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/adt.rs"),
                        ::tracing_core::__macro_support::Option::Some(627u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::adt"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("invalid enum discriminant: {0:#?}",
                                                    val) as &dyn Value))])
            });
    } else { ; }
};info!("invalid enum discriminant: {:#?}", val);
628                    let guar = tcx.dcx().emit_err(crate::error::ConstEvalNonIntError {
629                        span: tcx.def_span(expr_did),
630                    });
631                    Err(guar)
632                }
633            }
634            Err(err) => {
635                let guar = match err {
636                    ErrorHandled::Reported(info, _) => info.into(),
637                    ErrorHandled::TooGeneric(..) => tcx.dcx().span_delayed_bug(
638                        tcx.def_span(expr_did),
639                        "enum discriminant depends on generics",
640                    ),
641                };
642                Err(guar)
643            }
644        }
645    }
646
647    #[inline]
648    pub fn discriminants(
649        self,
650        tcx: TyCtxt<'tcx>,
651    ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
652        if !self.is_enum() {
    ::core::panicking::panic("assertion failed: self.is_enum()")
};assert!(self.is_enum());
653        let repr_type = self.repr().discr_type();
654        let initial = repr_type.initial_discriminant(tcx);
655        let mut prev_discr = None::<Discr<'tcx>>;
656        self.variants().iter_enumerated().map(move |(i, v)| {
657            let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
658            if let VariantDiscr::Explicit(expr_did) = v.discr
659                && let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did)
660            {
661                discr = new_discr;
662            }
663            prev_discr = Some(discr);
664
665            (i, discr)
666        })
667    }
668
669    #[inline]
670    pub fn variant_range(self) -> Range<VariantIdx> {
671        FIRST_VARIANT..self.variants().next_index()
672    }
673
674    /// Computes the discriminant value used by a specific variant.
675    /// Unlike `discriminants`, this is (amortized) constant-time,
676    /// only doing at most one query for evaluating an explicit
677    /// discriminant (the last one before the requested variant),
678    /// assuming there are no constant-evaluation errors there.
679    #[inline]
680    pub fn discriminant_for_variant(
681        self,
682        tcx: TyCtxt<'tcx>,
683        variant_index: VariantIdx,
684    ) -> Discr<'tcx> {
685        if !self.is_enum() {
    ::core::panicking::panic("assertion failed: self.is_enum()")
};assert!(self.is_enum());
686        let (val, offset) = self.discriminant_def_for_variant(variant_index);
687        let explicit_value = if let Some(expr_did) = val
688            && let Ok(val) = self.eval_explicit_discr(tcx, expr_did)
689        {
690            val
691        } else {
692            self.repr().discr_type().initial_discriminant(tcx)
693        };
694        explicit_value.checked_add(tcx, offset as u128).0
695    }
696
697    /// Yields a `DefId` for the discriminant and an offset to add to it
698    /// Alternatively, if there is no explicit discriminant, returns the
699    /// inferred discriminant directly.
700    pub fn discriminant_def_for_variant(self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
701        if !!self.variants().is_empty() {
    ::core::panicking::panic("assertion failed: !self.variants().is_empty()")
};assert!(!self.variants().is_empty());
702        let mut explicit_index = variant_index.as_u32();
703        let expr_did;
704        loop {
705            match self.variant(VariantIdx::from_u32(explicit_index)).discr {
706                ty::VariantDiscr::Relative(0) => {
707                    expr_did = None;
708                    break;
709                }
710                ty::VariantDiscr::Relative(distance) => {
711                    explicit_index -= distance;
712                }
713                ty::VariantDiscr::Explicit(did) => {
714                    expr_did = Some(did);
715                    break;
716                }
717            }
718        }
719        (expr_did, variant_index.as_u32() - explicit_index)
720    }
721
722    pub fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
723        tcx.adt_destructor(self.did())
724    }
725
726    // FIXME: consider combining this method with `AdtDef::destructor` and removing
727    // this version
728    pub fn async_destructor(self, tcx: TyCtxt<'tcx>) -> Option<AsyncDestructor> {
729        tcx.adt_async_destructor(self.did())
730    }
731
732    /// If this ADT is a struct, returns a type such that `Self: {Meta,Pointee,}Sized` if and only
733    /// if that type is `{Meta,Pointee,}Sized`, or `None` if this ADT is always
734    /// `{Meta,Pointee,}Sized`.
735    pub fn sizedness_constraint(
736        self,
737        tcx: TyCtxt<'tcx>,
738        sizedness: ty::SizedTraitKind,
739    ) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
740        if self.is_struct() { tcx.adt_sizedness_constraint((self.did(), sizedness)) } else { None }
741    }
742}
743
744#[derive(#[automatically_derived]
impl ::core::clone::Clone for Representability {
    #[inline]
    fn clone(&self) -> Representability {
        let _: ::core::clone::AssertParamIsClone<ErrorGuaranteed>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Representability { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Representability {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Representability::Representable =>
                ::core::fmt::Formatter::write_str(f, "Representable"),
            Representability::Infinite(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Infinite", &__self_0),
        }
    }
}Debug, const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for Representability {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                ::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
                match *self {
                    Representability::Representable => {}
                    Representability::Infinite(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable)]
745pub enum Representability {
746    Representable,
747    Infinite(ErrorGuaranteed),
748}