1use std::path::PathBuf;
8
9use winnow::ascii::{escaped, multispace1, till_line_ending};
10use winnow::combinator::{alt, cut_err, not, peek, preceded, repeat, terminated};
11use winnow::error::{ContextError, ModalResult, StrContext, StrContextValue};
12use winnow::prelude::*;
13use winnow::stream::{LocatingSlice, Location};
14use winnow::token::{literal, one_of, take_till, take_until, take_while};
15
16pub type PResult<T> = ModalResult<T, ContextError>;
20
21pub type Input<'i> = LocatingSlice<&'i str>;
25
26#[allow(missing_docs)] pub mod keyword {
33 macro_rules! keywords {
35 ($($(#[$doc:meta])* $name:ident = $word:literal,)*) => {
36 $($(#[$doc])* pub const $name: &str = $word;)*
37
38 pub const ALL: &[&str] = &[$($name),*];
40
41 #[must_use]
43 pub fn is(word: &str) -> bool {
44 matches!(word, $($word)|*)
45 }
46 };
47 }
48
49 keywords! {
50 HIGH = "High",
52 LOW = "Low",
53
54 STRUCT = "struct",
56 CONST = "const",
57
58 MEMORY_REGION = "MemoryRegion",
60 PROTECTION_DOMAIN = "ProtectionDomain",
61 SYSTEM = "System",
62 CHAN = "Chan",
63
64 SYNC = "Sync",
66 ASYNC = "Async",
67 VIA = "via",
68
69 BOOL = "bool",
71 TRUE = "true",
72 FALSE = "false",
73
74 UINT = "uint",
76 UINT8 = "uint8",
77 UINT16 = "uint16",
78 UINT32 = "uint32",
79 UINT64 = "uint64",
80 INT = "int",
81 INT8 = "int8",
82 INT16 = "int16",
83 INT32 = "int32",
84 INT64 = "int64",
85
86 VOID = "void",
88
89 BYTE = "byte",
91 ADDRESS = "Address",
92
93 IMPORT = "import",
95 AS = "as",
96 MAPPING = "Mapping",
97 IRQ = "irq",
98 EVT = "evt",
99 PROC = "proc",
100 SKIP = "Skip",
101 DIVERT = "Div",
103 DEFAULT = "default",
104 DBG = "dbg",
105 }
106}
107
108#[allow(missing_docs)] pub mod symbol {
115 pub const STRUCT_FIELD_ACCESS: &str = ".";
117 pub const ADDRESS_OF: &str = "&";
118 pub const DEREFERENCE: &str = "*";
119
120 pub const CHANNEL_UNI: &str = "-->";
122 pub const CHANNEL_BI: &str = "<->";
123 pub const EVENT_PREFIX: &str = "->";
124 pub const INTERLEAVE: &str = "|||";
125 pub const PARALLEL: &str = "||";
126 pub const SEQUENTIAL: &str = ";";
131 pub const CHOICE: &str = "[ ]";
132 pub const SEND: &str = "!";
133 pub const RECEIVE: &str = "?";
134
135 pub const ADD: &str = "+";
137 pub const SUB: &str = "-";
138 pub const MUL: &str = "*";
139 pub const DIV: &str = "/";
140 pub const MOD: &str = "%";
141
142 pub const EQUAL: &str = "==";
144 pub const NOT_EQUAL: &str = "!=";
145 pub const LESS_THAN: &str = "<";
146 pub const LESS_EQUAL: &str = "<=";
147 pub const GREATER_THAN: &str = ">";
148 pub const GREATER_EQUAL: &str = ">=";
149 pub const LOGICAL_AND: &str = "&&";
150 pub const LOGICAL_OR: &str = "||";
151 pub const LOGICAL_NOT: &str = "!";
152
153 pub const BITWISE_AND: &str = "&";
155 pub const BITWISE_OR: &str = "|";
156 pub const BITWISE_XOR: &str = "^";
157 pub const LEFT_SHIFT: &str = "<<";
158 pub const RIGHT_SHIFT: &str = ">>";
159}
160
161pub fn ws(input: &mut Input<'_>) -> PResult<()> {
169 repeat(0.., alt((multispace1.void(), line_comment, block_comment))).parse_next(input)
170}
171
172fn line_comment(input: &mut Input<'_>) -> PResult<()> {
174 ("//", till_line_ending).void().parse_next(input)
175}
176
177fn block_comment(input: &mut Input<'_>) -> PResult<()> {
179 ("/*", take_until(0.., "*/"), "*/").void().parse_next(input)
180}
181
182pub fn identifier<'i>(input: &mut Input<'i>) -> PResult<&'i str> {
192 word.verify(|name: &&str| !keyword::is(name))
193 .context(StrContext::Expected(StrContextValue::Description(
194 "an identifier, not a keyword",
195 )))
196 .parse_next(input)
197}
198
199fn word<'i>(input: &mut Input<'i>) -> PResult<&'i str> {
201 (
202 take_while(1, |c: char| c.is_ascii_alphabetic() || c == '_'),
203 take_while(0.., |c: char| c.is_ascii_alphanumeric() || c == '_'),
204 )
205 .take()
206 .parse_next(input)
207}
208
209pub fn binder<'i>(input: &mut Input<'i>) -> PResult<&'i str> {
212 preceded(
213 peek((word, ws, ':')),
214 cut_err(identifier).context(StrContext::Label("variable name")),
215 )
216 .parse_next(input)
217}
218
219pub fn upper_identifier(input: &mut Input<'_>) -> PResult<String> {
223 identifier
224 .verify(|s: &&str| s.chars().next().is_some_and(|c| c.is_ascii_uppercase()))
225 .map(str::to_string)
226 .parse_next(input)
227}
228
229pub fn hex(input: &mut Input<'_>) -> PResult<u64> {
235 preceded(
236 "0x",
237 (
238 one_of(|c: char| c.is_ascii_hexdigit()),
239 take_while(0.., |c: char| c.is_ascii_hexdigit() || c == '_'),
240 )
241 .take(),
242 )
243 .try_map(|s: &str| {
244 let clean: String = s.chars().filter(|&c| c != '_').collect();
245 u64::from_str_radix(&clean, 16)
246 })
247 .context(StrContext::Label("hex literal"))
248 .context(StrContext::Expected(StrContextValue::Description(
249 "0x followed by hex digits",
250 )))
251 .parse_next(input)
252}
253
254pub fn text(input: &mut Input<'_>) -> PResult<String> {
257 let plain = take_while(1.., |c: char| {
258 (' '..='~').contains(&c) && c != '"' && c != '\\'
259 });
260 let escape = alt((
261 '\\'.value("\\"),
262 '"'.value("\""),
263 'n'.value("\n"),
264 't'.value("\t"),
265 ));
266 preceded(
267 '"',
268 cut_err(terminated(escaped(plain, '\\', escape), '"')).context(StrContext::Expected(
269 StrContextValue::Description(
270 "printable ASCII up to a closing '\"', escaping only \\\\, \\\", \\n and \\t",
271 ),
272 )),
273 )
274 .parse_next(input)
275}
276
277pub fn bool_literal(input: &mut Input<'_>) -> PResult<bool> {
279 alt((
280 reserved(keyword::TRUE).value(true),
281 reserved(keyword::FALSE).value(false),
282 ))
283 .parse_next(input)
284}
285
286pub fn file_path(input: &mut Input<'_>) -> PResult<PathBuf> {
289 take_till(1.., ['"', '\n'])
290 .map(PathBuf::from)
291 .parse_next(input)
292}
293
294pub fn reserved<'i>(s: &'static str) -> impl FnMut(&mut Input<'i>) -> PResult<&'i str> {
300 move |input: &mut Input<'i>| {
301 terminated(
302 literal(s),
303 not(one_of(|c: char| c.is_ascii_alphanumeric() || c == '_')),
304 )
305 .parse_next(input)
306 }
307}
308
309pub fn offset(input: &mut Input<'_>) -> PResult<usize> {
313 Ok(input.current_token_start())
314}
315
316#[cfg(test)]
321mod tests {
322 use super::*;
323
324 #[test]
327 fn test_ws_empty() {
328 let mut input = LocatingSlice::new("hello");
329 ws(&mut input).unwrap();
330 assert_eq!(*input, "hello");
331 }
332
333 #[test]
334 fn test_ws_spaces_and_newlines() {
335 let mut input = LocatingSlice::new(" \n\t rest");
336 ws(&mut input).unwrap();
337 assert_eq!(*input, "rest");
338 }
339
340 #[test]
341 fn test_ws_line_comment() {
342 let mut input = LocatingSlice::new("// comment\nrest");
343 ws(&mut input).unwrap();
344 assert_eq!(*input, "rest");
345 }
346
347 #[test]
348 fn test_ws_block_comment() {
349 let mut input = LocatingSlice::new("/* block */rest");
350 ws(&mut input).unwrap();
351 assert_eq!(*input, "rest");
352 }
353
354 #[test]
355 fn test_ws_mixed() {
356 let mut input = LocatingSlice::new(" // line\n /* block */ \n rest");
357 ws(&mut input).unwrap();
358 assert_eq!(*input, "rest");
359 }
360
361 #[test]
364 fn test_identifier_simple() {
365 let mut input = LocatingSlice::new("foo rest");
366 assert_eq!(identifier(&mut input).unwrap(), "foo");
367 assert_eq!(*input, " rest");
368 }
369
370 #[test]
371 fn a_keyword_is_not_an_identifier() {
372 for kw in keyword::ALL {
373 let mut input = LocatingSlice::new(*kw);
374 assert!(identifier(&mut input).is_err(), "{kw}");
375 }
376 let mut input = LocatingSlice::new("irq_count");
378 assert_eq!(identifier(&mut input).unwrap(), "irq_count");
379 }
380
381 #[test]
382 fn test_identifier_with_underscores() {
383 let mut input = LocatingSlice::new("ring_buffer_1");
384 assert_eq!(identifier(&mut input).unwrap(), "ring_buffer_1");
385 }
386
387 #[test]
388 fn test_identifier_leading_underscore() {
389 let mut input = LocatingSlice::new("_private");
390 assert_eq!(identifier(&mut input).unwrap(), "_private");
391 }
392
393 #[test]
394 fn test_identifier_rejects_leading_digit() {
395 let mut input = LocatingSlice::new("123abc");
396 assert!(identifier(&mut input).is_err());
397 }
398
399 #[test]
400 fn test_upper_identifier_accepts_uppercase() {
401 let mut input = LocatingSlice::new("Notified rest");
402 assert_eq!(upper_identifier(&mut input).unwrap(), "Notified");
403 assert_eq!(*input, " rest");
404 }
405
406 #[test]
407 fn test_upper_identifier_rejects_lowercase() {
408 let mut input = LocatingSlice::new("notified");
409 assert!(upper_identifier(&mut input).is_err());
410 }
411
412 #[test]
415 fn test_hex_basic() {
416 let mut input = LocatingSlice::new("0x1000");
417 assert_eq!(hex(&mut input).unwrap(), 0x1000);
418 }
419
420 #[test]
421 fn test_hex_rejects_starting_underscore() {
422 let mut input = LocatingSlice::new("0x_1000");
423 assert!(hex(&mut input).is_err());
424 }
425
426 #[test]
427 fn test_hex_with_underscores() {
428 let mut input = LocatingSlice::new("0xFE00_0000");
429 assert_eq!(hex(&mut input).unwrap(), 0xFE00_0000);
430 }
431
432 #[test]
433 fn test_hex_uppercase() {
434 let mut input = LocatingSlice::new("0xDEAD_BEEF");
435 assert_eq!(hex(&mut input).unwrap(), 0xDEAD_BEEF);
436 }
437
438 #[test]
439 fn test_hex_rejects_decimal() {
440 let mut input = LocatingSlice::new("1000");
441 assert!(hex(&mut input).is_err());
442 }
443
444 #[test]
447 fn text_unescapes() {
448 let mut input = LocatingSlice::new(r#""a \"b\" \\ \n\t" rest"#);
449 assert_eq!(text(&mut input).unwrap(), "a \"b\" \\ \n\t");
450 assert_eq!(*input, " rest");
451 }
452
453 #[test]
454 fn text_may_be_empty() {
455 let mut input = LocatingSlice::new(r#""""#);
456 assert_eq!(text(&mut input).unwrap(), "");
457 }
458
459 #[test]
460 fn text_rejects_an_unknown_escape() {
461 let mut input = LocatingSlice::new(r#""\x""#);
462 assert!(text(&mut input).is_err());
463 }
464
465 #[test]
466 fn text_rejects_a_raw_newline() {
467 let mut input = LocatingSlice::new("\"a\nb\"");
468 assert!(text(&mut input).is_err());
469 }
470
471 #[test]
474 fn test_bool_true() {
475 let mut input = LocatingSlice::new("true");
476 assert!(bool_literal(&mut input).unwrap());
477 }
478
479 #[test]
480 fn test_bool_false() {
481 let mut input = LocatingSlice::new("false");
482 assert!(!bool_literal(&mut input).unwrap());
483 }
484
485 #[test]
486 fn test_bool_rejects_other() {
487 let mut input = LocatingSlice::new("yes");
488 assert!(bool_literal(&mut input).is_err());
489 }
490
491 #[test]
494 fn test_file_path_c() {
495 let mut input = LocatingSlice::new("eth.c");
496 assert_eq!(file_path(&mut input).unwrap(), PathBuf::from("eth.c"));
497 }
498
499 #[test]
500 fn test_file_path_takes_any_path_up_to_the_quote() {
501 for path in ["foo.py", "drivers/driver.rs", "c/util.h"] {
503 let mut input = LocatingSlice::new(path);
504 assert_eq!(
505 file_path(&mut input).unwrap(),
506 PathBuf::from(path),
507 "{path}"
508 );
509 }
510 let mut input = LocatingSlice::new("\"eth.c\"");
511 assert!(file_path(&mut input).is_err(), "a quote is not a path");
512 }
513
514 #[test]
517 fn test_reserved_keyword() {
518 let mut input = LocatingSlice::new("Mapping rest");
519 assert_eq!(
520 reserved(keyword::MAPPING).parse_next(&mut input).unwrap(),
521 "Mapping"
522 );
523 assert_eq!(*input, " rest");
524 }
525
526 #[test]
527 fn test_reserved_symbol() {
528 let mut input = LocatingSlice::new("<-> rest");
529 assert_eq!(
530 reserved(symbol::CHANNEL_BI).parse_next(&mut input).unwrap(),
531 "<->"
532 );
533 assert_eq!(*input, " rest");
534 }
535
536 #[test]
537 fn test_reserved_mismatch() {
538 let mut input = LocatingSlice::new("Chan");
539 assert!(reserved(keyword::SYSTEM).parse_next(&mut input).is_err());
540 }
541}