Skip to main content

vihaco_module/
module.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4use crate::color::Themed;
5pub use crate::program_header::{
6    ConstantDirective, ConstantValue, Focus, FunctionDirective, HeaderError, ProgramDirective,
7    ProgramHeader, StandardDirective,
8};
9pub use crate::program_metadata::ProgramMetadata;
10
11/// A module for a single section.
12#[derive(Debug, Clone, PartialEq)]
13pub struct LocalModule<I, V, Ty, Info = NoInfo> {
14    pub code: Vec<I>,
15    pub functions: Vec<FunctionInfo<Ty>>,
16    /// The section's symbol table: every `@name:` definition and its address.
17    pub symbols: Vec<Symbol>,
18    pub constants: Vec<V>,
19    pub strings: Vec<String>,
20    pub main_function: Option<u32>,
21    pub source_symbols: Vec<SourceSymbolInfo>,
22    pub extra: Info,
23}
24
25impl<I, V, Ty, Info> Default for LocalModule<I, V, Ty, Info>
26where
27    Info: Default,
28{
29    fn default() -> Self {
30        Self {
31            code: Vec::new(),
32            functions: Vec::new(),
33            symbols: Vec::new(),
34            constants: Vec::new(),
35            strings: Vec::new(),
36            main_function: None,
37            source_symbols: Vec::new(),
38            extra: Info::default(),
39        }
40    }
41}
42
43/// A source-level symbol, declared by `.source_symbol <index> "<name>"`.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct SourceSymbolInfo {
46    pub index: u32,
47    pub name: String,
48}
49
50/// A function's runtime record: its declaration plus the executable range
51/// resolved from the section's symbol table.
52#[derive(Debug, Clone, PartialEq)]
53pub struct FunctionInfo<Type> {
54    pub name: u32, // index into the string interner
55    pub signature: Signature<Type>,
56    /// Reserved local slots, including parameters, for this function.
57    pub local_count: u32,
58    /// Address of the function's symbol definition.
59    pub start_address: u32,
60    /// Exclusive end: the next function symbol's address, or the code length.
61    pub end_address: u32,
62    pub file: u32,
63}
64
65/// A function declaration, assembled from a `.func` header directive.
66///
67/// It carries everything about a function except where it is: the executable
68/// range comes from the `@name:` symbol definition with the same name in the
69/// section's `.text`.
70#[derive(Debug, Clone, PartialEq)]
71pub struct FunctionDecl<Type> {
72    pub name: u32, // index into the string interner
73    pub signature: Signature<Type>,
74    /// Reserved local slots, including parameters, for this function.
75    pub local_count: u32,
76    pub file: u32,
77}
78
79#[derive(Debug, Clone, PartialEq)]
80pub struct Signature<Ty> {
81    pub params: Vec<Parameter<Ty>>,
82    pub ret: Vec<Ty>,
83}
84
85#[derive(Debug, Clone, PartialEq)]
86pub struct Parameter<Ty> {
87    pub name: u32, // index into the string interner
88    pub ty: Ty,
89}
90
91/// One symbol table entry: a name bound to an instruction address.
92///
93/// Symbols are defined in `.text` as `@name:` and occupy no instruction slot;
94/// `address` is the index of the next instruction (possibly the code length).
95/// References such as `@name` in operands are resolved through this table.
96#[derive(Debug, Clone, PartialEq, Eq, Hash)]
97pub struct Symbol {
98    pub name: String,
99    pub address: u32,
100}
101
102#[derive(Debug, Clone, PartialEq, Default, vihaco_parser_derive::Parse)]
103#[syntax_class(metadata)]
104#[pattern = "`{` `}`"]
105pub struct NoInfo;
106
107impl std::fmt::Display for NoInfo {
108    fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        Ok(())
110    }
111}
112
113impl<I, V, Ty, Info> std::fmt::Display for LocalModule<I, V, Ty, Info>
114where
115    I: std::fmt::Display,
116    V: std::fmt::Display,
117    Ty: std::fmt::Display,
118    Info: std::fmt::Display,
119{
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        ".text".keyword().fmt(f)?;
122        writeln!(f)?;
123
124        for (addr, inst) in self.code.iter().enumerate() {
125            write!(f, "0x{:04X} ", addr)?;
126            inst.fmt(f)?;
127            writeln!(f)?;
128        }
129
130        writeln!(f)?;
131        ".const".keyword().fmt(f)?;
132        writeln!(f)?;
133        for (const_idx, constant) in self.constants.iter().enumerate() {
134            write!(f, "0x{:04X} ", const_idx)?;
135            constant.fmt(f)?;
136            writeln!(f)?;
137        }
138
139        writeln!(f)?;
140        ".string".keyword().fmt(f)?;
141        writeln!(f)?;
142        for (string_idx, string) in self.strings.iter().enumerate() {
143            if string_idx > 0 {
144                writeln!(f)?;
145            }
146            write!(f, "0x{:04X} \"{}\"", string_idx, string.escape_default())?;
147        }
148
149        writeln!(f)?;
150        if !self.source_symbols.is_empty() {
151            ".machine".keyword().fmt(f)?;
152            writeln!(f, " symbols {{")?;
153            for symbol in &self.source_symbols {
154                writeln!(f, "  {}: {},", symbol.index, symbol.name)?;
155            }
156            writeln!(f, "}}")?;
157            writeln!(f)?;
158        }
159        writeln!(f)?;
160        ".feature".keyword().fmt(f)?;
161        writeln!(f)?;
162        self.extra.fmt(f)?;
163        Ok(())
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[derive(Debug, Clone, PartialEq)]
172    enum MockInst {
173        Push(u64),
174        Add,
175        Print,
176        Halt,
177    }
178
179    impl std::fmt::Display for MockInst {
180        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181            match self {
182                MockInst::Push(v) => write!(f, "push {}", v),
183                MockInst::Add => write!(f, "add"),
184                MockInst::Print => write!(f, "print"),
185                MockInst::Halt => write!(f, "halt"),
186            }
187        }
188    }
189
190    #[test]
191    fn test_module() {
192        let mut module: LocalModule<MockInst, u64, &str> = LocalModule::default();
193        module.code.push(MockInst::Push(42));
194        module.code.push(MockInst::Push(42));
195        module.code.push(MockInst::Add);
196        module.code.push(MockInst::Print);
197        module.code.push(MockInst::Halt);
198
199        module.constants.push(42);
200        module.constants.push(100);
201
202        module.strings.push("hello".to_string());
203        module.strings.push("world".to_string());
204        println!("{:#}", module);
205    }
206}