1use std::collections::{HashMap, HashSet};
4
5use crate::Instruction;
6
7#[derive(Debug, Clone)]
9pub struct Module {
10 pub name: String,
12
13 pub code: Vec<Instruction>,
16
17 pub functions: HashMap<(String, u8), FunctionDef>,
19
20 pub exports: HashSet<(String, u8)>,
22}
23
24#[derive(Debug, Clone)]
26pub struct FunctionDef {
27 pub name: String,
29
30 pub arity: u8,
32
33 pub entry: usize,
35}
36
37impl Module {
38 pub fn new(name: String) -> Self {
40 Self {
41 name,
42 code: Vec::new(),
43 functions: HashMap::new(),
44 exports: HashSet::new(),
45 }
46 }
47
48 pub fn add_function(&mut self, name: String, arity: u8, code: Vec<Instruction>) {
53 let entry = self.code.len();
54
55 self.code.extend(code);
56 self.functions
57 .insert((name.clone(), arity), FunctionDef { name, arity, entry });
58 }
59
60 pub fn add_function_at(&mut self, name: String, arity: u8, entry: usize) {
64 self.functions
65 .insert((name.clone(), arity), FunctionDef { name, arity, entry });
66 }
67
68 pub fn export(&mut self, name: &str, arity: u8) {
70 self.exports.insert((name.to_string(), arity));
71 }
72
73 pub fn get_function(&self, name: &str, arity: u8) -> Option<&FunctionDef> {
75 self.functions.get(&(name.to_string(), arity))
76 }
77
78 pub fn is_exported(&self, name: &str, arity: u8) -> bool {
80 self.exports.contains(&(name.to_string(), arity))
81 }
82}