1 use crate::mir::interpret::ErrorHandled;
3 use crate::ty::util::{Discr, IntTypeExt};
4 use rustc_data_structures::captures::Captures;
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::intern::Interned;
8 use rustc_data_structures::stable_hasher::HashingControls;
9 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
11 use rustc_hir::def::{CtorKind, DefKind, Res};
12 use rustc_hir::def_id::DefId;
13 use rustc_index::vec::{Idx, IndexVec};
14 use rustc_query_system::ich::StableHashingContext;
15 use rustc_session::DataTypeKind;
16 use rustc_span::symbol::sym;
17 use rustc_target::abi::{ReprOptions, VariantIdx};
19 use std::cell::RefCell;
20 use std::cmp::Ordering;
21 use std::hash::{Hash, Hasher};
25 use super::{Destructor, FieldDef, GenericPredicates, Ty, TyCtxt, VariantDef, VariantDiscr};
28 #[derive(HashStable, TyEncodable, TyDecodable)]
29 pub struct AdtFlags: u32 {
30 const NO_ADT_FLAGS = 0;
31 /// Indicates whether the ADT is an enum.
32 const IS_ENUM = 1 << 0;
33 /// Indicates whether the ADT is a union.
34 const IS_UNION = 1 << 1;
35 /// Indicates whether the ADT is a struct.
36 const IS_STRUCT = 1 << 2;
37 /// Indicates whether the ADT is a struct and has a constructor.
38 const HAS_CTOR = 1 << 3;
39 /// Indicates whether the type is `PhantomData`.
40 const IS_PHANTOM_DATA = 1 << 4;
41 /// Indicates whether the type has a `#[fundamental]` attribute.
42 const IS_FUNDAMENTAL = 1 << 5;
43 /// Indicates whether the type is `Box`.
44 const IS_BOX = 1 << 6;
45 /// Indicates whether the type is `ManuallyDrop`.
46 const IS_MANUALLY_DROP = 1 << 7;
47 /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
48 /// (i.e., this flag is never set unless this ADT is an enum).
49 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
50 /// Indicates whether the type is `UnsafeCell`.
51 const IS_UNSAFE_CELL = 1 << 9;
55 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
57 /// These are all interned (by `alloc_adt_def`) into the global arena.
59 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
60 /// This is slightly wrong because `union`s are not ADTs.
61 /// Moreover, Rust only allows recursive data types through indirection.
63 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
67 /// It may seem impossible to represent recursive types using [`Ty`],
68 /// since [`TyKind::Adt`] includes [`AdtDef`], which includes its fields,
69 /// creating a cycle. However, `AdtDef` does not actually include the *types*
70 /// of its fields; it includes just their [`DefId`]s.
72 /// [`TyKind::Adt`]: ty::TyKind::Adt
74 /// For example, the following type:
77 /// struct S { x: Box<S> }
80 /// is essentially represented with [`Ty`] as the following pseudocode:
82 /// ```ignore (illustrative)
86 /// where `x` here represents the `DefId` of `S.x`. Then, the `DefId`
87 /// can be used with [`TyCtxt::type_of()`] to get the type of the field.
88 #[derive(TyEncodable, TyDecodable)]
89 pub struct AdtDefData {
90 /// The `DefId` of the struct, enum or union item.
92 /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
93 variants: IndexVec<VariantIdx, VariantDef>,
94 /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
96 /// Repr options provided by the user.
100 impl PartialOrd for AdtDefData {
101 fn partial_cmp(&self, other: &AdtDefData) -> Option<Ordering> {
102 Some(self.cmp(&other))
106 /// There should be only one AdtDef for each `did`, therefore
107 /// it is fine to implement `Ord` only based on `did`.
108 impl Ord for AdtDefData {
109 fn cmp(&self, other: &AdtDefData) -> Ordering {
110 self.did.cmp(&other.did)
114 /// There should be only one AdtDef for each `did`, therefore
115 /// it is fine to implement `PartialEq` only based on `did`.
116 impl PartialEq for AdtDefData {
118 fn eq(&self, other: &Self) -> bool {
119 self.did == other.did
123 impl Eq for AdtDefData {}
125 /// There should be only one AdtDef for each `did`, therefore
126 /// it is fine to implement `Hash` only based on `did`.
127 impl Hash for AdtDefData {
129 fn hash<H: Hasher>(&self, s: &mut H) {
134 impl<'a> HashStable<StableHashingContext<'a>> for AdtDefData {
135 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
137 static CACHE: RefCell<FxHashMap<(usize, HashingControls), Fingerprint>> = Default::default();
140 let hash: Fingerprint = CACHE.with(|cache| {
141 let addr = self as *const AdtDefData as usize;
142 let hashing_controls = hcx.hashing_controls();
143 *cache.borrow_mut().entry((addr, hashing_controls)).or_insert_with(|| {
144 let ty::AdtDefData { did, ref variants, ref flags, ref repr } = *self;
146 let mut hasher = StableHasher::new();
147 did.hash_stable(hcx, &mut hasher);
148 variants.hash_stable(hcx, &mut hasher);
149 flags.hash_stable(hcx, &mut hasher);
150 repr.hash_stable(hcx, &mut hasher);
156 hash.hash_stable(hcx, hasher);
160 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
161 #[rustc_pass_by_value]
162 pub struct AdtDef<'tcx>(pub Interned<'tcx, AdtDefData>);
164 impl<'tcx> AdtDef<'tcx> {
166 pub fn did(self) -> DefId {
171 pub fn variants(self) -> &'tcx IndexVec<VariantIdx, VariantDef> {
176 pub fn variant(self, idx: VariantIdx) -> &'tcx VariantDef {
177 &self.0.0.variants[idx]
181 pub fn flags(self) -> AdtFlags {
186 pub fn repr(self) -> ReprOptions {
191 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, HashStable, TyEncodable, TyDecodable)]
198 impl Into<DataTypeKind> for AdtKind {
199 fn into(self) -> DataTypeKind {
201 AdtKind::Struct => DataTypeKind::Struct,
202 AdtKind::Union => DataTypeKind::Union,
203 AdtKind::Enum => DataTypeKind::Enum,
209 /// Creates a new `AdtDefData`.
214 variants: IndexVec<VariantIdx, VariantDef>,
217 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
218 let mut flags = AdtFlags::NO_ADT_FLAGS;
220 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
221 debug!("found non-exhaustive variant list for {:?}", did);
222 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
225 flags |= match kind {
226 AdtKind::Enum => AdtFlags::IS_ENUM,
227 AdtKind::Union => AdtFlags::IS_UNION,
228 AdtKind::Struct => AdtFlags::IS_STRUCT,
231 if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor.is_some() {
232 flags |= AdtFlags::HAS_CTOR;
235 if tcx.has_attr(did, sym::fundamental) {
236 flags |= AdtFlags::IS_FUNDAMENTAL;
238 if Some(did) == tcx.lang_items().phantom_data() {
239 flags |= AdtFlags::IS_PHANTOM_DATA;
241 if Some(did) == tcx.lang_items().owned_box() {
242 flags |= AdtFlags::IS_BOX;
244 if Some(did) == tcx.lang_items().manually_drop() {
245 flags |= AdtFlags::IS_MANUALLY_DROP;
247 if Some(did) == tcx.lang_items().unsafe_cell_type() {
248 flags |= AdtFlags::IS_UNSAFE_CELL;
251 AdtDefData { did, variants, flags, repr }
255 impl<'tcx> AdtDef<'tcx> {
256 /// Returns `true` if this is a struct.
258 pub fn is_struct(self) -> bool {
259 self.flags().contains(AdtFlags::IS_STRUCT)
262 /// Returns `true` if this is a union.
264 pub fn is_union(self) -> bool {
265 self.flags().contains(AdtFlags::IS_UNION)
268 /// Returns `true` if this is an enum.
270 pub fn is_enum(self) -> bool {
271 self.flags().contains(AdtFlags::IS_ENUM)
274 /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
276 pub fn is_variant_list_non_exhaustive(self) -> bool {
277 self.flags().contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
280 /// Returns the kind of the ADT.
282 pub fn adt_kind(self) -> AdtKind {
285 } else if self.is_union() {
292 /// Returns a description of this abstract data type.
293 pub fn descr(self) -> &'static str {
294 match self.adt_kind() {
295 AdtKind::Struct => "struct",
296 AdtKind::Union => "union",
297 AdtKind::Enum => "enum",
301 /// Returns a description of a variant of this abstract data type.
303 pub fn variant_descr(self) -> &'static str {
304 match self.adt_kind() {
305 AdtKind::Struct => "struct",
306 AdtKind::Union => "union",
307 AdtKind::Enum => "variant",
311 /// If this function returns `true`, it implies that `is_struct` must return `true`.
313 pub fn has_ctor(self) -> bool {
314 self.flags().contains(AdtFlags::HAS_CTOR)
317 /// Returns `true` if this type is `#[fundamental]` for the purposes
318 /// of coherence checking.
320 pub fn is_fundamental(self) -> bool {
321 self.flags().contains(AdtFlags::IS_FUNDAMENTAL)
324 /// Returns `true` if this is `PhantomData<T>`.
326 pub fn is_phantom_data(self) -> bool {
327 self.flags().contains(AdtFlags::IS_PHANTOM_DATA)
330 /// Returns `true` if this is `Box<T>`.
332 pub fn is_box(self) -> bool {
333 self.flags().contains(AdtFlags::IS_BOX)
336 /// Returns `true` if this is `UnsafeCell<T>`.
338 pub fn is_unsafe_cell(self) -> bool {
339 self.flags().contains(AdtFlags::IS_UNSAFE_CELL)
342 /// Returns `true` if this is `ManuallyDrop<T>`.
344 pub fn is_manually_drop(self) -> bool {
345 self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
348 /// Returns `true` if this type has a destructor.
349 pub fn has_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
350 self.destructor(tcx).is_some()
353 pub fn has_non_const_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
354 matches!(self.destructor(tcx), Some(Destructor { constness: hir::Constness::NotConst, .. }))
357 /// Asserts this is a struct or union and returns its unique variant.
358 pub fn non_enum_variant(self) -> &'tcx VariantDef {
359 assert!(self.is_struct() || self.is_union());
360 &self.variant(VariantIdx::new(0))
364 pub fn predicates(self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
365 tcx.predicates_of(self.did())
368 /// Returns an iterator over all fields contained
371 pub fn all_fields(self) -> impl Iterator<Item = &'tcx FieldDef> + Clone {
372 self.variants().iter().flat_map(|v| v.fields.iter())
375 /// Whether the ADT lacks fields. Note that this includes uninhabited enums,
376 /// e.g., `enum Void {}` is considered payload free as well.
377 pub fn is_payloadfree(self) -> bool {
378 // Treat the ADT as not payload-free if arbitrary_enum_discriminant is used (#88621).
379 // This would disallow the following kind of enum from being casted into integer.
387 if self.variants().iter().any(|v| {
388 matches!(v.discr, VariantDiscr::Explicit(_)) && v.ctor_kind() != Some(CtorKind::Const)
392 self.variants().iter().all(|v| v.fields.is_empty())
395 /// Return a `VariantDef` given a variant id.
396 pub fn variant_with_id(self, vid: DefId) -> &'tcx VariantDef {
397 self.variants().iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
400 /// Return a `VariantDef` given a constructor id.
401 pub fn variant_with_ctor_id(self, cid: DefId) -> &'tcx VariantDef {
404 .find(|v| v.ctor_def_id() == Some(cid))
405 .expect("variant_with_ctor_id: unknown variant")
408 /// Return the index of `VariantDef` given a variant id.
409 pub fn variant_index_with_id(self, vid: DefId) -> VariantIdx {
412 .find(|(_, v)| v.def_id == vid)
413 .expect("variant_index_with_id: unknown variant")
417 /// Return the index of `VariantDef` given a constructor id.
418 pub fn variant_index_with_ctor_id(self, cid: DefId) -> VariantIdx {
421 .find(|(_, v)| v.ctor_def_id() == Some(cid))
422 .expect("variant_index_with_ctor_id: unknown variant")
426 pub fn variant_of_res(self, res: Res) -> &'tcx VariantDef {
428 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
429 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
430 Res::Def(DefKind::Struct, _)
431 | Res::Def(DefKind::Union, _)
432 | Res::Def(DefKind::TyAlias, _)
433 | Res::Def(DefKind::AssocTy, _)
434 | Res::SelfTyParam { .. }
435 | Res::SelfTyAlias { .. }
436 | Res::SelfCtor(..) => self.non_enum_variant(),
437 _ => bug!("unexpected res {:?} in variant_of_res", res),
442 pub fn eval_explicit_discr(self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
443 assert!(self.is_enum());
444 let param_env = tcx.param_env(expr_did);
445 let repr_type = self.repr().discr_type();
446 match tcx.const_eval_poly(expr_did) {
448 let ty = repr_type.to_ty(tcx);
449 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
450 trace!("discriminants: {} ({:?})", b, repr_type);
451 Some(Discr { val: b, ty })
453 info!("invalid enum discriminant: {:#?}", val);
454 tcx.sess.emit_err(crate::error::ConstEvalNonIntError {
455 span: tcx.def_span(expr_did),
461 let msg = match err {
462 ErrorHandled::Reported(_) => "enum discriminant evaluation failed",
463 ErrorHandled::TooGeneric => "enum discriminant depends on generics",
465 tcx.sess.delay_span_bug(tcx.def_span(expr_did), msg);
472 pub fn discriminants(
475 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
476 assert!(self.is_enum());
477 let repr_type = self.repr().discr_type();
478 let initial = repr_type.initial_discriminant(tcx);
479 let mut prev_discr = None::<Discr<'tcx>>;
480 self.variants().iter_enumerated().map(move |(i, v)| {
481 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
482 if let VariantDiscr::Explicit(expr_did) = v.discr {
483 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
487 prev_discr = Some(discr);
494 pub fn variant_range(self) -> Range<VariantIdx> {
495 VariantIdx::new(0)..VariantIdx::new(self.variants().len())
498 /// Computes the discriminant value used by a specific variant.
499 /// Unlike `discriminants`, this is (amortized) constant-time,
500 /// only doing at most one query for evaluating an explicit
501 /// discriminant (the last one before the requested variant),
502 /// assuming there are no constant-evaluation errors there.
504 pub fn discriminant_for_variant(
507 variant_index: VariantIdx,
509 assert!(self.is_enum());
510 let (val, offset) = self.discriminant_def_for_variant(variant_index);
511 let explicit_value = val
512 .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
513 .unwrap_or_else(|| self.repr().discr_type().initial_discriminant(tcx));
514 explicit_value.checked_add(tcx, offset as u128).0
517 /// Yields a `DefId` for the discriminant and an offset to add to it
518 /// Alternatively, if there is no explicit discriminant, returns the
519 /// inferred discriminant directly.
520 pub fn discriminant_def_for_variant(self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
521 assert!(!self.variants().is_empty());
522 let mut explicit_index = variant_index.as_u32();
525 match self.variant(VariantIdx::from_u32(explicit_index)).discr {
526 ty::VariantDiscr::Relative(0) => {
530 ty::VariantDiscr::Relative(distance) => {
531 explicit_index -= distance;
533 ty::VariantDiscr::Explicit(did) => {
534 expr_did = Some(did);
539 (expr_did, variant_index.as_u32() - explicit_index)
542 pub fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
543 tcx.adt_destructor(self.did())
546 /// Returns a list of types such that `Self: Sized` if and only
547 /// if that type is `Sized`, or `TyErr` if this type is recursive.
549 /// Oddly enough, checking that the sized-constraint is `Sized` is
550 /// actually more expressive than checking all members:
551 /// the `Sized` trait is inductive, so an associated type that references
552 /// `Self` would prevent its containing ADT from being `Sized`.
554 /// Due to normalization being eager, this applies even if
555 /// the associated type is behind a pointer (e.g., issue #31299).
556 pub fn sized_constraint(self, tcx: TyCtxt<'tcx>) -> ty::EarlyBinder<&'tcx [Ty<'tcx>]> {
557 ty::EarlyBinder(tcx.adt_sized_constraint(self.did()))
561 #[derive(Clone, Copy, Debug)]
562 #[derive(HashStable)]
563 pub enum Representability {