Skip to main content

fic/parser/
system.rs

1//! Parser for Fiducia System Description (`.fis`) files.
2//!
3//! Implements grammar rules for parsing `.fis` files, which define system-level
4//! declarations: the data layer (struct types and constants, #69), memory
5//! regions, protection domains, channels, and system composition. All of
6//! these are top-level items of the same `.fis` grammar surface, so their
7//! parsers live together in this one file (see [`crate::ast`] for the node
8//! type definitions themselves).
9//!
10//! # Example
11//!
12//! ```
13//! let input = r#"
14//! struct Packet { id: uint32; length: uint16; }
15//! const RBD_COUNT: uint = 64;
16//! MemoryRegion uart(0x1000, 0x1000, 0xFE00_0000);
17//! ProtectionDomain driver(200, 33);
18//! ProtectionDomain app(100);
19//! Chan notify = driver <-> app;
20//! System = driver ||| app;
21//! "#;
22//!
23//! let system = fic::parser::parse_system(input).unwrap();
24//! assert_eq!(system.protection_domains.len(), 2);
25//! assert_eq!(system.structs.len(), 1);
26//! assert_eq!(system.consts.len(), 1);
27//! ```
28
29use std::path::PathBuf;
30
31use winnow::combinator::{alt, cut_err, delimited, not, opt, preceded, separated, seq, terminated};
32use winnow::error::{AddContext, ContextError, ErrMode, StrContext, StrContextValue};
33
34use winnow::prelude::*;
35
36use crate::ast::{
37    Address, ChannelBuffer, ChannelDecl, ChannelKind, DataDecl, MemoryRegionDecl, PageSize,
38    ProtectionDomainDecl, SecurityLabel, System, SystemDecl,
39};
40use crate::error::Diagnostic;
41
42use super::data::data_decl;
43use super::recovery::parse_with_recovery;
44
45use winnow::ascii::dec_uint;
46
47use super::lexer::{hex, identifier, keyword, offset, reserved, symbol, ws, Input, PResult};
48use super::types::{array_size, parse as parse_type, security_label};
49
50// ============================================================================
51// Declaration Parsers — Memory Region / Protection Domain / System
52// ============================================================================
53
54/// Parse a memory region declaration
55/// secLabel? '`MemoryRegion`' ID '(' size (',' pageSize)? (',' physAddr)? ')' ';'
56fn memory_region_decl(input: &mut Input<'_>) -> PResult<MemoryRegionDecl> {
57    let (mut decl, span) = seq! {
58        MemoryRegionDecl {
59            security_label: opt(security_label).map(|o| o.unwrap_or(SecurityLabel::Low)),
60            _: (ws, reserved(keyword::MEMORY_REGION), ws),
61
62            // After MemoryRegion keyword, commit
63            name: cut_err(identifier.map(str::to_string))
64                .context(StrContext::Label("memory region name")),
65            _: cut_err((ws, '(', ws))
66                .context(StrContext::Expected(StrContextValue::CharLiteral('('))),
67            size: cut_err(hex.map(Address::from))
68                .context(StrContext::Label("memory region size")),
69
70            page_size: opt(preceded((ws, ",", ws), opt(hex.map(Address::from)))).map(|o| o.flatten().and_then(|addr| PageSize::try_from(addr).ok()).unwrap_or_default()),
71            phys_addr: opt(preceded((ws, ",", ws), opt(hex.map(Address::from)))).map(Option::flatten),
72
73            _: cut_err((ws, ')', ws, ';', ws))
74                .context(StrContext::Expected(StrContextValue::Description("closing ')' and ';'"))),
75            span: "".value(0..0usize),
76        }
77    }
78    .with_span()
79    .parse_next(input)?;
80    decl.span = span;
81
82    if !decl.size.is_aligned(decl.page_size) {
83        return Err(ErrMode::Cut(ContextError::new().add_context(
84            input,
85            &input.checkpoint(),
86            StrContext::Label(match decl.page_size {
87                PageSize::Small => "size must be a multiple of 0x1000 (4 KiB)",
88                PageSize::Large => "size must be a multiple of 0x200000 (2 MiB)",
89            }),
90        )));
91    }
92    if let Some(phys) = decl.phys_addr {
93        if !phys.is_aligned(decl.page_size) {
94            return Err(ErrMode::Cut(ContextError::new().add_context(
95                input,
96                &input.checkpoint(),
97                StrContext::Label(match decl.page_size {
98                    PageSize::Small => "phys_addr must be aligned to 0x1000 (4 KiB)",
99                    PageSize::Large => "phys_addr must be aligned to 0x200000 (2 MiB)",
100                }),
101            )));
102        }
103    }
104
105    Ok(decl)
106}
107
108/// Parse a protection domain declaration
109/// '`ProtectionDomain`' ID '(' priority (',' irq (',' budget (',' period)?)?)? ')' ';'
110fn protection_domain_decl(input: &mut Input<'_>) -> PResult<ProtectionDomainDecl> {
111    let (mut decl, span) = seq! {
112        ProtectionDomainDecl {
113            _: (reserved(keyword::PROTECTION_DOMAIN), ws),
114
115            // After ProtectionDomain keyword, commit
116            name: cut_err(identifier.map(str::to_string))
117                .context(StrContext::Label("protection domain name")),
118            _: cut_err(('(', ws))
119                .context(StrContext::Expected(StrContextValue::CharLiteral('('))),
120            priority: cut_err(dec_uint::<_, u8, _>.verify(|&val| val < 255))
121                .context(StrContext::Label("priority"))
122                .context(StrContext::Expected(StrContextValue::Description("integer 0-254"))),
123
124            irq: opt(preceded((ws, ",", ws), opt(dec_uint::<_, u16, _>))).map(Option::flatten),
125            budget: opt(preceded((ws, ",", ws), opt(dec_uint::<_, u32, _>))).map(move |v| v.flatten().unwrap_or(ProtectionDomainDecl::DEFAULT_BUDGET)),
126            period: opt(preceded((ws, ",", ws), opt(dec_uint::<_, u32, _>))).map(move |v| v.flatten().unwrap_or(budget)),
127
128            _: cut_err((ws, ")", ws, ";", ws))
129                .context(StrContext::Expected(StrContextValue::Description("closing ')' and ';'"))),
130            // The front end binds the `.fi`.
131            fi: "".value(PathBuf::new()),
132            span: "".value(0..0usize),
133        }
134    }
135    .with_span()
136    .parse_next(input)?;
137    decl.span = span;
138    Ok(decl)
139}
140
141/// Parse a system declaration
142/// 'System' '=' pdId ('|||' pdId)* ';'
143fn system_decl(input: &mut Input<'_>) -> PResult<SystemDecl> {
144    let (mut decl, span) = seq! {
145        SystemDecl {
146            _: (ws, reserved(keyword::SYSTEM), ws),
147
148            // After System keyword, commit
149            _: cut_err('=')
150                .context(StrContext::Expected(StrContextValue::CharLiteral('='))),
151            _: ws,
152            pds: cut_err(separated(1.., (offset, identifier).map(|(off, name)| (name.to_string(), off)), (ws, reserved(symbol::INTERLEAVE), ws)))
153                .context(StrContext::Label("system composition")),
154            _: cut_err((ws, ';', ws))
155                .context(StrContext::Expected(StrContextValue::CharLiteral(';'))),
156            span: "".value(0..0usize),
157        }
158    }
159    .with_span()
160    .parse_next(input)?;
161    decl.span = span;
162    Ok(decl)
163}
164
165// ============================================================================
166// Declaration Parsers — Channel
167// ============================================================================
168
169/// Parse a buffered-capable channel declaration: the async unidirectional channel.
170///
171/// ```text
172/// [Async] Chan name = pdA --> pdB;                    // signal only
173/// [Async] Chan name = pdA --> pdB via buf<Type>;      // with a buffer
174/// ```
175///
176/// The `Async` keyword is optional — `Chan` without `Sync` is always async.
177/// The `via` clause is optional; when present it names the backing [`MemoryRegion`]
178/// and the slot type, which every buffer names.
179/// The trailing `;` is optional. Any other arrow backtracks to [`signal_channel_decl`].
180fn async_channel_decl(input: &mut Input<'_>) -> PResult<ChannelDecl> {
181    let start = offset(input)?;
182    let mut decl = seq! {
183        ChannelDecl {
184            _: (ws, opt(reserved(keyword::ASYNC)), ws),
185            _: reserved(keyword::CHAN),
186            _: cut_err(not((ws, '<')))
187                .context(StrContext::Label("channel type"))
188                .context(StrContext::Expected(StrContextValue::Description(
189                    "no type on an async channel: `Chan<T>` is for `Sync` channels; a buffered one names its type in `via region<T>`",
190                ))),
191            _: ws,
192
193            // After Chan keyword, commit
194            name: cut_err(identifier.map(str::to_string))
195                .context(StrContext::Label("channel name")),
196            _: cut_err((ws, '=', ws))
197                .context(StrContext::Expected(StrContextValue::CharLiteral('='))),
198            sender_offset: offset,
199            sender: cut_err(identifier.map(str::to_string))
200                .context(StrContext::Label("first protection domain")),
201            kind: delimited(ws, reserved(symbol::CHANNEL_UNI).value(ChannelKind::AsyncUni), ws),
202            receiver_offset: offset,
203            receiver: cut_err(identifier.map(str::to_string))
204                .context(StrContext::Label("second protection domain")),
205            _: ws,
206            buffer: opt(preceded(
207                (reserved(keyword::VIA), ws),
208                cut_err(seq!(ChannelBuffer {
209                    region: identifier.map(str::to_string),
210                    _: ('<', ws),
211                    payload: parse_type,
212                    capacity: opt(preceded((ws, ',', ws), array_size)),
213                    _: (ws, '>'),
214                }))
215                .context(StrContext::Expected(StrContextValue::Description(
216                    "a buffer, its payload type and optionally its capacity: `via region<T>` or `via region<T, N>`",
217                ))),
218            ))
219                .context(StrContext::Label("channel buffer")),
220            _: opt((";", ws)),
221            payload: "".value(None),
222            span: "".value(0..0usize),
223        }
224    }
225    .parse_next(input)?;
226    decl.span = start..offset(input)?;
227    Ok(decl)
228}
229
230/// Parse a channel declaration that carries no buffer: the sync channel and the
231/// async bidirectional one.
232///
233/// ```text
234/// Sync Chan name = pdA --> pdB;
235/// Sync Chan<T> name = pdA --> pdB;    // carries a `T` in the message registers
236/// [Async] Chan name = pdA <-> pdB;
237/// ```
238///
239/// Sync channels carry synchronous call/reply semantics; only `-->` is supported.
240/// A `via` after either is an error at the `via`: a buffered channel is one-way
241/// and asynchronous, so it is [`async_channel_decl`]'s.
242/// The trailing `;` is optional.
243fn signal_channel_decl(input: &mut Input<'_>) -> PResult<ChannelDecl> {
244    let start = offset(input)?;
245    let sync = delimited(
246        ws,
247        opt(alt((
248            reserved(keyword::SYNC).value(true),
249            reserved(keyword::ASYNC).value(false),
250        ))),
251        ws,
252    )
253    .map(|sync| sync == Some(true))
254    .parse_next(input)?;
255    let mut decl = seq! {
256        ChannelDecl {
257            _: reserved(keyword::CHAN),
258            payload: opt(preceded(
259                (ws, '<', ws),
260                cut_err(terminated(parse_type, (ws, '>')))
261                    .context(StrContext::Expected(StrContextValue::Description(
262                        "the value's type: `Sync Chan<T>`",
263                    ))),
264            )),
265            _: ws,
266
267            // After Chan keyword, commit
268            name: cut_err(identifier.map(str::to_string))
269                .context(StrContext::Label("channel name")),
270            _: cut_err((ws, '=', ws))
271                .context(StrContext::Expected(StrContextValue::CharLiteral('='))),
272            sender_offset: offset,
273            sender: cut_err(identifier.map(str::to_string))
274                .context(StrContext::Label("first protection domain")),
275            kind: cut_err(
276                delimited(ws, alt((
277                    reserved(symbol::CHANNEL_BI).value(ChannelKind::AsyncBi),
278                    reserved(symbol::CHANNEL_UNI).value(ChannelKind::SyncUni),
279                )), ws)
280                .verify(|kind| (*kind == ChannelKind::SyncUni) == sync))
281                .context(StrContext::Label("channel notation"))
282                .context(StrContext::Expected(StrContextValue::Description(
283                    if sync { "'-->'" } else { "'<->' or '-->'" },
284                ))),
285            receiver_offset: offset,
286            receiver: cut_err(identifier.map(str::to_string))
287                .context(StrContext::Label("second protection domain")),
288            _: ws,
289            _: cut_err(not(reserved(keyword::VIA)))
290                .context(StrContext::Label("channel buffer"))
291                .context(StrContext::Expected(StrContextValue::Description(
292                    "no buffer on a signal-only channel: declare a buffered channel as an async '-->'",
293                ))),
294            buffer: "".value(None),
295            _: opt((";", ws)),
296            span: "".value(0..0usize),
297        }
298    }
299    .parse_next(input)?;
300    decl.span = start..offset(input)?;
301    Ok(decl)
302}
303
304/// Parse any channel declaration: the buffered-capable `-->` first, which backtracks
305/// on any other arrow or on `Sync`.
306fn channel_decl(input: &mut Input<'_>) -> PResult<ChannelDecl> {
307    alt((async_channel_decl, signal_channel_decl)).parse_next(input)
308}
309
310// ============================================================================
311// Top-level Parser
312// ============================================================================
313
314/// Dispatch type for the top-level `.fis` parser — separates parsing from
315/// mutation so that `alt()` branches don't need simultaneous `&mut System` borrows.
316enum Item {
317    Data(DataDecl),
318    MemoryRegion(MemoryRegionDecl),
319    ProtectionDomain(ProtectionDomainDecl),
320    Channel(ChannelDecl),
321    System(SystemDecl),
322}
323
324/// Parse a `.fis` system description with error recovery.
325///
326/// On parse errors, skips to the next `;` and continues collecting
327/// items and errors. Returns all errors if any occurred.
328///
329/// # Examples
330///
331/// ```
332/// let system = fic::parser::parse_system("ProtectionDomain pd1(100);").unwrap();
333/// assert_eq!(system.protection_domains.len(), 1);
334/// ```
335///
336/// ```
337/// let result = fic::parser::parse_system("not valid syntax;");
338/// assert!(result.is_err());
339/// ```
340pub fn parse(input: &str) -> Result<System, Vec<Diagnostic>> {
341    let mut sys = System {
342        structs: Vec::new(),
343        consts: Vec::new(),
344        memory_regions: Vec::new(),
345        protection_domains: Vec::new(),
346        channels: Vec::new(),
347        system: None,
348        filename: String::new(),
349    };
350
351    let errors = parse_with_recovery(
352        input,
353        "unexpected content after declarations",
354        alt((
355            data_decl.map(Item::Data),
356            memory_region_decl.map(Item::MemoryRegion),
357            protection_domain_decl.map(Item::ProtectionDomain),
358            channel_decl.map(Item::Channel),
359            system_decl.map(Item::System),
360        ))
361        .context(StrContext::Label("system item")),
362        |item, _errors| match item {
363            Item::Data(DataDecl::Struct(s)) => sys.structs.push(s),
364            Item::Data(DataDecl::Const(c)) => sys.consts.push(c),
365            Item::MemoryRegion(mr) => sys.memory_regions.push(mr),
366            Item::ProtectionDomain(pd) => sys.protection_domains.push(pd),
367            Item::Channel(ch) => sys.channels.push(ch),
368            Item::System(s) => sys.system = Some(s),
369        },
370    );
371
372    if errors.is_empty() {
373        Ok(sys)
374    } else {
375        Err(errors)
376    }
377}
378
379// ============================================================================
380// Tests
381// ============================================================================
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386    use crate::ast::{ArraySize, ExprKind, PrimitiveType, Type};
387    use winnow::stream::LocatingSlice;
388
389    // --- MemoryRegion ---
390
391    #[test]
392    fn test_parse_memory_region_basic() {
393        let input = "MemoryRegion uart(0x1000);";
394        let mut remaining = LocatingSlice::new(input);
395        let r = memory_region_decl(&mut remaining).unwrap();
396        assert_eq!(r.name, "uart");
397        assert_eq!(r.size, Address::new(0x1000));
398        assert_eq!(r.security_label, SecurityLabel::Low);
399        assert_eq!(r.page_size, PageSize::Small);
400        assert_eq!(r.phys_addr, None);
401        assert_eq!(r.span, 0..input.len());
402    }
403
404    #[test]
405    fn test_parse_memory_region_with_security_label() {
406        let input = "High MemoryRegion secret(0x200000);";
407        let mut remaining = LocatingSlice::new(input);
408        let r = memory_region_decl(&mut remaining).unwrap();
409        assert_eq!(r.name, "secret");
410        assert_eq!(r.security_label, SecurityLabel::High);
411    }
412
413    #[test]
414    fn test_parse_memory_region_with_page_size() {
415        let input = "MemoryRegion buf(0x200000, 0x200000);";
416        let mut remaining = LocatingSlice::new(input);
417        let r = memory_region_decl(&mut remaining).unwrap();
418        assert_eq!(r.size, Address::new(0x0020_0000));
419        assert_eq!(r.page_size, PageSize::Large);
420        assert_eq!(r.phys_addr, None);
421    }
422
423    #[test]
424    fn test_parse_memory_region_with_phys_addr() {
425        let input = "MemoryRegion mmio(0x1000, 0x1000, 0xFE00_0000);";
426        let mut remaining = LocatingSlice::new(input);
427        let r = memory_region_decl(&mut remaining).unwrap();
428        assert_eq!(r.size, Address::new(0x1000));
429        assert_eq!(r.page_size, PageSize::Small);
430        assert_eq!(r.phys_addr, Some(Address::new(0xFE00_0000)));
431    }
432
433    #[test]
434    fn test_parse_memory_region_skip_page_size() {
435        // Skip page_size with empty slot, provide phys_addr
436        let input = "MemoryRegion mmio(0x1000, , 0xFE00_0000);";
437        let mut remaining = LocatingSlice::new(input);
438        let r = memory_region_decl(&mut remaining).unwrap();
439        assert_eq!(r.size, Address::new(0x1000));
440        assert_eq!(r.page_size, PageSize::Small); // default
441        assert_eq!(r.phys_addr, Some(Address::new(0xFE00_0000)));
442    }
443
444    // --- ProtectionDomain ---
445
446    #[test]
447    fn test_parse_pd_priority_only() {
448        let input = "ProtectionDomain pd1(100);";
449        let mut remaining = LocatingSlice::new(input);
450        let r = protection_domain_decl(&mut remaining).unwrap();
451        assert_eq!(r.name, "pd1");
452        assert_eq!(r.priority, 100);
453        assert_eq!(r.irq, None);
454        assert_eq!(r.budget, ProtectionDomainDecl::DEFAULT_BUDGET);
455        assert_eq!(r.period, ProtectionDomainDecl::DEFAULT_BUDGET);
456    }
457
458    #[test]
459    fn test_parse_pd_with_irq() {
460        let input = "ProtectionDomain driver(200, 33);";
461        let mut remaining = LocatingSlice::new(input);
462        let r = protection_domain_decl(&mut remaining).unwrap();
463        assert_eq!(r.name, "driver");
464        assert_eq!(r.priority, 200);
465        assert_eq!(r.irq, Some(33));
466        assert_eq!(r.budget, ProtectionDomainDecl::DEFAULT_BUDGET);
467    }
468
469    #[test]
470    fn test_parse_pd_with_large_irq() {
471        let input = "ProtectionDomain pd(100, 159);";
472        let mut remaining = LocatingSlice::new(input);
473        let r = protection_domain_decl(&mut remaining).unwrap();
474        assert_eq!(r.irq, Some(159));
475    }
476
477    #[test]
478    fn test_parse_pd_with_budget_and_period() {
479        let input = "ProtectionDomain rt(250, 10, 500, 2000);";
480        let mut remaining = LocatingSlice::new(input);
481        let r = protection_domain_decl(&mut remaining).unwrap();
482        assert_eq!(r.priority, 250);
483        assert_eq!(r.irq, Some(10));
484        assert_eq!(r.budget, 500);
485        assert_eq!(r.period, 2000);
486    }
487
488    #[test]
489    fn test_parse_pd_period_defaults_to_budget() {
490        let input = "ProtectionDomain rt(250, 10, 500);";
491        let mut remaining = LocatingSlice::new(input);
492        let r = protection_domain_decl(&mut remaining).unwrap();
493        assert_eq!(r.budget, 500);
494        assert_eq!(r.period, 500);
495    }
496
497    #[test]
498    fn test_parse_pd_skip_irq_set_budget() {
499        // Skip IRQ with empty slot, provide budget
500        let input = "ProtectionDomain pd(100, , 500);";
501        let mut remaining = LocatingSlice::new(input);
502        let r = protection_domain_decl(&mut remaining).unwrap();
503        assert_eq!(r.priority, 100);
504        assert_eq!(r.irq, None);
505        assert_eq!(r.budget, 500);
506        assert_eq!(r.period, 500); // defaults to budget
507    }
508
509    #[test]
510    fn test_parse_pd_skip_irq_set_budget_and_period() {
511        let input = "ProtectionDomain pd(100, , 500, 2000);";
512        let mut remaining = LocatingSlice::new(input);
513        let r = protection_domain_decl(&mut remaining).unwrap();
514        assert_eq!(r.priority, 100);
515        assert_eq!(r.irq, None);
516        assert_eq!(r.budget, 500);
517        assert_eq!(r.period, 2000);
518    }
519
520    #[test]
521    fn test_parse_pd_skip_irq_and_budget() {
522        // Skip both IRQ and budget, provide period
523        let input = "ProtectionDomain pd(100, , , 2000);";
524        let mut remaining = LocatingSlice::new(input);
525        let r = protection_domain_decl(&mut remaining).unwrap();
526        assert_eq!(r.priority, 100);
527        assert_eq!(r.irq, None);
528        assert_eq!(r.budget, ProtectionDomainDecl::DEFAULT_BUDGET);
529        assert_eq!(r.period, 2000);
530    }
531
532    // --- System ---
533
534    #[test]
535    fn test_parse_system_single_pd() {
536        let input = "System = main;";
537        let mut remaining = LocatingSlice::new(input);
538        let r = system_decl(&mut remaining).unwrap();
539        assert_eq!(r.pds.len(), 1);
540        assert_eq!(r.pds[0].0, "main");
541    }
542
543    #[test]
544    fn test_parse_system_multiple_pds() {
545        let input = "System = a ||| b ||| c;";
546        let mut remaining = LocatingSlice::new(input);
547        let r = system_decl(&mut remaining).unwrap();
548        assert_eq!(r.pds.len(), 3);
549        assert_eq!(r.pds[0].0, "a");
550        assert_eq!(r.pds[1].0, "b");
551        assert_eq!(r.pds[2].0, "c");
552    }
553
554    // --- Channel ---
555
556    #[test]
557    fn test_parse_sync_channel() {
558        let input = "Sync Chan notify = producer --> consumer;";
559        let mut remaining = LocatingSlice::new(input);
560        let r = signal_channel_decl(&mut remaining).unwrap();
561        assert_eq!(r.kind, ChannelKind::SyncUni);
562        assert_eq!(r.name, "notify");
563        assert_eq!(r.sender, "producer");
564        assert_eq!(r.receiver, "consumer");
565    }
566
567    #[test]
568    fn a_sync_channel_may_carry_a_type() {
569        for input in [
570            "Sync Chan<Req> ask = client --> server;",
571            "Sync Chan < int32 > ask = client --> server;",
572        ] {
573            let r = channel_decl(&mut LocatingSlice::new(input)).unwrap();
574            assert_eq!(r.kind, ChannelKind::SyncUni, "{input}");
575            assert_eq!(r.name, "ask", "{input}");
576            assert!(r.payload.is_some(), "{input}");
577            assert_eq!(r.buffer, None, "{input}");
578        }
579        let r = channel_decl(&mut LocatingSlice::new("Sync Chan ask = a --> b;")).unwrap();
580        assert!(r.payload.is_none());
581    }
582
583    #[test]
584    fn an_async_channel_carries_no_type() {
585        for input in [
586            "Chan<int32> c = a --> b;",
587            "Async Chan<int32> c = a --> b;",
588            "Chan<int32> c = a <-> b;",
589        ] {
590            let err = channel_decl(&mut LocatingSlice::new(input)).unwrap_err();
591            assert!(
592                format!("{err:?}").contains("`Chan<T>` is for `Sync` channels"),
593                "{input}: {err:?}"
594            );
595        }
596    }
597
598    #[test]
599    fn test_parse_async_channel_bidirectional() {
600        // implicit and explicit Async keyword both accepted
601        for input in &[
602            "Chan ch1 = pd_a <-> pd_b;",
603            "Async Chan ch1 = pd_a <-> pd_b;",
604        ] {
605            let mut remaining = LocatingSlice::new(*input);
606            let r = channel_decl(&mut remaining).unwrap();
607            assert_eq!(r.kind, ChannelKind::AsyncBi);
608            assert_eq!(r.sender, "pd_a");
609            assert_eq!(r.receiver, "pd_b");
610            assert_eq!(r.buffer, None);
611        }
612    }
613
614    #[test]
615    fn test_parse_async_channel_unidirectional() {
616        let input = "Chan tx = sender --> receiver;";
617        let mut remaining = LocatingSlice::new(input);
618        let r = async_channel_decl(&mut remaining).unwrap();
619        assert_eq!(r.kind, ChannelKind::AsyncUni);
620        assert_eq!(r.name, "tx");
621        assert_eq!(r.sender, "sender");
622        assert_eq!(r.receiver, "receiver");
623        assert_eq!(r.buffer, None);
624    }
625
626    #[test]
627    fn a_buffer_without_a_type_is_rejected() {
628        let input = "Chan c = pd1 --> pd2 via buf;";
629        let mut remaining = LocatingSlice::new(input);
630        assert!(async_channel_decl(&mut remaining).is_err());
631    }
632
633    #[test]
634    fn a_buffer_may_declare_its_capacity() {
635        for (input, capacity) in [
636            (
637                "Chan c = pd1 --> pd2 via buf<Buf, 512>;",
638                ArraySize::Lit(512),
639            ),
640            (
641                "Chan c = pd1 --> pd2 via buf< Buf ,NUM_BUFFERS >;",
642                ArraySize::Named("NUM_BUFFERS".to_string()),
643            ),
644        ] {
645            let mut remaining = LocatingSlice::new(input);
646            let r = async_channel_decl(&mut remaining).unwrap();
647            assert_eq!(
648                r.buffer,
649                Some(ChannelBuffer {
650                    region: "buf".to_string(),
651                    payload: Type::Struct("Buf".to_string()),
652                    capacity: Some(capacity),
653                }),
654                "{input}"
655            );
656        }
657        let mut remaining = LocatingSlice::new("Chan c = pd1 --> pd2 via buf<Buf, >;");
658        assert!(async_channel_decl(&mut remaining).is_err());
659    }
660
661    #[test]
662    fn test_parse_async_channel_typed_buffer_primitive() {
663        let input = "Chan c = pd1 --> pd2 via buf<uint32>;";
664        let mut remaining = LocatingSlice::new(input);
665        let r = async_channel_decl(&mut remaining).unwrap();
666        assert_eq!(
667            r.buffer,
668            Some(ChannelBuffer {
669                region: "buf".to_string(),
670                payload: Type::Primitive(PrimitiveType::UInt32),
671                capacity: None,
672            })
673        );
674    }
675
676    #[test]
677    fn test_parse_async_channel_typed_buffer_struct() {
678        let input = "Chan c = pd1 --> pd2 via ring_buf<Packet>;";
679        let mut remaining = LocatingSlice::new(input);
680        let r = async_channel_decl(&mut remaining).unwrap();
681        assert_eq!(
682            r.buffer,
683            Some(ChannelBuffer {
684                region: "ring_buf".to_string(),
685                payload: Type::Struct("Packet".to_string()),
686                capacity: None,
687            })
688        );
689    }
690
691    // A buffered channel is one-way: `via` after `<->` is rejected at the `via`.
692    #[test]
693    fn a_bidirectional_channel_has_no_buffer() {
694        let input = "Chan c = pd1 <-> pd2 via buf<Packet>;";
695        let errors = parse(input).unwrap_err();
696        assert_eq!(errors.len(), 1, "{errors:?}");
697        let message = errors[0].message();
698        assert!(
699            message.contains("no buffer on a signal-only channel"),
700            "{message}"
701        );
702        let via = input.find("via").unwrap();
703        assert_eq!(errors[0].span().start, via);
704        // The same declaration with `-->` parses.
705        assert!(parse("Chan c = pd1 --> pd2 via buf<Packet>;").is_ok());
706    }
707
708    // A synchronous channel has no buffer either: `via` is rejected at the `via`.
709    #[test]
710    fn a_sync_channel_has_no_buffer() {
711        let input = "Sync Chan c = pd1 --> pd2 via buf<Packet>;";
712        let errors = parse(input).unwrap_err();
713        assert_eq!(errors.len(), 1, "{errors:?}");
714        let message = errors[0].message();
715        assert!(
716            message.contains("no buffer on a signal-only channel"),
717            "{message}"
718        );
719        assert_eq!(errors[0].span().start, input.find("via").unwrap());
720        assert!(parse("Sync Chan c = pd1 --> pd2 ;").is_ok());
721    }
722
723    // The buffered parser backtracks on any other arrow, so a bad one is the signal
724    // parser's error, and `Sync` takes only `-->`.
725    #[test]
726    fn a_bad_channel_arrow_is_reported() {
727        for (input, expected) in [
728            ("Chan c = pd1 => pd2;", "expected '<->' or '-->'"),
729            ("Sync Chan c = pd1 <-> pd2;", "expected '-->'"),
730        ] {
731            let errors = parse(input).unwrap_err();
732            assert_eq!(errors.len(), 1, "{input}: {errors:?}");
733            let message = errors[0].message();
734            assert!(message.contains(expected), "{input}: {message}");
735        }
736    }
737
738    // Guard: payload requires a buffer — `<Type>` without `via buf` must not be silently
739    // captured. The channel parses successfully up to `pd2`, leaves `<uint32>` unconsumed,
740    // and the outer parser would then reject the leftover token.
741    #[test]
742    fn test_payload_without_buffer_not_captured() {
743        let input = "Chan c = pd1 --> pd2 <uint32>";
744        let mut remaining = LocatingSlice::new(input);
745        let r = async_channel_decl(&mut remaining).unwrap();
746        assert_eq!(r.buffer, None);
747        assert_eq!(*remaining, "<uint32>"); // left unconsumed, not silently swallowed
748    }
749
750    // `via` commits to a buffer: one with no region is an error.
751    #[test]
752    fn a_buffer_without_a_region_is_rejected() {
753        let input = "Chan c = pd1 --> pd2 via <uint32>";
754        let mut remaining = LocatingSlice::new(input);
755        assert!(async_channel_decl(&mut remaining).is_err());
756    }
757
758    // --- Data (struct / const) ---
759
760    fn parse_one_data(input: &str) -> DataDecl {
761        let mut remaining = LocatingSlice::new(input);
762        data_decl(&mut remaining).unwrap()
763    }
764
765    #[test]
766    fn test_struct_basic() {
767        let DataDecl::Struct(s) =
768            parse_one_data("struct Packet {\n    id: uint32;\n    length: uint16;\n}")
769        else {
770            panic!("expected struct")
771        };
772        assert_eq!(s.name, "Packet");
773        assert_eq!(s.fields.len(), 2);
774        assert_eq!(s.fields[0].name, "id");
775        assert_eq!(s.fields[0].ty, Type::Primitive(PrimitiveType::UInt32));
776        assert_eq!(s.fields[1].name, "length");
777    }
778
779    #[test]
780    fn test_struct_empty() {
781        let DataDecl::Struct(s) = parse_one_data("struct Unit {}") else {
782            panic!("expected struct")
783        };
784        assert!(s.fields.is_empty(), "{:?}", s.fields);
785    }
786
787    #[test]
788    fn test_struct_nested_field_type() {
789        let DataDecl::Struct(s) = parse_one_data("struct Header { packet: Packet; flags: uint8; }")
790        else {
791            panic!("expected struct")
792        };
793        assert_eq!(s.fields[0].ty, Type::Struct("Packet".to_string()));
794    }
795
796    #[test]
797    fn test_struct_packed() {
798        let src = "@attr(packed)\nstruct P { a: uint8; b: uint32; }";
799        let DataDecl::Struct(s) = parse_one_data(src) else {
800            panic!("expected struct")
801        };
802        assert!(s.packed);
803        assert_eq!(&src[s.span.clone()], src, "the span covers the annotation");
804        let DataDecl::Struct(s) = parse_one_data("struct P {}") else {
805            panic!("expected struct")
806        };
807        assert!(!s.packed, "padded by default");
808    }
809
810    #[test]
811    fn test_attr_rejects_an_unknown_attribute_or_a_const() {
812        for input in [
813            "@attr(aligned) struct P {}",
814            "@attr(packed) const N: uint = 1;",
815        ] {
816            let mut remaining = LocatingSlice::new(input);
817            assert!(
818                matches!(data_decl(&mut remaining), Err(ErrMode::Cut(_))),
819                "{input}"
820            );
821        }
822    }
823
824    #[test]
825    fn test_struct_missing_semicolon_rejected() {
826        let input = "struct P { id: uint32 }";
827        let mut remaining = LocatingSlice::new(input);
828        assert!(data_decl(&mut remaining).is_err());
829    }
830
831    #[test]
832    fn test_const_literal() {
833        let DataDecl::Const(c) = parse_one_data("const RBD_COUNT: uint = 64;") else {
834            panic!("expected const")
835        };
836        assert_eq!(c.name, "RBD_COUNT");
837        assert_eq!(c.ty, Type::Primitive(PrimitiveType::UInt));
838    }
839
840    #[test]
841    fn test_const_expression_rhs() {
842        // Full Expr grammar in const position: folding happens in the pass.
843        let DataDecl::Const(c) =
844            parse_one_data("const RING_BYTES: uint = RBD_COUNT * sizeof(Packet);")
845        else {
846            panic!("expected const")
847        };
848        assert_eq!(c.name, "RING_BYTES");
849        assert!(matches!(c.value.kind, ExprKind::Binary { .. }));
850    }
851
852    #[test]
853    fn test_const_missing_type_rejected() {
854        let input = "const N = 4;";
855        let mut remaining = LocatingSlice::new(input);
856        assert!(data_decl(&mut remaining).is_err());
857    }
858
859    #[test]
860    fn test_struct_span_bounds() {
861        let src = "struct P { id: uint32; }";
862        let DataDecl::Struct(s) = parse_one_data(src) else {
863            panic!()
864        };
865        assert_eq!(&src[s.span.clone()], src);
866    }
867
868    // --- Top-level parse ---
869
870    #[test]
871    fn test_parse_empty_system() {
872        let result = parse("").unwrap();
873        assert!(result.memory_regions.is_empty());
874        assert!(result.protection_domains.is_empty());
875        assert!(result.channels.is_empty());
876        assert!(result.system.is_none());
877    }
878
879    #[test]
880    fn test_parse_full_system() {
881        let input = r"
882Low MemoryRegion buf(0x1000);
883ProtectionDomain pd1(100);
884Chan ch = pd1 <-> pd2;
885System = pd1 ||| pd2;
886";
887        let result = parse(input).unwrap();
888        assert_eq!(result.memory_regions.len(), 1);
889        assert_eq!(result.protection_domains.len(), 1);
890        assert_eq!(result.channels.len(), 1);
891        assert!(result.system.is_some());
892    }
893
894    #[test]
895    fn test_parse_system_with_comments() {
896        let input = r"
897// Line comment
898ProtectionDomain pd1(100);
899/* Block comment */
900ProtectionDomain pd2(200);
901";
902        let result = parse(input).unwrap();
903        assert_eq!(result.protection_domains.len(), 2);
904    }
905
906    #[test]
907    fn test_parse_rejects_trailing_garbage() {
908        let input = "ProtectionDomain pd1(100); garbage";
909        assert!(parse(input).is_err());
910    }
911
912    // --- Data validation ---
913
914    #[test]
915    fn test_parse_mr_size_not_aligned() {
916        let input = "MemoryRegion bad(0x1001);";
917        let result = parse(input);
918        assert!(result.is_err());
919        let errors = result.unwrap_err();
920        assert!(errors[0].to_string().contains("multiple of 0x1000 (4 KiB)"));
921    }
922
923    #[test]
924    fn test_parse_mr_phys_addr_not_aligned() {
925        let input = "MemoryRegion bad(0x1000, 0x1000, 0x1001);";
926        let result = parse(input);
927        assert!(result.is_err());
928        let errors = result.unwrap_err();
929        assert!(errors[0].to_string().contains("aligned to 0x1000 (4 KiB)"));
930    }
931
932    /// Parse all `.fis` fixture files in `tests/` and verify they parse without errors.
933    #[test]
934    fn test_all_fis_fixtures_parse() {
935        use std::fs;
936        use std::path::Path;
937
938        let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests");
939        for entry in fs::read_dir(&dir).expect("failed to read tests/") {
940            let path = entry.unwrap().path();
941            if path.extension().is_some_and(|e| e == "fis") {
942                let src = fs::read_to_string(&path)
943                    .unwrap_or_else(|err| panic!("failed to read {}: {err}", path.display()));
944                let result = parse(&src);
945                assert!(
946                    result.is_ok(),
947                    "{}: {}",
948                    path.display(),
949                    result
950                        .unwrap_err()
951                        .iter()
952                        .map(std::string::ToString::to_string)
953                        .collect::<Vec<_>>()
954                        .join("\n")
955                );
956                let result = result.unwrap();
957                assert!(
958                    !result.protection_domains.is_empty()
959                        || !result.memory_regions.is_empty()
960                        || !result.channels.is_empty()
961                        || result.system.is_some(),
962                    "{}: no declarations",
963                    path.display()
964                );
965            }
966        }
967    }
968}