]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/adt.rs
Rollup merge of #92425 - calebzulawski:simd-cast, r=workingjubilee
[rust.git] / compiler / rustc_middle / src / ty / adt.rs
1 use crate::mir::interpret::ErrorHandled;
2 use crate::ty;
3 use crate::ty::util::{Discr, IntTypeExt};
4 use rustc_data_structures::captures::Captures;
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::stable_hasher::HashingControls;
8 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
9 use rustc_errors::ErrorReported;
10 use rustc_hir as hir;
11 use rustc_hir::def::{CtorKind, DefKind, Res};
12 use rustc_hir::def_id::DefId;
13 use rustc_index::vec::{Idx, IndexVec};
14 use rustc_query_system::ich::StableHashingContext;
15 use rustc_session::DataTypeKind;
16 use rustc_span::symbol::sym;
17 use rustc_target::abi::VariantIdx;
18
19 use std::cell::RefCell;
20 use std::cmp::Ordering;
21 use std::hash::{Hash, Hasher};
22 use std::ops::Range;
23 use std::str;
24
25 use super::{
26     Destructor, FieldDef, GenericPredicates, ReprOptions, Ty, TyCtxt, VariantDef, VariantDiscr,
27 };
28
29 #[derive(Clone, HashStable, Debug)]
30 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
31
32 bitflags! {
33     #[derive(HashStable, TyEncodable, TyDecodable)]
34     pub struct AdtFlags: u32 {
35         const NO_ADT_FLAGS        = 0;
36         /// Indicates whether the ADT is an enum.
37         const IS_ENUM             = 1 << 0;
38         /// Indicates whether the ADT is a union.
39         const IS_UNION            = 1 << 1;
40         /// Indicates whether the ADT is a struct.
41         const IS_STRUCT           = 1 << 2;
42         /// Indicates whether the ADT is a struct and has a constructor.
43         const HAS_CTOR            = 1 << 3;
44         /// Indicates whether the type is `PhantomData`.
45         const IS_PHANTOM_DATA     = 1 << 4;
46         /// Indicates whether the type has a `#[fundamental]` attribute.
47         const IS_FUNDAMENTAL      = 1 << 5;
48         /// Indicates whether the type is `Box`.
49         const IS_BOX              = 1 << 6;
50         /// Indicates whether the type is `ManuallyDrop`.
51         const IS_MANUALLY_DROP    = 1 << 7;
52         /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
53         /// (i.e., this flag is never set unless this ADT is an enum).
54         const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
55     }
56 }
57
58 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
59 ///
60 /// These are all interned (by `alloc_adt_def`) into the global arena.
61 ///
62 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
63 /// This is slightly wrong because `union`s are not ADTs.
64 /// Moreover, Rust only allows recursive data types through indirection.
65 ///
66 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
67 ///
68 /// # Recursive types
69 ///
70 /// It may seem impossible to represent recursive types using [`Ty`],
71 /// since [`TyKind::Adt`] includes [`AdtDef`], which includes its fields,
72 /// creating a cycle. However, `AdtDef` does not actually include the *types*
73 /// of its fields; it includes just their [`DefId`]s.
74 ///
75 /// [`TyKind::Adt`]: ty::TyKind::Adt
76 ///
77 /// For example, the following type:
78 ///
79 /// ```
80 /// struct S { x: Box<S> }
81 /// ```
82 ///
83 /// is essentially represented with [`Ty`] as the following pseudocode:
84 ///
85 /// ```
86 /// struct S { x }
87 /// ```
88 ///
89 /// where `x` here represents the `DefId` of `S.x`. Then, the `DefId`
90 /// can be used with [`TyCtxt::type_of()`] to get the type of the field.
91 #[derive(TyEncodable, TyDecodable)]
92 pub struct AdtDef {
93     /// The `DefId` of the struct, enum or union item.
94     pub did: DefId,
95     /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
96     pub variants: IndexVec<VariantIdx, VariantDef>,
97     /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
98     flags: AdtFlags,
99     /// Repr options provided by the user.
100     pub repr: ReprOptions,
101 }
102
103 impl PartialOrd for AdtDef {
104     fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
105         Some(self.cmp(&other))
106     }
107 }
108
109 /// There should be only one AdtDef for each `did`, therefore
110 /// it is fine to implement `Ord` only based on `did`.
111 impl Ord for AdtDef {
112     fn cmp(&self, other: &AdtDef) -> Ordering {
113         self.did.cmp(&other.did)
114     }
115 }
116
117 /// There should be only one AdtDef for each `did`, therefore
118 /// it is fine to implement `PartialEq` only based on `did`.
119 impl PartialEq for AdtDef {
120     #[inline]
121     fn eq(&self, other: &Self) -> bool {
122         self.did == other.did
123     }
124 }
125
126 impl Eq for AdtDef {}
127
128 /// There should be only one AdtDef for each `did`, therefore
129 /// it is fine to implement `Hash` only based on `did`.
130 impl Hash for AdtDef {
131     #[inline]
132     fn hash<H: Hasher>(&self, s: &mut H) {
133         self.did.hash(s)
134     }
135 }
136
137 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
138     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
139         thread_local! {
140             static CACHE: RefCell<FxHashMap<(usize, HashingControls), Fingerprint>> = Default::default();
141         }
142
143         let hash: Fingerprint = CACHE.with(|cache| {
144             let addr = self as *const AdtDef as usize;
145             let hashing_controls = hcx.hashing_controls();
146             *cache.borrow_mut().entry((addr, hashing_controls)).or_insert_with(|| {
147                 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
148
149                 let mut hasher = StableHasher::new();
150                 did.hash_stable(hcx, &mut hasher);
151                 variants.hash_stable(hcx, &mut hasher);
152                 flags.hash_stable(hcx, &mut hasher);
153                 repr.hash_stable(hcx, &mut hasher);
154
155                 hasher.finish()
156             })
157         });
158
159         hash.hash_stable(hcx, hasher);
160     }
161 }
162
163 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, TyEncodable, TyDecodable)]
164 pub enum AdtKind {
165     Struct,
166     Union,
167     Enum,
168 }
169
170 impl Into<DataTypeKind> for AdtKind {
171     fn into(self) -> DataTypeKind {
172         match self {
173             AdtKind::Struct => DataTypeKind::Struct,
174             AdtKind::Union => DataTypeKind::Union,
175             AdtKind::Enum => DataTypeKind::Enum,
176         }
177     }
178 }
179
180 impl<'tcx> AdtDef {
181     /// Creates a new `AdtDef`.
182     pub(super) fn new(
183         tcx: TyCtxt<'_>,
184         did: DefId,
185         kind: AdtKind,
186         variants: IndexVec<VariantIdx, VariantDef>,
187         repr: ReprOptions,
188     ) -> Self {
189         debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
190         let mut flags = AdtFlags::NO_ADT_FLAGS;
191
192         if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
193             debug!("found non-exhaustive variant list for {:?}", did);
194             flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
195         }
196
197         flags |= match kind {
198             AdtKind::Enum => AdtFlags::IS_ENUM,
199             AdtKind::Union => AdtFlags::IS_UNION,
200             AdtKind::Struct => AdtFlags::IS_STRUCT,
201         };
202
203         if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
204             flags |= AdtFlags::HAS_CTOR;
205         }
206
207         let attrs = tcx.get_attrs(did);
208         if tcx.sess.contains_name(&attrs, sym::fundamental) {
209             flags |= AdtFlags::IS_FUNDAMENTAL;
210         }
211         if Some(did) == tcx.lang_items().phantom_data() {
212             flags |= AdtFlags::IS_PHANTOM_DATA;
213         }
214         if Some(did) == tcx.lang_items().owned_box() {
215             flags |= AdtFlags::IS_BOX;
216         }
217         if Some(did) == tcx.lang_items().manually_drop() {
218             flags |= AdtFlags::IS_MANUALLY_DROP;
219         }
220
221         AdtDef { did, variants, flags, repr }
222     }
223
224     /// Returns `true` if this is a struct.
225     #[inline]
226     pub fn is_struct(&self) -> bool {
227         self.flags.contains(AdtFlags::IS_STRUCT)
228     }
229
230     /// Returns `true` if this is a union.
231     #[inline]
232     pub fn is_union(&self) -> bool {
233         self.flags.contains(AdtFlags::IS_UNION)
234     }
235
236     /// Returns `true` if this is an enum.
237     #[inline]
238     pub fn is_enum(&self) -> bool {
239         self.flags.contains(AdtFlags::IS_ENUM)
240     }
241
242     /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
243     #[inline]
244     pub fn is_variant_list_non_exhaustive(&self) -> bool {
245         self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
246     }
247
248     /// Returns the kind of the ADT.
249     #[inline]
250     pub fn adt_kind(&self) -> AdtKind {
251         if self.is_enum() {
252             AdtKind::Enum
253         } else if self.is_union() {
254             AdtKind::Union
255         } else {
256             AdtKind::Struct
257         }
258     }
259
260     /// Returns a description of this abstract data type.
261     pub fn descr(&self) -> &'static str {
262         match self.adt_kind() {
263             AdtKind::Struct => "struct",
264             AdtKind::Union => "union",
265             AdtKind::Enum => "enum",
266         }
267     }
268
269     /// Returns a description of a variant of this abstract data type.
270     #[inline]
271     pub fn variant_descr(&self) -> &'static str {
272         match self.adt_kind() {
273             AdtKind::Struct => "struct",
274             AdtKind::Union => "union",
275             AdtKind::Enum => "variant",
276         }
277     }
278
279     /// If this function returns `true`, it implies that `is_struct` must return `true`.
280     #[inline]
281     pub fn has_ctor(&self) -> bool {
282         self.flags.contains(AdtFlags::HAS_CTOR)
283     }
284
285     /// Returns `true` if this type is `#[fundamental]` for the purposes
286     /// of coherence checking.
287     #[inline]
288     pub fn is_fundamental(&self) -> bool {
289         self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
290     }
291
292     /// Returns `true` if this is `PhantomData<T>`.
293     #[inline]
294     pub fn is_phantom_data(&self) -> bool {
295         self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
296     }
297
298     /// Returns `true` if this is Box<T>.
299     #[inline]
300     pub fn is_box(&self) -> bool {
301         self.flags.contains(AdtFlags::IS_BOX)
302     }
303
304     /// Returns `true` if this is `ManuallyDrop<T>`.
305     #[inline]
306     pub fn is_manually_drop(&self) -> bool {
307         self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
308     }
309
310     /// Returns `true` if this type has a destructor.
311     pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
312         self.destructor(tcx).is_some()
313     }
314
315     pub fn has_non_const_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
316         matches!(self.destructor(tcx), Some(Destructor { constness: hir::Constness::NotConst, .. }))
317     }
318
319     /// Asserts this is a struct or union and returns its unique variant.
320     pub fn non_enum_variant(&self) -> &VariantDef {
321         assert!(self.is_struct() || self.is_union());
322         &self.variants[VariantIdx::new(0)]
323     }
324
325     #[inline]
326     pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
327         tcx.predicates_of(self.did)
328     }
329
330     /// Returns an iterator over all fields contained
331     /// by this ADT.
332     #[inline]
333     pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
334         self.variants.iter().flat_map(|v| v.fields.iter())
335     }
336
337     /// Whether the ADT lacks fields. Note that this includes uninhabited enums,
338     /// e.g., `enum Void {}` is considered payload free as well.
339     pub fn is_payloadfree(&self) -> bool {
340         // Treat the ADT as not payload-free if arbitrary_enum_discriminant is used (#88621).
341         // This would disallow the following kind of enum from being casted into integer.
342         // ```
343         // enum Enum {
344         //    Foo() = 1,
345         //    Bar{} = 2,
346         //    Baz = 3,
347         // }
348         // ```
349         if self
350             .variants
351             .iter()
352             .any(|v| matches!(v.discr, VariantDiscr::Explicit(_)) && v.ctor_kind != CtorKind::Const)
353         {
354             return false;
355         }
356         self.variants.iter().all(|v| v.fields.is_empty())
357     }
358
359     /// Return a `VariantDef` given a variant id.
360     pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
361         self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
362     }
363
364     /// Return a `VariantDef` given a constructor id.
365     pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
366         self.variants
367             .iter()
368             .find(|v| v.ctor_def_id == Some(cid))
369             .expect("variant_with_ctor_id: unknown variant")
370     }
371
372     /// Return the index of `VariantDef` given a variant id.
373     pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
374         self.variants
375             .iter_enumerated()
376             .find(|(_, v)| v.def_id == vid)
377             .expect("variant_index_with_id: unknown variant")
378             .0
379     }
380
381     /// Return the index of `VariantDef` given a constructor id.
382     pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
383         self.variants
384             .iter_enumerated()
385             .find(|(_, v)| v.ctor_def_id == Some(cid))
386             .expect("variant_index_with_ctor_id: unknown variant")
387             .0
388     }
389
390     pub fn variant_of_res(&self, res: Res) -> &VariantDef {
391         match res {
392             Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
393             Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
394             Res::Def(DefKind::Struct, _)
395             | Res::Def(DefKind::Union, _)
396             | Res::Def(DefKind::TyAlias, _)
397             | Res::Def(DefKind::AssocTy, _)
398             | Res::SelfTy(..)
399             | Res::SelfCtor(..) => self.non_enum_variant(),
400             _ => bug!("unexpected res {:?} in variant_of_res", res),
401         }
402     }
403
404     #[inline]
405     pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
406         assert!(self.is_enum());
407         let param_env = tcx.param_env(expr_did);
408         let repr_type = self.repr.discr_type();
409         match tcx.const_eval_poly(expr_did) {
410             Ok(val) => {
411                 let ty = repr_type.to_ty(tcx);
412                 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
413                     trace!("discriminants: {} ({:?})", b, repr_type);
414                     Some(Discr { val: b, ty })
415                 } else {
416                     info!("invalid enum discriminant: {:#?}", val);
417                     crate::mir::interpret::struct_error(
418                         tcx.at(tcx.def_span(expr_did)),
419                         "constant evaluation of enum discriminant resulted in non-integer",
420                     )
421                     .emit();
422                     None
423                 }
424             }
425             Err(err) => {
426                 let msg = match err {
427                     ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
428                         "enum discriminant evaluation failed"
429                     }
430                     ErrorHandled::TooGeneric => "enum discriminant depends on generics",
431                 };
432                 tcx.sess.delay_span_bug(tcx.def_span(expr_did), msg);
433                 None
434             }
435         }
436     }
437
438     #[inline]
439     pub fn discriminants(
440         &'tcx self,
441         tcx: TyCtxt<'tcx>,
442     ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
443         assert!(self.is_enum());
444         let repr_type = self.repr.discr_type();
445         let initial = repr_type.initial_discriminant(tcx);
446         let mut prev_discr = None::<Discr<'tcx>>;
447         self.variants.iter_enumerated().map(move |(i, v)| {
448             let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
449             if let VariantDiscr::Explicit(expr_did) = v.discr {
450                 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
451                     discr = new_discr;
452                 }
453             }
454             prev_discr = Some(discr);
455
456             (i, discr)
457         })
458     }
459
460     #[inline]
461     pub fn variant_range(&self) -> Range<VariantIdx> {
462         VariantIdx::new(0)..VariantIdx::new(self.variants.len())
463     }
464
465     /// Computes the discriminant value used by a specific variant.
466     /// Unlike `discriminants`, this is (amortized) constant-time,
467     /// only doing at most one query for evaluating an explicit
468     /// discriminant (the last one before the requested variant),
469     /// assuming there are no constant-evaluation errors there.
470     #[inline]
471     pub fn discriminant_for_variant(
472         &self,
473         tcx: TyCtxt<'tcx>,
474         variant_index: VariantIdx,
475     ) -> Discr<'tcx> {
476         assert!(self.is_enum());
477         let (val, offset) = self.discriminant_def_for_variant(variant_index);
478         let explicit_value = val
479             .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
480             .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
481         explicit_value.checked_add(tcx, offset as u128).0
482     }
483
484     /// Yields a `DefId` for the discriminant and an offset to add to it
485     /// Alternatively, if there is no explicit discriminant, returns the
486     /// inferred discriminant directly.
487     pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
488         assert!(!self.variants.is_empty());
489         let mut explicit_index = variant_index.as_u32();
490         let expr_did;
491         loop {
492             match self.variants[VariantIdx::from_u32(explicit_index)].discr {
493                 ty::VariantDiscr::Relative(0) => {
494                     expr_did = None;
495                     break;
496                 }
497                 ty::VariantDiscr::Relative(distance) => {
498                     explicit_index -= distance;
499                 }
500                 ty::VariantDiscr::Explicit(did) => {
501                     expr_did = Some(did);
502                     break;
503                 }
504             }
505         }
506         (expr_did, variant_index.as_u32() - explicit_index)
507     }
508
509     pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
510         tcx.adt_destructor(self.did)
511     }
512
513     /// Returns a list of types such that `Self: Sized` if and only
514     /// if that type is `Sized`, or `TyErr` if this type is recursive.
515     ///
516     /// Oddly enough, checking that the sized-constraint is `Sized` is
517     /// actually more expressive than checking all members:
518     /// the `Sized` trait is inductive, so an associated type that references
519     /// `Self` would prevent its containing ADT from being `Sized`.
520     ///
521     /// Due to normalization being eager, this applies even if
522     /// the associated type is behind a pointer (e.g., issue #31299).
523     pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
524         tcx.adt_sized_constraint(self.did).0
525     }
526 }