sonatina_ir/
module.rs

1use std::sync::{Arc, Mutex};
2
3use cranelift_entity::{entity_impl, PrimaryMap};
4
5use crate::Function;
6
7use crate::{global_variable::GlobalVariableStore, isa::TargetIsa, types::TypeStore};
8
9use super::Linkage;
10
11#[derive(Debug)]
12pub struct Module {
13    /// Holds all function declared in the contract.
14    pub funcs: PrimaryMap<FuncRef, Function>,
15
16    pub ctx: ModuleCtx,
17}
18
19impl Module {
20    #[doc(hidden)]
21    pub fn new(isa: TargetIsa) -> Self {
22        Self {
23            funcs: PrimaryMap::default(),
24            ctx: ModuleCtx::new(isa),
25        }
26    }
27
28    /// Returns `func_ref` in the module.
29    pub fn iter_functions(&self) -> impl Iterator<Item = FuncRef> {
30        self.funcs.keys()
31    }
32
33    /// Returns `true` if the function has external linkage.
34    pub fn is_external(&self, func_ref: FuncRef) -> bool {
35        self.funcs[func_ref].sig.linkage() == Linkage::External
36    }
37}
38
39#[derive(Debug, Clone)]
40pub struct ModuleCtx {
41    pub isa: TargetIsa,
42    // TODO: Consider using `RwLock` instead of `Mutex`.
43    type_store: Arc<Mutex<TypeStore>>,
44    // TODO: Consider using `RwLock` instead of `Mutex`.
45    gv_store: Arc<Mutex<GlobalVariableStore>>,
46}
47
48impl ModuleCtx {
49    pub fn new(isa: TargetIsa) -> Self {
50        Self {
51            isa,
52            type_store: Arc::new(Mutex::new(TypeStore::default())),
53            gv_store: Arc::new(Mutex::new(GlobalVariableStore::default())),
54        }
55    }
56
57    pub fn with_ty_store<F, R>(&self, f: F) -> R
58    where
59        F: FnOnce(&TypeStore) -> R,
60    {
61        f(&self.type_store.lock().unwrap())
62    }
63
64    pub fn with_ty_store_mut<F, R>(&self, f: F) -> R
65    where
66        F: FnOnce(&mut TypeStore) -> R,
67    {
68        f(&mut self.type_store.lock().unwrap())
69    }
70
71    pub fn with_gv_store<F, R>(&self, f: F) -> R
72    where
73        F: FnOnce(&GlobalVariableStore) -> R,
74    {
75        f(&self.gv_store.lock().unwrap())
76    }
77
78    pub fn with_gv_store_mut<F, R>(&self, f: F) -> R
79    where
80        F: FnOnce(&mut GlobalVariableStore) -> R,
81    {
82        f(&mut self.gv_store.lock().unwrap())
83    }
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
87pub struct FuncRef(u32);
88entity_impl!(FuncRef);