Skip to main content

charon_lib/ast/items/
type_decl.rs

1use derive_generic_visitor::*;
2use enum_as_inner::EnumAsInner;
3use serde::{Deserialize, Serialize};
4use serde_state::{DeserializeState, SerializeState};
5
6use crate::ast::*;
7use crate::ids::IndexVec;
8use crate::utils::serialize_map_to_array::SeqHashMapToArray;
9
10/// A type declaration.
11///
12/// Types can be opaque or transparent.
13///
14/// Transparent types are local types not marked as opaque.
15/// Opaque types are the others: local types marked as opaque, and non-local
16/// types (coming from external dependencies).
17///
18/// In case the type is transparent, the declaration also contains the
19/// type definition (see [TypeDeclKind]).
20///
21/// A type can only be an ADT (structure or enumeration), as type aliases are
22/// inlined in MIR.
23#[derive(Debug, Clone)]
24#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
25#[serde_state(state_implements = DedupSerializerState)]
26pub struct TypeDecl {
27    pub def_id: TypeDeclId,
28    /// Meta information associated with the item.
29    pub item_meta: ItemMeta,
30    pub generics: GenericParams,
31    /// The context of the type: distinguishes top-level items from closure-related items etc.
32    pub src: TypeSource,
33    /// The type kind: enum, struct, or opaque.
34    pub kind: TypeDeclKind,
35    /// The layout of the type for each target. Information may be partial because of generics or
36    /// dynamically-sized types. If we cannot compute a layout, the target has no entry.
37    pub layout: TargetLayouts,
38    /// The layouts of the monomorphic instances of this type that were reached while translating.
39    /// This is empty in monomorphic mode, or when the type is already monomorphic; just use `layout` instead.
40    #[serde(with = "SeqHashMapToArray::<GenericArgs, TargetLayouts>")]
41    pub monomorphic_layouts: SeqHashMap<GenericArgs, TargetLayouts>,
42    /// The metadata associated with a pointer to the type.
43    pub ptr_metadata: PtrMetadata,
44    /// Which built-in marker traits are implemented by this type. This is only known for
45    /// monomorphic types.
46    pub marker_traits: Option<Box<ImplementsMarkerTraits>>,
47}
48
49generate_index_type!(VariantId, "Variant");
50generate_index_type!(FieldId, "Field");
51
52#[derive(Debug, Clone)]
53#[derive(EnumAsInner)]
54#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
55pub enum TypeDeclKind {
56    Struct(IndexVec<FieldId, Field>),
57    Enum(IndexVec<VariantId, Variant>),
58    Union(IndexVec<FieldId, Field>),
59    /// An opaque type.
60    ///
61    /// Either a local type marked as opaque, or an external type.
62    Opaque,
63    /// An alias to another type. This only shows up in the top-level list of items, as rustc
64    /// inlines uses of type aliases everywhere else.
65    Alias(Ty),
66    /// Used if an error happened during the extraction, and we don't panic
67    /// on error.
68    #[cfg_attr(feature = "charon_on_charon", charon::rename("TDeclError"))]
69    Error(String),
70}
71
72#[derive(Debug, Clone)]
73#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
74#[serde_state(stateless)]
75pub struct Variant {
76    pub id: VariantId,
77    pub span: Span,
78    pub attr_info: AttrInfo,
79    #[cfg_attr(feature = "charon_on_charon", charon::rename("variant_name"))]
80    pub name: String,
81    #[serde_state(stateful)]
82    pub fields: IndexVec<FieldId, Field>,
83    /// The discriminant value outputted by `std::mem::discriminant` for this variant. This can be
84    /// different than the value stored in memory (called `tag`); that one is described by
85    /// [`Discriminator`] and [`VariantLayout::tagger`].
86    pub discriminant: IntegerValue,
87}
88
89#[derive(Debug, Clone)]
90#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
91#[serde_state(stateless)]
92pub struct Field {
93    pub span: Span,
94    pub attr_info: AttrInfo,
95    #[cfg_attr(feature = "charon_on_charon", charon::rename("field_name"))]
96    pub name: String,
97    /// Whether this field is positional, as in a tuple struct, tuple variant, or closure. If so,
98    /// its name is based on its position, such as `_0`; otherwise, it is a user-provided name.
99    pub is_positional: bool,
100    #[cfg_attr(feature = "charon_on_charon", charon::rename("field_ty"))]
101    #[serde_state(stateful)]
102    pub ty: Ty,
103}
104
105/// The metadata stored in a pointer. That's the information stored in pointers alongside
106/// their address. It's empty for `Sized` types, and interesting for unsized
107/// aka dynamically-sized types.
108#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
109#[derive(EnumAsInner)]
110#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
111#[serde_state(default_state = ())]
112pub enum PtrMetadata {
113    /// Types that need no metadata, namely `T: Sized` types.
114    #[cfg_attr(feature = "charon_on_charon", charon::rename("NoMetadata"))]
115    None,
116    /// Metadata for `[T]` and `str`, and user-defined types
117    /// that directly or indirectly contain one of the two.
118    /// Of type `usize`.
119    /// Notably, length for `[T]` denotes the number of elements in the slice.
120    /// While for `str` it denotes the number of bytes in the string.
121    Length,
122    /// Metadata for `dyn Trait`, referring to the vtable struct. Has type `&'static vtable`
123    VTable(TypeDeclRef),
124    /// Unknown due to generics, but will inherit from the given type.
125    /// This is consistent with `<Ty as Pointee>::Metadata`.
126    /// Of type `TyKind::Metadata(Ty)`.
127    InheritFrom(Ty),
128}
129
130/// Where a given type came from.
131#[derive(Debug, Clone)]
132#[derive(EnumAsInner)]
133#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
134#[cfg_attr(feature = "charon_on_charon", charon::variants_suffix("Type"))]
135pub enum TypeSource {
136    /// A normal type declaration.
137    Normal,
138    /// The struct that carries the captured variables of a closure.
139    Closure { info: ClosureInfo },
140    /// Defines the vtable struct for a trait.
141    VTable {
142        /// The `dyn Trait` predicate implemented by this vtable.
143        dyn_predicate: DynPredicate,
144        /// Record what each vtable field means.
145        field_map: IndexVec<FieldId, VTableField>,
146        /// For each implied clause that is also a supertrait clause, records which field of the
147        /// vtable corresponds to it.
148        supertrait_map: IndexVec<TraitClauseId, Option<FieldId>>,
149    },
150    /// A type declaration synthesised for a builtin ADT.
151    Builtin(BuiltinAdt),
152}
153
154/// Which marker traits this type implements.
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
157#[serde_state(stateless)]
158pub struct ImplementsMarkerTraits {
159    pub is_sized: bool,
160    pub is_send: bool,
161    pub is_sync: bool,
162    pub is_freeze: bool,
163    pub is_unpin: bool,
164}
165
166#[derive(Debug, Clone, PartialEq, Eq)]
167#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
168#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("VTable"))]
169pub enum VTableField {
170    Size,
171    Align,
172    Drop,
173    Method(TraitMethodId, MetadataPath),
174    SuperTrait(TraitClauseId),
175}
176
177/// Additional information for closures.
178#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
179#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
180pub struct ClosureInfo {
181    #[serde_state(stateless)]
182    pub kind: ClosureKind,
183    /// The `FnFoo::call` method that contains the closure body.
184    pub closure_body: FunDeclRef,
185    /// The `FnOnce` implementation of this closure -- always exists.
186    pub fn_once_impl: RegionBinder<TraitImplRef>,
187    /// The `FnMut` implementation of this closure, if any.
188    pub fn_mut_impl: Option<RegionBinder<TraitImplRef>>,
189    /// The `Fn` implementation of this closure, if any.
190    pub fn_impl: Option<RegionBinder<TraitImplRef>>,
191    /// The signature of the function that this closure represents.
192    pub signature: RegionBinder<FunSig>,
193}
194
195#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
196#[derive(Serialize, Deserialize, Drive, DriveMut, DriveTwo)]
197pub enum ClosureKind {
198    Fn,
199    FnMut,
200    FnOnce,
201}
202
203impl TypeDecl {
204    pub fn get_fields(&self, variant: Option<VariantId>) -> Option<&IndexVec<FieldId, Field>> {
205        match &self.kind {
206            TypeDeclKind::Struct(fields) | TypeDeclKind::Union(fields) => Some(fields),
207            TypeDeclKind::Enum(variants) => Some(&variants[variant.unwrap()].fields),
208            _ => None,
209        }
210    }
211
212    pub fn get_field(&self, variant: Option<VariantId>, field: FieldId) -> Option<&Field> {
213        self.get_fields(variant)?.get(field)
214    }
215
216    pub fn get_field_by_name(
217        &self,
218        variant: Option<VariantId>,
219        field_name: &str,
220    ) -> Option<(FieldId, &Field)> {
221        let fields = match &self.kind {
222            TypeDeclKind::Struct(fields) | TypeDeclKind::Union(fields) => fields,
223            TypeDeclKind::Enum(variants) => &variants[variant.unwrap()].fields,
224            _ => return None,
225        };
226        fields
227            .iter_enumerated()
228            .find(|(_, field)| field.name == field_name)
229    }
230
231    /// Returns a `TypeDeclRef` that refers to this type declaration, with identity generic arguments.
232    pub fn self_ref(&self) -> TypeDeclRef {
233        TypeDeclRef {
234            id: self.def_id,
235            generics: Box::new(self.generics.identity_args()),
236            builtin: self.src.as_builtin().cloned(),
237        }
238    }
239}
240
241impl Variant {
242    /// The new name for this variant, as suggested by the `#[charon::rename]` and
243    /// `#[charon::variants_prefix]` attributes.
244    pub fn renamed_name(&self) -> &str {
245        self.attr_info
246            .rename
247            .as_deref()
248            .unwrap_or(self.name.as_ref())
249    }
250
251    /// Whether this variant has a `#[charon::opaque]` annotation.
252    pub fn is_opaque(&self) -> bool {
253        self.attr_info
254            .attributes
255            .iter()
256            .any(|attr| attr.is_opaque())
257    }
258}
259
260impl Field {
261    /// The new name for this field, as suggested by the `#[charon::rename]` attribute.
262    pub fn renamed_name(&self) -> &str {
263        self.attr_info.rename.as_deref().unwrap_or(&self.name)
264    }
265
266    /// Whether this field has a `#[charon::opaque]` annotation.
267    pub fn is_opaque(&self) -> bool {
268        self.attr_info
269            .attributes
270            .iter()
271            .any(|attr| attr.is_opaque())
272    }
273}
274
275impl ClosureKind {
276    // pub fn trait_name(self) -> &'static str {}
277    pub fn method_name(self) -> &'static str {
278        match self {
279            ClosureKind::FnOnce => "call_once",
280            ClosureKind::FnMut => "call_mut",
281            ClosureKind::Fn => "call",
282        }
283    }
284}
285
286impl PtrMetadata {
287    pub fn into_type(self) -> Ty {
288        match self {
289            PtrMetadata::None => Ty::mk_unit(),
290            PtrMetadata::Length => Ty::mk_usize(),
291            PtrMetadata::VTable(type_decl_ref) => Ty::new(TyKind::Ref(
292                Region::Static,
293                Ty::new(TyKind::Adt(type_decl_ref)),
294                RefKind::Shared,
295            )),
296            PtrMetadata::InheritFrom(ty) => Ty::new(TyKind::PtrMetadata(ty)),
297        }
298    }
299}