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_attr_data_structures::{AttributeKind, find_attr};
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 `UnsafePinned`.
58        const IS_UNSAFE_PINNED              = 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 sizedness_constraint(
234        self,
235        tcx: TyCtxt<'tcx>,
236        sizedness: ty::SizedTraitKind,
237    ) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
238        self.sizedness_constraint(tcx, sizedness)
239    }
240
241    fn is_fundamental(self) -> bool {
242        self.is_fundamental()
243    }
244
245    fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<AdtDestructorKind> {
246        Some(match tcx.constness(self.destructor(tcx)?.did) {
247            hir::Constness::Const => AdtDestructorKind::Const,
248            hir::Constness::NotConst => AdtDestructorKind::NotConst,
249        })
250    }
251}
252
253#[derive(Copy, Clone, Debug, Eq, PartialEq, HashStable, TyEncodable, TyDecodable)]
254pub enum AdtKind {
255    Struct,
256    Union,
257    Enum,
258}
259
260impl From<AdtKind> for DataTypeKind {
261    fn from(val: AdtKind) -> Self {
262        match val {
263            AdtKind::Struct => DataTypeKind::Struct,
264            AdtKind::Union => DataTypeKind::Union,
265            AdtKind::Enum => DataTypeKind::Enum,
266        }
267    }
268}
269
270impl AdtDefData {
271    /// Creates a new `AdtDefData`.
272    pub(super) fn new(
273        tcx: TyCtxt<'_>,
274        did: DefId,
275        kind: AdtKind,
276        variants: IndexVec<VariantIdx, VariantDef>,
277        repr: ReprOptions,
278    ) -> Self {
279        debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
280        let mut flags = AdtFlags::NO_ADT_FLAGS;
281
282        if kind == AdtKind::Enum
283            && find_attr!(tcx.get_all_attrs(did), AttributeKind::NonExhaustive(..))
284        {
285            debug!("found non-exhaustive variant list for {:?}", did);
286            flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
287        }
288
289        flags |= match kind {
290            AdtKind::Enum => AdtFlags::IS_ENUM,
291            AdtKind::Union => AdtFlags::IS_UNION,
292            AdtKind::Struct => AdtFlags::IS_STRUCT,
293        };
294
295        if kind == AdtKind::Struct && variants[FIRST_VARIANT].ctor.is_some() {
296            flags |= AdtFlags::HAS_CTOR;
297        }
298
299        if tcx.has_attr(did, sym::fundamental) {
300            flags |= AdtFlags::IS_FUNDAMENTAL;
301        }
302        if tcx.is_lang_item(did, LangItem::PhantomData) {
303            flags |= AdtFlags::IS_PHANTOM_DATA;
304        }
305        if tcx.is_lang_item(did, LangItem::OwnedBox) {
306            flags |= AdtFlags::IS_BOX;
307        }
308        if tcx.is_lang_item(did, LangItem::ManuallyDrop) {
309            flags |= AdtFlags::IS_MANUALLY_DROP;
310        }
311        if tcx.is_lang_item(did, LangItem::UnsafeCell) {
312            flags |= AdtFlags::IS_UNSAFE_CELL;
313        }
314        if tcx.is_lang_item(did, LangItem::UnsafePinned) {
315            flags |= AdtFlags::IS_UNSAFE_PINNED;
316        }
317
318        AdtDefData { did, variants, flags, repr }
319    }
320}
321
322impl<'tcx> AdtDef<'tcx> {
323    /// Returns `true` if this is a struct.
324    #[inline]
325    pub fn is_struct(self) -> bool {
326        self.flags().contains(AdtFlags::IS_STRUCT)
327    }
328
329    /// Returns `true` if this is a union.
330    #[inline]
331    pub fn is_union(self) -> bool {
332        self.flags().contains(AdtFlags::IS_UNION)
333    }
334
335    /// Returns `true` if this is an enum.
336    #[inline]
337    pub fn is_enum(self) -> bool {
338        self.flags().contains(AdtFlags::IS_ENUM)
339    }
340
341    /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
342    ///
343    /// Note that this function will return `true` even if the ADT has been
344    /// defined in the crate currently being compiled. If that's not what you
345    /// want, see [`Self::variant_list_has_applicable_non_exhaustive`].
346    #[inline]
347    pub fn is_variant_list_non_exhaustive(self) -> bool {
348        self.flags().contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
349    }
350
351    /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`
352    /// and has been defined in another crate.
353    #[inline]
354    pub fn variant_list_has_applicable_non_exhaustive(self) -> bool {
355        self.is_variant_list_non_exhaustive() && !self.did().is_local()
356    }
357
358    /// Returns the kind of the ADT.
359    #[inline]
360    pub fn adt_kind(self) -> AdtKind {
361        if self.is_enum() {
362            AdtKind::Enum
363        } else if self.is_union() {
364            AdtKind::Union
365        } else {
366            AdtKind::Struct
367        }
368    }
369
370    /// Returns a description of this abstract data type.
371    pub fn descr(self) -> &'static str {
372        match self.adt_kind() {
373            AdtKind::Struct => "struct",
374            AdtKind::Union => "union",
375            AdtKind::Enum => "enum",
376        }
377    }
378
379    /// Returns a description of a variant of this abstract data type.
380    #[inline]
381    pub fn variant_descr(self) -> &'static str {
382        match self.adt_kind() {
383            AdtKind::Struct => "struct",
384            AdtKind::Union => "union",
385            AdtKind::Enum => "variant",
386        }
387    }
388
389    /// If this function returns `true`, it implies that `is_struct` must return `true`.
390    #[inline]
391    pub fn has_ctor(self) -> bool {
392        self.flags().contains(AdtFlags::HAS_CTOR)
393    }
394
395    /// Returns `true` if this type is `#[fundamental]` for the purposes
396    /// of coherence checking.
397    #[inline]
398    pub fn is_fundamental(self) -> bool {
399        self.flags().contains(AdtFlags::IS_FUNDAMENTAL)
400    }
401
402    /// Returns `true` if this is `PhantomData<T>`.
403    #[inline]
404    pub fn is_phantom_data(self) -> bool {
405        self.flags().contains(AdtFlags::IS_PHANTOM_DATA)
406    }
407
408    /// Returns `true` if this is `Box<T>`.
409    #[inline]
410    pub fn is_box(self) -> bool {
411        self.flags().contains(AdtFlags::IS_BOX)
412    }
413
414    /// Returns `true` if this is `UnsafeCell<T>`.
415    #[inline]
416    pub fn is_unsafe_cell(self) -> bool {
417        self.flags().contains(AdtFlags::IS_UNSAFE_CELL)
418    }
419
420    /// Returns `true` if this is `UnsafePinned<T>`.
421    #[inline]
422    pub fn is_unsafe_pinned(self) -> bool {
423        self.flags().contains(AdtFlags::IS_UNSAFE_PINNED)
424    }
425
426    /// Returns `true` if this is `ManuallyDrop<T>`.
427    #[inline]
428    pub fn is_manually_drop(self) -> bool {
429        self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
430    }
431
432    /// Returns `true` if this type has a destructor.
433    pub fn has_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
434        self.destructor(tcx).is_some()
435    }
436
437    /// Asserts this is a struct or union and returns its unique variant.
438    pub fn non_enum_variant(self) -> &'tcx VariantDef {
439        assert!(self.is_struct() || self.is_union());
440        self.variant(FIRST_VARIANT)
441    }
442
443    #[inline]
444    pub fn predicates(self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
445        tcx.predicates_of(self.did())
446    }
447
448    /// Returns an iterator over all fields contained
449    /// by this ADT (nested unnamed fields are not expanded).
450    #[inline]
451    pub fn all_fields(self) -> impl Iterator<Item = &'tcx FieldDef> + Clone {
452        self.variants().iter().flat_map(|v| v.fields.iter())
453    }
454
455    /// Whether the ADT lacks fields. Note that this includes uninhabited enums,
456    /// e.g., `enum Void {}` is considered payload free as well.
457    pub fn is_payloadfree(self) -> bool {
458        // Treat the ADT as not payload-free if arbitrary_enum_discriminant is used (#88621).
459        // This would disallow the following kind of enum from being casted into integer.
460        // ```
461        // enum Enum {
462        //    Foo() = 1,
463        //    Bar{} = 2,
464        //    Baz = 3,
465        // }
466        // ```
467        if self.variants().iter().any(|v| {
468            matches!(v.discr, VariantDiscr::Explicit(_)) && v.ctor_kind() != Some(CtorKind::Const)
469        }) {
470            return false;
471        }
472        self.variants().iter().all(|v| v.fields.is_empty())
473    }
474
475    /// Return a `VariantDef` given a variant id.
476    pub fn variant_with_id(self, vid: DefId) -> &'tcx VariantDef {
477        self.variants().iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
478    }
479
480    /// Return a `VariantDef` given a constructor id.
481    pub fn variant_with_ctor_id(self, cid: DefId) -> &'tcx VariantDef {
482        self.variants()
483            .iter()
484            .find(|v| v.ctor_def_id() == Some(cid))
485            .expect("variant_with_ctor_id: unknown variant")
486    }
487
488    /// Return the index of `VariantDef` given a variant id.
489    #[inline]
490    pub fn variant_index_with_id(self, vid: DefId) -> VariantIdx {
491        self.variants()
492            .iter_enumerated()
493            .find(|(_, v)| v.def_id == vid)
494            .expect("variant_index_with_id: unknown variant")
495            .0
496    }
497
498    /// Return the index of `VariantDef` given a constructor id.
499    pub fn variant_index_with_ctor_id(self, cid: DefId) -> VariantIdx {
500        self.variants()
501            .iter_enumerated()
502            .find(|(_, v)| v.ctor_def_id() == Some(cid))
503            .expect("variant_index_with_ctor_id: unknown variant")
504            .0
505    }
506
507    pub fn variant_of_res(self, res: Res) -> &'tcx VariantDef {
508        match res {
509            Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
510            Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
511            Res::Def(DefKind::Struct, _)
512            | Res::Def(DefKind::Union, _)
513            | Res::Def(DefKind::TyAlias, _)
514            | Res::Def(DefKind::AssocTy, _)
515            | Res::SelfTyParam { .. }
516            | Res::SelfTyAlias { .. }
517            | Res::SelfCtor(..) => self.non_enum_variant(),
518            _ => bug!("unexpected res {:?} in variant_of_res", res),
519        }
520    }
521
522    #[inline]
523    pub fn eval_explicit_discr(
524        self,
525        tcx: TyCtxt<'tcx>,
526        expr_did: DefId,
527    ) -> Result<Discr<'tcx>, ErrorGuaranteed> {
528        assert!(self.is_enum());
529
530        let repr_type = self.repr().discr_type();
531        match tcx.const_eval_poly(expr_did) {
532            Ok(val) => {
533                let typing_env = ty::TypingEnv::post_analysis(tcx, expr_did);
534                let ty = repr_type.to_ty(tcx);
535                if let Some(b) = val.try_to_bits_for_ty(tcx, typing_env, ty) {
536                    trace!("discriminants: {} ({:?})", b, repr_type);
537                    Ok(Discr { val: b, ty })
538                } else {
539                    info!("invalid enum discriminant: {:#?}", val);
540                    let guar = tcx.dcx().emit_err(crate::error::ConstEvalNonIntError {
541                        span: tcx.def_span(expr_did),
542                    });
543                    Err(guar)
544                }
545            }
546            Err(err) => {
547                let guar = match err {
548                    ErrorHandled::Reported(info, _) => info.into(),
549                    ErrorHandled::TooGeneric(..) => tcx.dcx().span_delayed_bug(
550                        tcx.def_span(expr_did),
551                        "enum discriminant depends on generics",
552                    ),
553                };
554                Err(guar)
555            }
556        }
557    }
558
559    #[inline]
560    pub fn discriminants(
561        self,
562        tcx: TyCtxt<'tcx>,
563    ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
564        assert!(self.is_enum());
565        let repr_type = self.repr().discr_type();
566        let initial = repr_type.initial_discriminant(tcx);
567        let mut prev_discr = None::<Discr<'tcx>>;
568        self.variants().iter_enumerated().map(move |(i, v)| {
569            let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
570            if let VariantDiscr::Explicit(expr_did) = v.discr {
571                if let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
572                    discr = new_discr;
573                }
574            }
575            prev_discr = Some(discr);
576
577            (i, discr)
578        })
579    }
580
581    #[inline]
582    pub fn variant_range(self) -> Range<VariantIdx> {
583        FIRST_VARIANT..self.variants().next_index()
584    }
585
586    /// Computes the discriminant value used by a specific variant.
587    /// Unlike `discriminants`, this is (amortized) constant-time,
588    /// only doing at most one query for evaluating an explicit
589    /// discriminant (the last one before the requested variant),
590    /// assuming there are no constant-evaluation errors there.
591    #[inline]
592    pub fn discriminant_for_variant(
593        self,
594        tcx: TyCtxt<'tcx>,
595        variant_index: VariantIdx,
596    ) -> Discr<'tcx> {
597        assert!(self.is_enum());
598        let (val, offset) = self.discriminant_def_for_variant(variant_index);
599        let explicit_value = if let Some(expr_did) = val
600            && let Ok(val) = self.eval_explicit_discr(tcx, expr_did)
601        {
602            val
603        } else {
604            self.repr().discr_type().initial_discriminant(tcx)
605        };
606        explicit_value.checked_add(tcx, offset as u128).0
607    }
608
609    /// Yields a `DefId` for the discriminant and an offset to add to it
610    /// Alternatively, if there is no explicit discriminant, returns the
611    /// inferred discriminant directly.
612    pub fn discriminant_def_for_variant(self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
613        assert!(!self.variants().is_empty());
614        let mut explicit_index = variant_index.as_u32();
615        let expr_did;
616        loop {
617            match self.variant(VariantIdx::from_u32(explicit_index)).discr {
618                ty::VariantDiscr::Relative(0) => {
619                    expr_did = None;
620                    break;
621                }
622                ty::VariantDiscr::Relative(distance) => {
623                    explicit_index -= distance;
624                }
625                ty::VariantDiscr::Explicit(did) => {
626                    expr_did = Some(did);
627                    break;
628                }
629            }
630        }
631        (expr_did, variant_index.as_u32() - explicit_index)
632    }
633
634    pub fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
635        tcx.adt_destructor(self.did())
636    }
637
638    // FIXME: consider combining this method with `AdtDef::destructor` and removing
639    // this version
640    pub fn async_destructor(self, tcx: TyCtxt<'tcx>) -> Option<AsyncDestructor> {
641        tcx.adt_async_destructor(self.did())
642    }
643
644    /// If this ADT is a struct, returns a type such that `Self: {Meta,Pointee,}Sized` if and only
645    /// if that type is `{Meta,Pointee,}Sized`, or `None` if this ADT is always
646    /// `{Meta,Pointee,}Sized`.
647    pub fn sizedness_constraint(
648        self,
649        tcx: TyCtxt<'tcx>,
650        sizedness: ty::SizedTraitKind,
651    ) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
652        if self.is_struct() { tcx.adt_sizedness_constraint((self.did(), sizedness)) } else { None }
653    }
654}
655
656#[derive(Clone, Copy, Debug, HashStable)]
657pub enum Representability {
658    Representable,
659    Infinite(ErrorGuaranteed),
660}