Skip to main content

vihaco_syntax/
lib.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4//! Typed SST parsing built from pattern-derived instruction and type syntax.
5//!
6//! A section's `.text` is a flat instruction stream, not structured code:
7//!
8//! ```text
9//! @main:
10//! execution::program::call 0, @helper
11//! execution::program::ret 1
12//! @helper:
13//! execution::program::const_u64 21
14//! execution::program::ret 1
15//! ```
16//!
17//! `@name:` binds a symbol to the address of the next instruction and occupies
18//! no slot; `@name` in an operand refers to a symbol and is resolved through the
19//! section's symbol table during lowering. Each statement (a symbol definition,
20//! an instruction, or `@name:` followed by an instruction) ends at the end of
21//! its line and continues onto the next line only inside an open bracket; see
22//! [`statements()`]. Indentation carries no meaning and `;` starts a comment.
23//! What a symbol *is* lives in the header: a function is a symbol with a
24//! matching `.func @name(...)` directive, which supplies its signature and
25//! locals. Its executable range runs from its symbol to the next function
26//! symbol.
27//!
28//! [`ParsedModule::parse_section`] yields the header, the code stream, and the
29//! symbol table. [`ParsedModule::lower_with_metadata`] validates them against
30//! the metadata, lowers instructions with their `Lower<C>` implementations,
31//! and assembles a module. Its context can use
32//! `vihaco_module::loader::MetadataLoweringContext` directly or wrap it to add
33//! consumer capabilities.
34//!
35//! With `program-image-execution`, `HeaderDeclarations<D>` parses a collection
36//! of declarations, one per line. The standard directives
37//! (`vihaco_module::module::ProgramDirective`: `.file`, `.func`, `.entry`,
38//! `.const`, `.source_symbol`) are pushed into a
39//! `vihaco_module::module::ProgramHeader`, which assembles the metadata;
40//! consumers apply their own declarations to an application-owned preparation
41//! context, then call `lower_code_with_metadata` with the completed metadata
42//! and instruction context. This supports contexts borrowing prepared
43//! configuration without moving the metadata during lowering.
44//!
45//! See `vihaco-stdlib/examples/loadable.rs` for standard and application
46//! directives in one header, metadata validation, and execution using dialect
47//! instructions consumed by components. Feature-off consumers retain the
48//! separate `Resolve` bridge.
49
50mod lower;
51mod types;
52
53pub use lower::lower_code;
54
55#[cfg(feature = "program-image-execution")]
56mod header;
57
58#[cfg(feature = "program-image-execution")]
59pub use header::HeaderDeclarations;
60
61#[cfg(feature = "program-image-execution")]
62pub use lower::lower_code_with_metadata;
63
64pub mod parse;
65#[cfg(not(feature = "typed-declarations"))]
66pub mod resolve;
67pub mod spanned;
68pub mod statements;
69
70pub use types::{ParsedModule, Symbol};
71pub use vihaco_parser::SurfaceInstruction;
72
73pub use parse::{block_i64_flat, block_i64_pairs, skip, symbol_definition};
74#[cfg(not(feature = "typed-declarations"))]
75pub use resolve::Resolve;
76pub use spanned::{
77    ParsedDeclarations, ParsedText, Spanned, SyntaxError, parse_declarations,
78    parse_declarations_at, parse_text, parse_text_at,
79};
80pub use statements::{Statement, Statements, statements};
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85    use chumsky::Parser as _;
86
87    // Minimal stub: an enum that derives Parse and has just two unit variants.
88    // Avoids pulling vihaco-cpu/-fpga into the test (cycle).
89    #[derive(Debug, Clone, PartialEq, vihaco_parser_derive::Parse)]
90    #[syntax_class(instruction, head = "stub")]
91    enum StubInst {
92        Halt,
93        Print,
94    }
95
96    #[derive(Debug, Clone, PartialEq)]
97    struct NoHeader;
98
99    impl vihaco_abi::traits::FromText for NoHeader {
100        fn from_text(_: &str) -> eyre::Result<Self> {
101            Ok(Self)
102        }
103    }
104
105    impl vihaco_bytecode::SSTHeader for NoHeader {}
106
107    fn parse(text: &str) -> eyre::Result<ParsedModule<StubInst, NoHeader>> {
108        let source = format!("sst v2\n.section main\n.text\n{text}");
109        let file = vihaco_bytecode::SSTFile::<vihaco_bytecode::NoContext>::from_text(&source)?;
110        ParsedModule::<StubInst, NoHeader>::parse_section(file.section("main").unwrap())
111    }
112
113    fn symbols(parsed: &ParsedModule<StubInst, NoHeader>) -> Vec<(&str, u32)> {
114        parsed
115            .symbols
116            .iter()
117            .map(|symbol| (symbol.name.as_str(), symbol.address))
118            .collect()
119    }
120
121    #[test]
122    fn parses_empty_text() {
123        let parsed = parse("").unwrap();
124        assert!(parsed.code.is_empty());
125        assert!(parsed.symbols.is_empty());
126    }
127
128    #[test]
129    fn symbols_bind_the_next_address_without_occupying_slots() {
130        let parsed = parse("@entry:\n@alias:\nstub.halt\nstub.print\n@exit:\n").unwrap();
131        assert_eq!(parsed.code, [StubInst::Halt, StubInst::Print]);
132        assert_eq!(symbols(&parsed), [("entry", 0), ("alias", 0), ("exit", 2)]);
133    }
134
135    #[test]
136    fn indentation_carries_no_meaning() {
137        let flat = parse("@main:\nstub.halt\n@done:\nstub.print\n").unwrap();
138        let indented = parse("    @main:\n\t\tstub.halt\n  @done:   stub.print   \n").unwrap();
139        let crlf = parse("@main: stub.halt\r\n@done: stub.print\r\n").unwrap();
140        assert_eq!(flat, indented);
141        assert_eq!(flat, crlf);
142    }
143
144    #[test]
145    fn statements_end_at_the_end_of_the_line() {
146        let err = parse("@main: stub.halt stub.print\n").unwrap_err();
147        assert!(
148            err.to_string().contains(
149                "expected end of line after the instruction `stub.halt`, found `stub.print`"
150            ),
151            "{err}"
152        );
153        assert!(parse("@main: @done: stub.halt\n").is_err());
154    }
155
156    #[test]
157    fn skips_line_comments() {
158        let parsed = parse("; leading\n@main: ; the entry\n    stub.halt ; stop\n").unwrap();
159        assert_eq!(parsed.code, [StubInst::Halt]);
160        assert_eq!(symbols(&parsed), [("main", 0)]);
161    }
162
163    #[test]
164    fn rejects_unknown_or_malformed_text() {
165        assert!(parse("foo bar 1 2.0").is_err());
166        assert!(
167            parse("@main").is_err(),
168            "a bare reference is not a definition"
169        );
170        assert!(parse("@: stub.halt").is_err());
171        assert!(parse("fn @main() { stub.halt }").is_err());
172    }
173
174    #[test]
175    fn text_errors_name_the_first_problem_by_file_line_and_column() {
176        let err = parse("stub.halt\n  foo bar\n@main\n").unwrap_err();
177        assert_eq!(
178            err.to_string(),
179            "failed to parse `.text` of section `main`: line 5, column 3: \
180             expected an instruction, found `foo` (and 1 more error)"
181        );
182    }
183
184    #[test]
185    fn rejects_malformed_known_instruction() {
186        #[derive(Debug, Clone, PartialEq, vihaco_parser_derive::Parse)]
187        #[syntax_class(instruction, head = "stub")]
188        enum OnlyOne {
189            Dump(u32),
190        }
191
192        let file = vihaco_bytecode::SSTFile::<vihaco_bytecode::NoContext>::from_text(
193            "sst v2\n.section main\n.text\nstub.dump foo\n",
194        )
195        .unwrap();
196        assert!(
197            ParsedModule::<OnlyOne, NoHeader>::parse_section(file.section("main").unwrap())
198                .is_err()
199        );
200    }
201
202    #[test]
203    fn lexical_helpers_return_explicit_newtypes() {
204        assert_eq!(
205            symbol_definition().parse("@main:").into_result(),
206            Ok("main".to_owned())
207        );
208        assert_eq!(
209            parse::symbol_ref().parse("@main").into_result(),
210            Ok(vihaco_parser::Ident("main".to_owned()))
211        );
212        assert_eq!(
213            parse::string_literal()
214                .parse("\"hello\\nworld\"")
215                .into_result(),
216            Ok(vihaco_parser::QuotedString("hello\nworld".to_owned()))
217        );
218    }
219
220    #[test]
221    fn block_i64_flat_parses_whitespace_separated_ints() {
222        let got = block_i64_flat().parse(" 0 1 2 3 ").into_result().unwrap();
223        assert_eq!(got, vec![0, 1, 2, 3]);
224    }
225
226    #[test]
227    fn block_i64_pairs_parses_rows() {
228        let got = block_i64_pairs()
229            .parse("\n  1 1\n  5 1\n  1 5\n")
230            .into_result()
231            .unwrap();
232        assert_eq!(got, vec![(1, 1), (5, 1), (1, 5)]);
233    }
234
235    #[test]
236    fn block_i64_flat_accepts_empty() {
237        let got = block_i64_flat().parse("").into_result().unwrap();
238        assert!(got.is_empty());
239    }
240}