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::def::{CtorKind, DefKind, Res};
13use rustc_hir::def_id::DefId;
14use rustc_hir::{self as hir, LangItem};
15use rustc_index::{IndexSlice, IndexVec};
16use rustc_macros::{HashStable, TyDecodable, TyEncodable};
17use rustc_query_system::ich::StableHashingContext;
18use rustc_session::DataTypeKind;
19use rustc_span::sym;
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    }
59}
60rustc_data_structures::external_bitflags_debug! { AdtFlags }
61
62/// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
63///
64/// These are all interned (by `mk_adt_def`) into the global arena.
65///
66/// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
67/// This is slightly wrong because `union`s are not ADTs.
68/// Moreover, Rust only allows recursive data types through indirection.
69///
70/// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
71///
72/// # Recursive types
73///
74/// It may seem impossible to represent recursive types using [`Ty`],
75/// since [`TyKind::Adt`] includes [`AdtDef`], which includes its fields,
76/// creating a cycle. However, `AdtDef` does not actually include the *types*
77/// of its fields; it includes just their [`DefId`]s.
78///
79/// [`TyKind::Adt`]: ty::TyKind::Adt
80///
81/// For example, the following type:
82///
83/// ```
84/// struct S { x: Box<S> }
85/// ```
86///
87/// is essentially represented with [`Ty`] as the following pseudocode:
88///
89/// ```ignore (illustrative)
90/// struct S { x }
91/// ```
92///
93/// where `x` here represents the `DefId` of `S.x`. Then, the `DefId`
94/// can be used with [`TyCtxt::type_of()`] to get the type of the field.
95#[derive(TyEncodable, TyDecodable)]
96pub struct AdtDefData {
97    /// The `DefId` of the struct, enum or union item.
98    pub did: DefId,
99    /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
100    variants: IndexVec<VariantIdx, VariantDef>,
101    /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
102    flags: AdtFlags,
103    /// Repr options provided by the user.
104    repr: ReprOptions,
105}
106
107impl PartialEq for AdtDefData {
108    #[inline]
109    fn eq(&self, other: &Self) -> bool {
110        // There should be only one `AdtDefData` for each `def_id`, therefore
111        // it is fine to implement `PartialEq` only based on `def_id`.
112        //
113        // Below, we exhaustively destructure `self` and `other` so that if the
114        // definition of `AdtDefData` changes, a compile-error will be produced,
115        // reminding us to revisit this assumption.
116
117        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        // Double check that implicit assumption detailed above.
123        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
136/// There should be only one AdtDef for each `did`, therefore
137/// it is fine to implement `Hash` only based on `did`.
138impl 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    /// Creates a new `AdtDefData`.
271    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 && tcx.has_attr(did, sym::non_exhaustive) {
282            debug!("found non-exhaustive variant list for {:?}", did);
283            flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
284        }
285
286        flags |= match kind {
287            AdtKind::Enum => AdtFlags::IS_ENUM,
288            AdtKind::Union => AdtFlags::IS_UNION,
289            AdtKind::Struct => AdtFlags::IS_STRUCT,
290        };
291
292        if kind == AdtKind::Struct && variants[FIRST_VARIANT].ctor.is_some() {
293            flags |= AdtFlags::HAS_CTOR;
294        }
295
296        if tcx.has_attr(did, sym::fundamental) {
297            flags |= AdtFlags::IS_FUNDAMENTAL;
298        }
299        if tcx.is_lang_item(did, LangItem::PhantomData) {
300            flags |= AdtFlags::IS_PHANTOM_DATA;
301        }
302        if tcx.is_lang_item(did, LangItem::OwnedBox) {
303            flags |= AdtFlags::IS_BOX;
304        }
305        if tcx.is_lang_item(did, LangItem::ManuallyDrop) {
306            flags |= AdtFlags::IS_MANUALLY_DROP;
307        }
308        if tcx.is_lang_item(did, LangItem::UnsafeCell) {
309            flags |= AdtFlags::IS_UNSAFE_CELL;
310        }
311        if tcx.is_lang_item(did, LangItem::UnsafePinned) {
312            flags |= AdtFlags::IS_UNSAFE_PINNED;
313        }
314
315        AdtDefData { did, variants, flags, repr }
316    }
317}
318
319impl<'tcx> AdtDef<'tcx> {
320    /// Returns `true` if this is a struct.
321    #[inline]
322    pub fn is_struct(self) -> bool {
323        self.flags().contains(AdtFlags::IS_STRUCT)
324    }
325
326    /// Returns `true` if this is a union.
327    #[inline]
328    pub fn is_union(self) -> bool {
329        self.flags().contains(AdtFlags::IS_UNION)
330    }
331
332    /// Returns `true` if this is an enum.
333    #[inline]
334    pub fn is_enum(self) -> bool {
335        self.flags().contains(AdtFlags::IS_ENUM)
336    }
337
338    /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
339    ///
340    /// Note that this function will return `true` even if the ADT has been
341    /// defined in the crate currently being compiled. If that's not what you
342    /// want, see [`Self::variant_list_has_applicable_non_exhaustive`].
343    #[inline]
344    pub fn is_variant_list_non_exhaustive(self) -> bool {
345        self.flags().contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
346    }
347
348    /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`
349    /// and has been defined in another crate.
350    #[inline]
351    pub fn variant_list_has_applicable_non_exhaustive(self) -> bool {
352        self.is_variant_list_non_exhaustive() && !self.did().is_local()
353    }
354
355    /// Returns the kind of the ADT.
356    #[inline]
357    pub fn adt_kind(self) -> AdtKind {
358        if self.is_enum() {
359            AdtKind::Enum
360        } else if self.is_union() {
361            AdtKind::Union
362        } else {
363            AdtKind::Struct
364        }
365    }
366
367    /// Returns a description of this abstract data type.
368    pub fn descr(self) -> &'static str {
369        match self.adt_kind() {
370            AdtKind::Struct => "struct",
371            AdtKind::Union => "union",
372            AdtKind::Enum => "enum",
373        }
374    }
375
376    /// Returns a description of a variant of this abstract data type.
377    #[inline]
378    pub fn variant_descr(self) -> &'static str {
379        match self.adt_kind() {
380            AdtKind::Struct => "struct",
381            AdtKind::Union => "union",
382            AdtKind::Enum => "variant",
383        }
384    }
385
386    /// If this function returns `true`, it implies that `is_struct` must return `true`.
387    #[inline]
388    pub fn has_ctor(self) -> bool {
389        self.flags().contains(AdtFlags::HAS_CTOR)
390    }
391
392    /// Returns `true` if this type is `#[fundamental]` for the purposes
393    /// of coherence checking.
394    #[inline]
395    pub fn is_fundamental(self) -> bool {
396        self.flags().contains(AdtFlags::IS_FUNDAMENTAL)
397    }
398
399    /// Returns `true` if this is `PhantomData<T>`.
400    #[inline]
401    pub fn is_phantom_data(self) -> bool {
402        self.flags().contains(AdtFlags::IS_PHANTOM_DATA)
403    }
404
405    /// Returns `true` if this is `Box<T>`.
406    #[inline]
407    pub fn is_box(self) -> bool {
408        self.flags().contains(AdtFlags::IS_BOX)
409    }
410
411    /// Returns `true` if this is `UnsafeCell<T>`.
412    #[inline]
413    pub fn is_unsafe_cell(self) -> bool {
414        self.flags().contains(AdtFlags::IS_UNSAFE_CELL)
415    }
416
417    /// Returns `true` if this is `UnsafePinned<T>`.
418    #[inline]
419    pub fn is_unsafe_pinned(self) -> bool {
420        self.flags().contains(AdtFlags::IS_UNSAFE_PINNED)
421    }
422
423    /// Returns `true` if this is `ManuallyDrop<T>`.
424    #[inline]
425    pub fn is_manually_drop(self) -> bool {
426        self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
427    }
428
429    /// Returns `true` if this type has a destructor.
430    pub fn has_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
431        self.destructor(tcx).is_some()
432    }
433
434    /// Asserts this is a struct or union and returns its unique variant.
435    pub fn non_enum_variant(self) -> &'tcx VariantDef {
436        assert!(self.is_struct() || self.is_union());
437        self.variant(FIRST_VARIANT)
438    }
439
440    #[inline]
441    pub fn predicates(self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
442        tcx.predicates_of(self.did())
443    }
444
445    /// Returns an iterator over all fields contained
446    /// by this ADT (nested unnamed fields are not expanded).
447    #[inline]
448    pub fn all_fields(self) -> impl Iterator<Item = &'tcx FieldDef> + Clone {
449        self.variants().iter().flat_map(|v| v.fields.iter())
450    }
451
452    /// Whether the ADT lacks fields. Note that this includes uninhabited enums,
453    /// e.g., `enum Void {}` is considered payload free as well.
454    pub fn is_payloadfree(self) -> bool {
455        // Treat the ADT as not payload-free if arbitrary_enum_discriminant is used (#88621).
456        // This would disallow the following kind of enum from being casted into integer.
457        // ```
458        // enum Enum {
459        //    Foo() = 1,
460        //    Bar{} = 2,
461        //    Baz = 3,
462        // }
463        // ```
464        if self.variants().iter().any(|v| {
465            matches!(v.discr, VariantDiscr::Explicit(_)) && v.ctor_kind() != Some(CtorKind::Const)
466        }) {
467            return false;
468        }
469        self.variants().iter().all(|v| v.fields.is_empty())
470    }
471
472    /// Return a `VariantDef` given a variant id.
473    pub fn variant_with_id(self, vid: DefId) -> &'tcx VariantDef {
474        self.variants().iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
475    }
476
477    /// Return a `VariantDef` given a constructor id.
478    pub fn variant_with_ctor_id(self, cid: DefId) -> &'tcx VariantDef {
479        self.variants()
480            .iter()
481            .find(|v| v.ctor_def_id() == Some(cid))
482            .expect("variant_with_ctor_id: unknown variant")
483    }
484
485    /// Return the index of `VariantDef` given a variant id.
486    #[inline]
487    pub fn variant_index_with_id(self, vid: DefId) -> VariantIdx {
488        self.variants()
489            .iter_enumerated()
490            .find(|(_, v)| v.def_id == vid)
491            .expect("variant_index_with_id: unknown variant")
492            .0
493    }
494
495    /// Return the index of `VariantDef` given a constructor id.
496    pub fn variant_index_with_ctor_id(self, cid: DefId) -> VariantIdx {
497        self.variants()
498            .iter_enumerated()
499            .find(|(_, v)| v.ctor_def_id() == Some(cid))
500            .expect("variant_index_with_ctor_id: unknown variant")
501            .0
502    }
503
504    pub fn variant_of_res(self, res: Res) -> &'tcx VariantDef {
505        match res {
506            Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
507            Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
508            Res::Def(DefKind::Struct, _)
509            | Res::Def(DefKind::Union, _)
510            | Res::Def(DefKind::TyAlias, _)
511            | Res::Def(DefKind::AssocTy, _)
512            | Res::SelfTyParam { .. }
513            | Res::SelfTyAlias { .. }
514            | Res::SelfCtor(..) => self.non_enum_variant(),
515            _ => bug!("unexpected res {:?} in variant_of_res", res),
516        }
517    }
518
519    #[inline]
520    pub fn eval_explicit_discr(
521        self,
522        tcx: TyCtxt<'tcx>,
523        expr_did: DefId,
524    ) -> Result<Discr<'tcx>, ErrorGuaranteed> {
525        assert!(self.is_enum());
526
527        let repr_type = self.repr().discr_type();
528        match tcx.const_eval_poly(expr_did) {
529            Ok(val) => {
530                let typing_env = ty::TypingEnv::post_analysis(tcx, expr_did);
531                let ty = repr_type.to_ty(tcx);
532                if let Some(b) = val.try_to_bits_for_ty(tcx, typing_env, ty) {
533                    trace!("discriminants: {} ({:?})", b, repr_type);
534                    Ok(Discr { val: b, ty })
535                } else {
536                    info!("invalid enum discriminant: {:#?}", val);
537                    let guar = tcx.dcx().emit_err(crate::error::ConstEvalNonIntError {
538                        span: tcx.def_span(expr_did),
539                    });
540                    Err(guar)
541                }
542            }
543            Err(err) => {
544                let guar = match err {
545                    ErrorHandled::Reported(info, _) => info.into(),
546                    ErrorHandled::TooGeneric(..) => tcx.dcx().span_delayed_bug(
547                        tcx.def_span(expr_did),
548                        "enum discriminant depends on generics",
549                    ),
550                };
551                Err(guar)
552            }
553        }
554    }
555
556    #[inline]
557    pub fn discriminants(
558        self,
559        tcx: TyCtxt<'tcx>,
560    ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
561        assert!(self.is_enum());
562        let repr_type = self.repr().discr_type();
563        let initial = repr_type.initial_discriminant(tcx);
564        let mut prev_discr = None::<Discr<'tcx>>;
565        self.variants().iter_enumerated().map(move |(i, v)| {
566            let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
567            if let VariantDiscr::Explicit(expr_did) = v.discr {
568                if let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
569                    discr = new_discr;
570                }
571            }
572            prev_discr = Some(discr);
573
574            (i, discr)
575        })
576    }
577
578    #[inline]
579    pub fn variant_range(self) -> Range<VariantIdx> {
580        FIRST_VARIANT..self.variants().next_index()
581    }
582
583    /// Computes the discriminant value used by a specific variant.
584    /// Unlike `discriminants`, this is (amortized) constant-time,
585    /// only doing at most one query for evaluating an explicit
586    /// discriminant (the last one before the requested variant),
587    /// assuming there are no constant-evaluation errors there.
588    #[inline]
589    pub fn discriminant_for_variant(
590        self,
591        tcx: TyCtxt<'tcx>,
592        variant_index: VariantIdx,
593    ) -> Discr<'tcx> {
594        assert!(self.is_enum());
595        let (val, offset) = self.discriminant_def_for_variant(variant_index);
596        let explicit_value = if let Some(expr_did) = val
597            && let Ok(val) = self.eval_explicit_discr(tcx, expr_did)
598        {
599            val
600        } else {
601            self.repr().discr_type().initial_discriminant(tcx)
602        };
603        explicit_value.checked_add(tcx, offset as u128).0
604    }
605
606    /// Yields a `DefId` for the discriminant and an offset to add to it
607    /// Alternatively, if there is no explicit discriminant, returns the
608    /// inferred discriminant directly.
609    pub fn discriminant_def_for_variant(self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
610        assert!(!self.variants().is_empty());
611        let mut explicit_index = variant_index.as_u32();
612        let expr_did;
613        loop {
614            match self.variant(VariantIdx::from_u32(explicit_index)).discr {
615                ty::VariantDiscr::Relative(0) => {
616                    expr_did = None;
617                    break;
618                }
619                ty::VariantDiscr::Relative(distance) => {
620                    explicit_index -= distance;
621                }
622                ty::VariantDiscr::Explicit(did) => {
623                    expr_did = Some(did);
624                    break;
625                }
626            }
627        }
628        (expr_did, variant_index.as_u32() - explicit_index)
629    }
630
631    pub fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
632        tcx.adt_destructor(self.did())
633    }
634
635    // FIXME: consider combining this method with `AdtDef::destructor` and removing
636    // this version
637    pub fn async_destructor(self, tcx: TyCtxt<'tcx>) -> Option<AsyncDestructor> {
638        tcx.adt_async_destructor(self.did())
639    }
640
641    /// If this ADT is a struct, returns a type such that `Self: {Meta,Pointee,}Sized` if and only
642    /// if that type is `{Meta,Pointee,}Sized`, or `None` if this ADT is always
643    /// `{Meta,Pointee,}Sized`.
644    pub fn sizedness_constraint(
645        self,
646        tcx: TyCtxt<'tcx>,
647        sizedness: ty::SizedTraitKind,
648    ) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
649        if self.is_struct() { tcx.adt_sizedness_constraint((self.did(), sizedness)) } else { None }
650    }
651}
652
653#[derive(Clone, Copy, Debug, HashStable)]
654pub enum Representability {
655    Representable,
656    Infinite(ErrorGuaranteed),
657}