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 const IS_ENUM = 1 << 0;
37 const IS_UNION = 1 << 1;
39 const IS_STRUCT = 1 << 2;
41 const HAS_CTOR = 1 << 3;
43 const IS_PHANTOM_DATA = 1 << 4;
45 const IS_FUNDAMENTAL = 1 << 5;
47 const IS_BOX = 1 << 6;
49 const IS_MANUALLY_DROP = 1 << 7;
51 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
54 const IS_UNSAFE_CELL = 1 << 9;
56 const IS_UNSAFE_PINNED = 1 << 10;
58 }
59}
60rustc_data_structures::external_bitflags_debug! { AdtFlags }
61
62#[derive(TyEncodable, TyDecodable)]
96pub struct AdtDefData {
97 pub did: DefId,
99 variants: IndexVec<VariantIdx, VariantDef>,
101 flags: AdtFlags,
103 repr: ReprOptions,
105}
106
107impl PartialEq for AdtDefData {
108 #[inline]
109 fn eq(&self, other: &Self) -> bool {
110 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 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
136impl 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 sized_constraint(self, tcx: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
233 self.sized_constraint(tcx)
234 }
235
236 fn is_fundamental(self) -> bool {
237 self.is_fundamental()
238 }
239
240 fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<AdtDestructorKind> {
241 Some(match tcx.constness(self.destructor(tcx)?.did) {
242 hir::Constness::Const => AdtDestructorKind::Const,
243 hir::Constness::NotConst => AdtDestructorKind::NotConst,
244 })
245 }
246}
247
248#[derive(Copy, Clone, Debug, Eq, PartialEq, HashStable, TyEncodable, TyDecodable)]
249pub enum AdtKind {
250 Struct,
251 Union,
252 Enum,
253}
254
255impl From<AdtKind> for DataTypeKind {
256 fn from(val: AdtKind) -> Self {
257 match val {
258 AdtKind::Struct => DataTypeKind::Struct,
259 AdtKind::Union => DataTypeKind::Union,
260 AdtKind::Enum => DataTypeKind::Enum,
261 }
262 }
263}
264
265impl AdtDefData {
266 pub(super) fn new(
268 tcx: TyCtxt<'_>,
269 did: DefId,
270 kind: AdtKind,
271 variants: IndexVec<VariantIdx, VariantDef>,
272 repr: ReprOptions,
273 ) -> Self {
274 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
275 let mut flags = AdtFlags::NO_ADT_FLAGS;
276
277 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
278 debug!("found non-exhaustive variant list for {:?}", did);
279 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
280 }
281
282 flags |= match kind {
283 AdtKind::Enum => AdtFlags::IS_ENUM,
284 AdtKind::Union => AdtFlags::IS_UNION,
285 AdtKind::Struct => AdtFlags::IS_STRUCT,
286 };
287
288 if kind == AdtKind::Struct && variants[FIRST_VARIANT].ctor.is_some() {
289 flags |= AdtFlags::HAS_CTOR;
290 }
291
292 if tcx.has_attr(did, sym::fundamental) {
293 flags |= AdtFlags::IS_FUNDAMENTAL;
294 }
295 if tcx.is_lang_item(did, LangItem::PhantomData) {
296 flags |= AdtFlags::IS_PHANTOM_DATA;
297 }
298 if tcx.is_lang_item(did, LangItem::OwnedBox) {
299 flags |= AdtFlags::IS_BOX;
300 }
301 if tcx.is_lang_item(did, LangItem::ManuallyDrop) {
302 flags |= AdtFlags::IS_MANUALLY_DROP;
303 }
304 if tcx.is_lang_item(did, LangItem::UnsafeCell) {
305 flags |= AdtFlags::IS_UNSAFE_CELL;
306 }
307 if tcx.is_lang_item(did, LangItem::UnsafePinned) {
308 flags |= AdtFlags::IS_UNSAFE_PINNED;
309 }
310
311 AdtDefData { did, variants, flags, repr }
312 }
313}
314
315impl<'tcx> AdtDef<'tcx> {
316 #[inline]
318 pub fn is_struct(self) -> bool {
319 self.flags().contains(AdtFlags::IS_STRUCT)
320 }
321
322 #[inline]
324 pub fn is_union(self) -> bool {
325 self.flags().contains(AdtFlags::IS_UNION)
326 }
327
328 #[inline]
330 pub fn is_enum(self) -> bool {
331 self.flags().contains(AdtFlags::IS_ENUM)
332 }
333
334 #[inline]
340 pub fn is_variant_list_non_exhaustive(self) -> bool {
341 self.flags().contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
342 }
343
344 #[inline]
347 pub fn variant_list_has_applicable_non_exhaustive(self) -> bool {
348 self.is_variant_list_non_exhaustive() && !self.did().is_local()
349 }
350
351 #[inline]
353 pub fn adt_kind(self) -> AdtKind {
354 if self.is_enum() {
355 AdtKind::Enum
356 } else if self.is_union() {
357 AdtKind::Union
358 } else {
359 AdtKind::Struct
360 }
361 }
362
363 pub fn descr(self) -> &'static str {
365 match self.adt_kind() {
366 AdtKind::Struct => "struct",
367 AdtKind::Union => "union",
368 AdtKind::Enum => "enum",
369 }
370 }
371
372 #[inline]
374 pub fn variant_descr(self) -> &'static str {
375 match self.adt_kind() {
376 AdtKind::Struct => "struct",
377 AdtKind::Union => "union",
378 AdtKind::Enum => "variant",
379 }
380 }
381
382 #[inline]
384 pub fn has_ctor(self) -> bool {
385 self.flags().contains(AdtFlags::HAS_CTOR)
386 }
387
388 #[inline]
391 pub fn is_fundamental(self) -> bool {
392 self.flags().contains(AdtFlags::IS_FUNDAMENTAL)
393 }
394
395 #[inline]
397 pub fn is_phantom_data(self) -> bool {
398 self.flags().contains(AdtFlags::IS_PHANTOM_DATA)
399 }
400
401 #[inline]
403 pub fn is_box(self) -> bool {
404 self.flags().contains(AdtFlags::IS_BOX)
405 }
406
407 #[inline]
409 pub fn is_unsafe_cell(self) -> bool {
410 self.flags().contains(AdtFlags::IS_UNSAFE_CELL)
411 }
412
413 #[inline]
415 pub fn is_unsafe_pinned(self) -> bool {
416 self.flags().contains(AdtFlags::IS_UNSAFE_PINNED)
417 }
418
419 #[inline]
421 pub fn is_manually_drop(self) -> bool {
422 self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
423 }
424
425 pub fn has_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
427 self.destructor(tcx).is_some()
428 }
429
430 pub fn non_enum_variant(self) -> &'tcx VariantDef {
432 assert!(self.is_struct() || self.is_union());
433 self.variant(FIRST_VARIANT)
434 }
435
436 #[inline]
437 pub fn predicates(self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
438 tcx.predicates_of(self.did())
439 }
440
441 #[inline]
444 pub fn all_fields(self) -> impl Iterator<Item = &'tcx FieldDef> + Clone {
445 self.variants().iter().flat_map(|v| v.fields.iter())
446 }
447
448 pub fn is_payloadfree(self) -> bool {
451 if self.variants().iter().any(|v| {
461 matches!(v.discr, VariantDiscr::Explicit(_)) && v.ctor_kind() != Some(CtorKind::Const)
462 }) {
463 return false;
464 }
465 self.variants().iter().all(|v| v.fields.is_empty())
466 }
467
468 pub fn variant_with_id(self, vid: DefId) -> &'tcx VariantDef {
470 self.variants().iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
471 }
472
473 pub fn variant_with_ctor_id(self, cid: DefId) -> &'tcx VariantDef {
475 self.variants()
476 .iter()
477 .find(|v| v.ctor_def_id() == Some(cid))
478 .expect("variant_with_ctor_id: unknown variant")
479 }
480
481 #[inline]
483 pub fn variant_index_with_id(self, vid: DefId) -> VariantIdx {
484 self.variants()
485 .iter_enumerated()
486 .find(|(_, v)| v.def_id == vid)
487 .expect("variant_index_with_id: unknown variant")
488 .0
489 }
490
491 pub fn variant_index_with_ctor_id(self, cid: DefId) -> VariantIdx {
493 self.variants()
494 .iter_enumerated()
495 .find(|(_, v)| v.ctor_def_id() == Some(cid))
496 .expect("variant_index_with_ctor_id: unknown variant")
497 .0
498 }
499
500 pub fn variant_of_res(self, res: Res) -> &'tcx VariantDef {
501 match res {
502 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
503 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
504 Res::Def(DefKind::Struct, _)
505 | Res::Def(DefKind::Union, _)
506 | Res::Def(DefKind::TyAlias, _)
507 | Res::Def(DefKind::AssocTy, _)
508 | Res::SelfTyParam { .. }
509 | Res::SelfTyAlias { .. }
510 | Res::SelfCtor(..) => self.non_enum_variant(),
511 _ => bug!("unexpected res {:?} in variant_of_res", res),
512 }
513 }
514
515 #[inline]
516 pub fn eval_explicit_discr(
517 self,
518 tcx: TyCtxt<'tcx>,
519 expr_did: DefId,
520 ) -> Result<Discr<'tcx>, ErrorGuaranteed> {
521 assert!(self.is_enum());
522
523 let repr_type = self.repr().discr_type();
524 match tcx.const_eval_poly(expr_did) {
525 Ok(val) => {
526 let typing_env = ty::TypingEnv::post_analysis(tcx, expr_did);
527 let ty = repr_type.to_ty(tcx);
528 if let Some(b) = val.try_to_bits_for_ty(tcx, typing_env, ty) {
529 trace!("discriminants: {} ({:?})", b, repr_type);
530 Ok(Discr { val: b, ty })
531 } else {
532 info!("invalid enum discriminant: {:#?}", val);
533 let guar = tcx.dcx().emit_err(crate::error::ConstEvalNonIntError {
534 span: tcx.def_span(expr_did),
535 });
536 Err(guar)
537 }
538 }
539 Err(err) => {
540 let guar = match err {
541 ErrorHandled::Reported(info, _) => info.into(),
542 ErrorHandled::TooGeneric(..) => tcx.dcx().span_delayed_bug(
543 tcx.def_span(expr_did),
544 "enum discriminant depends on generics",
545 ),
546 };
547 Err(guar)
548 }
549 }
550 }
551
552 #[inline]
553 pub fn discriminants(
554 self,
555 tcx: TyCtxt<'tcx>,
556 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
557 assert!(self.is_enum());
558 let repr_type = self.repr().discr_type();
559 let initial = repr_type.initial_discriminant(tcx);
560 let mut prev_discr = None::<Discr<'tcx>>;
561 self.variants().iter_enumerated().map(move |(i, v)| {
562 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
563 if let VariantDiscr::Explicit(expr_did) = v.discr {
564 if let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
565 discr = new_discr;
566 }
567 }
568 prev_discr = Some(discr);
569
570 (i, discr)
571 })
572 }
573
574 #[inline]
575 pub fn variant_range(self) -> Range<VariantIdx> {
576 FIRST_VARIANT..self.variants().next_index()
577 }
578
579 #[inline]
585 pub fn discriminant_for_variant(
586 self,
587 tcx: TyCtxt<'tcx>,
588 variant_index: VariantIdx,
589 ) -> Discr<'tcx> {
590 assert!(self.is_enum());
591 let (val, offset) = self.discriminant_def_for_variant(variant_index);
592 let explicit_value = if let Some(expr_did) = val
593 && let Ok(val) = self.eval_explicit_discr(tcx, expr_did)
594 {
595 val
596 } else {
597 self.repr().discr_type().initial_discriminant(tcx)
598 };
599 explicit_value.checked_add(tcx, offset as u128).0
600 }
601
602 pub fn discriminant_def_for_variant(self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
606 assert!(!self.variants().is_empty());
607 let mut explicit_index = variant_index.as_u32();
608 let expr_did;
609 loop {
610 match self.variant(VariantIdx::from_u32(explicit_index)).discr {
611 ty::VariantDiscr::Relative(0) => {
612 expr_did = None;
613 break;
614 }
615 ty::VariantDiscr::Relative(distance) => {
616 explicit_index -= distance;
617 }
618 ty::VariantDiscr::Explicit(did) => {
619 expr_did = Some(did);
620 break;
621 }
622 }
623 }
624 (expr_did, variant_index.as_u32() - explicit_index)
625 }
626
627 pub fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
628 tcx.adt_destructor(self.did())
629 }
630
631 pub fn async_destructor(self, tcx: TyCtxt<'tcx>) -> Option<AsyncDestructor> {
634 tcx.adt_async_destructor(self.did())
635 }
636
637 pub fn sized_constraint(self, tcx: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
640 if self.is_struct() { tcx.adt_sized_constraint(self.did()) } else { None }
641 }
642}
643
644#[derive(Clone, Copy, Debug, HashStable)]
645pub enum Representability {
646 Representable,
647 Infinite(ErrorGuaranteed),
648}