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