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_attr_ir::find_attr;
8use rustc_attr_ir::lang_items::LangItem;
9use rustc_data_structures::fingerprint::Fingerprint;
10use rustc_data_structures::fx::FxHashMap;
11use rustc_data_structures::intern::Interned;
12use rustc_data_structures::stable_hash::{
13    StableHash, StableHashControls, StableHashCtxt, StableHasher,
14};
15use rustc_errors::ErrorGuaranteed;
16use rustc_hir as hir;
17use rustc_hir::def::{CtorKind, DefKind, Res};
18use rustc_hir::def_id::DefId;
19use rustc_index::{IndexSlice, IndexVec};
20use rustc_macros::{StableHash, TyDecodable, TyEncodable};
21use rustc_session::DataTypeKind;
22use rustc_span::{bug, sym};
23use rustc_type_ir::FieldInfo;
24use rustc_type_ir::solve::AdtDestructorKind;
25use tracing::{debug, info, trace};
26
27use super::{
28    AsyncDestructor, Destructor, FieldDef, GenericClauses, Ty, TyCtxt, VariantDef, VariantDiscr,
29};
30use crate::mir::interpret::ErrorHandled;
31use crate::ty::util::{Discr, IntTypeExt};
32use crate::ty::{self, ConstKind};
33
34#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for AdtFlags {
}
#[automatically_derived]impl ::core::clone::Clone for AdtFlags {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<u16>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for AdtFlags { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for AdtFlags
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for AdtFlags {
    #[inline]
    fn eq(&self, other: &Self) -> 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 ::rustc_data_structures::stable_hash::StableHash for AdtFlags {
            #[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 {
                    AdtFlags(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for AdtFlags {
            fn encode(&self, __encoder: &mut __E) {
                let AdtFlags(ref __binding_0) = *self;
                ::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)]
35pub struct AdtFlags(u16);
36impl 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);
    #[doc = r" Indicates whether the type is `MaybeDangling<_>`."]
    #[doc =
    r#" Note that this is not the only type with "maybe dangling" semantics!"#]
    #[doc = r" Use `ty.is_like_maybe_dangling()` to check for that."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_MAYBE_DANGLING: Self = Self::from_bits_retain(1 << 14);
}
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)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_MAYBE_DANGLING",
                            AdtFlags::IS_MAYBE_DANGLING)
                    }];
    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 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()));
                    }
                };
                ;
                {
                    if name == "IS_MAYBE_DANGLING" {
                        return ::bitflags::__private::core::option::Option::Some(Self(AdtFlags::IS_MAYBE_DANGLING.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! {
37    impl AdtFlags: u16 {
38        const NO_ADT_FLAGS        = 0;
39        /// Indicates whether the ADT is an enum.
40        const IS_ENUM             = 1 << 0;
41        /// Indicates whether the ADT is a union.
42        const IS_UNION            = 1 << 1;
43        /// Indicates whether the ADT is a struct.
44        const IS_STRUCT           = 1 << 2;
45        /// Indicates whether the ADT is a struct and has a constructor.
46        const HAS_CTOR            = 1 << 3;
47        /// Indicates whether the type is `PhantomData`.
48        const IS_PHANTOM_DATA     = 1 << 4;
49        /// Indicates whether the type has a `#[fundamental]` attribute.
50        const IS_FUNDAMENTAL      = 1 << 5;
51        /// Indicates whether the type is `Box`.
52        const IS_BOX              = 1 << 6;
53        /// Indicates whether the type is `ManuallyDrop`.
54        const IS_MANUALLY_DROP    = 1 << 7;
55        /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
56        /// (i.e., this flag is never set unless this ADT is an enum).
57        const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
58        /// Indicates whether the type is `UnsafeCell`.
59        const IS_UNSAFE_CELL              = 1 << 9;
60        /// Indicates whether the type is `UnsafePinned`.
61        const IS_UNSAFE_PINNED              = 1 << 10;
62        /// Indicates whether the type is `Pin`.
63        const IS_PIN                        = 1 << 11;
64        /// Indicates whether the type is `#[pin_project]`.
65        const IS_PIN_PROJECT                = 1 << 12;
66        /// Indicates whether the type is `FieldRepresentingType`.
67        const IS_FIELD_REPRESENTING_TYPE    = 1 << 13;
68        /// Indicates whether the type is `MaybeDangling<_>`.
69        /// Note that this is not the only type with "maybe dangling" semantics!
70        /// Use `ty.is_like_maybe_dangling()` to check for that.
71        const IS_MAYBE_DANGLING             = 1 << 14;
72    }
73}
74impl ::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 }
75
76/// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
77///
78/// These are all interned (by `mk_adt_def`) into the global arena.
79///
80/// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
81/// This is slightly wrong because `union`s are not ADTs.
82/// Moreover, Rust only allows recursive data types through indirection.
83///
84/// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
85///
86/// # Recursive types
87///
88/// It may seem impossible to represent recursive types using [`Ty`],
89/// since [`TyKind::Adt`] includes [`AdtDef`], which includes its fields,
90/// creating a cycle. However, `AdtDef` does not actually include the *types*
91/// of its fields; it includes just their [`DefId`]s.
92///
93/// [`TyKind::Adt`]: ty::TyKind::Adt
94///
95/// For example, the following type:
96///
97/// ```
98/// struct S { x: Box<S> }
99/// ```
100///
101/// is essentially represented with [`Ty`] as the following pseudocode:
102///
103/// ```ignore (illustrative)
104/// struct S { x }
105/// ```
106///
107/// where `x` here represents the `DefId` of `S.x`. Then, the `DefId`
108/// can be used with [`TyCtxt::type_of()`] to get the type of the field.
109#[derive(const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for AdtDefData {
            fn encode(&self, __encoder: &mut __E) {
                let AdtDefData {
                        did: ref __binding_0,
                        variants: ref __binding_1,
                        flags: ref __binding_2,
                        repr: ref __binding_3 } = *self;
                ::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)]
110pub struct AdtDefData {
111    /// The `DefId` of the struct, enum or union item.
112    pub did: DefId,
113    /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
114    variants: IndexVec<VariantIdx, VariantDef>,
115    /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
116    flags: AdtFlags,
117    /// Repr options provided by the user.
118    repr: ReprOptions,
119}
120
121impl PartialEq for AdtDefData {
122    #[inline]
123    fn eq(&self, other: &Self) -> bool {
124        // There should be only one `AdtDefData` for each `def_id`, therefore
125        // it is fine to implement `PartialEq` only based on `def_id`.
126        //
127        // Below, we exhaustively destructure `self` and `other` so that if the
128        // definition of `AdtDefData` changes, a compile-error will be produced,
129        // reminding us to revisit this assumption.
130
131        let Self { did: self_def_id, variants: _, flags: _, repr: _ } = self;
132        let Self { did: other_def_id, variants: _, flags: _, repr: _ } = other;
133
134        let res = self_def_id == other_def_id;
135
136        // Double check that implicit assumption detailed above.
137        if truecfg!(debug_assertions) && res {
138            let deep = self.flags == other.flags
139                && self.repr == other.repr
140                && self.variants == other.variants;
141            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");
142        }
143
144        res
145    }
146}
147
148impl Eq for AdtDefData {}
149
150/// There should be only one AdtDef for each `did`, therefore
151/// it is fine to implement `Hash` only based on `did`.
152impl Hash for AdtDefData {
153    #[inline]
154    fn hash<H: Hasher>(&self, s: &mut H) {
155        self.did.hash(s)
156    }
157}
158
159impl StableHash for AdtDefData {
160    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
161        const CACHE:
    ::std::thread::LocalKey<RefCell<FxHashMap<(usize, StableHashControls),
    Fingerprint>>> =
    {
        #[allow(mismatched_lifetime_syntaxes)]
        #[inline]
        fn __rust_std_internal_init_fn(_lifetime_elision:
                ::std::marker::PhantomData<&'static ()>)
            -> RefCell<FxHashMap<(usize, StableHashControls), Fingerprint>> {
            Default::default()
        }
        unsafe {
            ::std::thread::LocalKey::new(const {
                        if ::std::mem::needs_drop::<RefCell<FxHashMap<(usize,
                                    StableHashControls), Fingerprint>>>() {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::LazyStorage<RefCell<FxHashMap<(usize,
                                        StableHashControls), Fingerprint>>, ()> =
                                        ::std::thread::local_impl::LazyStorage::new();
                                    __RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
                                        || __rust_std_internal_init_fn(::std::marker::PhantomData))
                                }
                        } else {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::LazyStorage<RefCell<FxHashMap<(usize,
                                        StableHashControls), Fingerprint>>, !> =
                                        ::std::thread::local_impl::LazyStorage::new();
                                    __RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
                                        || __rust_std_internal_init_fn(::std::marker::PhantomData))
                                }
                        }
                    })
        }
    };thread_local! {
162            static CACHE: RefCell<FxHashMap<(usize, StableHashControls), Fingerprint>> = Default::default();
163        }
164
165        let hash: Fingerprint = CACHE.with(|cache| {
166            let addr = self as *const AdtDefData as usize;
167            let stable_hash_controls = hcx.stable_hash_controls();
168            *cache.borrow_mut().entry((addr, stable_hash_controls)).or_insert_with(|| {
169                let ty::AdtDefData { did, ref variants, ref flags, ref repr } = *self;
170
171                let mut hasher = StableHasher::new();
172                did.stable_hash(hcx, &mut hasher);
173                variants.stable_hash(hcx, &mut hasher);
174                flags.stable_hash(hcx, &mut hasher);
175                repr.stable_hash(hcx, &mut hasher);
176
177                hasher.finish()
178            })
179        });
180
181        hash.stable_hash(hcx, hasher);
182    }
183}
184
185#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for AdtDef<'tcx> { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for AdtDef<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for AdtDef<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Interned<'tcx, AdtDefData>>;
        *self
    }
}Clone, #[automatically_derived]impl<'tcx> ::core::marker::StructuralPartialEq for
    AdtDef<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::cmp::PartialEq for AdtDef<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> 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> ::rustc_data_structures::stable_hash::StableHash for
            AdtDef<'tcx> {
            #[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 {
                    AdtDef(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
186#[cfg_attr(bootstrap, rustc_pass_by_value)]
187#[cfg_attr(not(bootstrap), lint::pass_by_value)]
188pub struct AdtDef<'tcx>(pub Interned<'tcx, AdtDefData>);
189
190impl<'tcx> AdtDef<'tcx> {
191    #[inline]
192    pub fn did(self) -> DefId {
193        self.0.0.did
194    }
195
196    #[inline]
197    pub fn variants(self) -> &'tcx IndexSlice<VariantIdx, VariantDef> {
198        &self.0.0.variants
199    }
200
201    #[inline]
202    pub fn variant(self, idx: VariantIdx) -> &'tcx VariantDef {
203        &self.0.0.variants[idx]
204    }
205
206    #[inline]
207    pub fn flags(self) -> AdtFlags {
208        self.0.0.flags
209    }
210
211    #[inline]
212    pub fn repr(self) -> ReprOptions {
213        self.0.0.repr
214    }
215
216    /// Whether MIR may project into the fields of this ADT.
217    ///
218    /// MCP#838 bans field projections into SIMD types, including scalable
219    /// vectors.
220    ///
221    /// Codegen requires `DynMetadata` to be manipulated as a whole, with its
222    /// insides being treated as opaque..
223    pub fn can_project_fields(self, tcx: TyCtxt<'tcx>) -> bool {
224        !self.repr().simd()
225            && !self.repr().scalable()
226            && !tcx.is_lang_item(self.did(), LangItem::DynMetadata)
227    }
228
229    pub fn field_representing_type_info(
230        self,
231        tcx: TyCtxt<'tcx>,
232        args: ty::GenericArgs<'tcx>,
233    ) -> Option<FieldInfo<TyCtxt<'tcx>>> {
234        if !self.is_field_representing_type() {
235            return None;
236        }
237        let base = args.type_at(0);
238        let variant_idx = match args.const_at(1).kind() {
239            ConstKind::Value(v) => VariantIdx::from_u32(v.to_leaf().to_u32()),
240            _ => return None,
241        };
242        let field_idx = match args.const_at(2).kind() {
243            ConstKind::Value(v) => FieldIdx::from_u32(v.to_leaf().to_u32()),
244            _ => return None,
245        };
246        let (ty, variant, name) = match base.kind() {
247            ty::Adt(base_def, base_args) => {
248                let variant = base_def.variant(variant_idx);
249                let field = &variant.fields[field_idx];
250                let ty = field.ty(tcx, *base_args).skip_norm_wip();
251                (ty, base_def.is_enum().then_some(variant.name), field.name)
252            }
253            ty::Tuple(tys) => {
254                if variant_idx != FIRST_VARIANT {
255                    ::rustc_span::macros::bug_impl(None,
    format_args!("expected variant of tuple to be FIRST_VARIANT, but found {0:?}",
        variant_idx), Location::caller())bug!("expected variant of tuple to be FIRST_VARIANT, but found {variant_idx:?}")
256                }
257                (
258                    if let Some(ty) = tys.get(field_idx.index()) {
259                        *ty
260                    } else {
261                        ::rustc_span::macros::bug_impl(None,
    format_args!("expected valid tuple index, but got {1:?}, tuple length: {0}",
        tys.len(), field_idx), Location::caller())bug!(
262                            "expected valid tuple index, but got {field_idx:?}, tuple length: {}",
263                            tys.len()
264                        )
265                    },
266                    None,
267                    sym::integer(field_idx.index()),
268                )
269            }
270            _ => ::core::panicking::panic_default_msg()panic!(),
271        };
272        Some(FieldInfo { base, ty, variant, variant_idx, name, field_idx })
273    }
274}
275
276impl<'tcx> rustc_type_ir::inherent::AdtDef<TyCtxt<'tcx>> for AdtDef<'tcx> {
277    fn def_id(self) -> DefId {
278        self.did()
279    }
280
281    fn is_struct(self) -> bool {
282        self.is_struct()
283    }
284
285    fn is_packed(self) -> bool {
286        self.repr().packed()
287    }
288
289    fn struct_tail_ty(self, interner: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
290        Some(interner.type_of(self.non_enum_variant().tail_opt()?.did))
291    }
292
293    fn is_phantom_data(self) -> bool {
294        self.is_phantom_data()
295    }
296
297    fn is_manually_drop(self) -> bool {
298        self.is_manually_drop()
299    }
300
301    fn field_representing_type_info(
302        self,
303        tcx: TyCtxt<'tcx>,
304        args: ty::GenericArgs<'tcx>,
305    ) -> Option<FieldInfo<TyCtxt<'tcx>>> {
306        self.field_representing_type_info(tcx, args)
307    }
308
309    fn all_field_tys(
310        self,
311        tcx: TyCtxt<'tcx>,
312    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = Ty<'tcx>>> {
313        ty::EarlyBinder::bind_iter(
314            self.all_fields().map(move |field| tcx.type_of(field.did).skip_binder()),
315        )
316    }
317
318    fn sizedness_constraint(
319        self,
320        tcx: TyCtxt<'tcx>,
321        sizedness: ty::SizedTraitKind,
322    ) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
323        self.sizedness_constraint(tcx, sizedness)
324    }
325
326    fn is_fundamental(self) -> bool {
327        self.is_fundamental()
328    }
329
330    fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<AdtDestructorKind> {
331        Some(match tcx.constness(self.destructor(tcx)?.did) {
332            hir::Constness::Const { always: true } => {
    ::core::panicking::panic_fmt(format_args!("not implemented: {0}",
            format_args!("FIXME(comptime)")));
}unimplemented!("FIXME(comptime)"),
333            hir::Constness::Const { always: false } => AdtDestructorKind::Const,
334            hir::Constness::NotConst => AdtDestructorKind::NotConst,
335        })
336    }
337}
338
339#[derive(#[automatically_derived]impl ::core::marker::Copy for AdtKind { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for AdtKind {
}
#[automatically_derived]impl ::core::clone::Clone for AdtKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for AdtKind {
    #[inline]
    #[rustc_trivial_field_reads]
    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 { }Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for AdtKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for AdtKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for AdtKind {
            #[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 {
                    AdtKind::Struct => 0u8.stable_hash(__hcx, __hasher),
                    AdtKind::Union => 1u8.stable_hash(__hcx, __hasher),
                    AdtKind::Enum => 2u8.stable_hash(__hcx, __hasher),
                }
                match *self {
                    AdtKind::Struct => {}
                    AdtKind::Union => {}
                    AdtKind::Enum => {}
                }
            }
        }
    };StableHash, 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);
            }
        }
    };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)]
340pub enum AdtKind {
341    Struct,
342    Union,
343    Enum,
344}
345
346impl From<AdtKind> for DataTypeKind {
347    fn from(val: AdtKind) -> Self {
348        match val {
349            AdtKind::Struct => DataTypeKind::Struct,
350            AdtKind::Union => DataTypeKind::Union,
351            AdtKind::Enum => DataTypeKind::Enum,
352        }
353    }
354}
355
356impl AdtKind {
357    pub fn article(self) -> &'static str {
358        match self {
359            AdtKind::Struct => "a",
360            // https://english.stackexchange.com/a/266324
361            AdtKind::Union => "a",
362            AdtKind::Enum => "an",
363        }
364    }
365}
366
367impl AdtDefData {
368    /// Creates a new `AdtDefData`.
369    pub(super) fn new(
370        tcx: TyCtxt<'_>,
371        did: DefId,
372        kind: AdtKind,
373        variants: IndexVec<VariantIdx, VariantDef>,
374        repr: ReprOptions,
375    ) -> Self {
376        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/adt.rs:376",
                        "rustc_middle::ty::adt", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/adt.rs"),
                        ::tracing_core::__macro_support::Option::Some(376u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("AdtDef::new({0:?}, {1:?}, {2:?}, {3:?})",
                                                    did, kind, variants, repr) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
377        let mut flags = AdtFlags::NO_ADT_FLAGS;
378
379        if kind == AdtKind::Enum && {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(NonExhaustive(..)) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Tool { .. } |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, did, NonExhaustive(..)) {
380            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/adt.rs:380",
                        "rustc_middle::ty::adt", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/adt.rs"),
                        ::tracing_core::__macro_support::Option::Some(380u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("found non-exhaustive variant list for {0:?}",
                                                    did) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("found non-exhaustive variant list for {:?}", did);
381            flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
382        }
383        if {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(PinV2(..)) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Tool { .. } |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, did, PinV2(..)) {
384            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/adt.rs:384",
                        "rustc_middle::ty::adt", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/adt.rs"),
                        ::tracing_core::__macro_support::Option::Some(384u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("found pin-project type {0:?}",
                                                    did) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("found pin-project type {:?}", did);
385            flags |= AdtFlags::IS_PIN_PROJECT;
386        }
387
388        flags |= match kind {
389            AdtKind::Enum => AdtFlags::IS_ENUM,
390            AdtKind::Union => AdtFlags::IS_UNION,
391            AdtKind::Struct => AdtFlags::IS_STRUCT,
392        };
393
394        if kind == AdtKind::Struct && variants[FIRST_VARIANT].ctor.is_some() {
395            flags |= AdtFlags::HAS_CTOR;
396        }
397
398        if {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(Fundamental) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Tool { .. } |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, did, Fundamental) {
399            flags |= AdtFlags::IS_FUNDAMENTAL;
400        }
401        flags |= match tcx.as_lang_item(did) {
402            Some(LangItem::PhantomData) => AdtFlags::IS_PHANTOM_DATA,
403            Some(LangItem::OwnedBox) => AdtFlags::IS_BOX,
404            Some(LangItem::ManuallyDrop) => AdtFlags::IS_MANUALLY_DROP,
405            Some(LangItem::MaybeDangling) => AdtFlags::IS_MAYBE_DANGLING,
406            Some(LangItem::UnsafeCell) => AdtFlags::IS_UNSAFE_CELL,
407            Some(LangItem::UnsafePinned) => AdtFlags::IS_UNSAFE_PINNED,
408            Some(LangItem::Pin) => AdtFlags::IS_PIN,
409            Some(LangItem::FieldRepresentingType) => AdtFlags::IS_FIELD_REPRESENTING_TYPE,
410            _ => AdtFlags::NO_ADT_FLAGS,
411        };
412
413        AdtDefData { did, variants, flags, repr }
414    }
415}
416
417impl<'tcx> AdtDef<'tcx> {
418    /// Returns `true` if this is a struct.
419    #[inline]
420    pub fn is_struct(self) -> bool {
421        self.flags().contains(AdtFlags::IS_STRUCT)
422    }
423
424    /// Returns `true` if this is a union.
425    #[inline]
426    pub fn is_union(self) -> bool {
427        self.flags().contains(AdtFlags::IS_UNION)
428    }
429
430    /// Returns `true` if this is an enum.
431    #[inline]
432    pub fn is_enum(self) -> bool {
433        self.flags().contains(AdtFlags::IS_ENUM)
434    }
435
436    /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
437    ///
438    /// Note that this function will return `true` even if the ADT has been
439    /// defined in the crate currently being compiled. If that's not what you
440    /// want, see [`Self::variant_list_has_applicable_non_exhaustive`].
441    #[inline]
442    pub fn is_variant_list_non_exhaustive(self) -> bool {
443        self.flags().contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
444    }
445
446    /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`
447    /// and has been defined in another crate.
448    #[inline]
449    pub fn variant_list_has_applicable_non_exhaustive(self) -> bool {
450        self.is_variant_list_non_exhaustive() && !self.did().is_local()
451    }
452
453    /// Returns the kind of the ADT.
454    #[inline]
455    pub fn adt_kind(self) -> AdtKind {
456        if self.is_enum() {
457            AdtKind::Enum
458        } else if self.is_union() {
459            AdtKind::Union
460        } else {
461            AdtKind::Struct
462        }
463    }
464
465    /// Returns a description of this abstract data type.
466    pub fn descr(self) -> &'static str {
467        match self.adt_kind() {
468            AdtKind::Struct => "struct",
469            AdtKind::Union => "union",
470            AdtKind::Enum => "enum",
471        }
472    }
473
474    /// Returns a description of this abstract data type with the article.
475    pub fn article(self) -> &'static str {
476        match self.adt_kind() {
477            AdtKind::Struct | AdtKind::Union => "a",
478            AdtKind::Enum => "an",
479        }
480    }
481
482    /// Returns a description of a variant of this abstract data type.
483    #[inline]
484    pub fn variant_descr(self) -> &'static str {
485        match self.adt_kind() {
486            AdtKind::Struct => "struct",
487            AdtKind::Union => "union",
488            AdtKind::Enum => "variant",
489        }
490    }
491
492    /// If this function returns `true`, it implies that `is_struct` must return `true`.
493    #[inline]
494    pub fn has_ctor(self) -> bool {
495        self.flags().contains(AdtFlags::HAS_CTOR)
496    }
497
498    /// Returns `true` if this type is `#[fundamental]` for the purposes
499    /// of coherence checking.
500    #[inline]
501    pub fn is_fundamental(self) -> bool {
502        self.flags().contains(AdtFlags::IS_FUNDAMENTAL)
503    }
504
505    /// Returns `true` if this is `PhantomData<T>`.
506    #[inline]
507    pub fn is_phantom_data(self) -> bool {
508        self.flags().contains(AdtFlags::IS_PHANTOM_DATA)
509    }
510
511    /// Returns `true` if this is `Box<T>`.
512    #[inline]
513    pub fn is_box(self) -> bool {
514        self.flags().contains(AdtFlags::IS_BOX)
515    }
516
517    /// Returns `true` if this is `UnsafeCell<T>`.
518    #[inline]
519    pub fn is_unsafe_cell(self) -> bool {
520        self.flags().contains(AdtFlags::IS_UNSAFE_CELL)
521    }
522
523    /// Returns `true` if this is `UnsafePinned<T>`.
524    #[inline]
525    pub fn is_unsafe_pinned(self) -> bool {
526        self.flags().contains(AdtFlags::IS_UNSAFE_PINNED)
527    }
528
529    /// Returns `true` if this is `ManuallyDrop<T>`.
530    #[inline]
531    pub fn is_manually_drop(self) -> bool {
532        self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
533    }
534
535    /// Returns `true` if this is `Pin<T>`.
536    #[inline]
537    pub fn is_pin(self) -> bool {
538        self.flags().contains(AdtFlags::IS_PIN)
539    }
540
541    /// Returns `true` is this is `#[pin_v2]` for the purposes
542    /// of structural pinning.
543    #[inline]
544    pub fn is_pin_project(self) -> bool {
545        self.flags().contains(AdtFlags::IS_PIN_PROJECT)
546    }
547
548    pub fn is_field_representing_type(self) -> bool {
549        self.flags().contains(AdtFlags::IS_FIELD_REPRESENTING_TYPE)
550    }
551
552    /// Returns `true` if this type has a destructor.
553    pub fn has_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
554        self.destructor(tcx).is_some()
555    }
556
557    /// Asserts this is a struct or union and returns its unique variant.
558    pub fn non_enum_variant(self) -> &'tcx VariantDef {
559        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());
560        self.variant(FIRST_VARIANT)
561    }
562
563    #[inline]
564    pub fn clauses(self, tcx: TyCtxt<'tcx>) -> GenericClauses<'tcx> {
565        tcx.clauses_of(self.did())
566    }
567
568    /// Returns an iterator over all fields contained
569    /// by this ADT (nested unnamed fields are not expanded).
570    #[inline]
571    pub fn all_fields(self) -> impl Iterator<Item = &'tcx FieldDef> + Clone {
572        self.variants().iter().flat_map(|v| v.fields.iter())
573    }
574
575    /// Whether the ADT lacks fields. Note that this includes uninhabited enums,
576    /// e.g., `enum Void {}` is considered payload free as well.
577    pub fn is_payloadfree(self) -> bool {
578        // Treat the ADT as not payload-free if arbitrary_enum_discriminant is used (#88621).
579        // This would disallow the following kind of enum from being casted into integer.
580        // ```
581        // enum Enum {
582        //    Foo() = 1,
583        //    Bar{} = 2,
584        //    Baz = 3,
585        // }
586        // ```
587        if self.variants().iter().any(|v| {
588            #[allow(non_exhaustive_omitted_patterns)] match v.discr {
    VariantDiscr::Explicit(_) => true,
    _ => false,
}matches!(v.discr, VariantDiscr::Explicit(_)) && v.ctor_kind() != Some(CtorKind::Const)
589        }) {
590            return false;
591        }
592        self.variants().iter().all(|v| v.fields.is_empty())
593    }
594
595    /// Return a `VariantDef` given a variant id.
596    pub fn variant_with_id(self, vid: DefId) -> &'tcx VariantDef {
597        self.variants().iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
598    }
599
600    /// Return a `VariantDef` given a constructor id.
601    pub fn variant_with_ctor_id(self, cid: DefId) -> &'tcx VariantDef {
602        self.variants()
603            .iter()
604            .find(|v| v.ctor_def_id() == Some(cid))
605            .expect("variant_with_ctor_id: unknown variant")
606    }
607
608    /// Return the index of `VariantDef` given a variant id.
609    #[inline]
610    pub fn variant_index_with_id(self, vid: DefId) -> VariantIdx {
611        self.variants()
612            .iter_enumerated()
613            .find(|(_, v)| v.def_id == vid)
614            .expect("variant_index_with_id: unknown variant")
615            .0
616    }
617
618    /// Return the index of `VariantDef` given a constructor id.
619    pub fn variant_index_with_ctor_id(self, cid: DefId) -> VariantIdx {
620        self.variants()
621            .iter_enumerated()
622            .find(|(_, v)| v.ctor_def_id() == Some(cid))
623            .expect("variant_index_with_ctor_id: unknown variant")
624            .0
625    }
626
627    pub fn variant_of_res(self, res: Res) -> &'tcx VariantDef {
628        match res {
629            Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
630            Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
631            Res::Def(DefKind::Struct, _)
632            | Res::Def(DefKind::Union, _)
633            | Res::Def(DefKind::TyAlias, _)
634            | Res::Def(DefKind::AssocTy, _)
635            | Res::SelfTyParam { .. }
636            | Res::SelfTyAlias { .. }
637            | Res::SelfCtor(..) => self.non_enum_variant(),
638            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected res {0:?} in variant_of_res", res),
    Location::caller())bug!("unexpected res {:?} in variant_of_res", res),
639        }
640    }
641
642    #[inline]
643    pub fn eval_explicit_discr(
644        self,
645        tcx: TyCtxt<'tcx>,
646        expr_did: DefId,
647    ) -> Result<Discr<'tcx>, ErrorGuaranteed> {
648        if !self.is_enum() {
    ::core::panicking::panic("assertion failed: self.is_enum()")
};assert!(self.is_enum());
649
650        let repr_type = self.repr().discr_type();
651        match tcx.const_eval_poly(expr_did) {
652            Ok(val) => {
653                let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, expr_did);
654                let ty = repr_type.to_ty(tcx);
655                if let Some(b) = val.try_to_bits_for_ty(tcx, typing_env, ty) {
656                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/adt.rs:656",
                        "rustc_middle::ty::adt", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/adt.rs"),
                        ::tracing_core::__macro_support::Option::Some(656u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("discriminants: {0} ({1:?})",
                                                    b, repr_type) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("discriminants: {} ({:?})", b, repr_type);
657                    Ok(Discr { val: b, ty })
658                } else {
659                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/adt.rs:659",
                        "rustc_middle::ty::adt", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/adt.rs"),
                        ::tracing_core::__macro_support::Option::Some(659u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("invalid enum discriminant: {0:#?}",
                                                    val) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("invalid enum discriminant: {:#?}", val);
660                    let guar = tcx.dcx().emit_err(crate::diagnostics::ConstEvalNonIntError {
661                        span: tcx.def_span(expr_did),
662                    });
663                    Err(guar)
664                }
665            }
666            Err(err) => {
667                let guar = match err {
668                    ErrorHandled::Reported(info, _) => info.into(),
669                    ErrorHandled::TooGeneric(..) => tcx.dcx().span_delayed_bug(
670                        tcx.def_span(expr_did),
671                        "enum discriminant depends on generics",
672                    ),
673                };
674                Err(guar)
675            }
676        }
677    }
678
679    #[inline]
680    pub fn discriminants(
681        self,
682        tcx: TyCtxt<'tcx>,
683    ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
684        if !self.is_enum() {
    ::core::panicking::panic("assertion failed: self.is_enum()")
};assert!(self.is_enum());
685        let repr_type = self.repr().discr_type();
686        let initial = repr_type.initial_discriminant(tcx);
687        let mut prev_discr = None::<Discr<'tcx>>;
688        self.variants().iter_enumerated().map(move |(i, v)| {
689            let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
690            if let VariantDiscr::Explicit(expr_did) = v.discr
691                && let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did)
692            {
693                discr = new_discr;
694            }
695            prev_discr = Some(discr);
696
697            (i, discr)
698        })
699    }
700
701    #[inline]
702    pub fn variant_range(self) -> Range<VariantIdx> {
703        FIRST_VARIANT..self.variants().next_index()
704    }
705
706    /// Computes the discriminant value used by a specific variant.
707    /// Unlike `discriminants`, this is (amortized) constant-time,
708    /// only doing at most one query for evaluating an explicit
709    /// discriminant (the last one before the requested variant),
710    /// assuming there are no constant-evaluation errors there.
711    #[inline]
712    pub fn discriminant_for_variant(
713        self,
714        tcx: TyCtxt<'tcx>,
715        variant_index: VariantIdx,
716    ) -> Discr<'tcx> {
717        if !self.is_enum() {
    ::core::panicking::panic("assertion failed: self.is_enum()")
};assert!(self.is_enum());
718        let (val, offset) = self.discriminant_def_for_variant(variant_index);
719        let explicit_value = if let Some(expr_did) = val
720            && let Ok(val) = self.eval_explicit_discr(tcx, expr_did)
721        {
722            val
723        } else {
724            self.repr().discr_type().initial_discriminant(tcx)
725        };
726        explicit_value.checked_add(tcx, offset as u128).0
727    }
728
729    /// Yields a `DefId` for the discriminant and an offset to add to it
730    /// Alternatively, if there is no explicit discriminant, returns the
731    /// inferred discriminant directly.
732    pub fn discriminant_def_for_variant(self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
733        if !!self.variants().is_empty() {
    ::core::panicking::panic("assertion failed: !self.variants().is_empty()")
};assert!(!self.variants().is_empty());
734        let mut explicit_index = variant_index.as_u32();
735        let expr_did;
736        loop {
737            match self.variant(VariantIdx::from_u32(explicit_index)).discr {
738                ty::VariantDiscr::Relative(0) => {
739                    expr_did = None;
740                    break;
741                }
742                ty::VariantDiscr::Relative(distance) => {
743                    explicit_index -= distance;
744                }
745                ty::VariantDiscr::Explicit(did) => {
746                    expr_did = Some(did);
747                    break;
748                }
749            }
750        }
751        (expr_did, variant_index.as_u32() - explicit_index)
752    }
753
754    pub fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
755        tcx.adt_destructor(self.did())
756    }
757
758    // FIXME: consider combining this method with `AdtDef::destructor` and removing
759    // this version
760    pub fn async_destructor(self, tcx: TyCtxt<'tcx>) -> Option<AsyncDestructor> {
761        tcx.adt_async_destructor(self.did())
762    }
763
764    /// If this ADT is a struct, returns a type such that `Self: {Meta,Pointee,}Sized` if and only
765    /// if that type is `{Meta,Pointee,}Sized`, or `None` if this ADT is always
766    /// `{Meta,Pointee,}Sized`.
767    pub fn sizedness_constraint(
768        self,
769        tcx: TyCtxt<'tcx>,
770        sizedness: ty::SizedTraitKind,
771    ) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
772        if self.is_struct() { tcx.adt_sizedness_constraint((self.did(), sizedness)) } else { None }
773    }
774}