Skip to main content

cbcl_parser/
protocol_parser.rs

1//! Causal protocol parser (REQ-201, SPEC-015 REQ-704).
2//!
3//! Parses `(protocol (then ...)+)` S-expressions into `CausalProtocol`.
4//! Desugars variadic `(then a b c)` to pairwise edges: a→b, b→c.
5//!
6//! ## Bounded repetition (SPEC-015 REQ-704, CON-701)
7//!
8//! A `(repeat <k> <step>…)` form may appear in step position inside a
9//! `(then …)` chain (and nowhere else); `<k>` is a `nat` (post-parse
10//! predicate: positive integer atom) and each `<step>` is a node-ref or a
11//! nested `repeat`. The form macro-expands **once, at parse** into `k`
12//! sequential copies of its body spliced into the enclosing chain, so the
13//! ordinary pairwise-edge desugaring chains the copies by `:caused-by`
14//! type references and R1–R3, R5, R6 run over the *expanded* protocol.
15//!
16//! Synthesised copy names live in a non-user namespace: copy `i` of step
17//! `x` is `x#i`, and `'#'` ([`cbcl_core::protocol::REPEAT_SEPARATOR`]) is
18//! outside the legal symbol alphabet (`parser::is_symbol_char`; it
19//! introduces `#t`/`#f`), so collision with any user-declared performative
20//! is impossible by construction. Iteration seams are structural: a body
21//! ending in `(any a b)` seams as `(any a#i b#i) → first-of-copy-i+1`
22//! (the choice over the alternatives' copy-instances), one ending in
23//! `(all …)` seams on the fan-in's copy-instance; nested `repeat`
24//! multiplies bounds and suffixes again (`x#1#2`).
25
26#![forbid(unsafe_code)]
27
28use alloc::collections::BTreeMap;
29use alloc::collections::BTreeSet;
30use alloc::string::{String, ToString};
31use alloc::vec::Vec;
32use cbcl_core::protocol::{CausalProtocol, NodeRef, StepDecl, BEGIN_KEYWORD, REPEAT_SEPARATOR};
33use cbcl_core::sexpr::{Atom, SExpr};
34use core::fmt;
35
36/// Absolute ceiling on `(repeat …)` macro-expansion, equal to the largest
37/// `max-expansion-size` any valid dialect may declare (R2,
38/// `ResourceBounds::is_valid` caps it at 8192). An expansion beyond this
39/// can never install, so the parser rejects it *before materialising it*
40/// (typed, fail closed); the dialect's own declared budget is enforced
41/// separately at install (SPEC-015 REQ-704).
42const REPEAT_EXPANSION_CEILING: u64 = 8192;
43
44/// Errors from parsing a `(protocol ...)` declaration.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum ProtocolParseError {
47    /// Top-level form is not a list.
48    NotAList,
49    /// First element is not `protocol`.
50    NotProtocol,
51    /// No `(then ...)` declarations found.
52    NoThenClauses,
53    /// A `(then ...)` clause has fewer than 2 node-refs.
54    ThenTooFew,
55    /// Expected a `(then ...)` clause but found something else.
56    ExpectedThen { found: String },
57    /// Node-ref is not a valid symbol, `(any ...)`, or `(all ...)`.
58    InvalidNodeRef { detail: String },
59    /// `(any ...)` or `(all ...)` has fewer than 2 arguments.
60    GroupTooFew { kind: String },
61    /// `(any ...)` or `(all ...)` contains a non-symbol argument.
62    GroupNonSymbol { kind: String },
63    /// `(repeat ...)` count is not a `nat` (CON-701): a positive integer
64    /// atom. Zero, negatives, and non-integer atoms are all rejected.
65    RepeatCountNotNat { found: String },
66    /// `(repeat ...)` has no protocol-steps in its body (CON-701 requires
67    /// `protocol-step+`).
68    RepeatEmptyBody,
69    /// `(repeat ...)` body references `begin`; the protocol root is a
70    /// keyword, not a repeatable step.
71    RepeatContainsBegin,
72    /// `(repeat ...)` expansion (nested repeats multiply) exceeds the
73    /// absolute R2 ceiling — rejected before materialisation.
74    RepeatBudgetExceeded { steps: u64 },
75}
76
77impl fmt::Display for ProtocolParseError {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        match self {
80            Self::NotAList => write!(f, "protocol declaration must be a list"),
81            Self::NotProtocol => write!(f, "expected 'protocol' keyword"),
82            Self::NoThenClauses => {
83                write!(f, "protocol must contain at least one (then ...) clause")
84            }
85            Self::ThenTooFew => write!(f, "(then ...) requires at least 2 node-refs"),
86            Self::ExpectedThen { found } => {
87                write!(f, "expected (then ...) clause, found: {found}")
88            }
89            Self::InvalidNodeRef { detail } => write!(f, "invalid node-ref: {detail}"),
90            Self::GroupTooFew { kind } => {
91                write!(f, "({kind} ...) requires at least 2 performative-refs")
92            }
93            Self::GroupNonSymbol { kind } => {
94                write!(f, "({kind} ...) arguments must be symbols")
95            }
96            Self::RepeatCountNotNat { found } => {
97                write!(
98                    f,
99                    "(repeat ...) count must be a positive integer (CON-701 nat), found: {found}"
100                )
101            }
102            Self::RepeatEmptyBody => {
103                write!(f, "(repeat ...) requires at least one protocol-step")
104            }
105            Self::RepeatContainsBegin => {
106                write!(f, "(repeat ...) body must not reference 'begin'")
107            }
108            Self::RepeatBudgetExceeded { steps } => {
109                write!(
110                    f,
111                    "(repeat ...) expands to {steps} step instances, exceeding the \
112                     R2 expansion ceiling {REPEAT_EXPANSION_CEILING}"
113                )
114            }
115        }
116    }
117}
118
119/// Parse a `(protocol (then ...)+)` S-expression into a `CausalProtocol` (REQ-201).
120pub fn parse_protocol(sexpr: &SExpr) -> Result<CausalProtocol, ProtocolParseError> {
121    let items = match sexpr {
122        SExpr::List(items) => items,
123        _ => return Err(ProtocolParseError::NotAList),
124    };
125
126    if items.is_empty() || !items[0].is_symbol("protocol") {
127        return Err(ProtocolParseError::NotProtocol);
128    }
129
130    if items.len() < 2 {
131        return Err(ProtocolParseError::NoThenClauses);
132    }
133
134    let mut steps: BTreeMap<String, StepDecl> = BTreeMap::new();
135
136    // One expansion budget for the whole protocol: every step instance a
137    // `(repeat …)` form materialises is charged against the absolute R2
138    // ceiling, so the parser's output size stays bounded by construction
139    // (SPEC-015 REQ-704).
140    let mut expansion_used: u64 = 0;
141
142    for clause in &items[1..] {
143        let edges = parse_then_clause(clause, &mut expansion_used)?;
144        for (pred, succ) in edges {
145            // For each performative in the predecessor, record the successor.
146            for p in pred.performatives() {
147                let step = steps.entry(p.into()).or_insert_with(|| StepDecl {
148                    performative: p.into(),
149                    predecessors: Vec::new(),
150                    successors: Vec::new(),
151                });
152                step.successors.push(succ.clone());
153            }
154            // For each performative in the successor, record the predecessor.
155            for s in succ.performatives() {
156                let step = steps.entry(s.into()).or_insert_with(|| StepDecl {
157                    performative: s.into(),
158                    predecessors: Vec::new(),
159                    successors: Vec::new(),
160                });
161                step.predecessors.push(pred.clone());
162            }
163        }
164    }
165
166    Ok(CausalProtocol { steps })
167}
168
169/// Parse a `(then protocol-step ...)` clause and return pairwise edges.
170///
171/// Variadic: `(then a b c)` desugars to edges `[(a, b), (b, c)]`.
172/// A `(repeat k …)` form in step position (SPEC-015 REQ-704) is
173/// macro-expanded here — its copies splice into the chain, so the
174/// pairwise desugaring produces both the intra-copy edges and the
175/// structural seam edges between consecutive copies.
176fn parse_then_clause(
177    sexpr: &SExpr,
178    expansion_used: &mut u64,
179) -> Result<Vec<(NodeRef, NodeRef)>, ProtocolParseError> {
180    let items = match sexpr {
181        SExpr::List(items) if !items.is_empty() => items,
182        SExpr::List(_) => {
183            return Err(ProtocolParseError::ExpectedThen {
184                found: "empty list".into(),
185            })
186        }
187        _ => {
188            return Err(ProtocolParseError::ExpectedThen {
189                found: alloc::format!("{sexpr}"),
190            })
191        }
192    };
193
194    if !items[0].is_symbol("then") {
195        return Err(ProtocolParseError::ExpectedThen {
196            found: alloc::format!("{}", items[0]),
197        });
198    }
199
200    let mut refs: Vec<NodeRef> = Vec::new();
201    for item in &items[1..] {
202        if is_repeat_form(item) {
203            expand_repeat(item, &mut refs, expansion_used)?;
204        } else {
205            refs.push(parse_node_ref(item)?);
206        }
207    }
208
209    if refs.len() < 2 {
210        return Err(ProtocolParseError::ThenTooFew);
211    }
212
213    // Desugar variadic to pairwise edges.
214    let edges = refs
215        .windows(2)
216        .map(|w| (w[0].clone(), w[1].clone()))
217        .collect();
218    Ok(edges)
219}
220
221/// Is this S-expression a `(repeat …)` form?
222fn is_repeat_form(sexpr: &SExpr) -> bool {
223    matches!(sexpr, SExpr::List(items) if !items.is_empty() && items[0].is_symbol("repeat"))
224}
225
226/// CON-701 `nat`: a post-parse predicate on the recognised atom — the
227/// atom must be an integer and positive. The S-expression lexer
228/// recognises integer text into a canonical `i64` atom (a leading-zero
229/// spelling does not survive recognition as a distinct atom), so the
230/// predicate here is positivity on the recognised integer; zero,
231/// negatives, symbols, strings, and lists are all typed rejections.
232fn parse_nat(sexpr: &SExpr) -> Result<u64, ProtocolParseError> {
233    match sexpr {
234        SExpr::Atom(Atom::Num(n)) if *n >= 1 => Ok(*n as u64),
235        other => Err(ProtocolParseError::RepeatCountNotNat {
236            found: alloc::format!("{other}"),
237        }),
238    }
239}
240
241/// Charge `n` synthesised step instances against the protocol-wide
242/// expansion budget; over the ceiling is a typed rejection *before*
243/// anything is materialised.
244fn charge_expansion(used: &mut u64, n: u64) -> Result<(), ProtocolParseError> {
245    let total = used.saturating_add(n);
246    if total > REPEAT_EXPANSION_CEILING {
247        return Err(ProtocolParseError::RepeatBudgetExceeded { steps: total });
248    }
249    *used = total;
250    Ok(())
251}
252
253/// Suffix every performative name in a node-ref with the copy index,
254/// producing the copy-instance in the non-user `#` namespace:
255/// `x` → `x#i`, `(any a b)` → `(any a#i b#i)`, `(all p q)` → `(all p#i q#i)`.
256fn suffix_node_ref(nr: &NodeRef, index: u64) -> NodeRef {
257    let suffix = |s: &String| alloc::format!("{s}{REPEAT_SEPARATOR}{index}");
258    match nr {
259        NodeRef::Single(s) => NodeRef::Single(suffix(s)),
260        NodeRef::Any(set) => NodeRef::Any(set.iter().map(suffix).collect()),
261        NodeRef::All(set) => NodeRef::All(set.iter().map(suffix).collect()),
262    }
263}
264
265/// Macro-expand a `(repeat <k> <step>…)` form (SPEC-015 REQ-704, CON-701)
266/// into `k` sequential copies of its body, appended to `out` so the
267/// enclosing `(then …)` chain's pairwise desugaring wires the copies
268/// together. Seams are structural: whatever node-ref ends the body —
269/// single, `(any …)` choice, or `(all …)` fan-in — its copy-instance is
270/// the predecessor of the next copy's first step.
271///
272/// Nested `repeat` expands innermost-first (its instances are suffixed
273/// again by the outer form) and multiplies the charged budget.
274fn expand_repeat(
275    sexpr: &SExpr,
276    out: &mut Vec<NodeRef>,
277    used: &mut u64,
278) -> Result<(), ProtocolParseError> {
279    let items = match sexpr {
280        SExpr::List(items) if !items.is_empty() && items[0].is_symbol("repeat") => items,
281        _ => {
282            return Err(ProtocolParseError::InvalidNodeRef {
283                detail: alloc::format!("{sexpr}"),
284            })
285        }
286    };
287    if items.len() < 2 {
288        return Err(ProtocolParseError::RepeatCountNotNat {
289            found: "<missing>".into(),
290        });
291    }
292    let k = parse_nat(&items[1])?;
293    if items.len() < 3 {
294        return Err(ProtocolParseError::RepeatEmptyBody);
295    }
296
297    // Parse the body: node-refs or nested repeat forms. Each materialised
298    // instance is charged as it is produced.
299    let mut body: Vec<NodeRef> = Vec::new();
300    for step in &items[2..] {
301        if is_repeat_form(step) {
302            expand_repeat(step, &mut body, used)?;
303        } else {
304            let nr = parse_node_ref(step)?;
305            if nr.performatives().any(|p| p == BEGIN_KEYWORD) {
306                return Err(ProtocolParseError::RepeatContainsBegin);
307            }
308            charge_expansion(used, 1)?;
309            body.push(nr);
310        }
311    }
312
313    // The body's own instances were charged while parsing; the remaining
314    // k−1 copies are charged multiplicatively (nested repeat therefore
315    // multiplies bounds), before materialisation.
316    let extra = (k - 1)
317        .checked_mul(body.len() as u64)
318        .ok_or(ProtocolParseError::RepeatBudgetExceeded { steps: u64::MAX })?;
319    charge_expansion(used, extra)?;
320
321    for i in 1..=k {
322        out.extend(body.iter().map(|nr| suffix_node_ref(nr, i)));
323    }
324    Ok(())
325}
326
327/// Reject a symbol that trespasses on the synthesised-copy namespace.
328///
329/// The text parser can never produce a symbol containing
330/// [`REPEAT_SEPARATOR`] (`'#'` is outside `is_symbol_char`), so this only
331/// fires for programmatically built S-expression trees — kept fail-closed
332/// so the non-user namespace stays non-user on every input path.
333fn check_user_symbol(s: &str) -> Result<(), ProtocolParseError> {
334    if s.contains(REPEAT_SEPARATOR) {
335        return Err(ProtocolParseError::InvalidNodeRef {
336            detail: alloc::format!(
337                "'{s}' contains '{REPEAT_SEPARATOR}', reserved for synthesised repeat copies"
338            ),
339        });
340    }
341    Ok(())
342}
343
344/// Parse a node-ref: bare symbol, `(any ...)`, or `(all ...)`.
345fn parse_node_ref(sexpr: &SExpr) -> Result<NodeRef, ProtocolParseError> {
346    match sexpr {
347        SExpr::Atom(Atom::Symbol(s)) => {
348            check_user_symbol(s)?;
349            Ok(NodeRef::Single(s.clone()))
350        }
351        SExpr::List(items) if !items.is_empty() => {
352            let head = match &items[0] {
353                SExpr::Atom(Atom::Symbol(s)) => s.as_str(),
354                _ => {
355                    return Err(ProtocolParseError::InvalidNodeRef {
356                        detail: alloc::format!("list head is not a symbol: {}", items[0]),
357                    })
358                }
359            };
360
361            match head {
362                "any" | "all" => {
363                    let kind = head.to_string();
364                    if items.len() < 3 {
365                        return Err(ProtocolParseError::GroupTooFew { kind: kind.clone() });
366                    }
367                    let mut set = BTreeSet::new();
368                    for item in &items[1..] {
369                        match item {
370                            SExpr::Atom(Atom::Symbol(s)) => {
371                                check_user_symbol(s)?;
372                                set.insert(s.clone());
373                            }
374                            _ => {
375                                return Err(ProtocolParseError::GroupNonSymbol {
376                                    kind: kind.clone(),
377                                })
378                            }
379                        }
380                    }
381                    if head == "any" {
382                        Ok(NodeRef::Any(set))
383                    } else {
384                        Ok(NodeRef::All(set))
385                    }
386                }
387                _ => Err(ProtocolParseError::InvalidNodeRef {
388                    detail: alloc::format!("unknown node-ref head: {head}"),
389                }),
390            }
391        }
392        _ => Err(ProtocolParseError::InvalidNodeRef {
393            detail: alloc::format!("{sexpr}"),
394        }),
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401    use alloc::vec;
402    use cbcl_core::sexpr::{Atom, SExpr};
403
404    fn sym(s: &str) -> SExpr {
405        SExpr::Atom(Atom::Symbol(String::from(s)))
406    }
407
408    fn list(items: Vec<SExpr>) -> SExpr {
409        SExpr::List(items)
410    }
411
412    // ================================================================
413    // TEST-201: Compaction — pure sequence
414    // ================================================================
415
416    #[test]
417    fn parse_compaction_protocol() {
418        // (protocol (then begin pause pause-ack get-memory memory-dump set-memory set-memory-ack resume))
419        let sexpr = list(vec![
420            sym("protocol"),
421            list(vec![
422                sym("then"),
423                sym("begin"),
424                sym("pause"),
425                sym("pause-ack"),
426                sym("get-memory"),
427                sym("memory-dump"),
428                sym("set-memory"),
429                sym("set-memory-ack"),
430                sym("resume"),
431            ]),
432        ]);
433        let proto = parse_protocol(&sexpr).unwrap();
434        // begin -> pause -> pause-ack -> ... -> resume (7 edges)
435        assert!(proto.steps.contains_key("begin"));
436        assert!(proto.steps.contains_key("resume"));
437        assert_eq!(proto.steps["begin"].successors.len(), 1);
438        assert_eq!(
439            proto.steps["begin"].successors[0],
440            NodeRef::Single("pause".into())
441        );
442        assert_eq!(proto.steps["pause"].predecessors.len(), 1);
443        assert_eq!(
444            proto.steps["pause"].predecessors[0],
445            NodeRef::Single("begin".into())
446        );
447        assert_eq!(proto.steps["resume"].predecessors.len(), 1);
448        assert!(proto.steps["resume"].successors.is_empty());
449    }
450
451    // ================================================================
452    // TEST-201: Document operations — choice + concurrent fan-out
453    // ================================================================
454
455    #[test]
456    fn parse_document_ops_protocol() {
457        // (protocol
458        //   (then begin (any read write close))
459        //   (then read content)
460        //   (then write ack)
461        //   (then (any content ack) (any read write close)))
462        let sexpr = list(vec![
463            sym("protocol"),
464            list(vec![
465                sym("then"),
466                sym("begin"),
467                list(vec![sym("any"), sym("read"), sym("write"), sym("close")]),
468            ]),
469            list(vec![sym("then"), sym("read"), sym("content")]),
470            list(vec![sym("then"), sym("write"), sym("ack")]),
471            list(vec![
472                sym("then"),
473                list(vec![sym("any"), sym("content"), sym("ack")]),
474                list(vec![sym("any"), sym("read"), sym("write"), sym("close")]),
475            ]),
476        ]);
477        let proto = parse_protocol(&sexpr).unwrap();
478        assert!(proto.steps.contains_key("begin"));
479        assert!(proto.steps.contains_key("read"));
480        assert!(proto.steps.contains_key("write"));
481        assert!(proto.steps.contains_key("close"));
482        assert!(proto.steps.contains_key("content"));
483        assert!(proto.steps.contains_key("ack"));
484
485        // begin has one successor: (any read write close)
486        assert_eq!(proto.steps["begin"].successors.len(), 1);
487        let expected_any: BTreeSet<String> = ["read", "write", "close"]
488            .iter()
489            .map(|s| String::from(*s))
490            .collect();
491        assert_eq!(
492            proto.steps["begin"].successors[0],
493            NodeRef::Any(expected_any)
494        );
495    }
496
497    // ================================================================
498    // TEST-201: Request-response loop
499    // ================================================================
500
501    #[test]
502    fn parse_request_response_protocol() {
503        // (protocol (then (any begin response) request response))
504        let sexpr = list(vec![
505            sym("protocol"),
506            list(vec![
507                sym("then"),
508                list(vec![sym("any"), sym("begin"), sym("response")]),
509                sym("request"),
510                sym("response"),
511            ]),
512        ]);
513        let proto = parse_protocol(&sexpr).unwrap();
514        assert!(proto.steps.contains_key("begin"));
515        assert!(proto.steps.contains_key("request"));
516        assert!(proto.steps.contains_key("response"));
517        // request has predecessor (any begin response) and successor response
518        assert_eq!(proto.steps["request"].predecessors.len(), 1);
519        assert_eq!(proto.steps["request"].successors.len(), 1);
520        assert_eq!(
521            proto.steps["request"].successors[0],
522            NodeRef::Single("response".into())
523        );
524    }
525
526    // ================================================================
527    // TEST-201: Scatter-gather — concurrent fan-out then fan-in
528    // ================================================================
529
530    #[test]
531    fn parse_scatter_gather_protocol() {
532        // (protocol
533        //   (then begin (all search-a search-b search-c))
534        //   (then search-a result-a)
535        //   (then search-b result-b)
536        //   (then search-c result-c)
537        //   (then (all result-a result-b result-c) merge-results))
538        let sexpr = list(vec![
539            sym("protocol"),
540            list(vec![
541                sym("then"),
542                sym("begin"),
543                list(vec![
544                    sym("all"),
545                    sym("search-a"),
546                    sym("search-b"),
547                    sym("search-c"),
548                ]),
549            ]),
550            list(vec![sym("then"), sym("search-a"), sym("result-a")]),
551            list(vec![sym("then"), sym("search-b"), sym("result-b")]),
552            list(vec![sym("then"), sym("search-c"), sym("result-c")]),
553            list(vec![
554                sym("then"),
555                list(vec![
556                    sym("all"),
557                    sym("result-a"),
558                    sym("result-b"),
559                    sym("result-c"),
560                ]),
561                sym("merge-results"),
562            ]),
563        ]);
564        let proto = parse_protocol(&sexpr).unwrap();
565        assert!(proto.steps.contains_key("begin"));
566        assert!(proto.steps.contains_key("merge-results"));
567        assert!(proto.steps.contains_key("search-a"));
568        assert!(proto.steps.contains_key("result-a"));
569
570        // merge-results predecessor is (all result-a result-b result-c)
571        assert_eq!(proto.steps["merge-results"].predecessors.len(), 1);
572        let expected_all: BTreeSet<String> = ["result-a", "result-b", "result-c"]
573            .iter()
574            .map(|s| String::from(*s))
575            .collect();
576        assert_eq!(
577            proto.steps["merge-results"].predecessors[0],
578            NodeRef::All(expected_all)
579        );
580    }
581
582    // ================================================================
583    // TEST-201: Two-phase commit
584    // ================================================================
585
586    #[test]
587    fn parse_two_phase_commit_protocol() {
588        // (protocol
589        //   (then begin prepare)
590        //   (then prepare (any vote-yes vote-no))
591        //   (then (all vote-yes vote-yes) commit)
592        //   (then vote-no abort))
593        let sexpr = list(vec![
594            sym("protocol"),
595            list(vec![sym("then"), sym("begin"), sym("prepare")]),
596            list(vec![
597                sym("then"),
598                sym("prepare"),
599                list(vec![sym("any"), sym("vote-yes"), sym("vote-no")]),
600            ]),
601            list(vec![
602                sym("then"),
603                list(vec![sym("all"), sym("vote-yes"), sym("vote-yes")]),
604                sym("commit"),
605            ]),
606            list(vec![sym("then"), sym("vote-no"), sym("abort")]),
607        ]);
608        let proto = parse_protocol(&sexpr).unwrap();
609        assert!(proto.steps.contains_key("begin"));
610        assert!(proto.steps.contains_key("prepare"));
611        assert!(proto.steps.contains_key("vote-yes"));
612        assert!(proto.steps.contains_key("vote-no"));
613        assert!(proto.steps.contains_key("commit"));
614        assert!(proto.steps.contains_key("abort"));
615    }
616
617    // ================================================================
618    // Error cases
619    // ================================================================
620
621    #[test]
622    fn reject_non_list() {
623        assert_eq!(
624            parse_protocol(&sym("protocol")).unwrap_err(),
625            ProtocolParseError::NotAList
626        );
627    }
628
629    #[test]
630    fn reject_not_protocol() {
631        let sexpr = list(vec![
632            sym("not-protocol"),
633            list(vec![sym("then"), sym("a"), sym("b")]),
634        ]);
635        assert_eq!(
636            parse_protocol(&sexpr).unwrap_err(),
637            ProtocolParseError::NotProtocol
638        );
639    }
640
641    #[test]
642    fn reject_empty_protocol() {
643        let sexpr = list(vec![sym("protocol")]);
644        assert_eq!(
645            parse_protocol(&sexpr).unwrap_err(),
646            ProtocolParseError::NoThenClauses
647        );
648    }
649
650    #[test]
651    fn reject_then_too_few() {
652        let sexpr = list(vec![sym("protocol"), list(vec![sym("then"), sym("a")])]);
653        assert_eq!(
654            parse_protocol(&sexpr).unwrap_err(),
655            ProtocolParseError::ThenTooFew
656        );
657    }
658
659    #[test]
660    fn reject_non_then_clause() {
661        let sexpr = list(vec![
662            sym("protocol"),
663            list(vec![sym("not-then"), sym("a"), sym("b")]),
664        ]);
665        assert!(matches!(
666            parse_protocol(&sexpr).unwrap_err(),
667            ProtocolParseError::ExpectedThen { .. }
668        ));
669    }
670
671    #[test]
672    fn reject_any_too_few() {
673        let sexpr = list(vec![
674            sym("protocol"),
675            list(vec![
676                sym("then"),
677                list(vec![sym("any"), sym("a")]),
678                sym("b"),
679            ]),
680        ]);
681        assert!(matches!(
682            parse_protocol(&sexpr).unwrap_err(),
683            ProtocolParseError::GroupTooFew { .. }
684        ));
685    }
686
687    #[test]
688    fn reject_all_too_few() {
689        let sexpr = list(vec![
690            sym("protocol"),
691            list(vec![
692                sym("then"),
693                list(vec![sym("all"), sym("a")]),
694                sym("b"),
695            ]),
696        ]);
697        assert!(matches!(
698            parse_protocol(&sexpr).unwrap_err(),
699            ProtocolParseError::GroupTooFew { .. }
700        ));
701    }
702
703    #[test]
704    fn reject_group_non_symbol() {
705        let sexpr = list(vec![
706            sym("protocol"),
707            list(vec![
708                sym("then"),
709                list(vec![sym("any"), sym("a"), list(vec![sym("nested")])]),
710                sym("b"),
711            ]),
712        ]);
713        assert!(matches!(
714            parse_protocol(&sexpr).unwrap_err(),
715            ProtocolParseError::GroupNonSymbol { .. }
716        ));
717    }
718
719    // ================================================================
720    // Round-trip from text
721    // ================================================================
722
723    #[test]
724    fn parse_from_text_compaction() {
725        let input = "(protocol (then begin pause pause-ack get-memory memory-dump set-memory set-memory-ack resume))";
726        let sexpr = crate::parser::parse(input).unwrap();
727        let proto = parse_protocol(&sexpr).unwrap();
728        assert_eq!(proto.steps.len(), 8);
729    }
730
731    #[test]
732    fn parse_from_text_scatter_gather() {
733        let input = "(protocol (then begin (all search-a search-b search-c)) (then search-a result-a) (then search-b result-b) (then search-c result-c) (then (all result-a result-b result-c) merge-results))";
734        let sexpr = crate::parser::parse(input).unwrap();
735        let proto = parse_protocol(&sexpr).unwrap();
736        assert!(proto.steps.contains_key("merge-results"));
737    }
738}