Skip to main content

fic/parser/
lexer.rs

1//! Lexer primitives and keywords for the Fiducia language.
2//!
3//! This module provides shared tokenization utilities used by all Fiducia parsers:
4//! keywords, identifiers, numeric/string/boolean literals, file paths,
5//! whitespace, and comment handling.
6
7use 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
16/// Result type alias for parser functions.
17///
18/// Wraps winnow's `ModalResult` with `ContextError` for rich diagnostics.
19pub type PResult<T> = ModalResult<T, ContextError>;
20
21/// Parser input type: a `&str` that tracks its own byte offset
22/// (`winnow::stream::Location`), enabling `Parser::span()`/`with_span()`
23/// and `current_token_start()` for span and error-position tracking.
24pub type Input<'i> = LocatingSlice<&'i str>;
25
26// ============================================================================
27// Keywords
28// ============================================================================
29
30/// Reserved keyword constants shared across Fiducia parsers.
31#[allow(missing_docs)] // self-evident string literals; per-item docs would be pure noise
32pub mod keyword {
33    /// Each keyword as a const, [`ALL`] and [`is`], from one list.
34    macro_rules! keywords {
35        ($($(#[$doc:meta])* $name:ident = $word:literal,)*) => {
36            $($(#[$doc])* pub const $name: &str = $word;)*
37
38            /// Every keyword.
39            pub const ALL: &[&str] = &[$($name),*];
40
41            /// Whether `word` is a keyword: a `match`, not a scan of [`ALL`].
42            #[must_use]
43            pub fn is(word: &str) -> bool {
44                matches!(word, $($word)|*)
45            }
46        };
47    }
48
49    keywords! {
50        // Security labels
51        HIGH = "High",
52        LOW = "Low",
53
54        // Data and Expression keywords
55        STRUCT = "struct",
56        CONST = "const",
57
58        // .fis keywords
59        MEMORY_REGION = "MemoryRegion",
60        PROTECTION_DOMAIN = "ProtectionDomain",
61        SYSTEM = "System",
62        CHAN = "Chan",
63
64        // Channel labels
65        SYNC = "Sync",
66        ASYNC = "Async",
67        VIA = "via",
68
69        // Boolean literals
70        BOOL = "bool",
71        TRUE = "true",
72        FALSE = "false",
73
74        // Integer type keywords
75        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        // Pointer types (removed — Fiducia has no pointer types)
87        VOID = "void",
88
89        // Scalar types
90        BYTE = "byte",
91        ADDRESS = "Address",
92
93        // .fi keywords
94        IMPORT = "import",
95        AS = "as",
96        MAPPING = "Mapping",
97        IRQ = "irq",
98        EVT = "evt",
99        PROC = "proc",
100        SKIP = "Skip",
101        /// Divergence (self loop) keyword, replacing `Omega` (Ω) from `CoreFi` paper.
102        DIVERT = "Div",
103        DEFAULT = "default",
104        DBG = "dbg",
105    }
106}
107
108// ============================================================================
109// Symbols
110// ============================================================================
111
112/// Operator and punctuation symbol constants.
113#[allow(missing_docs)] // self-evident string literals; per-item docs would be pure noise
114pub mod symbol {
115    // Pointers and References
116    pub const STRUCT_FIELD_ACCESS: &str = ".";
117    pub const ADDRESS_OF: &str = "&";
118    pub const DEREFERENCE: &str = "*";
119
120    // Process Algebra Operators
121    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    /// Used as a separator between process expressions inside a body. The
127    /// bare literal `;` is reserved for terminating a process declaration;
128    /// reference this constant via `symbol::SEQUENTIAL` so the two roles
129    /// read distinctly at call sites.
130    pub const SEQUENTIAL: &str = ";";
131    pub const CHOICE: &str = "[ ]";
132    pub const SEND: &str = "!";
133    pub const RECEIVE: &str = "?";
134
135    // Arithmetic Operators
136    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    // Logical Operators
143    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    // Bitwise Operators
154    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
161// ============================================================================
162// Whitespace and Comments
163// ============================================================================
164
165/// Skip whitespace and comments (zero or more).
166///
167/// Handles spaces, tabs, newlines, `// line` comments, and `/* block */` comments.
168pub fn ws(input: &mut Input<'_>) -> PResult<()> {
169    repeat(0.., alt((multispace1.void(), line_comment, block_comment))).parse_next(input)
170}
171
172/// Parse a line comment: `// ...`
173fn line_comment(input: &mut Input<'_>) -> PResult<()> {
174    ("//", till_line_ending).void().parse_next(input)
175}
176
177/// Parse a block comment: `/* ... */`
178fn block_comment(input: &mut Input<'_>) -> PResult<()> {
179    ("/*", take_until(0.., "*/"), "*/").void().parse_next(input)
180}
181
182// ============================================================================
183// Identifiers and Literals
184// ============================================================================
185
186/// Parse an identifier: a word that is not a keyword.
187///
188/// Returns the borrowed slice — no allocation on parse (or on backtrack).
189/// Call sites that store the name in the AST take ownership there with
190/// `.map(str::to_string)`.
191pub 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
199/// A word, `[a-zA-Z_][a-zA-Z0-9_]*`: an identifier or a keyword.
200fn 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
209/// Parse the name of `name :` (a variable, parameter or carrier),
210/// committed at the `:`.
211pub 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
219/// Parse an identifier whose first character is ASCII uppercase:
220/// `UpperCamelCase`. Used for process names in declaration position
221/// (`proc Name(...)`) and process references (`Name(args)`).
222pub 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
229/// Parse a hex literal: `0x[0-9a-fA-F][0-9a-fA-F_]*`.
230///
231/// Underscores are allowed as visual separators (e.g., `0xFE00_0000`) —
232/// addresses are where grouping pays. Plain decimal positions use
233/// `winnow::ascii::dec_uint` directly (digits only, no separators).
234pub 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
254/// Parse a text literal: `"..."` of printable ASCII, with the escapes
255/// `\\`, `\"`, `\n` and `\t`; committed after the opening quote.
256pub 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
277/// Parse a boolean literal (`true` or `false`).
278pub 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
286/// Parse a file path, as written up to the closing quote: what it names is
287/// the front end's to decide, not the grammar's.
288pub fn file_path(input: &mut Input<'_>) -> PResult<PathBuf> {
289    take_till(1.., ['"', '\n'])
290        .map(PathBuf::from)
291        .parse_next(input)
292}
293
294// ============================================================================
295// Keyword and Symbol Utilities
296// ============================================================================
297
298/// Parse a reserved token (keyword or symbol) as an exact literal match.
299pub 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
309/// Zero-consuming parser returning the current byte offset — used to record
310/// a reference site's offset (e.g. a channel's `sender`/`receiver`, a
311/// mapping's region name) alongside its own span.
312pub fn offset(input: &mut Input<'_>) -> PResult<usize> {
313    Ok(input.current_token_start())
314}
315
316// ============================================================================
317// Tests
318// ============================================================================
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323
324    // --- Whitespace and Comments ---
325
326    #[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    // --- Identifiers ---
362
363    #[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        // Only a whole word is a keyword.
377        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    // --- Hex ---
413
414    #[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    // --- Text ---
445
446    #[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    // --- Bool Literal ---
472
473    #[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    // --- File Path ---
492
493    #[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        // What the file is, the front end decides; the grammar takes the path.
502        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    // --- Reserved ---
515
516    #[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}