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 const IS_ANONYMOUS = 1 << 11;
60 }
61}
62rustc_data_structures::external_bitflags_debug! { AdtFlags }
63
64#[derive(TyEncodable, TyDecodable)]
98pub struct AdtDefData {
99 pub did: DefId,
101 variants: IndexVec<VariantIdx, VariantDef>,
103 flags: AdtFlags,
105 repr: ReprOptions,
107}
108
109impl PartialEq for AdtDefData {
110 #[inline]
111 fn eq(&self, other: &Self) -> bool {
112 let Self { did: self_def_id, variants: _, flags: _, repr: _ } = self;
120 let Self { did: other_def_id, variants: _, flags: _, repr: _ } = other;
121
122 let res = self_def_id == other_def_id;
123
124 if cfg!(debug_assertions) && res {
126 let deep = self.flags == other.flags
127 && self.repr == other.repr
128 && self.variants == other.variants;
129 assert!(deep, "AdtDefData for the same def-id has differing data");
130 }
131
132 res
133 }
134}
135
136impl Eq for AdtDefData {}
137
138impl Hash for AdtDefData {
141 #[inline]
142 fn hash<H: Hasher>(&self, s: &mut H) {
143 self.did.hash(s)
144 }
145}
146
147impl<'a> HashStable<StableHashingContext<'a>> for AdtDefData {
148 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
149 thread_local! {
150 static CACHE: RefCell<FxHashMap<(usize, HashingControls), Fingerprint>> = Default::default();
151 }
152
153 let hash: Fingerprint = CACHE.with(|cache| {
154 let addr = self as *const AdtDefData as usize;
155 let hashing_controls = hcx.hashing_controls();
156 *cache.borrow_mut().entry((addr, hashing_controls)).or_insert_with(|| {
157 let ty::AdtDefData { did, ref variants, ref flags, ref repr } = *self;
158
159 let mut hasher = StableHasher::new();
160 did.hash_stable(hcx, &mut hasher);
161 variants.hash_stable(hcx, &mut hasher);
162 flags.hash_stable(hcx, &mut hasher);
163 repr.hash_stable(hcx, &mut hasher);
164
165 hasher.finish()
166 })
167 });
168
169 hash.hash_stable(hcx, hasher);
170 }
171}
172
173#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
174#[rustc_pass_by_value]
175pub struct AdtDef<'tcx>(pub Interned<'tcx, AdtDefData>);
176
177impl<'tcx> AdtDef<'tcx> {
178 #[inline]
179 pub fn did(self) -> DefId {
180 self.0.0.did
181 }
182
183 #[inline]
184 pub fn variants(self) -> &'tcx IndexSlice<VariantIdx, VariantDef> {
185 &self.0.0.variants
186 }
187
188 #[inline]
189 pub fn variant(self, idx: VariantIdx) -> &'tcx VariantDef {
190 &self.0.0.variants[idx]
191 }
192
193 #[inline]
194 pub fn flags(self) -> AdtFlags {
195 self.0.0.flags
196 }
197
198 #[inline]
199 pub fn repr(self) -> ReprOptions {
200 self.0.0.repr
201 }
202}
203
204impl<'tcx> rustc_type_ir::inherent::AdtDef<TyCtxt<'tcx>> for AdtDef<'tcx> {
205 fn def_id(self) -> DefId {
206 self.did()
207 }
208
209 fn is_struct(self) -> bool {
210 self.is_struct()
211 }
212
213 fn struct_tail_ty(self, interner: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
214 Some(interner.type_of(self.non_enum_variant().tail_opt()?.did))
215 }
216
217 fn is_phantom_data(self) -> bool {
218 self.is_phantom_data()
219 }
220
221 fn is_manually_drop(self) -> bool {
222 self.is_manually_drop()
223 }
224
225 fn all_field_tys(
226 self,
227 tcx: TyCtxt<'tcx>,
228 ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = Ty<'tcx>>> {
229 ty::EarlyBinder::bind(
230 self.all_fields().map(move |field| tcx.type_of(field.did).skip_binder()),
231 )
232 }
233
234 fn sized_constraint(self, tcx: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
235 self.sized_constraint(tcx)
236 }
237
238 fn is_fundamental(self) -> bool {
239 self.is_fundamental()
240 }
241
242 fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<AdtDestructorKind> {
243 Some(match tcx.constness(self.destructor(tcx)?.did) {
244 hir::Constness::Const => AdtDestructorKind::Const,
245 hir::Constness::NotConst => AdtDestructorKind::NotConst,
246 })
247 }
248}
249
250#[derive(Copy, Clone, Debug, Eq, PartialEq, HashStable, TyEncodable, TyDecodable)]
251pub enum AdtKind {
252 Struct,
253 Union,
254 Enum,
255}
256
257impl From<AdtKind> for DataTypeKind {
258 fn from(val: AdtKind) -> Self {
259 match val {
260 AdtKind::Struct => DataTypeKind::Struct,
261 AdtKind::Union => DataTypeKind::Union,
262 AdtKind::Enum => DataTypeKind::Enum,
263 }
264 }
265}
266
267impl AdtDefData {
268 pub(super) fn new(
270 tcx: TyCtxt<'_>,
271 did: DefId,
272 kind: AdtKind,
273 variants: IndexVec<VariantIdx, VariantDef>,
274 repr: ReprOptions,
275 ) -> Self {
276 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
277 let mut flags = AdtFlags::NO_ADT_FLAGS;
278
279 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
280 debug!("found non-exhaustive variant list for {:?}", did);
281 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
282 }
283
284 flags |= match kind {
285 AdtKind::Enum => AdtFlags::IS_ENUM,
286 AdtKind::Union => AdtFlags::IS_UNION,
287 AdtKind::Struct => AdtFlags::IS_STRUCT,
288 };
289
290 if kind == AdtKind::Struct && variants[FIRST_VARIANT].ctor.is_some() {
291 flags |= AdtFlags::HAS_CTOR;
292 }
293
294 if tcx.has_attr(did, sym::fundamental) {
295 flags |= AdtFlags::IS_FUNDAMENTAL;
296 }
297 if tcx.is_lang_item(did, LangItem::PhantomData) {
298 flags |= AdtFlags::IS_PHANTOM_DATA;
299 }
300 if tcx.is_lang_item(did, LangItem::OwnedBox) {
301 flags |= AdtFlags::IS_BOX;
302 }
303 if tcx.is_lang_item(did, LangItem::ManuallyDrop) {
304 flags |= AdtFlags::IS_MANUALLY_DROP;
305 }
306 if tcx.is_lang_item(did, LangItem::UnsafeCell) {
307 flags |= AdtFlags::IS_UNSAFE_CELL;
308 }
309 if tcx.is_lang_item(did, LangItem::UnsafePinned) {
310 flags |= AdtFlags::IS_UNSAFE_PINNED;
311 }
312
313 AdtDefData { did, variants, flags, repr }
314 }
315}
316
317impl<'tcx> AdtDef<'tcx> {
318 #[inline]
320 pub fn is_struct(self) -> bool {
321 self.flags().contains(AdtFlags::IS_STRUCT)
322 }
323
324 #[inline]
326 pub fn is_union(self) -> bool {
327 self.flags().contains(AdtFlags::IS_UNION)
328 }
329
330 #[inline]
332 pub fn is_enum(self) -> bool {
333 self.flags().contains(AdtFlags::IS_ENUM)
334 }
335
336 #[inline]
342 pub fn is_variant_list_non_exhaustive(self) -> bool {
343 self.flags().contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
344 }
345
346 #[inline]
349 pub fn variant_list_has_applicable_non_exhaustive(self) -> bool {
350 self.is_variant_list_non_exhaustive() && !self.did().is_local()
351 }
352
353 #[inline]
355 pub fn adt_kind(self) -> AdtKind {
356 if self.is_enum() {
357 AdtKind::Enum
358 } else if self.is_union() {
359 AdtKind::Union
360 } else {
361 AdtKind::Struct
362 }
363 }
364
365 pub fn descr(self) -> &'static str {
367 match self.adt_kind() {
368 AdtKind::Struct => "struct",
369 AdtKind::Union => "union",
370 AdtKind::Enum => "enum",
371 }
372 }
373
374 #[inline]
376 pub fn variant_descr(self) -> &'static str {
377 match self.adt_kind() {
378 AdtKind::Struct => "struct",
379 AdtKind::Union => "union",
380 AdtKind::Enum => "variant",
381 }
382 }
383
384 #[inline]
386 pub fn has_ctor(self) -> bool {
387 self.flags().contains(AdtFlags::HAS_CTOR)
388 }
389
390 #[inline]
393 pub fn is_fundamental(self) -> bool {
394 self.flags().contains(AdtFlags::IS_FUNDAMENTAL)
395 }
396
397 #[inline]
399 pub fn is_phantom_data(self) -> bool {
400 self.flags().contains(AdtFlags::IS_PHANTOM_DATA)
401 }
402
403 #[inline]
405 pub fn is_box(self) -> bool {
406 self.flags().contains(AdtFlags::IS_BOX)
407 }
408
409 #[inline]
411 pub fn is_unsafe_cell(self) -> bool {
412 self.flags().contains(AdtFlags::IS_UNSAFE_CELL)
413 }
414
415 #[inline]
417 pub fn is_unsafe_pinned(self) -> bool {
418 self.flags().contains(AdtFlags::IS_UNSAFE_PINNED)
419 }
420
421 #[inline]
423 pub fn is_manually_drop(self) -> bool {
424 self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
425 }
426
427 pub fn has_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
429 self.destructor(tcx).is_some()
430 }
431
432 pub fn non_enum_variant(self) -> &'tcx VariantDef {
434 assert!(self.is_struct() || self.is_union());
435 self.variant(FIRST_VARIANT)
436 }
437
438 #[inline]
439 pub fn predicates(self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
440 tcx.predicates_of(self.did())
441 }
442
443 #[inline]
446 pub fn all_fields(self) -> impl Iterator<Item = &'tcx FieldDef> + Clone {
447 self.variants().iter().flat_map(|v| v.fields.iter())
448 }
449
450 pub fn is_payloadfree(self) -> bool {
453 if self.variants().iter().any(|v| {
463 matches!(v.discr, VariantDiscr::Explicit(_)) && v.ctor_kind() != Some(CtorKind::Const)
464 }) {
465 return false;
466 }
467 self.variants().iter().all(|v| v.fields.is_empty())
468 }
469
470 pub fn variant_with_id(self, vid: DefId) -> &'tcx VariantDef {
472 self.variants().iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
473 }
474
475 pub fn variant_with_ctor_id(self, cid: DefId) -> &'tcx VariantDef {
477 self.variants()
478 .iter()
479 .find(|v| v.ctor_def_id() == Some(cid))
480 .expect("variant_with_ctor_id: unknown variant")
481 }
482
483 #[inline]
485 pub fn variant_index_with_id(self, vid: DefId) -> VariantIdx {
486 self.variants()
487 .iter_enumerated()
488 .find(|(_, v)| v.def_id == vid)
489 .expect("variant_index_with_id: unknown variant")
490 .0
491 }
492
493 pub fn variant_index_with_ctor_id(self, cid: DefId) -> VariantIdx {
495 self.variants()
496 .iter_enumerated()
497 .find(|(_, v)| v.ctor_def_id() == Some(cid))
498 .expect("variant_index_with_ctor_id: unknown variant")
499 .0
500 }
501
502 pub fn variant_of_res(self, res: Res) -> &'tcx VariantDef {
503 match res {
504 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
505 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
506 Res::Def(DefKind::Struct, _)
507 | Res::Def(DefKind::Union, _)
508 | Res::Def(DefKind::TyAlias, _)
509 | Res::Def(DefKind::AssocTy, _)
510 | Res::SelfTyParam { .. }
511 | Res::SelfTyAlias { .. }
512 | Res::SelfCtor(..) => self.non_enum_variant(),
513 _ => bug!("unexpected res {:?} in variant_of_res", res),
514 }
515 }
516
517 #[inline]
518 pub fn eval_explicit_discr(
519 self,
520 tcx: TyCtxt<'tcx>,
521 expr_did: DefId,
522 ) -> Result<Discr<'tcx>, ErrorGuaranteed> {
523 assert!(self.is_enum());
524
525 let repr_type = self.repr().discr_type();
526 match tcx.const_eval_poly(expr_did) {
527 Ok(val) => {
528 let typing_env = ty::TypingEnv::post_analysis(tcx, expr_did);
529 let ty = repr_type.to_ty(tcx);
530 if let Some(b) = val.try_to_bits_for_ty(tcx, typing_env, ty) {
531 trace!("discriminants: {} ({:?})", b, repr_type);
532 Ok(Discr { val: b, ty })
533 } else {
534 info!("invalid enum discriminant: {:#?}", val);
535 let guar = tcx.dcx().emit_err(crate::error::ConstEvalNonIntError {
536 span: tcx.def_span(expr_did),
537 });
538 Err(guar)
539 }
540 }
541 Err(err) => {
542 let guar = match err {
543 ErrorHandled::Reported(info, _) => info.into(),
544 ErrorHandled::TooGeneric(..) => tcx.dcx().span_delayed_bug(
545 tcx.def_span(expr_did),
546 "enum discriminant depends on generics",
547 ),
548 };
549 Err(guar)
550 }
551 }
552 }
553
554 #[inline]
555 pub fn discriminants(
556 self,
557 tcx: TyCtxt<'tcx>,
558 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
559 assert!(self.is_enum());
560 let repr_type = self.repr().discr_type();
561 let initial = repr_type.initial_discriminant(tcx);
562 let mut prev_discr = None::<Discr<'tcx>>;
563 self.variants().iter_enumerated().map(move |(i, v)| {
564 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
565 if let VariantDiscr::Explicit(expr_did) = v.discr {
566 if let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
567 discr = new_discr;
568 }
569 }
570 prev_discr = Some(discr);
571
572 (i, discr)
573 })
574 }
575
576 #[inline]
577 pub fn variant_range(self) -> Range<VariantIdx> {
578 FIRST_VARIANT..self.variants().next_index()
579 }
580
581 #[inline]
587 pub fn discriminant_for_variant(
588 self,
589 tcx: TyCtxt<'tcx>,
590 variant_index: VariantIdx,
591 ) -> Discr<'tcx> {
592 assert!(self.is_enum());
593 let (val, offset) = self.discriminant_def_for_variant(variant_index);
594 let explicit_value = if let Some(expr_did) = val
595 && let Ok(val) = self.eval_explicit_discr(tcx, expr_did)
596 {
597 val
598 } else {
599 self.repr().discr_type().initial_discriminant(tcx)
600 };
601 explicit_value.checked_add(tcx, offset as u128).0
602 }
603
604 pub fn discriminant_def_for_variant(self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
608 assert!(!self.variants().is_empty());
609 let mut explicit_index = variant_index.as_u32();
610 let expr_did;
611 loop {
612 match self.variant(VariantIdx::from_u32(explicit_index)).discr {
613 ty::VariantDiscr::Relative(0) => {
614 expr_did = None;
615 break;
616 }
617 ty::VariantDiscr::Relative(distance) => {
618 explicit_index -= distance;
619 }
620 ty::VariantDiscr::Explicit(did) => {
621 expr_did = Some(did);
622 break;
623 }
624 }
625 }
626 (expr_did, variant_index.as_u32() - explicit_index)
627 }
628
629 pub fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
630 tcx.adt_destructor(self.did())
631 }
632
633 pub fn async_destructor(self, tcx: TyCtxt<'tcx>) -> Option<AsyncDestructor> {
636 tcx.adt_async_destructor(self.did())
637 }
638
639 pub fn sized_constraint(self, tcx: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
642 if self.is_struct() { tcx.adt_sized_constraint(self.did()) } else { None }
643 }
644}
645
646#[derive(Clone, Copy, Debug, HashStable)]
647pub enum Representability {
648 Representable,
649 Infinite(ErrorGuaranteed),
650}