Skip to main content

vihaco_syntax/
parse.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4//! chumsky-0.10 combinators for the parsed-syntax shape.
5//!
6//! [`ParsedModule::parse_section`] is generic over the consumer's instruction
7//! type `I` and section-header type `H`.
8
9use chumsky::error::Simple;
10use chumsky::extra;
11use chumsky::prelude::*;
12use vihaco_parser::{Ident, QuotedString};
13
14use vihaco_bytecode::SSTHeader;
15use vihaco_bytecode::SSTSectionView;
16
17use crate::ParsedModule;
18
19type E<'src> = extra::Err<Simple<'src, char>>;
20
21/// Whitespace and `;`-to-end-of-line comments. Zero-or-more.
22///
23/// This skips newlines too; SST statements are split at line ends before the
24/// combinators run (see [`crate::statements()`]).
25pub fn skip<'src>() -> impl Parser<'src, &'src str, (), E<'src>> + Clone {
26    vihaco_parser::trivia()
27}
28
29/// `"…"` with `\\`, `\"`, `\n`, `\t`, `\r` escape sequences.
30pub fn string_literal<'src>() -> impl Parser<'src, &'src str, QuotedString, E<'src>> + Clone {
31    let escape = just('\\').ignore_then(choice((
32        just('"').to('"'),
33        just('\\').to('\\'),
34        just('n').to('\n'),
35        just('t').to('\t'),
36        just('r').to('\r'),
37        just('0').to('\0'),
38    )));
39    let char_or_escape = choice((
40        escape,
41        any().and_is(just('"').not()).and_is(just('\\').not()),
42    ));
43    just('"')
44        .ignore_then(char_or_escape.repeated().collect::<String>())
45        .then_ignore(just('"'))
46        .map(QuotedString)
47}
48
49/// `@name` — leading `@` consumed; name is `ident()`-shaped.
50pub fn symbol_ref<'src>() -> impl Parser<'src, &'src str, Ident, E<'src>> + Clone {
51    just('@').ignore_then(vihaco_parser::ident().map(Ident))
52}
53
54/// Block-body helper: parse a sequence of whitespace-separated `i64`s as
55/// **flat rows** between an outer `{` … `}` provided by the caller. The body
56/// itself is a sequence of `i64`s with any whitespace (including newlines)
57/// between them.
58///
59/// Real usage: `device slm.filling { 0 1 2 3 };`.
60pub fn block_i64_flat<'src>() -> impl Parser<'src, &'src str, Vec<i64>, E<'src>> + Clone {
61    let item = just('-')
62        .or_not()
63        .then(text::int(10))
64        .to_slice()
65        .map(|s: &str| s.parse::<i64>().unwrap());
66    // Allow any whitespace (incl. newlines) between numbers and around them.
67    let ws = any().filter(|c: &char| c.is_whitespace()).repeated();
68    ws.ignore_then(item)
69        .repeated()
70        .collect::<Vec<_>>()
71        .then_ignore(ws)
72}
73
74/// Block-body helper: parse rows of `i64 i64` pairs separated by whitespace.
75/// Within a row the two ints are whitespace-separated; rows themselves are
76/// also just whitespace-separated (newlines or other ws — the helper doesn't
77/// require row alignment).
78///
79/// Real usage: `device slm.traps { 1 1\n 5 1\n ... };`,
80/// `device camera.detect_sites { ... };`.
81pub fn block_i64_pairs<'src>() -> impl Parser<'src, &'src str, Vec<(i64, i64)>, E<'src>> + Clone {
82    let signed_int = just('-')
83        .or_not()
84        .then(text::int(10))
85        .to_slice()
86        .map(|s: &str| s.parse::<i64>().unwrap());
87    let inline_ws = any()
88        .filter(|c: &char| c.is_whitespace() && *c != '\n')
89        .repeated()
90        .at_least(1);
91    let ws = any().filter(|c: &char| c.is_whitespace()).repeated();
92
93    let pair = signed_int.then_ignore(inline_ws).then(signed_int);
94    ws.ignore_then(pair)
95        .repeated()
96        .collect::<Vec<_>>()
97        .then_ignore(ws)
98}
99
100/// `@name:` — a symbol definition. The name excludes `:` so the colon can
101/// terminate it.
102pub fn symbol_definition<'src>() -> impl Parser<'src, &'src str, String, E<'src>> + Clone {
103    just('@')
104        .ignore_then(
105            any()
106                .filter(|c: &char| {
107                    !c.is_whitespace()
108                        && !matches!(
109                            *c,
110                            ':' | '@'
111                                | ','
112                                | ';'
113                                | '('
114                                | ')'
115                                | '{'
116                                | '}'
117                                | '['
118                                | ']'
119                                | '"'
120                                | '\''
121                                | '`'
122                        )
123                })
124                .repeated()
125                .at_least(1)
126                .collect::<String>(),
127        )
128        .then_ignore(just(':'))
129}
130
131impl<I, H> ParsedModule<I, H> {
132    /// Parse a source section into its consumer instruction representation.
133    ///
134    /// Symbol names are not checked for uniqueness here; loading validates the
135    /// table against the header metadata. On failure the error names the first
136    /// problem by file line and column; [`crate::spanned::parse_text`] reports
137    /// every problem with its span.
138    pub fn parse_section<'src, C>(section: SSTSectionView<'src, C>) -> eyre::Result<Self>
139    where
140        H: SSTHeader,
141        I: vihaco_parser::Parse<'src> + 'src,
142    {
143        let header = section.parse_header::<H>()?;
144        let (first_line, _) =
145            crate::spanned::line_column(section.file_text(), section.text_span().start);
146        let parsed = crate::spanned::parse_text_at::<I>(section.text(), first_line);
147        if let Some(first) = parsed.errors.first() {
148            let offset = section.text_span().start + first.span.start;
149            let (line, column) = crate::spanned::line_column(section.file_text(), offset);
150            let more = match parsed.errors.len() - 1 {
151                0 => String::new(),
152                1 => " (and 1 more error)".to_owned(),
153                n => format!(" (and {n} more errors)"),
154            };
155            eyre::bail!(
156                "failed to parse `.text` of section `{}`: line {line}, column {column}: {first}{more}",
157                section.name(),
158            );
159        }
160        Ok(Self {
161            header,
162            code: parsed.code.into_iter().map(|item| item.value).collect(),
163            symbols: parsed.symbols.into_iter().map(|item| item.value).collect(),
164        })
165    }
166}