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 const IS_ENUM = 1 << 0;
38 const IS_UNION = 1 << 1;
40 const IS_STRUCT = 1 << 2;
42 const HAS_CTOR = 1 << 3;
44 const IS_PHANTOM_DATA = 1 << 4;
46 const IS_FUNDAMENTAL = 1 << 5;
48 const IS_BOX = 1 << 6;
50 const IS_MANUALLY_DROP = 1 << 7;
52 const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
55 const IS_UNSAFE_CELL = 1 << 9;
57 const IS_UNSAFE_PINNED = 1 << 10;
59 }
60}
61rustc_data_structures::external_bitflags_debug! { AdtFlags }
62
63#[derive(TyEncodable, TyDecodable)]
97pub struct AdtDefData {
98 pub did: DefId,
100 variants: IndexVec<VariantIdx, VariantDef>,
102 flags: AdtFlags,
104 repr: ReprOptions,
106}
107
108impl PartialEq for AdtDefData {
109 #[inline]
110 fn eq(&self, other: &Self) -> bool {
111 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 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
137impl 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 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 #[inline]
325 pub fn is_struct(self) -> bool {
326 self.flags().contains(AdtFlags::IS_STRUCT)
327 }
328
329 #[inline]
331 pub fn is_union(self) -> bool {
332 self.flags().contains(AdtFlags::IS_UNION)
333 }
334
335 #[inline]
337 pub fn is_enum(self) -> bool {
338 self.flags().contains(AdtFlags::IS_ENUM)
339 }
340
341 #[inline]
347 pub fn is_variant_list_non_exhaustive(self) -> bool {
348 self.flags().contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
349 }
350
351 #[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 #[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 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 #[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 #[inline]
391 pub fn has_ctor(self) -> bool {
392 self.flags().contains(AdtFlags::HAS_CTOR)
393 }
394
395 #[inline]
398 pub fn is_fundamental(self) -> bool {
399 self.flags().contains(AdtFlags::IS_FUNDAMENTAL)
400 }
401
402 #[inline]
404 pub fn is_phantom_data(self) -> bool {
405 self.flags().contains(AdtFlags::IS_PHANTOM_DATA)
406 }
407
408 #[inline]
410 pub fn is_box(self) -> bool {
411 self.flags().contains(AdtFlags::IS_BOX)
412 }
413
414 #[inline]
416 pub fn is_unsafe_cell(self) -> bool {
417 self.flags().contains(AdtFlags::IS_UNSAFE_CELL)
418 }
419
420 #[inline]
422 pub fn is_unsafe_pinned(self) -> bool {
423 self.flags().contains(AdtFlags::IS_UNSAFE_PINNED)
424 }
425
426 #[inline]
428 pub fn is_manually_drop(self) -> bool {
429 self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
430 }
431
432 pub fn has_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
434 self.destructor(tcx).is_some()
435 }
436
437 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 #[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 pub fn is_payloadfree(self) -> bool {
458 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 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 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 #[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 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 #[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 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 pub fn async_destructor(self, tcx: TyCtxt<'tcx>) -> Option<AsyncDestructor> {
641 tcx.adt_async_destructor(self.did())
642 }
643
644 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}