Skip to main content

vihaco_parser/
lib.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4pub mod impls;
5pub mod print;
6
7pub use impls::{bare_token, ident, metadata_key, trivia, BareToken, Ident, QuotedString};
8pub use print::{print_quoted, Print};
9
10use chumsky::error::Simple;
11use chumsky::extra;
12
13/// Marker for enums whose pattern-derived parser represents instruction
14/// syntax.
15///
16/// `#[derive(vihaco_parser_derive::Parse)]` implements this trait for enums annotated
17/// with `#[syntax_class(instruction)]` or `#[syntax_class(instruction, head = "...")]`.
18pub trait SurfaceInstruction {}
19
20/// A parser whose input is `&'src str` (char stream) and whose error type is `Simple<char>`.
21///
22/// The lifetime `'src` is the input lifetime. Output type `Self` is owned and does not borrow
23/// from the input. [`Print`] is the inverse: it writes a value in the spelling this parser
24/// accepts, and `#[derive(Parse)]` generates both from the same pattern.
25pub trait Parse<'src>: Sized {
26    fn parser() -> impl chumsky::Parser<'src, &'src str, Self, extra::Err<Simple<'src, char>>>;
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32    use chumsky::Parser;
33
34    fn parses<'src, T: Parse<'src>>(input: &'src str) -> T {
35        T::parser().parse(input).into_result().unwrap()
36    }
37
38    #[test]
39    fn i64_basic() {
40        assert_eq!(parses::<i64>("42"), 42);
41    }
42    #[test]
43    fn i32_basic() {
44        assert_eq!(parses::<i32>("7"), 7);
45    }
46    #[test]
47    fn u64_basic() {
48        assert_eq!(parses::<u64>("100"), 100);
49    }
50    #[test]
51    fn u32_basic() {
52        assert_eq!(parses::<u32>("0"), 0);
53    }
54    #[test]
55    fn usize_basic() {
56        assert_eq!(parses::<usize>("9"), 9);
57    }
58    #[test]
59    fn f64_int() {
60        assert_eq!(parses::<f64>("3"), 3.0);
61    }
62    #[test]
63    #[allow(clippy::approx_constant)]
64    fn f64_float() {
65        assert_eq!(parses::<f64>("3.14"), 3.14);
66    }
67    #[test]
68    fn f32_float() {
69        assert!((parses::<f32>("1.5") - 1.5f32).abs() < 1e-6);
70    }
71    #[test]
72    fn i64_negative() {
73        assert_eq!(parses::<i64>("-42"), -42);
74    }
75    #[test]
76    fn i32_negative() {
77        assert_eq!(parses::<i32>("-7"), -7);
78    }
79    #[test]
80    fn f64_negative() {
81        assert_eq!(parses::<f64>("-0.5"), -0.5);
82    }
83    #[test]
84    fn f64_negative_scientific() {
85        assert_eq!(parses::<f64>("-1.0e-3"), -1.0e-3);
86    }
87    #[test]
88    fn u64_rejects_negative() {
89        assert!(u64::parser().parse("-1").into_result().is_err());
90    }
91    #[test]
92    fn integer_overflow_is_a_parse_error() {
93        assert!(i32::parser().parse("2147483648").has_errors());
94        assert!(i32::parser().parse("-2147483649").has_errors());
95        assert!(i64::parser().parse("9223372036854775808").has_errors());
96        assert!(u32::parser().parse("4294967296").has_errors());
97        assert!(u64::parser().parse("18446744073709551616").has_errors());
98        assert_eq!(parses::<i32>("-2147483648"), i32::MIN);
99        assert_eq!(parses::<u64>("18446744073709551615"), u64::MAX);
100    }
101
102    #[test]
103    fn bool_true() {
104        assert!(parses::<bool>("true"));
105    }
106    #[test]
107    fn bool_false() {
108        assert!(!parses::<bool>("false"));
109    }
110    #[test]
111    fn ident_word() {
112        assert_eq!(parses::<Ident>("hello"), Ident("hello".to_owned()));
113    }
114
115    #[test]
116    fn ident_stops_at_whitespace() {
117        // Without a trailing end(), Parser::parse() requires consuming all input — so a
118        // token parser given "hello world" fails because " world" is left unconsumed.
119        // Use lazy() / nested combinators for composition; that's not this test's job.
120        let result = Ident::parser().parse("hello world").into_result();
121        assert!(result.is_err());
122    }
123
124    #[test]
125    fn ident_operand_with_colons() {
126        assert_eq!(
127            ident().parse("AOD0:T1:A").into_result().unwrap(),
128            "AOD0:T1:A"
129        );
130    }
131
132    #[test]
133    fn ident_stops_at_comma() {
134        let result = ident()
135            .then_ignore(chumsky::primitive::just(','))
136            .parse("foo,")
137            .into_result();
138        assert_eq!(result.unwrap(), "foo");
139    }
140
141    #[test]
142    fn ident_allows_dots() {
143        assert_eq!(ident().parse("a.b.c").into_result().unwrap(), "a.b.c");
144    }
145
146    #[test]
147    fn ident_digi_target() {
148        assert_eq!(ident().parse("DIGI:0").into_result().unwrap(), "DIGI:0");
149    }
150
151    #[test]
152    fn ident_rejects_symbol_sigil_and_quote_characters() {
153        assert!(Ident::parser().parse("@target").has_errors());
154        assert!(Ident::parser().parse("\"target\"").has_errors());
155        assert!(Ident::parser().parse("'target").has_errors());
156        assert!(Ident::parser().parse("`target`").has_errors());
157    }
158
159    #[test]
160    fn bare_token_accepts_symbol_sigil_but_rejects_quotes() {
161        assert_eq!(
162            parses::<BareToken>("@target"),
163            BareToken("@target".to_owned())
164        );
165        assert!(BareToken::parser().parse("\"target\"").has_errors());
166    }
167
168    #[test]
169    fn ident_rejects_empty() {
170        assert!(ident().parse("").into_result().is_err());
171    }
172
173    #[test]
174    fn ident_rejects_leading_ws() {
175        assert!(ident().parse("  hello").into_result().is_err());
176    }
177
178    #[test]
179    fn ident_stops_at_open_paren() {
180        let result = ident()
181            .then_ignore(chumsky::primitive::just('('))
182            .parse("foo(")
183            .into_result();
184        assert_eq!(result.unwrap(), "foo");
185    }
186
187    #[test]
188    fn ident_stops_at_brace() {
189        let result = ident()
190            .then_ignore(chumsky::primitive::just('{'))
191            .parse("device{")
192            .into_result();
193        assert_eq!(result.unwrap(), "device");
194    }
195
196    #[test]
197    fn quoted_string_supports_spaces_and_escapes() {
198        assert_eq!(
199            parses::<QuotedString>("\"hello\\nworld\""),
200            QuotedString("hello\nworld".to_owned())
201        );
202    }
203
204    #[test]
205    fn lexical_newtypes_expose_owned_and_borrowed_text() {
206        let ident = Ident("target".to_owned());
207        assert_eq!(ident.as_str(), "target");
208        assert_eq!(ident.to_string(), "target");
209        assert_eq!(String::from(ident), "target");
210    }
211
212    #[test]
213    fn vec_uses_square_brackets_and_commas() {
214        assert_eq!(parses::<Vec<f64>>("[1.0, 2.5]"), vec![1.0, 2.5]);
215        assert!(parses::<Vec<f64>>("[]").is_empty());
216    }
217
218    #[test]
219    fn tuple_uses_parentheses_and_a_comma() {
220        assert_eq!(parses::<(i64, f64)>("(1, 2.5)"), (1, 2.5));
221    }
222
223    #[test]
224    fn vec_supports_nested_tuple_items() {
225        assert_eq!(
226            parses::<Vec<(f64, f64)>>("[(1.0, 2.0), (3.0, 4.0)]"),
227            vec![(1.0, 2.0), (3.0, 4.0)]
228        );
229    }
230}