miden_assembly_syntax/library/
module.rs

1use alloc::{sync::Arc, vec::Vec};
2
3use midenc_hir_type::FunctionType;
4
5use super::LibraryPath;
6use crate::{
7    Word,
8    ast::{AttributeSet, ProcedureIndex, ProcedureName},
9};
10
11// MODULE INFO
12// ================================================================================================
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct ModuleInfo {
16    path: LibraryPath,
17    procedures: Vec<ProcedureInfo>,
18}
19
20impl ModuleInfo {
21    /// Returns a new [`ModuleInfo`] instantiated library path.
22    pub fn new(path: LibraryPath) -> Self {
23        Self { path, procedures: Vec::new() }
24    }
25
26    /// Adds a procedure to the module.
27    pub fn add_procedure(
28        &mut self,
29        name: ProcedureName,
30        digest: Word,
31        signature: Option<Arc<FunctionType>>,
32        attributes: AttributeSet,
33    ) {
34        self.procedures.push(ProcedureInfo { name, digest, signature, attributes });
35    }
36
37    /// Returns the module's library path.
38    pub fn path(&self) -> &LibraryPath {
39        &self.path
40    }
41
42    /// Returns the number of procedures in the module.
43    pub fn num_procedures(&self) -> usize {
44        self.procedures.len()
45    }
46
47    /// Returns the [`ProcedureInfo`] of the procedure at the provided index, if any.
48    pub fn get_procedure_by_index(&self, index: ProcedureIndex) -> Option<&ProcedureInfo> {
49        self.procedures.get(index.as_usize())
50    }
51
52    /// Returns the digest of the procedure with the provided name, if any.
53    pub fn get_procedure_digest_by_name(&self, name: &ProcedureName) -> Option<Word> {
54        self.procedures.iter().find_map(|proc_info| {
55            if &proc_info.name == name {
56                Some(proc_info.digest)
57            } else {
58                None
59            }
60        })
61    }
62
63    /// Returns an iterator over the procedure infos in the module with their corresponding
64    /// procedure index in the module.
65    pub fn procedures(&self) -> impl Iterator<Item = (ProcedureIndex, &ProcedureInfo)> {
66        self.procedures
67            .iter()
68            .enumerate()
69            .map(|(idx, proc)| (ProcedureIndex::new(idx), proc))
70    }
71
72    /// Returns an iterator over the MAST roots of procedures defined in this module.
73    pub fn procedure_digests(&self) -> impl Iterator<Item = Word> + '_ {
74        self.procedures.iter().map(|p| p.digest)
75    }
76}
77
78/// Stores the name and digest of a procedure.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct ProcedureInfo {
81    pub name: ProcedureName,
82    pub digest: Word,
83    pub signature: Option<Arc<FunctionType>>,
84    pub attributes: AttributeSet,
85}