Skip to main content

charon_lib/ast/
krate.rs

1use std::fmt;
2
3use derive_generic_visitor::{Drive, DriveMut, DriveTwo};
4use index_vec::Idx;
5use itertools::Itertools;
6use serde::{Deserialize, Serialize};
7use serde_state::{DeserializeState, SerializeState};
8
9use crate::ast::*;
10use crate::formatter::{AstFormatter, FmtCtx, IntoFormatter};
11use crate::ids::{IndexMap, IndexVec};
12use crate::pretty::FmtWithCtx;
13use crate::utils::serialize_map_to_array::SeqHashMapToArray;
14use enum_as_inner::EnumAsInner;
15
16/// A target triple, e.g. `x86_64-unknown-linux-gnu`.
17pub type TargetTriple = String;
18
19/// The complete data of a Rust crate.
20///
21/// A crate is mainly composed of 5 kinds of items:
22/// - Functions;
23/// - Type definitions;
24/// - Globals (constants and statics);
25/// - Trait declarations;
26/// - Trait implementations.
27///
28/// These can each be found in the corresponding `IndexVec`. They are in an unspecified (though
29/// deterministic) order.
30/// If you need a more robust order, see `ordered_decls`.
31///
32/// To get a `TranslatedCrate`, run `charon cargo` inside a Rust crate, then deserialize
33/// the resulting `crate_name.llbc` file using [`crate::deserialize_llbc`].
34#[derive(Default, Clone)]
35#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
36#[serde_state(state_implements = DedupSerializerState)]
37pub struct TranslatedCrate {
38    /// The name of the crate.
39    pub crate_name: String,
40
41    /// The preset used when calling Charon. Can be used to check that Charon was called with the
42    /// preset that a given consumer requires.
43    #[serde_state(stateless)]
44    pub preset: Option<crate::options::Preset>,
45
46    /// Information about each target platform for which the crate was translated. When translating
47    /// a crate normally this will have a single entry; when using `--targets` this will have one
48    /// entry per chosen target.
49    #[serde(with = "SeqHashMapToArray::<TargetTriple, TargetInfo>")]
50    pub target_information: SeqHashMap<TargetTriple, TargetInfo>,
51    /// Values of the runtime checks enabled for this crate.
52    #[serde_state(stateless)]
53    pub runtime_checks: RuntimeChecks,
54
55    /// The source files composing the crate and its dependencies. Each [`Span`] refers to a byte
56    /// range within one of these files.
57    // This field must come before any field containing spans, as the OCaml deserialization of
58    // spans requires the files to be deserialized already.
59    #[serde_state(stateless)]
60    pub files: IndexVec<FileId, File>,
61
62    /// The names of all registered items. Available so we can know the names even of items that
63    /// failed to translate.
64    /// Invariant: after translation, any existing `ItemId` must have an associated name, even
65    /// if the corresponding item wasn't translated.
66    #[serde(with = "SeqHashMapToArray::<ItemId, Name>")]
67    pub item_names: SeqHashMap<ItemId, Name>,
68    /// The names of all the registered associated items. Available so we can know the names even
69    /// of items that failed to translate.
70    /// Invariant: after translation, any existing `AssocItemId` must have an associated name, even
71    /// if the corresponding item wasn't translated.
72    pub assoc_item_names: IndexMap<TraitDeclId, AssocItemNames>,
73    /// Short names, for items whose last PathElem is unique.
74    #[serde(with = "SeqHashMapToArray::<ItemId, Name>")]
75    pub short_names: SeqHashMap<ItemId, Name>,
76
77    /// The type definitions (structs, enums, ...).
78    pub type_decls: IndexMap<TypeDeclId, TypeDecl>,
79    /// The function definitions.
80    ///
81    /// Each item with a body becomes a function: actual functions, methods, and unevaluated
82    /// consts/statics.
83    pub fun_decls: IndexMap<FunDeclId, FunDecl>,
84    /// The global definitions, which are constants, statics, and thread locals.
85    pub global_decls: IndexMap<GlobalDeclId, GlobalDecl>,
86    /// The trait declarations.
87    pub trait_decls: IndexMap<TraitDeclId, TraitDecl>,
88    /// The trait implementations.
89    pub trait_impls: IndexMap<TraitImplId, TraitImpl>,
90
91    /// For binary crates only, the function that runs when the program starts.
92    pub entry_point: Option<FunDeclRef>,
93
94    /// This contains a list of all the reachable items in the crate in a stable, logical order
95    /// based on crate and file order, then further grouped and sorted such that every item comes
96    /// after the items it depends on.
97    /// Mutually-dependent groups of items are identified as such.
98    /// This is meant for code-generation tools that want a stable output order.
99    ///
100    /// Not all the items in the `TranslatedCrate` are included: some trait impls are never
101    /// referred to by reachable items so could in principle be removed from the crate, but we keep
102    /// them around to be able to tell method implementations apart.
103    ///
104    /// `Some` after translation unless `--no-reorder-decls` is passed.
105    #[serde_state(stateless)]
106    pub ordered_decls: Option<Vec<DeclarationGroup>>,
107}
108
109#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
110#[derive(Serialize, Deserialize, Drive, DriveMut, DriveTwo)]
111pub struct RuntimeChecks {
112    pub ub_checks: bool,
113    pub overflow_checks: bool,
114    pub contract_checks: bool,
115}
116
117/// A (group of) top-level declaration(s), properly reordered.
118/// "G" stands for "generic"
119#[derive(Debug, Clone)]
120#[derive(EnumAsInner)]
121#[derive(Serialize, Deserialize)]
122#[cfg_attr(feature = "charon_on_charon", charon::variants_suffix("Group"))]
123pub enum GDeclarationGroup<Id> {
124    /// A non-recursive declaration
125    NonRec(Id),
126    /// A (group of mutually) recursive declaration(s)
127    Rec(Vec<Id>),
128}
129
130/// A (group of) top-level declaration(s), properly reordered.
131#[derive(Debug, Clone)]
132#[derive(EnumAsInner)]
133#[derive(Serialize, Deserialize)]
134#[cfg_attr(feature = "charon_on_charon", charon::variants_suffix("Group"))]
135pub enum DeclarationGroup {
136    /// A type declaration group
137    Type(GDeclarationGroup<TypeDeclId>),
138    /// A function declaration group
139    Fun(GDeclarationGroup<FunDeclId>),
140    /// A global declaration group
141    Global(GDeclarationGroup<GlobalDeclId>),
142    TraitDecl(GDeclarationGroup<TraitDeclId>),
143    TraitImpl(GDeclarationGroup<TraitImplId>),
144    /// Anything that doesn't fit into these categories.
145    Mixed(GDeclarationGroup<ItemId>),
146}
147
148#[derive(Default, Clone)]
149#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
150pub struct AssocItemNames {
151    pub types: IndexVec<AssocTypeId, TraitItemName>,
152    pub methods: IndexVec<TraitMethodId, TraitItemName>,
153    pub consts: IndexVec<AssocConstId, TraitItemName>,
154}
155
156impl TranslatedCrate {
157    pub fn item_name(&self, id: impl Into<ItemId>) -> &Name {
158        // `unwrap` is ok because we ensure to translate the item name as soon as we create a new
159        // item id.
160        self.item_names.get(&id.into()).unwrap()
161    }
162    pub fn assoc_item_name(
163        &self,
164        trait_id: TraitDeclId,
165        id: impl Into<AssocItemId>,
166    ) -> TraitItemName {
167        let names = &self.assoc_item_names[trait_id];
168        match id.into() {
169            AssocItemId::Type(id) => names.types[id],
170            AssocItemId::Method(id) => names.methods[id],
171            AssocItemId::Const(id) => names.consts[id],
172        }
173    }
174
175    pub fn item_short_name(&self, id: impl Into<ItemId>) -> &Name {
176        let id = id.into();
177        self.short_names
178            .get(&id)
179            .unwrap_or_else(|| self.item_name(id))
180    }
181
182    pub fn get_item(&self, trans_id: impl Into<ItemId>) -> Option<ItemRef<'_>> {
183        match trans_id.into() {
184            ItemId::Type(id) => self.type_decls.get(id).map(ItemRef::Type),
185            ItemId::Fun(id) => self.fun_decls.get(id).map(ItemRef::Fun),
186            ItemId::Global(id) => self.global_decls.get(id).map(ItemRef::Global),
187            ItemId::TraitDecl(id) => self.trait_decls.get(id).map(ItemRef::TraitDecl),
188            ItemId::TraitImpl(id) => self.trait_impls.get(id).map(ItemRef::TraitImpl),
189        }
190    }
191    pub fn get_item_mut(&mut self, trans_id: ItemId) -> Option<ItemRefMut<'_>> {
192        match trans_id {
193            ItemId::Type(id) => self.type_decls.get_mut(id).map(ItemRefMut::Type),
194            ItemId::Fun(id) => self.fun_decls.get_mut(id).map(ItemRefMut::Fun),
195            ItemId::Global(id) => self.global_decls.get_mut(id).map(ItemRefMut::Global),
196            ItemId::TraitDecl(id) => self.trait_decls.get_mut(id).map(ItemRefMut::TraitDecl),
197            ItemId::TraitImpl(id) => self.trait_impls.get_mut(id).map(ItemRefMut::TraitImpl),
198        }
199    }
200
201    /// Remove this item from the crate, including the name information about it.
202    ///
203    /// See also [`TranslatedCrate::remove_item_temporarily`].
204    pub fn remove_item(&mut self, trans_id: ItemId) -> Option<ItemByVal> {
205        self.short_names.swap_remove(&trans_id);
206        self.item_names.swap_remove(&trans_id);
207        self.remove_item_temporarily(trans_id)
208    }
209    /// Insert a new item into a slot, and record its name in the name map.
210    pub fn set_new_item_slot(&mut self, id: ItemId, item: impl Into<ItemByVal>) {
211        let item = item.into();
212        self.item_names
213            .insert(id, item.as_ref().item_meta().name.clone());
214        self.put_item_back(id, item);
215    }
216    /// Remove this item from the crate without touching the name maps.
217    /// Useful for modifying items whilst being able to access the rest of the crate.
218    /// Put the item back using [`TranslatedCrate::put_item_back`].
219    ///
220    /// See also [`TranslatedCrate::remove_item`].
221    pub fn remove_item_temporarily(&mut self, trans_id: ItemId) -> Option<ItemByVal> {
222        match trans_id {
223            ItemId::Type(id) => self.type_decls.remove(id).map(ItemByVal::Type),
224            ItemId::Fun(id) => self.fun_decls.remove(id).map(ItemByVal::Fun),
225            ItemId::Global(id) => self.global_decls.remove(id).map(ItemByVal::Global),
226            ItemId::TraitDecl(id) => self.trait_decls.remove(id).map(ItemByVal::TraitDecl),
227            ItemId::TraitImpl(id) => self.trait_impls.remove(id).map(ItemByVal::TraitImpl),
228        }
229    }
230    /// Insert the item into the corresponding slot without recording its name in the name map.
231    /// Only use if the item already has its name registered, e.g. if you got it using
232    /// [`TranslatedCrate::remove_item_temporarily`].
233    pub fn put_item_back(&mut self, id: ItemId, item: impl Into<ItemByVal>) {
234        match item.into() {
235            ItemByVal::Type(decl) => self.type_decls.set_slot(*id.as_type().unwrap(), decl),
236            ItemByVal::Fun(decl) => self.fun_decls.set_slot(*id.as_fun().unwrap(), decl),
237            ItemByVal::Global(decl) => self.global_decls.set_slot(*id.as_global().unwrap(), decl),
238            ItemByVal::TraitDecl(decl) => self
239                .trait_decls
240                .set_slot(*id.as_trait_decl().unwrap(), decl),
241            ItemByVal::TraitImpl(decl) => self
242                .trait_impls
243                .set_slot(*id.as_trait_impl().unwrap(), decl),
244        }
245    }
246
247    pub fn all_ids(&self) -> impl Iterator<Item = ItemId> + use<> {
248        self.type_decls
249            .all_indices()
250            .map(ItemId::Type)
251            .chain(self.trait_decls.all_indices().map(ItemId::TraitDecl))
252            .chain(self.trait_impls.all_indices().map(ItemId::TraitImpl))
253            .chain(self.global_decls.all_indices().map(ItemId::Global))
254            .chain(self.fun_decls.all_indices().map(ItemId::Fun))
255    }
256    pub fn all_items(&self) -> impl Iterator<Item = ItemRef<'_>> {
257        self.type_decls
258            .iter()
259            .map(ItemRef::Type)
260            .chain(self.trait_decls.iter().map(ItemRef::TraitDecl))
261            .chain(self.trait_impls.iter().map(ItemRef::TraitImpl))
262            .chain(self.global_decls.iter().map(ItemRef::Global))
263            .chain(self.fun_decls.iter().map(ItemRef::Fun))
264    }
265    pub fn all_items_mut(&mut self) -> impl Iterator<Item = ItemRefMut<'_>> {
266        self.type_decls
267            .iter_mut()
268            .map(ItemRefMut::Type)
269            .chain(self.trait_impls.iter_mut().map(ItemRefMut::TraitImpl))
270            .chain(self.trait_decls.iter_mut().map(ItemRefMut::TraitDecl))
271            .chain(self.fun_decls.iter_mut().map(ItemRefMut::Fun))
272            .chain(self.global_decls.iter_mut().map(ItemRefMut::Global))
273    }
274    pub fn all_items_with_ids(&self) -> impl Iterator<Item = (ItemId, ItemRef<'_>)> {
275        self.all_items().map(|item| (item.id(), item))
276    }
277
278    /// Iterate over all reachable items in dependency order. Panics if `--no-reorder-decls` cas
279    /// passed to Charon.
280    pub fn in_dependency_order(&self) -> impl Iterator<Item = ItemId> + '_ {
281        self.ordered_decls
282            .as_ref()
283            .expect(
284                "`in_dependency_order` no available if \
285                `--no-reorder-decls` was passed to Charon",
286            )
287            .iter()
288            .flat_map(DeclarationGroup::get_ids)
289    }
290
291    /// When translating without `--target`, there's only one target information; this method
292    /// retrieves it.
293    /// Panics if this crate was translated in multi-target mode.
294    pub fn the_target_information(&self) -> &TargetInfo {
295        self.target_information
296            .values()
297            .exactly_one()
298            .expect("called `the_target_information` on a multi-target crate")
299    }
300}
301
302impl fmt::Display for TranslatedCrate {
303    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
304        let fmt: &FmtCtx = &self.into_fmt();
305        self.fmt_with_ctx(fmt, f)
306    }
307}
308
309impl<C: AstFormatter> FmtWithCtx<C> for TranslatedCrate {
310    fn fmt_with_ctx(&self, fmt: &C, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311        if let Some(entry_point) = &self.entry_point {
312            writeln!(f, "// Entry point: {}\n", entry_point.with_ctx(fmt))?
313        }
314        match &self.ordered_decls {
315            None => {
316                // We do simple: types, globals, traits, functions
317                for d in &self.type_decls {
318                    writeln!(f, "{}\n", d.with_ctx(fmt))?
319                }
320                for d in &self.global_decls {
321                    writeln!(f, "{}\n", d.with_ctx(fmt))?
322                }
323                for d in &self.trait_decls {
324                    writeln!(f, "{}\n", d.with_ctx(fmt))?
325                }
326                for d in &self.trait_impls {
327                    writeln!(f, "{}\n", d.with_ctx(fmt))?
328                }
329                for d in &self.fun_decls {
330                    writeln!(f, "{}\n", d.with_ctx(fmt))?
331                }
332            }
333            Some(ordered_decls) => {
334                for gr in ordered_decls {
335                    for id in gr.get_ids() {
336                        match self.get_item(id) {
337                            Some(decl) => writeln!(f, "{}\n", decl.with_ctx(fmt))?,
338                            None => {
339                                let name = self.item_short_name(id).with_ctx(fmt);
340                                writeln!(f, "Missing decl: {id:?} ({name})\n")?;
341                            }
342                        }
343                    }
344                }
345            }
346        }
347        fmt::Result::Ok(())
348    }
349}
350
351impl<'a> IntoFormatter for &'a TranslatedCrate {
352    type C = FmtCtx<'a>;
353
354    fn into_fmt(self) -> Self::C {
355        FmtCtx {
356            translated: Some(self),
357            ..Default::default()
358        }
359    }
360}
361
362pub trait HasIdxMapOf<Id: Idx>: std::ops::Index<Id, Output: Sized> {
363    fn get_idx_map(&self) -> &IndexMap<Id, Self::Output>;
364    fn get_idx_map_mut(&mut self) -> &mut IndexMap<Id, Self::Output>;
365}
366
367/// Delegate `Index` implementations to subfields.
368macro_rules! mk_index_impls {
369    ($ty:ident.$field:ident[$idx:ty]: $output:ty) => {
370        impl std::ops::Index<$idx> for $ty {
371            type Output = $output;
372            fn index(&self, index: $idx) -> &Self::Output {
373                &self.$field[index]
374            }
375        }
376        impl std::ops::IndexMut<$idx> for $ty {
377            fn index_mut(&mut self, index: $idx) -> &mut Self::Output {
378                &mut self.$field[index]
379            }
380        }
381        impl HasIdxMapOf<$idx> for $ty {
382            fn get_idx_map(&self) -> &IndexMap<$idx, Self::Output> {
383                &self.$field
384            }
385            fn get_idx_map_mut(&mut self) -> &mut IndexMap<$idx, Self::Output> {
386                &mut self.$field
387            }
388        }
389    };
390}
391mk_index_impls!(TranslatedCrate.type_decls[TypeDeclId]: TypeDecl);
392mk_index_impls!(TranslatedCrate.fun_decls[FunDeclId]: FunDecl);
393mk_index_impls!(TranslatedCrate.global_decls[GlobalDeclId]: GlobalDecl);
394mk_index_impls!(TranslatedCrate.trait_decls[TraitDeclId]: TraitDecl);
395mk_index_impls!(TranslatedCrate.trait_impls[TraitImplId]: TraitImpl);