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