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 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 const IS_PIN = 1 << 11;
60 const IS_PIN_PROJECT = 1 << 12;
62 }
63}
64rustc_data_structures::external_bitflags_debug! { AdtFlags }
65
66#[derive(TyEncodable, TyDecodable)]
100pub struct AdtDefData {
101 pub did: DefId,
103 variants: IndexVec<VariantIdx, VariantDef>,
105 flags: AdtFlags,
107 repr: ReprOptions,
109}
110
111impl PartialEq for AdtDefData {
112 #[inline]
113 fn eq(&self, other: &Self) -> bool {
114 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 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
140impl 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 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 #[inline]
335 pub fn is_struct(self) -> bool {
336 self.flags().contains(AdtFlags::IS_STRUCT)
337 }
338
339 #[inline]
341 pub fn is_union(self) -> bool {
342 self.flags().contains(AdtFlags::IS_UNION)
343 }
344
345 #[inline]
347 pub fn is_enum(self) -> bool {
348 self.flags().contains(AdtFlags::IS_ENUM)
349 }
350
351 #[inline]
357 pub fn is_variant_list_non_exhaustive(self) -> bool {
358 self.flags().contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
359 }
360
361 #[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 #[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 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 #[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 #[inline]
401 pub fn has_ctor(self) -> bool {
402 self.flags().contains(AdtFlags::HAS_CTOR)
403 }
404
405 #[inline]
408 pub fn is_fundamental(self) -> bool {
409 self.flags().contains(AdtFlags::IS_FUNDAMENTAL)
410 }
411
412 #[inline]
414 pub fn is_phantom_data(self) -> bool {
415 self.flags().contains(AdtFlags::IS_PHANTOM_DATA)
416 }
417
418 #[inline]
420 pub fn is_box(self) -> bool {
421 self.flags().contains(AdtFlags::IS_BOX)
422 }
423
424 #[inline]
426 pub fn is_unsafe_cell(self) -> bool {
427 self.flags().contains(AdtFlags::IS_UNSAFE_CELL)
428 }
429
430 #[inline]
432 pub fn is_unsafe_pinned(self) -> bool {
433 self.flags().contains(AdtFlags::IS_UNSAFE_PINNED)
434 }
435
436 #[inline]
438 pub fn is_manually_drop(self) -> bool {
439 self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
440 }
441
442 #[inline]
444 pub fn is_pin(self) -> bool {
445 self.flags().contains(AdtFlags::IS_PIN)
446 }
447
448 #[inline]
451 pub fn is_pin_project(self) -> bool {
452 self.flags().contains(AdtFlags::IS_PIN_PROJECT)
453 }
454
455 pub fn has_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
457 self.destructor(tcx).is_some()
458 }
459
460 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 #[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 pub fn is_payloadfree(self) -> bool {
481 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 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 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 #[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 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 #[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 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 pub fn async_destructor(self, tcx: TyCtxt<'tcx>) -> Option<AsyncDestructor> {
664 tcx.adt_async_destructor(self.did())
665 }
666
667 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}