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::captures::Captures;
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_ANONYMOUS = 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 sized_constraint(self, tcx: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
234 self.sized_constraint(tcx)
235 }
236
237 fn is_fundamental(self) -> bool {
238 self.is_fundamental()
239 }
240
241 fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<AdtDestructorKind> {
242 Some(match self.destructor(tcx)?.constness {
243 hir::Constness::Const => AdtDestructorKind::Const,
244 hir::Constness::NotConst => AdtDestructorKind::NotConst,
245 })
246 }
247}
248
249#[derive(Copy, Clone, Debug, Eq, PartialEq, HashStable, TyEncodable, TyDecodable)]
250pub enum AdtKind {
251 Struct,
252 Union,
253 Enum,
254}
255
256impl From<AdtKind> for DataTypeKind {
257 fn from(val: AdtKind) -> Self {
258 match val {
259 AdtKind::Struct => DataTypeKind::Struct,
260 AdtKind::Union => DataTypeKind::Union,
261 AdtKind::Enum => DataTypeKind::Enum,
262 }
263 }
264}
265
266impl AdtDefData {
267 pub(super) fn new(
269 tcx: TyCtxt<'_>,
270 did: DefId,
271 kind: AdtKind,
272 variants: IndexVec<VariantIdx, VariantDef>,
273 repr: ReprOptions,
274 ) -> Self {
275 debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
276 let mut flags = AdtFlags::NO_ADT_FLAGS;
277
278 if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
279 debug!("found non-exhaustive variant list for {:?}", did);
280 flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
281 }
282
283 flags |= match kind {
284 AdtKind::Enum => AdtFlags::IS_ENUM,
285 AdtKind::Union => AdtFlags::IS_UNION,
286 AdtKind::Struct => AdtFlags::IS_STRUCT,
287 };
288
289 if kind == AdtKind::Struct && variants[FIRST_VARIANT].ctor.is_some() {
290 flags |= AdtFlags::HAS_CTOR;
291 }
292
293 if tcx.has_attr(did, sym::fundamental) {
294 flags |= AdtFlags::IS_FUNDAMENTAL;
295 }
296 if tcx.is_lang_item(did, LangItem::PhantomData) {
297 flags |= AdtFlags::IS_PHANTOM_DATA;
298 }
299 if tcx.is_lang_item(did, LangItem::OwnedBox) {
300 flags |= AdtFlags::IS_BOX;
301 }
302 if tcx.is_lang_item(did, LangItem::ManuallyDrop) {
303 flags |= AdtFlags::IS_MANUALLY_DROP;
304 }
305 if tcx.is_lang_item(did, LangItem::UnsafeCell) {
306 flags |= AdtFlags::IS_UNSAFE_CELL;
307 }
308
309 AdtDefData { did, variants, flags, repr }
310 }
311}
312
313impl<'tcx> AdtDef<'tcx> {
314 #[inline]
316 pub fn is_struct(self) -> bool {
317 self.flags().contains(AdtFlags::IS_STRUCT)
318 }
319
320 #[inline]
322 pub fn is_union(self) -> bool {
323 self.flags().contains(AdtFlags::IS_UNION)
324 }
325
326 #[inline]
328 pub fn is_enum(self) -> bool {
329 self.flags().contains(AdtFlags::IS_ENUM)
330 }
331
332 #[inline]
334 pub fn is_variant_list_non_exhaustive(self) -> bool {
335 self.flags().contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
336 }
337
338 #[inline]
340 pub fn adt_kind(self) -> AdtKind {
341 if self.is_enum() {
342 AdtKind::Enum
343 } else if self.is_union() {
344 AdtKind::Union
345 } else {
346 AdtKind::Struct
347 }
348 }
349
350 pub fn descr(self) -> &'static str {
352 match self.adt_kind() {
353 AdtKind::Struct => "struct",
354 AdtKind::Union => "union",
355 AdtKind::Enum => "enum",
356 }
357 }
358
359 #[inline]
361 pub fn variant_descr(self) -> &'static str {
362 match self.adt_kind() {
363 AdtKind::Struct => "struct",
364 AdtKind::Union => "union",
365 AdtKind::Enum => "variant",
366 }
367 }
368
369 #[inline]
371 pub fn has_ctor(self) -> bool {
372 self.flags().contains(AdtFlags::HAS_CTOR)
373 }
374
375 #[inline]
378 pub fn is_fundamental(self) -> bool {
379 self.flags().contains(AdtFlags::IS_FUNDAMENTAL)
380 }
381
382 #[inline]
384 pub fn is_phantom_data(self) -> bool {
385 self.flags().contains(AdtFlags::IS_PHANTOM_DATA)
386 }
387
388 #[inline]
390 pub fn is_box(self) -> bool {
391 self.flags().contains(AdtFlags::IS_BOX)
392 }
393
394 #[inline]
396 pub fn is_unsafe_cell(self) -> bool {
397 self.flags().contains(AdtFlags::IS_UNSAFE_CELL)
398 }
399
400 #[inline]
402 pub fn is_manually_drop(self) -> bool {
403 self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
404 }
405
406 #[inline]
408 pub fn is_anonymous(self) -> bool {
409 self.flags().contains(AdtFlags::IS_ANONYMOUS)
410 }
411
412 pub fn has_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
414 self.destructor(tcx).is_some()
415 }
416
417 pub fn non_enum_variant(self) -> &'tcx VariantDef {
419 assert!(self.is_struct() || self.is_union());
420 self.variant(FIRST_VARIANT)
421 }
422
423 #[inline]
424 pub fn predicates(self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
425 tcx.predicates_of(self.did())
426 }
427
428 #[inline]
431 pub fn all_fields(self) -> impl Iterator<Item = &'tcx FieldDef> + Clone {
432 self.variants().iter().flat_map(|v| v.fields.iter())
433 }
434
435 pub fn is_payloadfree(self) -> bool {
438 if self.variants().iter().any(|v| {
448 matches!(v.discr, VariantDiscr::Explicit(_)) && v.ctor_kind() != Some(CtorKind::Const)
449 }) {
450 return false;
451 }
452 self.variants().iter().all(|v| v.fields.is_empty())
453 }
454
455 pub fn variant_with_id(self, vid: DefId) -> &'tcx VariantDef {
457 self.variants().iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
458 }
459
460 pub fn variant_with_ctor_id(self, cid: DefId) -> &'tcx VariantDef {
462 self.variants()
463 .iter()
464 .find(|v| v.ctor_def_id() == Some(cid))
465 .expect("variant_with_ctor_id: unknown variant")
466 }
467
468 #[inline]
470 pub fn variant_index_with_id(self, vid: DefId) -> VariantIdx {
471 self.variants()
472 .iter_enumerated()
473 .find(|(_, v)| v.def_id == vid)
474 .expect("variant_index_with_id: unknown variant")
475 .0
476 }
477
478 pub fn variant_index_with_ctor_id(self, cid: DefId) -> VariantIdx {
480 self.variants()
481 .iter_enumerated()
482 .find(|(_, v)| v.ctor_def_id() == Some(cid))
483 .expect("variant_index_with_ctor_id: unknown variant")
484 .0
485 }
486
487 pub fn variant_of_res(self, res: Res) -> &'tcx VariantDef {
488 match res {
489 Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
490 Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
491 Res::Def(DefKind::Struct, _)
492 | Res::Def(DefKind::Union, _)
493 | Res::Def(DefKind::TyAlias, _)
494 | Res::Def(DefKind::AssocTy, _)
495 | Res::SelfTyParam { .. }
496 | Res::SelfTyAlias { .. }
497 | Res::SelfCtor(..) => self.non_enum_variant(),
498 _ => bug!("unexpected res {:?} in variant_of_res", res),
499 }
500 }
501
502 #[inline]
503 pub fn eval_explicit_discr(
504 self,
505 tcx: TyCtxt<'tcx>,
506 expr_did: DefId,
507 ) -> Result<Discr<'tcx>, ErrorGuaranteed> {
508 assert!(self.is_enum());
509
510 let repr_type = self.repr().discr_type();
511 match tcx.const_eval_poly(expr_did) {
512 Ok(val) => {
513 let typing_env = ty::TypingEnv::post_analysis(tcx, expr_did);
514 let ty = repr_type.to_ty(tcx);
515 if let Some(b) = val.try_to_bits_for_ty(tcx, typing_env, ty) {
516 trace!("discriminants: {} ({:?})", b, repr_type);
517 Ok(Discr { val: b, ty })
518 } else {
519 info!("invalid enum discriminant: {:#?}", val);
520 let guar = tcx.dcx().emit_err(crate::error::ConstEvalNonIntError {
521 span: tcx.def_span(expr_did),
522 });
523 Err(guar)
524 }
525 }
526 Err(err) => {
527 let guar = match err {
528 ErrorHandled::Reported(info, _) => info.into(),
529 ErrorHandled::TooGeneric(..) => tcx.dcx().span_delayed_bug(
530 tcx.def_span(expr_did),
531 "enum discriminant depends on generics",
532 ),
533 };
534 Err(guar)
535 }
536 }
537 }
538
539 #[inline]
540 pub fn discriminants(
541 self,
542 tcx: TyCtxt<'tcx>,
543 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
544 assert!(self.is_enum());
545 let repr_type = self.repr().discr_type();
546 let initial = repr_type.initial_discriminant(tcx);
547 let mut prev_discr = None::<Discr<'tcx>>;
548 self.variants().iter_enumerated().map(move |(i, v)| {
549 let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
550 if let VariantDiscr::Explicit(expr_did) = v.discr {
551 if let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
552 discr = new_discr;
553 }
554 }
555 prev_discr = Some(discr);
556
557 (i, discr)
558 })
559 }
560
561 #[inline]
562 pub fn variant_range(self) -> Range<VariantIdx> {
563 FIRST_VARIANT..self.variants().next_index()
564 }
565
566 #[inline]
572 pub fn discriminant_for_variant(
573 self,
574 tcx: TyCtxt<'tcx>,
575 variant_index: VariantIdx,
576 ) -> Discr<'tcx> {
577 assert!(self.is_enum());
578 let (val, offset) = self.discriminant_def_for_variant(variant_index);
579 let explicit_value = if let Some(expr_did) = val
580 && let Ok(val) = self.eval_explicit_discr(tcx, expr_did)
581 {
582 val
583 } else {
584 self.repr().discr_type().initial_discriminant(tcx)
585 };
586 explicit_value.checked_add(tcx, offset as u128).0
587 }
588
589 pub fn discriminant_def_for_variant(self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
593 assert!(!self.variants().is_empty());
594 let mut explicit_index = variant_index.as_u32();
595 let expr_did;
596 loop {
597 match self.variant(VariantIdx::from_u32(explicit_index)).discr {
598 ty::VariantDiscr::Relative(0) => {
599 expr_did = None;
600 break;
601 }
602 ty::VariantDiscr::Relative(distance) => {
603 explicit_index -= distance;
604 }
605 ty::VariantDiscr::Explicit(did) => {
606 expr_did = Some(did);
607 break;
608 }
609 }
610 }
611 (expr_did, variant_index.as_u32() - explicit_index)
612 }
613
614 pub fn destructor(self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
615 tcx.adt_destructor(self.did())
616 }
617
618 pub fn async_destructor(self, tcx: TyCtxt<'tcx>) -> Option<AsyncDestructor> {
621 tcx.adt_async_destructor(self.did())
622 }
623
624 pub fn sized_constraint(self, tcx: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
627 if self.is_struct() { tcx.adt_sized_constraint(self.did()) } else { None }
628 }
629}
630
631#[derive(Clone, Copy, Debug, HashStable)]
632pub enum Representability {
633 Representable,
634 Infinite(ErrorGuaranteed),
635}