1use std::cell::RefCell;
2use std::hash::{Hash, Hasher};
3use std::ops::Range;
4use std::str;
5
6use rustc_abi::{FIRST_VARIANT, 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::attrs::AttributeKind;
13use rustc_hir::def::{CtorKind, DefKind, Res};
14use rustc_hir::def_id::DefId;
15use rustc_hir::{self as hir, LangItem, find_attr};
16use rustc_index::{IndexSlice, IndexVec};
17use rustc_macros::{HashStable, TyDecodable, TyEncodable};
18use rustc_query_system::ich::StableHashingContext;
19use rustc_session::DataTypeKind;
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::mir::interpret::ErrorHandled;
27use crate::ty;
28use crate::ty::util::{Discr, IntTypeExt};
29
30#[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
31pub struct AdtFlags(u16);
32bitflags::bitflags! {
33    impl AdtFlags: u16 {
34        const NO_ADT_FLAGS        = 0;
35        const IS_ENUM             = 1 << 0;
37        const IS_UNION            = 1 << 1;
39        const IS_STRUCT           = 1 << 2;
41        const HAS_CTOR            = 1 << 3;
43        const IS_PHANTOM_DATA     = 1 << 4;
45        const IS_FUNDAMENTAL      = 1 << 5;
47        const IS_BOX              = 1 << 6;
49        const IS_MANUALLY_DROP    = 1 << 7;
51        const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
54        const IS_UNSAFE_CELL              = 1 << 9;
56        const IS_UNSAFE_PINNED              = 1 << 10;
58    }
59}
60rustc_data_structures::external_bitflags_debug! { AdtFlags }
61
62#[derive(TyEncodable, TyDecodable)]
96pub struct AdtDefData {
97    pub did: DefId,
99    variants: IndexVec<VariantIdx, VariantDef>,
101    flags: AdtFlags,
103    repr: ReprOptions,
105}
106
107impl PartialEq for AdtDefData {
108    #[inline]
109    fn eq(&self, other: &Self) -> bool {
110        let Self { did: self_def_id, variants: _, flags: _, repr: _ } = self;
118        let Self { did: other_def_id, variants: _, flags: _, repr: _ } = other;
119
120        let res = self_def_id == other_def_id;
121
122        if cfg!(debug_assertions) && res {
124            let deep = self.flags == other.flags
125                && self.repr == other.repr
126                && self.variants == other.variants;
127            assert!(deep, "AdtDefData for the same def-id has differing data");
128        }
129
130        res
131    }
132}
133
134impl Eq for AdtDefData {}
135
136impl Hash for AdtDefData {
139    #[inline]
140    fn hash<H: Hasher>(&self, s: &mut H) {
141        self.did.hash(s)
142    }
143}
144
145impl<'a> HashStable<StableHashingContext<'a>> for AdtDefData {
146    fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
147        thread_local! {
148            static CACHE: RefCell<FxHashMap<(usize, HashingControls), Fingerprint>> = Default::default();
149        }
150
151        let hash: Fingerprint = CACHE.with(|cache| {
152            let addr = self as *const AdtDefData as usize;
153            let hashing_controls = hcx.hashing_controls();
154            *cache.borrow_mut().entry((addr, hashing_controls)).or_insert_with(|| {
155                let ty::AdtDefData { did, ref variants, ref flags, ref repr } = *self;
156
157                let mut hasher = StableHasher::new();
158                did.hash_stable(hcx, &mut hasher);
159                variants.hash_stable(hcx, &mut hasher);
160                flags.hash_stable(hcx, &mut hasher);
161                repr.hash_stable(hcx, &mut hasher);
162
163                hasher.finish()
164            })
165        });
166
167        hash.hash_stable(hcx, hasher);
168    }
169}
170
171#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
172#[rustc_pass_by_value]
173pub struct AdtDef<'tcx>(pub Interned<'tcx, AdtDefData>);
174
175impl<'tcx> AdtDef<'tcx> {
176    #[inline]
177    pub fn did(self) -> DefId {
178        self.0.0.did
179    }
180
181    #[inline]
182    pub fn variants(self) -> &'tcx IndexSlice<VariantIdx, VariantDef> {
183        &self.0.0.variants
184    }
185
186    #[inline]
187    pub fn variant(self, idx: VariantIdx) -> &'tcx VariantDef {
188        &self.0.0.variants[idx]
189    }
190
191    #[inline]
192    pub fn flags(self) -> AdtFlags {
193        self.0.0.flags
194    }
195
196    #[inline]
197    pub fn repr(self) -> ReprOptions {
198        self.0.0.repr
199    }
200}
201
202impl<'tcx> rustc_type_ir::inherent::AdtDef<TyCtxt<'tcx>> for AdtDef<'tcx> {
203    fn def_id(self) -> DefId {
204        self.did()
205    }
206
207    fn is_struct(self) -> bool {
208        self.is_struct()
209    }
210
211    fn struct_tail_ty(self, interner: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
212        Some(interner.type_of(self.non_enum_variant().tail_opt()?.did))
213    }
214
215    fn is_phantom_data(self) -> bool {
216        self.is_phantom_data()
217    }
218
219    fn is_manually_drop(self) -> bool {
220        self.is_manually_drop()
221    }
222
223    fn all_field_tys(
224        self,
225        tcx: TyCtxt<'tcx>,
226    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = Ty<'tcx>>> {
227        ty::EarlyBinder::bind(
228            self.all_fields().map(move |field| tcx.type_of(field.did).skip_binder()),
229        )
230    }
231
232    fn sizedness_constraint(
233        self,
234        tcx: TyCtxt<'tcx>,
235        sizedness: ty::SizedTraitKind,
236    ) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
237        self.sizedness_constraint(tcx, sizedness)
238    }
239
240    fn is_fundamental(self) -> bool {
241        self.is_fundamental()
242    }
243
244    fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<AdtDestructorKind> {
245        Some(match tcx.constness(self.destructor(tcx)?.did) {
246            hir::Constness::Const => AdtDestructorKind::Const,
247            hir::Constness::NotConst => AdtDestructorKind::NotConst,
248        })
249    }
250}
251
252#[derive(Copy, Clone, Debug, Eq, PartialEq, HashStable, TyEncodable, TyDecodable)]
253pub enum AdtKind {
254    Struct,
255    Union,
256    Enum,
257}
258
259impl From<AdtKind> for DataTypeKind {
260    fn from(val: AdtKind) -> Self {
261        match val {
262            AdtKind::Struct => DataTypeKind::Struct,
263            AdtKind::Union => DataTypeKind::Union,
264            AdtKind::Enum => DataTypeKind::Enum,
265        }
266    }
267}
268
269impl AdtDefData {
270    pub(super) fn new(
272        tcx: TyCtxt<'_>,
273        did: DefId,
274        kind: AdtKind,
275        variants: IndexVec<VariantIdx, VariantDef>,
276        repr: ReprOptions,
277    ) -> Self {
278        debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
279        let mut flags = AdtFlags::NO_ADT_FLAGS;
280
281        if kind == AdtKind::Enum
282            && find_attr!(tcx.get_all_attrs(did), AttributeKind::NonExhaustive(..))
283        {
284            debug!("found non-exhaustive variant list for {:?}", did);
285            flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
286        }
287
288        flags |= match kind {
289            AdtKind::Enum => AdtFlags::IS_ENUM,
290            AdtKind::Union => AdtFlags::IS_UNION,
291            AdtKind::Struct => AdtFlags::IS_STRUCT,
292        };
293
294        if kind == AdtKind::Struct && variants[FIRST_VARIANT].ctor.is_some() {
295            flags |= AdtFlags::HAS_CTOR;
296        }
297
298        if find_attr!(tcx.get_all_attrs(did), AttributeKind::Fundamental) {
299            flags |= AdtFlags::IS_FUNDAMENTAL;
300        }
301        if tcx.is_lang_item(did, LangItem::PhantomData) {
302            flags |= AdtFlags::IS_PHANTOM_DATA;
303        }
304        if tcx.is_lang_item(did, LangItem::OwnedBox) {
305            flags |= AdtFlags::IS_BOX;
306        }
307        if tcx.is_lang_item(did, LangItem::ManuallyDrop) {
308            flags |= AdtFlags::IS_MANUALLY_DROP;
309        }
310        if tcx.is_lang_item(did, LangItem::UnsafeCell) {
311            flags |= AdtFlags::IS_UNSAFE_CELL;
312        }
313        if tcx.is_lang_item(did, LangItem::UnsafePinned) {
314            flags |= AdtFlags::IS_UNSAFE_PINNED;
315        }
316
317        AdtDefData { did, variants, flags, repr }
318    }
319}
320
321impl<'tcx> AdtDef<'tcx> {
322    #[inline]
324    pub fn is_struct(self) -> bool {
325        self.flags().contains(AdtFlags::IS_STRUCT)
326    }
327
328    #[inline]
330    pub fn is_union(self) -> bool {
331        self.flags().contains(AdtFlags::IS_UNION)
332    }
333
334    #[inline]
336    pub fn is_enum(self) -> bool {
337        self.flags().contains(AdtFlags::IS_ENUM)
338    }
339
340    #[inline]
346    pub fn is_variant_list_non_exhaustive(self) -> bool {
347        self.flags().contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
348    }
349
350    #[inline]
353    pub fn variant_list_has_applicable_non_exhaustive(self) -> bool {
354        self.is_variant_list_non_exhaustive() && !self.did().is_local()
355    }
356
357    #[inline]
359    pub fn adt_kind(self) -> AdtKind {
360        if self.is_enum() {
361            AdtKind::Enum
362        } else if self.is_union() {
363            AdtKind::Union
364        } else {
365            AdtKind::Struct
366        }
367    }
368
369    pub fn descr(self) -> &'static str {
371        match self.adt_kind() {
372            AdtKind::Struct => "struct",
373            AdtKind::Union => "union",
374            AdtKind::Enum => "enum",
375        }
376    }
377
378    #[inline]
380    pub fn variant_descr(self) -> &'static str {
381        match self.adt_kind() {
382            AdtKind::Struct => "struct",
383            AdtKind::Union => "union",
384            AdtKind::Enum => "variant",
385        }
386    }
387
388    #[inline]
390    pub fn has_ctor(self) -> bool {
391        self.flags().contains(AdtFlags::HAS_CTOR)
392    }
393
394    #[inline]
397    pub fn is_fundamental(self) -> bool {
398        self.flags().contains(AdtFlags::IS_FUNDAMENTAL)
399    }
400
401    #[inline]
403    pub fn is_phantom_data(self) -> bool {
404        self.flags().contains(AdtFlags::IS_PHANTOM_DATA)
405    }
406
407    #[inline]
409    pub fn is_box(self) -> bool {
410        self.flags().contains(AdtFlags::IS_BOX)
411    }
412
413    #[inline]
415    pub fn is_unsafe_cell(self) -> bool {
416        self.flags().contains(AdtFlags::IS_UNSAFE_CELL)
417    }
418
419    #[inline]
421    pub fn is_unsafe_pinned(self) -> bool {
422        self.flags().contains(AdtFlags::IS_UNSAFE_PINNED)
423    }
424
425    #[inline]
427    pub fn is_manually_drop(self) -> bool {
428        self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
429    }
430
431    pub fn has_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
433        self.destructor(tcx).is_some()
434    }
435
436    pub fn non_enum_variant(self) -> &'tcx VariantDef {
438        assert!(self.is_struct() || self.is_union());
439        self.variant(FIRST_VARIANT)
440    }
441
442    #[inline]
443    pub fn predicates(self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
444        tcx.predicates_of(self.did())
445    }
446
447    #[inline]
450    pub fn all_fields(self) -> impl Iterator<Item = &'tcx FieldDef> + Clone {
451        self.variants().iter().flat_map(|v| v.fields.iter())
452    }
453
454    pub fn is_payloadfree(self) -> bool {
457        if self.variants().iter().any(|v| {
467            matches!(v.discr, VariantDiscr::Explicit(_)) && v.ctor_kind() != Some(CtorKind::Const)
468        }) {
469            return false;
470        }
471        self.variants().iter().all(|v| v.fields.is_empty())
472    }
473
474    pub fn variant_with_id(self, vid: DefId) -> &'tcx VariantDef {
476        self.variants().iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
477    }
478
479    pub fn variant_with_ctor_id(self, cid: DefId) -> &'tcx VariantDef {
481        self.variants()
482            .iter()
483            .find(|v| v.ctor_def_id() == Some(cid))
484            .expect("variant_with_ctor_id: unknown variant")
485    }
486
487    #[inline]
489    pub fn variant_index_with_id(self, vid: DefId) -> VariantIdx {
490        self.variants()
491            .iter_enumerated()
492            .find(|(_, v)| v.def_id == vid)
493            .expect("variant_index_with_id: unknown variant")
494            .0
495    }
496
497    pub fn variant_index_with_ctor_id(self, cid: DefId) -> VariantIdx {
499        self.variants()
500            .iter_enumerated()
501            .find(|(_, v)| v.ctor_def_id() == Some(cid))
502            .expect("variant_index_with_ctor_id: unknown variant")
503            .0
504    }
505
506    pub fn variant_of_res(self, res: Res) -> &'tcx VariantDef {
507        match res {
508            Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
509            Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
510            Res::Def(DefKind::Struct, _)
511            | Res::Def(DefKind::Union, _)
512            | Res::Def(DefKind::TyAlias, _)
513            | Res::Def(DefKind::AssocTy, _)
514            | Res::SelfTyParam { .. }
515            | Res::SelfTyAlias { .. }
516            | Res::SelfCtor(..) => self.non_enum_variant(),
517            _ => bug!("unexpected res {:?} in variant_of_res", res),
518        }
519    }
520
521    #[inline]
522    pub fn eval_explicit_discr(
523        self,
524        tcx: TyCtxt<'tcx>,
525        expr_did: DefId,
526    ) -> Result<Discr<'tcx>, ErrorGuaranteed> {
527        assert!(self.is_enum());
528
529        let repr_type = self.repr().discr_type();
530        match tcx.const_eval_poly(expr_did) {
531            Ok(val) => {
532                let typing_env = ty::TypingEnv::post_analysis(tcx, expr_did);
533                let ty = repr_type.to_ty(tcx);
534                if let Some(b) = val.try_to_bits_for_ty(tcx, typing_env, ty) {
535                    trace!("discriminants: {} ({:?})", b, repr_type);
536                    Ok(Discr { val: b, ty })
537                } else {
538                    info!("invalid enum discriminant: {:#?}", val);
539                    let guar = tcx.dcx().emit_err(crate::error::ConstEvalNonIntError {
540                        span: tcx.def_span(expr_did),
541                    });
542                    Err(guar)
543                }
544            }
545            Err(err) => {
546                let guar = match err {
547                    ErrorHandled::Reported(info, _) => info.into(),
548                    ErrorHandled::TooGeneric(..) => tcx.dcx().span_delayed_bug(
549                        tcx.def_span(expr_did),
550                        "enum discriminant depends on generics",
551                    ),
552                };
553                Err(guar)
554            }
555        }
556    }
557
558    #[inline]
559    pub fn discriminants(
560        self,
561        tcx: TyCtxt<'tcx>,
562    ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
563        assert!(self.is_enum());
564        let repr_type = self.repr().discr_type();
565        let initial = repr_type.initial_discriminant(tcx);
566        let mut prev_discr = None::<Discr<'tcx>>;
567        self.variants().iter_enumerated().map(move |(i, v)| {
568            let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
569            if let VariantDiscr::Explicit(expr_did) = v.discr
570                && let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did)
571            {
572                discr = new_discr;
573            }
574            prev_discr = Some(discr);
575
576            (i, discr)
577        })
578    }
579
580    #[inline]
581    pub fn variant_range(self) -> Range<VariantIdx> {
582        FIRST_VARIANT..self.variants().next_index()
583    }
584
585    #[inline]
591    pub fn discriminant_for_variant(
592        self,
593        tcx: TyCtxt<'tcx>,
594        variant_index: VariantIdx,
595    ) -> Discr<'tcx> {
596        assert!(self.is_enum());
597        let (val, offset) = self.discriminant_def_for_variant(variant_index);
598        let explicit_value = if let Some(expr_did) = val
599            && let Ok(val) = self.eval_explicit_discr(tcx, expr_did)
600        {
601            val
602        } else {
603            self.repr().discr_type().initial_discriminant(tcx)
604        };
605        explicit_value.checked_add(tcx, offset as u128).0
606    }
607
608    pub fn discriminant_def_for_variant(self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
612        assert!(!self.variants().is_empty());
613        let mut explicit_index = variant_index.as_u32();
614        let expr_did;
615        loop {
616            match self.variant(VariantIdx::from_u32(explicit_index)).discr {
617                ty::VariantDiscr::Relative(0) => {
618                    expr_did = None;
619                    break;
620                }
621                ty::VariantDiscr::Relative(distance) => {
622                    explicit_index -= distance;
623                }
624                ty::VariantDiscr::Explicit(did) => {
625                    expr_did = Some(did);
626                    break;
627                }
628            }
629        }
630        (expr_did, variant_index.as_u32() - explicit_index)
631    }
632
633    pub fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
634        tcx.adt_destructor(self.did())
635    }
636
637    pub fn async_destructor(self, tcx: TyCtxt<'tcx>) -> Option<AsyncDestructor> {
640        tcx.adt_async_destructor(self.did())
641    }
642
643    pub fn sizedness_constraint(
647        self,
648        tcx: TyCtxt<'tcx>,
649        sizedness: ty::SizedTraitKind,
650    ) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
651        if self.is_struct() { tcx.adt_sizedness_constraint((self.did(), sizedness)) } else { None }
652    }
653}
654
655#[derive(Clone, Copy, Debug, HashStable)]
656pub enum Representability {
657    Representable,
658    Infinite(ErrorGuaranteed),
659}