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, ReprOptions, VariantIdx};
7use rustc_data_structures::captures::Captures;
8use rustc_data_structures::fingerprint::Fingerprint;
9use rustc_data_structures::fx::FxHashMap;
10use rustc_data_structures::intern::Interned;
11use rustc_data_structures::stable_hasher::{HashStable, HashingControls, StableHasher};
12use rustc_errors::ErrorGuaranteed;
13use rustc_hir::def::{CtorKind, DefKind, Res};
14use rustc_hir::def_id::DefId;
15use rustc_hir::{self as hir, LangItem};
16use rustc_index::{IndexSlice, IndexVec};
17use rustc_macros::{HashStable, TyDecodable, TyEncodable};
18use rustc_query_system::ich::StableHashingContext;
19use rustc_session::DataTypeKind;
20use rustc_span::sym;
21use rustc_type_ir::solve::AdtDestructorKind;
22use tracing::{debug, info, trace};
23
24use super::{
25    AsyncDestructor, Destructor, FieldDef, GenericPredicates, Ty, TyCtxt, VariantDef, VariantDiscr,
26};
27use crate::mir::interpret::ErrorHandled;
28use crate::ty;
29use crate::ty::util::{Discr, IntTypeExt};
30
31#[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
32pub struct AdtFlags(u16);
33bitflags::bitflags! {
34    impl AdtFlags: u16 {
35        const NO_ADT_FLAGS        = 0;
36        /// Indicates whether the ADT is an enum.
37        const IS_ENUM             = 1 << 0;
38        /// Indicates whether the ADT is a union.
39        const IS_UNION            = 1 << 1;
40        /// Indicates whether the ADT is a struct.
41        const IS_STRUCT           = 1 << 2;
42        /// Indicates whether the ADT is a struct and has a constructor.
43        const HAS_CTOR            = 1 << 3;
44        /// Indicates whether the type is `PhantomData`.
45        const IS_PHANTOM_DATA     = 1 << 4;
46        /// Indicates whether the type has a `#[fundamental]` attribute.
47        const IS_FUNDAMENTAL      = 1 << 5;
48        /// Indicates whether the type is `Box`.
49        const IS_BOX              = 1 << 6;
50        /// Indicates whether the type is `ManuallyDrop`.
51        const IS_MANUALLY_DROP    = 1 << 7;
52        /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
53        /// (i.e., this flag is never set unless this ADT is an enum).
54        const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
55        /// Indicates whether the type is `UnsafeCell`.
56        const IS_UNSAFE_CELL              = 1 << 9;
57        /// Indicates whether the type is anonymous.
58        const IS_ANONYMOUS                = 1 << 10;
59    }
60}
61rustc_data_structures::external_bitflags_debug! { AdtFlags }
62
63/// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
64///
65/// These are all interned (by `mk_adt_def`) into the global arena.
66///
67/// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
68/// This is slightly wrong because `union`s are not ADTs.
69/// Moreover, Rust only allows recursive data types through indirection.
70///
71/// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
72///
73/// # Recursive types
74///
75/// It may seem impossible to represent recursive types using [`Ty`],
76/// since [`TyKind::Adt`] includes [`AdtDef`], which includes its fields,
77/// creating a cycle. However, `AdtDef` does not actually include the *types*
78/// of its fields; it includes just their [`DefId`]s.
79///
80/// [`TyKind::Adt`]: ty::TyKind::Adt
81///
82/// For example, the following type:
83///
84/// ```
85/// struct S { x: Box<S> }
86/// ```
87///
88/// is essentially represented with [`Ty`] as the following pseudocode:
89///
90/// ```ignore (illustrative)
91/// struct S { x }
92/// ```
93///
94/// where `x` here represents the `DefId` of `S.x`. Then, the `DefId`
95/// can be used with [`TyCtxt::type_of()`] to get the type of the field.
96#[derive(TyEncodable, TyDecodable)]
97pub struct AdtDefData {
98    /// The `DefId` of the struct, enum or union item.
99    pub did: DefId,
100    /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
101    variants: IndexVec<VariantIdx, VariantDef>,
102    /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
103    flags: AdtFlags,
104    /// Repr options provided by the user.
105    repr: ReprOptions,
106}
107
108impl PartialEq for AdtDefData {
109    #[inline]
110    fn eq(&self, other: &Self) -> bool {
111        // There should be only one `AdtDefData` for each `def_id`, therefore
112        // it is fine to implement `PartialEq` only based on `def_id`.
113        //
114        // Below, we exhaustively destructure `self` and `other` so that if the
115        // definition of `AdtDefData` changes, a compile-error will be produced,
116        // reminding us to revisit this assumption.
117
118        let Self { did: self_def_id, variants: _, flags: _, repr: _ } = self;
119        let Self { did: other_def_id, variants: _, flags: _, repr: _ } = other;
120
121        let res = self_def_id == other_def_id;
122
123        // Double check that implicit assumption detailed above.
124        if cfg!(debug_assertions) && res {
125            let deep = self.flags == other.flags
126                && self.repr == other.repr
127                && self.variants == other.variants;
128            assert!(deep, "AdtDefData for the same def-id has differing data");
129        }
130
131        res
132    }
133}
134
135impl Eq for AdtDefData {}
136
137/// There should be only one AdtDef for each `did`, therefore
138/// it is fine to implement `Hash` only based on `did`.
139impl Hash for AdtDefData {
140    #[inline]
141    fn hash<H: Hasher>(&self, s: &mut H) {
142        self.did.hash(s)
143    }
144}
145
146impl<'a> HashStable<StableHashingContext<'a>> for AdtDefData {
147    fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
148        thread_local! {
149            static CACHE: RefCell<FxHashMap<(usize, HashingControls), Fingerprint>> = Default::default();
150        }
151
152        let hash: Fingerprint = CACHE.with(|cache| {
153            let addr = self as *const AdtDefData as usize;
154            let hashing_controls = hcx.hashing_controls();
155            *cache.borrow_mut().entry((addr, hashing_controls)).or_insert_with(|| {
156                let ty::AdtDefData { did, ref variants, ref flags, ref repr } = *self;
157
158                let mut hasher = StableHasher::new();
159                did.hash_stable(hcx, &mut hasher);
160                variants.hash_stable(hcx, &mut hasher);
161                flags.hash_stable(hcx, &mut hasher);
162                repr.hash_stable(hcx, &mut hasher);
163
164                hasher.finish()
165            })
166        });
167
168        hash.hash_stable(hcx, hasher);
169    }
170}
171
172#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
173#[rustc_pass_by_value]
174pub struct AdtDef<'tcx>(pub Interned<'tcx, AdtDefData>);
175
176impl<'tcx> AdtDef<'tcx> {
177    #[inline]
178    pub fn did(self) -> DefId {
179        self.0.0.did
180    }
181
182    #[inline]
183    pub fn variants(self) -> &'tcx IndexSlice<VariantIdx, VariantDef> {
184        &self.0.0.variants
185    }
186
187    #[inline]
188    pub fn variant(self, idx: VariantIdx) -> &'tcx VariantDef {
189        &self.0.0.variants[idx]
190    }
191
192    #[inline]
193    pub fn flags(self) -> AdtFlags {
194        self.0.0.flags
195    }
196
197    #[inline]
198    pub fn repr(self) -> ReprOptions {
199        self.0.0.repr
200    }
201}
202
203impl<'tcx> rustc_type_ir::inherent::AdtDef<TyCtxt<'tcx>> for AdtDef<'tcx> {
204    fn def_id(self) -> DefId {
205        self.did()
206    }
207
208    fn is_struct(self) -> bool {
209        self.is_struct()
210    }
211
212    fn struct_tail_ty(self, interner: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
213        Some(interner.type_of(self.non_enum_variant().tail_opt()?.did))
214    }
215
216    fn is_phantom_data(self) -> bool {
217        self.is_phantom_data()
218    }
219
220    fn is_manually_drop(self) -> bool {
221        self.is_manually_drop()
222    }
223
224    fn all_field_tys(
225        self,
226        tcx: TyCtxt<'tcx>,
227    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = Ty<'tcx>>> {
228        ty::EarlyBinder::bind(
229            self.all_fields().map(move |field| tcx.type_of(field.did).skip_binder()),
230        )
231    }
232
233    fn sized_constraint(self, tcx: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
234        self.sized_constraint(tcx)
235    }
236
237    fn is_fundamental(self) -> bool {
238        self.is_fundamental()
239    }
240
241    fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<AdtDestructorKind> {
242        Some(match self.destructor(tcx)?.constness {
243            hir::Constness::Const => AdtDestructorKind::Const,
244            hir::Constness::NotConst => AdtDestructorKind::NotConst,
245        })
246    }
247}
248
249#[derive(Copy, Clone, Debug, Eq, PartialEq, HashStable, TyEncodable, TyDecodable)]
250pub enum AdtKind {
251    Struct,
252    Union,
253    Enum,
254}
255
256impl From<AdtKind> for DataTypeKind {
257    fn from(val: AdtKind) -> Self {
258        match val {
259            AdtKind::Struct => DataTypeKind::Struct,
260            AdtKind::Union => DataTypeKind::Union,
261            AdtKind::Enum => DataTypeKind::Enum,
262        }
263    }
264}
265
266impl AdtDefData {
267    /// Creates a new `AdtDefData`.
268    pub(super) fn new(
269        tcx: TyCtxt<'_>,
270        did: DefId,
271        kind: AdtKind,
272        variants: IndexVec<VariantIdx, VariantDef>,
273        repr: ReprOptions,
274    ) -> Self {
275        debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
276        let mut flags = AdtFlags::NO_ADT_FLAGS;
277
278        if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
279            debug!("found non-exhaustive variant list for {:?}", did);
280            flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
281        }
282
283        flags |= match kind {
284            AdtKind::Enum => AdtFlags::IS_ENUM,
285            AdtKind::Union => AdtFlags::IS_UNION,
286            AdtKind::Struct => AdtFlags::IS_STRUCT,
287        };
288
289        if kind == AdtKind::Struct && variants[FIRST_VARIANT].ctor.is_some() {
290            flags |= AdtFlags::HAS_CTOR;
291        }
292
293        if tcx.has_attr(did, sym::fundamental) {
294            flags |= AdtFlags::IS_FUNDAMENTAL;
295        }
296        if tcx.is_lang_item(did, LangItem::PhantomData) {
297            flags |= AdtFlags::IS_PHANTOM_DATA;
298        }
299        if tcx.is_lang_item(did, LangItem::OwnedBox) {
300            flags |= AdtFlags::IS_BOX;
301        }
302        if tcx.is_lang_item(did, LangItem::ManuallyDrop) {
303            flags |= AdtFlags::IS_MANUALLY_DROP;
304        }
305        if tcx.is_lang_item(did, LangItem::UnsafeCell) {
306            flags |= AdtFlags::IS_UNSAFE_CELL;
307        }
308
309        AdtDefData { did, variants, flags, repr }
310    }
311}
312
313impl<'tcx> AdtDef<'tcx> {
314    /// Returns `true` if this is a struct.
315    #[inline]
316    pub fn is_struct(self) -> bool {
317        self.flags().contains(AdtFlags::IS_STRUCT)
318    }
319
320    /// Returns `true` if this is a union.
321    #[inline]
322    pub fn is_union(self) -> bool {
323        self.flags().contains(AdtFlags::IS_UNION)
324    }
325
326    /// Returns `true` if this is an enum.
327    #[inline]
328    pub fn is_enum(self) -> bool {
329        self.flags().contains(AdtFlags::IS_ENUM)
330    }
331
332    /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
333    #[inline]
334    pub fn is_variant_list_non_exhaustive(self) -> bool {
335        self.flags().contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
336    }
337
338    /// Returns the kind of the ADT.
339    #[inline]
340    pub fn adt_kind(self) -> AdtKind {
341        if self.is_enum() {
342            AdtKind::Enum
343        } else if self.is_union() {
344            AdtKind::Union
345        } else {
346            AdtKind::Struct
347        }
348    }
349
350    /// Returns a description of this abstract data type.
351    pub fn descr(self) -> &'static str {
352        match self.adt_kind() {
353            AdtKind::Struct => "struct",
354            AdtKind::Union => "union",
355            AdtKind::Enum => "enum",
356        }
357    }
358
359    /// Returns a description of a variant of this abstract data type.
360    #[inline]
361    pub fn variant_descr(self) -> &'static str {
362        match self.adt_kind() {
363            AdtKind::Struct => "struct",
364            AdtKind::Union => "union",
365            AdtKind::Enum => "variant",
366        }
367    }
368
369    /// If this function returns `true`, it implies that `is_struct` must return `true`.
370    #[inline]
371    pub fn has_ctor(self) -> bool {
372        self.flags().contains(AdtFlags::HAS_CTOR)
373    }
374
375    /// Returns `true` if this type is `#[fundamental]` for the purposes
376    /// of coherence checking.
377    #[inline]
378    pub fn is_fundamental(self) -> bool {
379        self.flags().contains(AdtFlags::IS_FUNDAMENTAL)
380    }
381
382    /// Returns `true` if this is `PhantomData<T>`.
383    #[inline]
384    pub fn is_phantom_data(self) -> bool {
385        self.flags().contains(AdtFlags::IS_PHANTOM_DATA)
386    }
387
388    /// Returns `true` if this is `Box<T>`.
389    #[inline]
390    pub fn is_box(self) -> bool {
391        self.flags().contains(AdtFlags::IS_BOX)
392    }
393
394    /// Returns `true` if this is `UnsafeCell<T>`.
395    #[inline]
396    pub fn is_unsafe_cell(self) -> bool {
397        self.flags().contains(AdtFlags::IS_UNSAFE_CELL)
398    }
399
400    /// Returns `true` if this is `ManuallyDrop<T>`.
401    #[inline]
402    pub fn is_manually_drop(self) -> bool {
403        self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
404    }
405
406    /// Returns `true` if this is an anonymous adt
407    #[inline]
408    pub fn is_anonymous(self) -> bool {
409        self.flags().contains(AdtFlags::IS_ANONYMOUS)
410    }
411
412    /// Returns `true` if this type has a destructor.
413    pub fn has_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
414        self.destructor(tcx).is_some()
415    }
416
417    /// Asserts this is a struct or union and returns its unique variant.
418    pub fn non_enum_variant(self) -> &'tcx VariantDef {
419        assert!(self.is_struct() || self.is_union());
420        self.variant(FIRST_VARIANT)
421    }
422
423    #[inline]
424    pub fn predicates(self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
425        tcx.predicates_of(self.did())
426    }
427
428    /// Returns an iterator over all fields contained
429    /// by this ADT (nested unnamed fields are not expanded).
430    #[inline]
431    pub fn all_fields(self) -> impl Iterator<Item = &'tcx FieldDef> + Clone {
432        self.variants().iter().flat_map(|v| v.fields.iter())
433    }
434
435    /// Whether the ADT lacks fields. Note that this includes uninhabited enums,
436    /// e.g., `enum Void {}` is considered payload free as well.
437    pub fn is_payloadfree(self) -> bool {
438        // Treat the ADT as not payload-free if arbitrary_enum_discriminant is used (#88621).
439        // This would disallow the following kind of enum from being casted into integer.
440        // ```
441        // enum Enum {
442        //    Foo() = 1,
443        //    Bar{} = 2,
444        //    Baz = 3,
445        // }
446        // ```
447        if self.variants().iter().any(|v| {
448            matches!(v.discr, VariantDiscr::Explicit(_)) && v.ctor_kind() != Some(CtorKind::Const)
449        }) {
450            return false;
451        }
452        self.variants().iter().all(|v| v.fields.is_empty())
453    }
454
455    /// Return a `VariantDef` given a variant id.
456    pub fn variant_with_id(self, vid: DefId) -> &'tcx VariantDef {
457        self.variants().iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
458    }
459
460    /// Return a `VariantDef` given a constructor id.
461    pub fn variant_with_ctor_id(self, cid: DefId) -> &'tcx VariantDef {
462        self.variants()
463            .iter()
464            .find(|v| v.ctor_def_id() == Some(cid))
465            .expect("variant_with_ctor_id: unknown variant")
466    }
467
468    /// Return the index of `VariantDef` given a variant id.
469    #[inline]
470    pub fn variant_index_with_id(self, vid: DefId) -> VariantIdx {
471        self.variants()
472            .iter_enumerated()
473            .find(|(_, v)| v.def_id == vid)
474            .expect("variant_index_with_id: unknown variant")
475            .0
476    }
477
478    /// Return the index of `VariantDef` given a constructor id.
479    pub fn variant_index_with_ctor_id(self, cid: DefId) -> VariantIdx {
480        self.variants()
481            .iter_enumerated()
482            .find(|(_, v)| v.ctor_def_id() == Some(cid))
483            .expect("variant_index_with_ctor_id: unknown variant")
484            .0
485    }
486
487    pub fn variant_of_res(self, res: Res) -> &'tcx VariantDef {
488        match res {
489            Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
490            Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
491            Res::Def(DefKind::Struct, _)
492            | Res::Def(DefKind::Union, _)
493            | Res::Def(DefKind::TyAlias, _)
494            | Res::Def(DefKind::AssocTy, _)
495            | Res::SelfTyParam { .. }
496            | Res::SelfTyAlias { .. }
497            | Res::SelfCtor(..) => self.non_enum_variant(),
498            _ => bug!("unexpected res {:?} in variant_of_res", res),
499        }
500    }
501
502    #[inline]
503    pub fn eval_explicit_discr(
504        self,
505        tcx: TyCtxt<'tcx>,
506        expr_did: DefId,
507    ) -> Result<Discr<'tcx>, ErrorGuaranteed> {
508        assert!(self.is_enum());
509
510        let repr_type = self.repr().discr_type();
511        match tcx.const_eval_poly(expr_did) {
512            Ok(val) => {
513                let typing_env = ty::TypingEnv::post_analysis(tcx, expr_did);
514                let ty = repr_type.to_ty(tcx);
515                if let Some(b) = val.try_to_bits_for_ty(tcx, typing_env, ty) {
516                    trace!("discriminants: {} ({:?})", b, repr_type);
517                    Ok(Discr { val: b, ty })
518                } else {
519                    info!("invalid enum discriminant: {:#?}", val);
520                    let guar = tcx.dcx().emit_err(crate::error::ConstEvalNonIntError {
521                        span: tcx.def_span(expr_did),
522                    });
523                    Err(guar)
524                }
525            }
526            Err(err) => {
527                let guar = match err {
528                    ErrorHandled::Reported(info, _) => info.into(),
529                    ErrorHandled::TooGeneric(..) => tcx.dcx().span_delayed_bug(
530                        tcx.def_span(expr_did),
531                        "enum discriminant depends on generics",
532                    ),
533                };
534                Err(guar)
535            }
536        }
537    }
538
539    #[inline]
540    pub fn discriminants(
541        self,
542        tcx: TyCtxt<'tcx>,
543    ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
544        assert!(self.is_enum());
545        let repr_type = self.repr().discr_type();
546        let initial = repr_type.initial_discriminant(tcx);
547        let mut prev_discr = None::<Discr<'tcx>>;
548        self.variants().iter_enumerated().map(move |(i, v)| {
549            let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
550            if let VariantDiscr::Explicit(expr_did) = v.discr {
551                if let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
552                    discr = new_discr;
553                }
554            }
555            prev_discr = Some(discr);
556
557            (i, discr)
558        })
559    }
560
561    #[inline]
562    pub fn variant_range(self) -> Range<VariantIdx> {
563        FIRST_VARIANT..self.variants().next_index()
564    }
565
566    /// Computes the discriminant value used by a specific variant.
567    /// Unlike `discriminants`, this is (amortized) constant-time,
568    /// only doing at most one query for evaluating an explicit
569    /// discriminant (the last one before the requested variant),
570    /// assuming there are no constant-evaluation errors there.
571    #[inline]
572    pub fn discriminant_for_variant(
573        self,
574        tcx: TyCtxt<'tcx>,
575        variant_index: VariantIdx,
576    ) -> Discr<'tcx> {
577        assert!(self.is_enum());
578        let (val, offset) = self.discriminant_def_for_variant(variant_index);
579        let explicit_value = if let Some(expr_did) = val
580            && let Ok(val) = self.eval_explicit_discr(tcx, expr_did)
581        {
582            val
583        } else {
584            self.repr().discr_type().initial_discriminant(tcx)
585        };
586        explicit_value.checked_add(tcx, offset as u128).0
587    }
588
589    /// Yields a `DefId` for the discriminant and an offset to add to it
590    /// Alternatively, if there is no explicit discriminant, returns the
591    /// inferred discriminant directly.
592    pub fn discriminant_def_for_variant(self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
593        assert!(!self.variants().is_empty());
594        let mut explicit_index = variant_index.as_u32();
595        let expr_did;
596        loop {
597            match self.variant(VariantIdx::from_u32(explicit_index)).discr {
598                ty::VariantDiscr::Relative(0) => {
599                    expr_did = None;
600                    break;
601                }
602                ty::VariantDiscr::Relative(distance) => {
603                    explicit_index -= distance;
604                }
605                ty::VariantDiscr::Explicit(did) => {
606                    expr_did = Some(did);
607                    break;
608                }
609            }
610        }
611        (expr_did, variant_index.as_u32() - explicit_index)
612    }
613
614    pub fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
615        tcx.adt_destructor(self.did())
616    }
617
618    // FIXME: consider combining this method with `AdtDef::destructor` and removing
619    // this version
620    pub fn async_destructor(self, tcx: TyCtxt<'tcx>) -> Option<AsyncDestructor> {
621        tcx.adt_async_destructor(self.did())
622    }
623
624    /// Returns a type such that `Self: Sized` if and only if that type is `Sized`,
625    /// or `None` if the type is always sized.
626    pub fn sized_constraint(self, tcx: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
627        if self.is_struct() { tcx.adt_sized_constraint(self.did()) } else { None }
628    }
629}
630
631#[derive(Clone, Copy, Debug, HashStable)]
632pub enum Representability {
633    Representable,
634    Infinite(ErrorGuaranteed),
635}