Skip to main content

fic/parser/
process.rs

1//! Parser for Fiducia processes.
2//!
3//! Processes appear in `.fi` files as flat declarations with the `proc`
4//! keyword. See [`crate::ast::process`] for the AST node documentation.
5//!
6//! ```text
7//! proc Notified()      { irq?159 -> Handle_eth(); Notified(); }
8//! proc Handle_eth()    { handle_irq -> Dispatch(); }
9//! proc Dispatch()      { [rx] receive -> Skip [] [!rx] cleanup -> Skip; }
10//! proc Reply(pkt: int) { [pass] o2d!pkt -> Skip [] [!pass] handle_ping -> Skip; }
11//! ```
12//!
13//! Every process referenced (`Handle_eth`, `Dispatch`) is declared in
14//! the same file; `receive`, `cleanup`, `handle_irq`, `handle_ping`
15//! are computation events declared as `evt` declarations, and `irq`,
16//! `o2d` are channel names from the surrounding `.fis`.
17//!
18//! Process names use `UpperCamelCase`. The header is
19//! `proc Name(args)? { body }`, where `args` use the `name: Type` form.
20//! Bodies are enclosed in `{}` and contain variable declarations (`x: Type;`)
21//! interleaved with process expressions, separated by `;`. Variable declarations
22//! self-terminate with `;`; process expressions use `;` as the body-item
23//! separator. Assignment statements and external calls belong in `evt` declarations.
24//!
25//! ## Operator precedence (loosest → tightest)
26//!
27//! 1. `;`            — sequential composition (separates body items)
28//! 2. `[]` / `default` — external choice; each branch must carry a
29//!    discriminator. The parser checks structurally and recurses
30//!    into `Seq`'s first item and nested `Choice`. The only deferred
31//!    case is `ProcessRef`, where the validator must resolve the
32//!    name. See [`is_valid_choice_branch`].
33//! 3. `[b]`          — guard
34//! 4. `->`           — event prefix (right-associative; Hoare page 4)
35//! 5. atoms          — `Skip`, `Div`, parens, process reference `Name(args)?`
36//!
37//! Concrete consequences:
38//!
39//! - `e -> P [] e2 -> Q` ≡ `Choice([Prefix(e, P), Prefix(e2, Q)])` —
40//!   the prefix binds tighter than the choice, so each branch is its
41//!   own prefix.
42//! - `e -> P ; Q` ≡ `(e -> P) ; Q` — prefix tighter than `;`.
43//! - `[b] e -> P [] e2 -> Q` ≡
44//!   `Choice([Guard(b, Prefix(e, P)), Prefix(e2, Q)])` — guard binds
45//!   the first branch only. Outer-guarding the whole choice requires
46//!   explicit parens: `[b] (e -> P [] e2 -> Q)`.
47//! - `p1 ; p2 [] p3` ≡ `p1 ; (p2 [] p3)` — `;` is loosest.
48//!
49//! Parenthesisation cuts through: `( ... )` re-enters at the top of
50//! the precedence chain (`process`).
51//!
52//! ## Limitations
53//!
54//! Argument lists for process invocations and computation event
55//! references are currently restricted to identifiers (and integer
56//! literals for IRQ-style channel events).
57
58use winnow::combinator::{
59    alt, cut_err, delimited, eof, fail, not, opt, peek, preceded, repeat, separated, seq,
60    terminated,
61};
62use winnow::error::{StrContext, StrContextValue};
63use winnow::Parser;
64
65use crate::ast::{BindAnnotation, Expr, ExprKind, Process, ProcessDecl, Type};
66use crate::parser::typed_param;
67
68use super::event;
69use super::expr::parse as parse_expr;
70use super::lexer::{identifier, keyword, reserved, symbol, upper_identifier, ws, Input, PResult};
71use super::statement::var_decl;
72
73// ============================================================================
74// Parsers
75// ============================================================================
76
77/// Parse one `platform.entry` pair inside an `@bind(...)` group.
78///
79/// Leading whitespace is consumed by the `@bind(` prefix / `,` separator in
80/// `bind_group`, so the span here already starts at the pair itself.
81fn bind_pair(input: &mut Input<'_>) -> PResult<BindAnnotation> {
82    let (mut ann, span) = seq! {
83        BindAnnotation {
84            platform: identifier.map(str::to_string)
85                .context(StrContext::Label("platform name")),
86            _: '.',
87            entry: cut_err(identifier.map(str::to_string))
88                .context(StrContext::Label("entry point name")),
89            span: "".value(0..0usize),
90        }
91    }
92    .with_span()
93    .parse_next(input)?;
94    ann.span = span;
95    Ok(ann)
96}
97
98/// Parse a `@bind(p1.e1, p2.e2, ...)` annotation: one or more
99/// `platform.entry` pairs in a single group. `fic` records the pairs;
100/// resolving them to kernel entry points is the project layer's job (`fire`).
101fn bind_group(input: &mut Input<'_>) -> PResult<Vec<BindAnnotation>> {
102    preceded(
103        (ws, "@bind", ws),
104        // Commit once the `@bind` keyword is seen.
105        cut_err(delimited(
106            ('(', ws),
107            separated(1.., bind_pair, (ws, ',', ws)),
108            (ws, ')'),
109        ))
110        .context(StrContext::Expected(StrContextValue::Description(
111            "@bind(platform.entry, ...), e.g. @bind(microkit.notified)",
112        ))),
113    )
114    .parse_next(input)
115}
116
117/// Parse a process declaration: `@bind(...)?  'proc' Name(params) '{' body '}'`.
118pub fn parse(input: &mut Input<'_>) -> PResult<ProcessDecl> {
119    let binds: Vec<BindAnnotation> = opt(bind_group).parse_next(input)?.unwrap_or_default();
120    if !binds.is_empty() {
121        // The annotation only attaches to a process declaration — commit.
122        cut_err(peek((ws, reserved(keyword::PROC))))
123            .context(StrContext::Expected(StrContextValue::Description(
124                "`proc` declaration after the @bind annotation",
125            )))
126            .parse_next(input)?;
127    }
128    let (mut decl, span) = seq! {
129        ProcessDecl {
130            _: (ws, reserved(keyword::PROC), ws),
131            name: cut_err(upper_identifier)
132                .context(StrContext::Label("process name")),
133            _: ws,
134            params: param_list,
135            _: cut_err((ws, '{', ws))
136                .context(StrContext::Expected(StrContextValue::CharLiteral('{'))),
137            body: process_body,
138            _: cut_err((ws, '}'))
139                .context(StrContext::Expected(StrContextValue::CharLiteral('}'))),
140            binds: "".value(Vec::new()),
141            span: "".value(0..0usize),
142        }
143    }
144    .with_span()
145    .parse_next(input)?;
146    decl.binds = binds;
147    decl.span = span;
148    Ok(decl)
149}
150
151/// Parse one item of a process body: a [`VarDecl`] (self-terminated with
152/// `;`) or a process expression, which needs an explicit `;` separator
153/// unless it's the body's last item.
154///
155/// `choices` commits hard (`cut_err`) as soon as it starts matching, so it
156/// must never be attempted while sitting at the closing boundary (`)` or
157/// `}`) — the `not(at_process_boundary)` guard keeps that branch from ever
158/// firing there, leaving `alt` to backtrack cleanly out of the whole item
159/// instead.
160fn body_item(input: &mut Input<'_>) -> PResult<Process> {
161    preceded(
162        ws,
163        alt((
164            var_decl.map(Process::Decl),
165            preceded(
166                not(at_process_boundary),
167                terminated(
168                    choices,
169                    (
170                        ws,
171                        alt((
172                            at_process_boundary.void(),
173                            cut_err(';')
174                                .void()
175                                .context(StrContext::Expected(StrContextValue::CharLiteral(';'))),
176                        )),
177                    ),
178                ),
179            ),
180        )),
181    )
182    .parse_next(input)
183}
184
185/// Parse the `{...}` body of a process declaration.
186///
187/// Items ([`VarDecl`]s and process expressions) may be freely interspersed;
188/// the body must contain at least one process expression (a body of only
189/// variable declarations is rejected).
190///
191/// Only variable declarations are permitted as statements — assignments and
192/// external calls belong in `evt` declarations.
193fn process_body(input: &mut Input<'_>) -> PResult<Process> {
194    let items: Vec<Process> = repeat(0.., body_item).parse_next(input)?;
195    let has_proc_expr = items.iter().any(|i| !matches!(i, Process::Decl(_)));
196    if items.is_empty() || !has_proc_expr {
197        return cut_err(fail)
198            .context(StrContext::Label(
199                "process body must contain at least one process expression",
200            ))
201            .parse_next(input);
202    }
203    Ok(if items.len() == 1 {
204        items.into_iter().next().unwrap()
205    } else {
206        Process::Seq(items)
207    })
208}
209
210/// Parse a parameter list `'(' (ident ':' Type (',' ident ':' Type)*)? ')'`.
211/// The parentheses are required: a process is `proc Name() { ... }`.
212fn param_list(input: &mut Input<'_>) -> PResult<Vec<(Type, String)>> {
213    delimited(
214        cut_err(('(', ws)).context(StrContext::Expected(StrContextValue::CharLiteral('('))),
215        separated(0.., typed_param, (ws, ',', ws)),
216        (ws, ')'),
217    )
218    .parse_next(input)
219}
220
221// ---------------------------------------------------------------------------
222// Process expression parsers, top-down by precedence.
223//
224// Loosest → tightest:
225//
226//     process          → process_choice (';' process_choice)* ';'    (Seq)
227//     process_choice   → process_guarded ('[]' process_guarded)*
228//                        ('default' process_guarded)?                (Choice with optional default;
229//                                                                     all branches must be prefix-led)
230//     process_guarded  → ('[' expr ']')? process_prefix              (Guard)
231//     process_prefix   → event '->' process_prefix                   (Prefix, right-associative)
232//                      | process_atom                                (fall through)
233//     process_atom     → 'Skip' | 'Div' | '(' process ')'
234//                      | Name '(' args? ')'                          (ProcessRef)
235//
236// Each layer either dispatches to its own enum variant or falls through
237// to the next-tighter layer when the operator isn't present. The choice-
238// branch restriction (Hoare 1985 §1.1.3, pages 7–10) is enforced via
239// `is_valid_choice_branch` — see that function's doc for the per-shape
240// rules and what is deferred to validation.
241// ---------------------------------------------------------------------------
242
243/// Parse a process expression — the body of a process declaration.
244/// Top of the precedence chain; handles `;` (sequential composition).
245///
246/// Items are separated by `;` (no trailing `;`). The smart separator
247/// only consumes `;` when another item follows; if the next thing is
248/// a declaration terminator (end-of-input, `)`, or the next process
249/// declaration), the `;` stays for the outer parser to consume.
250fn process(input: &mut Input<'_>) -> PResult<Process> {
251    let sep = terminated(
252        (ws, reserved(symbol::SEQUENTIAL), ws),
253        not(alt((preceded(ws, eof).value(()), at_process_boundary))),
254    );
255    let items: Vec<Process> = separated(1.., choices, sep).parse_next(input)?;
256    Ok(if items.len() == 1 {
257        items.into_iter().next().unwrap()
258    } else {
259        Process::Seq(items)
260    })
261}
262
263/// Peek-only stop signal for the `process` loop. Succeeds without
264/// consuming input when the `;`-separated body is about to end:
265///
266/// - A closing paren `)` — we're inside a parenthesised group.
267/// - A closing brace `}` — we're at the end of a `proc { }` body.
268fn at_process_boundary(input: &mut Input<'_>) -> PResult<()> {
269    alt((peek((ws, ')')).value(()), peek((ws, '}')).value(()))).parse_next(input)
270}
271
272/// Parse a choice expression: `guarded ('[]' guarded)* ('default' guarded)?`.
273///
274/// When the choice has more than one branch (or a `default`), each
275/// branch must carry a discriminator. The parser checks this
276/// structurally — see [`is_valid_choice_branch`] — recursing into
277/// compounds (`Seq`'s first element, nested `Choice`'s already-
278/// validated branches). The only deferred case is `ProcessRef`,
279/// which name resolution (`rast`) must resolve.
280fn choices(input: &mut Input<'_>) -> PResult<Process> {
281    type Parts = (Vec<Process>, Option<Box<Process>>);
282    cut_err(
283        (
284            separated(1.., guard, (ws, '[', ws, ']')),
285            opt(preceded(
286                (ws, reserved(keyword::DEFAULT)),
287                guard.map(Box::new),
288            )),
289        )
290            .verify(|(b, d): &Parts| choice_branches_valid(b, d.is_some())),
291    )
292    .context(StrContext::Label(
293        "choice branches must be guarded, prefix-led, or a process reference",
294    ))
295    .map(|(branches, default): Parts| {
296        if branches.len() == 1 && default.is_none() {
297            branches.into_iter().next().unwrap()
298        } else {
299            Process::Choice { branches, default }
300        }
301    })
302    .parse_next(input)
303}
304
305/// True iff the parsed branches are admissible as a choice. The
306/// default arm is *not* checked — it's taken when no other branch's
307/// guard succeeds, so being the fallback already discriminates it
308/// without needing its own prefix/guard/ref.
309///
310/// Returns true unconditionally when there's only one branch and no
311/// default — that's not really a choice, just a guarded/prefixed/
312/// atomic process.
313fn choice_branches_valid(branches: &[Process], has_default: bool) -> bool {
314    let is_choice = branches.len() > 1 || has_default;
315    !is_choice || branches.iter().all(is_valid_choice_branch)
316}
317
318/// Returns true iff `p` is admissible as a branch of an external
319/// choice at *parse time*. The function recurses into compound shapes
320/// instead of deferring them to validation, so most reducibility
321/// checks are done structurally:
322///
323/// - `Prefix` / `Guard` — immediate discriminators (event or boolean).
324/// - `Skip` / `Div` — rejected: always-enabled, no possible
325///   reduction.
326/// - `Seq(items)` — admissible iff `items[0]` is admissible. Only the
327///   first element determines the branch's first event; later items
328///   can be anything.
329/// - `Choice { .. }` — always admissible. Each inner branch was
330///   already validated when the nested choice was parsed, so the
331///   compound inherits validity.
332/// - `ProcessRef` — admitted at parse, *deferred* to name resolution.
333///   The parser doesn't yet know the program's names; the validator
334///   must reject references that resolve to bare `Skip` / `Div`.
335///
336/// Compounds reach the choice via parens (`(P; Q) [] R`), because
337/// `;` is looser than `[]` at the top level.
338#[allow(clippy::match_same_arms)] // Per-shape arms documented above; merging
339                                  // them would obscure the case analysis.
340fn is_valid_choice_branch(p: &Process) -> bool {
341    match p {
342        Process::Skip | Process::Div | Process::Decl(_) => false,
343        Process::Prefix(_, _) | Process::Guard(_, _) | Process::ProcessRef { .. } => true,
344        Process::Seq(items) => items.first().is_some_and(is_valid_choice_branch),
345        Process::Choice { .. } => true,
346    }
347}
348
349/// Is `e` structurally capable of being boolean-valued?
350///
351/// Full authority is the type checker — this only
352/// rejects shapes that can never be boolean regardless of type info
353/// (arithmetic/bitwise, integer literals, `sizeof`) at the **top node**;
354/// arithmetic nested inside a comparison (`[a + b == c]`) is unaffected.
355fn is_boolean_shaped(e: &Expr) -> bool {
356    use crate::ast::{BinaryOp, Lit, UnaryOp};
357    match &e.kind {
358        ExprKind::Lit(Lit::Bool(_))
359        | ExprKind::Var(_)
360        | ExprKind::Call(_)
361        | ExprKind::Field { .. } => true,
362        ExprKind::Lit(_) | ExprKind::Sizeof(_) | ExprKind::Cast { .. } => false,
363        ExprKind::Unary { op, .. } => matches!(op, UnaryOp::Not),
364        ExprKind::Binary { op, .. } => matches!(
365            op,
366            BinaryOp::Eq
367                | BinaryOp::Ne
368                | BinaryOp::Lt
369                | BinaryOp::Le
370                | BinaryOp::Gt
371                | BinaryOp::Ge
372                | BinaryOp::And
373                | BinaryOp::Or
374        ),
375    }
376}
377
378/// Parse a guarded process: `('[' expr ']')? prefix`.
379fn guard(input: &mut Input<'_>) -> PResult<Process> {
380    alt((
381        seq!(Process::Guard(
382            delimited(
383                (ws, '[', ws),
384                cut_err(
385                    parse_expr
386                        .verify(is_boolean_shaped)
387                        .context(StrContext::Label("guard"))
388                        .context(StrContext::Expected(StrContextValue::Description(
389                            "a boolean-valued expression (comparison, &&, ||, !, \
390                             boolean variable or call) — arithmetic like `a + b` \
391                             is not a guard",
392                        ))),
393                ),
394                (ws, ']')
395            ),
396            prefixed.map(Box::new),
397        )),
398        prefixed,
399    ))
400    .parse_next(input)
401}
402
403/// Parse a prefix expression: `event '->' prefix` (right-associative)
404/// or fall through to an atom. Atoms are tried first — `Skip`, `Div`,
405/// parens, and `Name(args)` are unambiguous and don't take an event
406/// prefix. Leading whitespace is consumed once here for both branches.
407fn prefixed(input: &mut Input<'_>) -> PResult<Process> {
408    preceded(
409        ws,
410        alt((
411            atom,
412            seq!(Process::Prefix(
413                event::parse,
414                _: (ws, "->", ws),
415                prefixed.map(Box::new),
416            )),
417        )),
418    )
419    .parse_next(input)
420}
421
422/// Parse an atomic process: `Skip`, `Div`, parens, or `Name(args)`.
423/// Caller is responsible for leading whitespace.
424fn atom(input: &mut Input<'_>) -> PResult<Process> {
425    alt((
426        delimited(('(', ws), process, (ws, ')')),
427        reserved(keyword::SKIP).value(Process::Skip),
428        reserved(keyword::DIVERT).value(Process::Div),
429        ref_proc,
430    ))
431    .parse_next(input)
432}
433
434/// Parse a process reference: `UIdent '(' (ident (',' ident)*)? ')'`.
435/// The name must begin with an ASCII uppercase letter — this distinguishes
436/// process references from computation-event names at parse time.
437fn ref_proc(input: &mut Input<'_>) -> PResult<Process> {
438    let (mut reference, span) = seq! { Process::ProcessRef {
439        name: upper_identifier,
440        params: delimited(
441            (ws, '(', ws),
442            separated(0.., identifier.map(str::to_string), (ws, ',', ws)),
443            (ws, ')'),
444        ),
445        span: "".value(0..0usize),
446    }}
447    .with_span()
448    .parse_next(input)?;
449    if let Process::ProcessRef { span: at, .. } = &mut reference {
450        *at = span;
451    }
452    Ok(reference)
453}
454
455// ============================================================================
456// Tests
457// ============================================================================
458
459#[cfg(test)]
460mod tests {
461    use super::*;
462    use crate::ast::{CommKind, Event, IrqKind};
463    use winnow::stream::LocatingSlice;
464
465    fn parse_one_process(input: &str) -> ProcessDecl {
466        let mut remaining = LocatingSlice::new(input);
467        parse(&mut remaining).unwrap()
468    }
469
470    #[test]
471    fn test_process_skip_only() {
472        let sp = parse_one_process("proc Done() { Skip; }");
473        assert_eq!(sp.name, "Done");
474        assert!(sp.params.is_empty(), "{:?}", sp.params);
475        assert!(matches!(sp.body, Process::Skip));
476    }
477
478    #[test]
479    fn test_process_span_covers_declaration_not_bind() {
480        let src = "@bind(microkit.init) proc Init() { Skip; }";
481        let sp = parse_one_process(src);
482        let start = src.find("proc").unwrap();
483        // Leading whitespace before `proc` is part of the span, as for
484        // every other declaration span.
485        assert_eq!(sp.span, start - 1..src.len());
486        assert_eq!(&src[sp.span.start..], " proc Init() { Skip; }");
487    }
488
489    #[test]
490    fn test_process_needs_its_parentheses() {
491        let mut remaining = LocatingSlice::new("proc Init { Skip; }");
492        assert!(parse(&mut remaining).is_err());
493    }
494
495    #[test]
496    fn test_process_init_must_be_uppercase() {
497        // The boot process is `UpperCamelCase` like any other; lowercase
498        // `init` is not a process name.
499        let sp = parse_one_process("proc Init() { notify_peer!1 -> Skip; }");
500        assert_eq!(sp.name, "Init");
501        assert!(sp.params.is_empty(), "{:?}", sp.params);
502
503        let input = "proc init() { notify_peer!1 -> Skip; }";
504        let mut remaining = LocatingSlice::new(input);
505        assert!(parse(&mut remaining).is_err());
506    }
507
508    #[test]
509    fn test_process_lowercase_name_rejected() {
510        let input = "proc handler() { Skip; }";
511        let mut remaining = LocatingSlice::new(input);
512        assert!(parse(&mut remaining).is_err());
513    }
514
515    #[test]
516    fn test_bind_annotation_single() {
517        let sp = parse_one_process("@bind(microkit.notified)\nproc Notified() { Skip; }");
518        assert_eq!(sp.name, "Notified");
519        assert_eq!(sp.binds.len(), 1);
520        assert_eq!(sp.binds[0].platform, "microkit");
521        assert_eq!(sp.binds[0].entry, "notified");
522    }
523
524    #[test]
525    fn test_bind_group_multiple_platforms() {
526        // One @bind(...) groups several platform.entry pairs on a single line.
527        let src = "@bind(microkit.notified, cheri.interrupt_handler)\nproc Notified() { Skip; }";
528        let sp = parse_one_process(src);
529        assert_eq!(sp.binds.len(), 2);
530        assert_eq!(sp.binds[0].platform, "microkit");
531        assert_eq!(sp.binds[0].entry, "notified");
532        assert_eq!(sp.binds[1].platform, "cheri");
533        assert_eq!(sp.binds[1].entry, "interrupt_handler");
534    }
535
536    #[test]
537    fn test_stacked_bind_lines_rejected() {
538        // Bindings must be one group; stacking multiple @bind lines is rejected.
539        let input = "@bind(microkit.notified)\n@bind(cheri.interrupt_handler)\nproc N() { Skip; }";
540        let mut remaining = LocatingSlice::new(input);
541        assert!(parse(&mut remaining).is_err());
542    }
543
544    #[test]
545    fn test_bind_pair_span_bounds() {
546        // Each pair's span covers just the `platform.entry` text.
547        let src = "@bind(microkit.notified)\nproc Notified() { Skip; }";
548        let sp = parse_one_process(src);
549        let span = sp.binds[0].span.clone();
550        assert_eq!(&src[span], "microkit.notified");
551    }
552
553    #[test]
554    fn test_bind_on_init_allowed() {
555        // Explicit bind on the boot process coexists with the name convention.
556        let sp = parse_one_process("@bind(cheri.init)\nproc Init() { Skip; }");
557        assert_eq!(sp.name, "Init");
558        assert_eq!(sp.binds[0].entry, "init");
559    }
560
561    #[test]
562    fn test_unannotated_process_has_no_binds() {
563        let sp = parse_one_process("proc Done() { Skip; }");
564        assert!(sp.binds.is_empty(), "{:?}", sp.binds);
565    }
566
567    #[test]
568    fn test_bind_missing_dot_rejected() {
569        let input = "@bind(microkit notified)\nproc Notified() { Skip; }";
570        let mut remaining = LocatingSlice::new(input);
571        assert!(parse(&mut remaining).is_err());
572    }
573
574    #[test]
575    fn test_bind_without_proc_rejected() {
576        let input = "@bind(microkit.notified)\nevt handle: eth.go();";
577        let mut remaining = LocatingSlice::new(input);
578        assert!(parse(&mut remaining).is_err());
579    }
580
581    #[test]
582    fn test_process_div() {
583        let sp = parse_one_process("proc Loop() { Div; }");
584        assert!(matches!(sp.body, Process::Div));
585    }
586
587    #[test]
588    fn test_process_with_param() {
589        let sp = parse_one_process("proc Reply(pkt: int) { Skip; }");
590        assert_eq!(sp.params.len(), 1);
591        assert_eq!(sp.params[0].1, "pkt");
592    }
593
594    #[test]
595    fn test_event_prefix_with_call_continuation() {
596        let sp = parse_one_process("proc Notified() { irq?159 -> Handle_eth(); }");
597        match &sp.body {
598            Process::Prefix(
599                Event::IEVENT {
600                    irq,
601                    kind: IrqKind::Await,
602                },
603                rest,
604            ) => {
605                assert_eq!(*irq, 159);
606                match rest.as_ref() {
607                    Process::ProcessRef { name, .. } => assert_eq!(name, "Handle_eth"),
608                    other => panic!("expected ProcessRef, got {other:?}"),
609                }
610            }
611            other => panic!("expected channel-recv prefix, got {other:?}"),
612        }
613    }
614
615    #[test]
616    fn test_event_send() {
617        let sp = parse_one_process("proc Send() { o2d!pkt -> Skip; }");
618        match &sp.body {
619            Process::Prefix(
620                Event::CMEvent {
621                    channel,
622                    kind: CommKind::Send { expr: Some(expr) },
623                    ..
624                },
625                _,
626            ) => {
627                assert_eq!(channel, "o2d");
628                assert!(matches!(expr.kind, ExprKind::Var(ref n) if n == "pkt"));
629            }
630            other => panic!("expected channel-send prefix, got {other:?}"),
631        }
632    }
633
634    #[test]
635    fn an_unbuffered_event_carries_nothing() {
636        let sp = parse_one_process("proc P() { ball? -> ball! -> P(); }");
637        let Process::Prefix(
638            Event::CMEvent {
639                kind: CommKind::Recv { var: None },
640                ..
641            },
642            rest,
643        ) = &sp.body
644        else {
645            panic!("expected `ball?`, got {:?}", sp.body);
646        };
647        assert!(matches!(
648            rest.as_ref(),
649            Process::Prefix(
650                Event::CMEvent {
651                    kind: CommKind::Send { expr: None },
652                    ..
653                },
654                _
655            )
656        ));
657    }
658
659    #[test]
660    fn a_negative_payload_is_not_the_arrow() {
661        let sp = parse_one_process("proc P() { c!-1 -> Skip; }");
662        assert!(matches!(
663            &sp.body,
664            Process::Prefix(
665                Event::CMEvent {
666                    kind: CommKind::Send {
667                        expr: Some(Expr {
668                            kind: ExprKind::Unary { .. },
669                            ..
670                        })
671                    },
672                    ..
673                },
674                _
675            )
676        ));
677    }
678
679    #[test]
680    fn test_irq_ack() {
681        let sp = parse_one_process("proc AckIrq() { irq!42 -> Skip; }");
682        match &sp.body {
683            Process::Prefix(
684                Event::IEVENT {
685                    irq,
686                    kind: IrqKind::Ack,
687                },
688                _,
689            ) => {
690                assert_eq!(*irq, 42);
691            }
692            other => panic!("expected IRQ ack prefix, got {other:?}"),
693        }
694    }
695
696    #[test]
697    fn test_irq_non_integer_payload_rejected() {
698        // `irq` is reserved: payload must be an integer literal.
699        let input = "proc Foo() { irq?bad -> Skip; }";
700        let mut remaining = LocatingSlice::new(input);
701        assert!(parse(&mut remaining).is_err());
702    }
703
704    #[test]
705    fn test_computation_event_prefix() {
706        let sp = parse_one_process("proc Foo() { handle_irq -> Skip; }");
707        match &sp.body {
708            Process::Prefix(Event::CPEvent { name, carriers, .. }, _) => {
709                assert_eq!(name, "handle_irq");
710                assert!(carriers.is_empty(), "{carriers:?}");
711            }
712            other => panic!("expected computation prefix, got {other:?}"),
713        }
714    }
715
716    #[test]
717    fn test_computation_event_prefix_with_carriers() {
718        let sp = parse_one_process("proc Foo() { handle_packet.size -> Skip; }");
719        match &sp.body {
720            Process::Prefix(Event::CPEvent { name, carriers, .. }, _) => {
721                assert_eq!(name, "handle_packet");
722                assert_eq!(carriers, &vec!["size".to_string()]);
723            }
724            other => panic!("expected computation prefix, got {other:?}"),
725        }
726    }
727
728    #[test]
729    fn test_computation_event_prefix_multi_carriers() {
730        let sp = parse_one_process("proc Foo() { handle_two.x.y -> Skip; }");
731        match &sp.body {
732            Process::Prefix(Event::CPEvent { name, carriers, .. }, _) => {
733                assert_eq!(name, "handle_two");
734                assert_eq!(carriers, &vec!["x".to_string(), "y".to_string()]);
735            }
736            other => panic!("expected computation prefix, got {other:?}"),
737        }
738    }
739
740    #[test]
741    fn test_choice() {
742        // Branches must be prefix-led; each one is a guarded prefix here.
743        let sp = parse_one_process("proc Foo() { [rx] e1 -> Skip [] [!rx] e2 -> Div; }");
744        match &sp.body {
745            Process::Choice {
746                branches,
747                default: None,
748            } => {
749                assert_eq!(branches.len(), 2);
750            }
751            other => panic!("expected Choice, got {other:?}"),
752        }
753    }
754
755    #[test]
756    fn test_choice_unguarded_skip_rejected() {
757        // Bare `Skip` / `Div` aren't admissible branches.
758        let input = "proc Foo() { Skip [] Skip; }";
759        let mut remaining = LocatingSlice::new(input);
760        assert!(parse(&mut remaining).is_err());
761    }
762
763    #[test]
764    fn test_choice_guarded_atom_branches_allowed() {
765        let sp = parse_one_process("proc Foo() { [a] Skip [] [b] Div; }");
766        match &sp.body {
767            Process::Choice {
768                branches,
769                default: None,
770            } => assert_eq!(branches.len(), 2),
771            other => panic!("expected Choice, got {other:?}"),
772        }
773    }
774
775    #[test]
776    fn test_choice_processref_branches_allowed() {
777        let sp = parse_one_process("proc Foo() { Bar() [] Baz(); }");
778        match &sp.body {
779            Process::Choice {
780                branches,
781                default: None,
782            } => assert_eq!(branches.len(), 2),
783            other => panic!("expected Choice, got {other:?}"),
784        }
785    }
786
787    #[test]
788    fn test_choice_seq_branch_via_parens() {
789        let sp = parse_one_process("proc Foo() { (Bar(); Skip) [] Qux(); }");
790        match &sp.body {
791            Process::Choice {
792                branches,
793                default: None,
794            } => {
795                assert_eq!(branches.len(), 2);
796                assert!(matches!(branches[0], Process::Seq(_)));
797                assert!(matches!(branches[1], Process::ProcessRef { .. }));
798            }
799            other => panic!("expected Choice, got {other:?}"),
800        }
801    }
802
803    #[test]
804    fn test_choice_seq_branch_with_skip_first_rejected() {
805        let input = "proc Foo() { (Skip; Bar()) [] Qux(); }";
806        let mut remaining = LocatingSlice::new(input);
807        assert!(parse(&mut remaining).is_err());
808    }
809
810    #[test]
811    fn test_guard_rejects_arithmetic_top_node() {
812        // [a + b] can never be boolean — rejected at parse time.
813        for bad in [
814            "proc F() { [a + b] Skip; }",
815            "proc F() { [42] Skip; }",
816            "proc F() { [x << 2] Skip; }",
817            "proc F() { [sizeof(uint8)] Skip; }",
818            "proc F() { [-x] Skip; }",
819        ] {
820            let mut remaining = LocatingSlice::new(bad);
821            assert!(parse(&mut remaining).is_err(), "should reject {bad}");
822        }
823    }
824
825    #[test]
826    fn test_guard_accepts_boolean_shapes() {
827        // Arithmetic inside a comparison is fine; bare vars and calls are
828        // presumed boolean until the type checker judges them.
829        for ok in [
830            "proc F() { [a + b == c] Skip; }",
831            "proc F() { [eir % 2 == 1] Skip; }",
832            "proc F() { [(eir & (1 << 25)) != 0] Skip; }",
833            "proc F() { [!flag && ready] Skip; }",
834            "proc F() { [eth.isforward()] Skip; }",
835            "proc F() { [true] Skip; }",
836        ] {
837            let mut remaining = LocatingSlice::new(ok);
838            assert!(parse(&mut remaining).is_ok(), "should accept {ok}");
839        }
840    }
841
842    #[test]
843    fn test_guard() {
844        let sp = parse_one_process("proc Foo() { [rx] Skip; }");
845        match &sp.body {
846            Process::Guard(_, _) => {}
847            other => panic!("expected Guard, got {other:?}"),
848        }
849    }
850
851    #[test]
852    fn test_process_ref_no_args() {
853        let sp = parse_one_process("proc Foo() { Notified(); }");
854        match &sp.body {
855            Process::ProcessRef { name, params, .. } => {
856                assert_eq!(name, "Notified");
857                assert!(params.is_empty(), "{params:?}");
858            }
859            other => panic!("expected ProcessRef, got {other:?}"),
860        }
861    }
862
863    #[test]
864    fn test_process_ref_lowercase_rejected() {
865        // Lowercase names are computation events, not process references.
866        let input = "proc Foo() { notified(); }";
867        let mut remaining = LocatingSlice::new(input);
868        assert!(parse(&mut remaining).is_err());
869    }
870
871    #[test]
872    fn test_process_ref_with_arg() {
873        let sp = parse_one_process("proc Foo() { Reply(pkt); }");
874        match &sp.body {
875            Process::ProcessRef { name, params, .. } => {
876                assert_eq!(name, "Reply");
877                assert_eq!(params, &vec!["pkt".to_string()]);
878            }
879            other => panic!("expected ProcessRef, got {other:?}"),
880        }
881    }
882
883    #[test]
884    fn test_multi_item_body() {
885        let sp = parse_one_process("proc Notified() { irq?159 -> Handle_eth(); Notified(); }");
886        match sp.body {
887            Process::Seq(items) => assert_eq!(items.len(), 2),
888            other => panic!("expected Seq, got {other:?}"),
889        }
890    }
891
892    #[test]
893    fn test_default_choice() {
894        let sp = parse_one_process("proc Foo() { [a] e1 -> Skip [] [b] e2 -> Div default Skip; }");
895        match &sp.body {
896            Process::Choice {
897                branches,
898                default: Some(d),
899            } => {
900                assert_eq!(branches.len(), 2);
901                assert!(matches!(**d, Process::Skip));
902            }
903            other => panic!("expected Choice with default, got {other:?}"),
904        }
905    }
906
907    #[test]
908    fn test_decl_in_body() {
909        // Variable declaration followed by a process expression.
910        let sp = parse_one_process("proc Foo() { buf: int; handle_irq -> Skip; }");
911        match sp.body {
912            Process::Seq(items) => {
913                assert_eq!(items.len(), 2);
914                assert!(matches!(items[0], Process::Decl(_)));
915                assert!(matches!(items[1], Process::Prefix(_, _)));
916            }
917            other => panic!("expected Seq, got {other:?}"),
918        }
919    }
920
921    #[test]
922    fn test_decl_only_body_rejected() {
923        // A body of only variable declarations is rejected (no process expression).
924        let input = "proc Foo() { x: int; }";
925        let mut remaining = LocatingSlice::new(input);
926        assert!(parse(&mut remaining).is_err());
927    }
928
929    #[test]
930    fn test_call_stmt_in_body_rejected() {
931        // Function calls are not allowed directly in a proc body.
932        let input = "proc Foo() { eth.go(); }";
933        let mut remaining = LocatingSlice::new(input);
934        assert!(parse(&mut remaining).is_err());
935    }
936
937    #[test]
938    fn test_missing_proc_keyword_rejected() {
939        let input = "Foo() = Skip;";
940        let mut remaining = LocatingSlice::new(input);
941        assert!(parse(&mut remaining).is_err());
942    }
943
944    #[test]
945    fn test_empty_body_rejected() {
946        let input = "proc Foo() { }";
947        let mut remaining = LocatingSlice::new(input);
948        assert!(parse(&mut remaining).is_err());
949    }
950
951    #[test]
952    fn test_lowercase_name_rejected() {
953        let input = "proc foo() { Skip; }";
954        let mut remaining = LocatingSlice::new(input);
955        assert!(parse(&mut remaining).is_err());
956    }
957}