Skip to main content

acl_core/
protocol.rs

1//! `.aclp` — ACL protocol programs (spec §33).
2//!
3//! A protocol program turns the conversation itself into source code:
4//! roles, session state, and handlers keyed on speech acts. The compile
5//! step enforces the dialogue matrix (§16) at BUILD time — a program that
6//! answers `query` with `request` does not compile.
7
8use crate::dialogue::dialogue_legal;
9use crate::runtime::handler_executor;
10use crate::idl::IdlError;
11use crate::Performative;
12use std::collections::BTreeMap;
13
14// ---------------------------------------------------------------- model
15
16#[derive(Debug, Clone, PartialEq)]
17pub struct StateDecl {
18    pub name: String,
19    pub ty: Option<String>,
20}
21
22impl PartialEq for Handler {
23    /// equality ignores `line` — source position is provenance, not
24    /// semantics (pretty-roundtrip equality relies on this)
25    fn eq(&self, other: &Self) -> bool {
26        self.trigger == other.trigger
27            && self.guard == other.guard
28            && self.actions == other.actions
29    }
30}
31
32/// What fires a handler.
33#[derive(Debug, Clone, PartialEq)]
34pub enum OnTrigger {
35    /// `on request("quote") from buyer` — incoming speech act (optionally
36    /// patterned, attributed to a sender role, and in n-role protocols
37    /// optionally restricted to ONE executor via `as <role>`)
38    Event {
39        performative: Performative,
40        pattern: Option<String>,
41        from: Option<String>,
42        as_role: Option<String>,
43        /// §50: conversation phase gate — handler fires only in this phase
44        phase: Option<String>,
45    },
46    /// `on breach` — a commitment this role owes was broken
47    Breach,
48    /// `on expired` — the session/commitment deadline passed
49    Expired,
50    /// §34: `every 60s while <guard> as <role>` — time-driven handler;
51    /// the HOST injects ticks (runtime stays clock-free and deterministic).
52    /// Unattributed timers fire in every role.
53    Timer { every_ms: i64, guard: Option<Guard>, as_role: Option<String> },
54}
55
56/// What a handler does. Phase 1: the speech-act statement set.
57#[derive(Debug, Clone, PartialEq)]
58pub enum ProtocolAction {
59    /// `send propose to seller` — MUST be dialogue-legal for the trigger;
60    /// `to` names the receiving role (defaults to the counterpart)
61    Send { performative: Performative, to: Option<String>, fields: Option<BTreeMap<String, String>>, retry: Option<Retry> },
62    /// `begin` — activate the pending commitment (proposed -> active)
63    Begin,
64    /// `fulfil` — mark the commitment fulfilled (active -> fulfilled)
65    Fulfil,
66    /// `retract(fact_name)` — belief revision as a statement (§32.1)
67    Retract { target: String },
68    /// §35.1: `set <state> = <expr>;` — `field` targets a record field
69    /// (`set q.price = 5;`)
70    Set { name: String, field: Option<String>, expr: Expr },
71    /// §35.2: `push <state>, <expr>;` — append to a list state
72    Push { state: String, expr: Expr },
73    /// §35.2: `put <state>, <key>, <expr>;` — set a map entry
74    Put { state: String, key: String, expr: Expr },
75    /// §35.3: `for <var> in <list_state> { ... }` — fan-out over a collection
76    For { var: String, over: String, actions: Vec<ProtocolAction> },
77    /// §35.4: `abort;` — trigger compensation handlers immediately
78    Abort,
79    /// §38.1: `return <expr>;` — only legal inside a function body
80    Return { expr: Expr },
81    /// §38.8: `broadcast <perf> [payload] to <list_state>;` — fan-out to
82    /// every role named in a list state (contract-net announce)
83    Broadcast { performative: Performative, fields: Option<BTreeMap<String, String>>, to: String },
84    /// §50: `enter <phase>;` — transition the session's conversation phase
85    Enter { phase: String },
86    /// §51: `begin <id>;` / `fulfil <id>;` — NAMED commitments (several
87    /// obligations per session, each with its own lifecycle)
88    BeginId { id: String },
89    FulfilId { id: String },
90    /// §45: `try { ... } catch { ... };` — a failing action inside the
91    /// body (set/push/put eval error, container violation, fmt failure)
92    /// cuts the body short and runs the catch actions instead of routing
93    /// to the session's `on error` handler
94    Try { body: Vec<ProtocolAction>, catch: Vec<ProtocolAction> },
95    /// §44: `await N <perf> into <list> within <dur> as <flag>;` —
96    /// declarative collection: matching events push their payload into the
97    /// list state; when N arrive the flag goes true; on deadline it goes
98    /// false. No handler needs to be written for the collected events.
99    Await { count: i64, performative: Performative, into: String, within_ms: i64, flag: String },
100}
101
102/// §35.5: retry policy on sends — declarative, driven by the runtime's
103/// own deterministic timers (no clock).
104#[derive(Debug, Clone, PartialEq)]
105pub struct Retry {
106    pub attempts: u32,
107    pub backoff_ms: i64,
108    /// exponential (double) backoff between attempts
109    pub exponential: bool,
110}
111
112/// §34: guard — boolean expression over session states, evaluated at
113/// dispatch time. `quoted`, `not quoted`, `a and b`, `a or b`.
114#[derive(Debug, Clone, PartialEq)]
115pub enum Guard {
116    Atom { name: String, neg: bool },
117    And(Box<Guard>, Box<Guard>),
118    Or(Box<Guard>, Box<Guard>),
119    /// §38.3: full expression guard — `when $p > 100` — evaluated with
120    /// the trigger's captures in scope (captures shadow session states)
121    ExprGuard(Expr),
122}
123
124impl Guard {
125    pub fn eval(&self, states: &BTreeMap<String, bool>) -> bool {
126        match self {
127            Guard::Atom { name, neg } => {
128                let v = states.get(name).copied().unwrap_or(false);
129                if *neg { !v } else { v }
130            }
131            Guard::And(a, b) => a.eval(states) && b.eval(states),
132            Guard::Or(a, b) => a.eval(states) || b.eval(states),
133            Guard::ExprGuard(_) => true, // resolved by the runtime (needs captures)
134        }
135    }
136    pub fn names(&self) -> Vec<&str> {
137        match self {
138            Guard::Atom { name, .. } => vec![name.as_str()],
139            Guard::And(a, b) | Guard::Or(a, b) => {
140                let mut v = a.names();
141                v.extend(b.names());
142                v
143            }
144            Guard::ExprGuard(_) => vec![], // runtime resolves captures
145        }
146    }
147}
148
149/// parse `a and not b or c` — precedence: not > and > or (left-assoc)
150pub fn parse_guard(src: &str) -> Result<Guard, String> {
151    fn or(it: &mut std::iter::Peekable<std::str::SplitAsciiWhitespace<'_>>) -> Result<Guard, String> {
152        let mut left = and(it)?;
153        while it.peek() == Some(&"or") {
154            it.next();
155            let right = and(it)?;
156            left = Guard::Or(Box::new(left), Box::new(right));
157        }
158        Ok(left)
159    }
160    fn and(it: &mut std::iter::Peekable<std::str::SplitAsciiWhitespace<'_>>) -> Result<Guard, String> {
161        let mut left = atom(it)?;
162        while it.peek() == Some(&"and") {
163            it.next();
164            let right = atom(it)?;
165            left = Guard::And(Box::new(left), Box::new(right));
166        }
167        Ok(left)
168    }
169    fn atom(it: &mut std::iter::Peekable<std::str::SplitAsciiWhitespace<'_>>) -> Result<Guard, String> {
170        let w = it.next().ok_or_else(|| "empty guard".to_string())?;
171        if w == "not" {
172            let n = it.next().ok_or_else(|| "'not' needs a state".to_string())?;
173            return Ok(Guard::Atom { name: n.to_string(), neg: true });
174        }
175        Ok(Guard::Atom { name: w.to_string(), neg: false })
176    }
177    // §38.3: expression guards — `when $p > 100`, `when $p == "x"` — any
178    // guard containing a capture reference or a comparison operator is an
179    // expression guard (parsed and evaluated by the runtime with captures)
180    if src.contains('$') || src.contains('<') || src.contains('>')
181        || src.contains("==") || src.contains("!=") {
182        return match Expr::parse_expr(src) {
183            Ok(e) => Ok(Guard::ExprGuard(e)),
184            Err(err) => Err(format!("bad expression guard '{src}': {err}")),
185        };
186    }
187    let mut it = src.split_ascii_whitespace().peekable();
188    let g = or(&mut it)?;
189    if it.peek().is_some() {
190        return Err(format!("trailing tokens in guard: '{src}'"));
191    }
192    Ok(g)
193}
194
195#[derive(Debug, Clone)]
196pub struct Handler {
197    pub trigger: OnTrigger,
198    pub guard: Option<Guard>,
199    pub actions: Vec<ProtocolAction>,
200    /// source line of the `on` declaration — 0 for synthetic handlers
201    /// (stdlib fragments, runtime-synthesized) — used by check() so that
202    /// diagnostics point at the handler
203    pub line: usize,
204}
205/// §35: expression language for `set` — pure functions over session
206/// state and the triggering event's fields. No I/O, no clock: the only
207/// effects a program can cause are speech acts (§35.6).
208#[derive(Debug, Clone, PartialEq)]
209pub enum Expr {
210    LitInt(i64),
211    LitStr(String),
212    LitBool(bool),
213    State(String),
214    /// §38.3: capture reference `$p` — resolves to the value captured by
215    /// the trigger's pattern. Captures shadow session states.
216    Capture(String),
217    /// `arg.price` — field of the triggering event's structured payload
218    Arg(String),
219    Bin { op: BinOp, l: Box<Expr>, r: Box<Expr> },
220    Not(Box<Expr>),
221    /// builtin pure functions: add sub mul div min max len sum count
222    /// concat upper lower str int exists abs — plus user-defined
223    /// §38.1 functions (resolved after builtins)
224    Call { name: String, args: Vec<Expr> },
225    /// §38.2: field access on records: `last_quote.price`
226    Field { base: Box<Expr>, name: String },
227    /// §38.2: record literal: `make(Quote, price: 5, currency: "usd")`
228    /// (parsed via Call when the callee names a declared type)
229    RecLit { ty: String, fields: Vec<(String, Expr)> },
230}
231
232#[derive(Debug, Clone, Copy, PartialEq)]
233pub enum BinOp {
234    Add, Sub, Mul, Div,
235    Lt, Le, Gt, Ge, Eq, Ne,
236    And, Or,
237}
238
239impl Expr {
240    /// parse one expression string (recursive descent, real tokenizer)
241    pub fn parse_expr(src: &str) -> Result<Expr, String> {
242        #[derive(Debug, Clone, PartialEq)]
243        enum Tok {
244            Word(String),
245            Int(i64),
246            Str(String),
247            Op(&'static str),
248        }
249        fn tokenize(src: &str) -> Result<Vec<Tok>, String> {
250            let mut toks = Vec::new();
251            let cs: Vec<char> = src.chars().collect();
252            let mut i = 0;
253            while i < cs.len() {
254                let c = cs[i];
255                if c.is_whitespace() { i += 1; continue; }
256                if c == '"' {
257                    let mut j = i + 1;
258                    while j < cs.len() && cs[j] != '"' { j += 1; }
259                    if j >= cs.len() { return Err("unterminated string".into()); }
260                    toks.push(Tok::Str(cs[i + 1..j].iter().collect()));
261                    i = j + 1;
262                    continue;
263                }
264                if c.is_ascii_digit() {
265                    let mut j = i;
266                    while j < cs.len() && cs[j].is_ascii_digit() { j += 1; }
267                    toks.push(Tok::Int(cs[i..j].iter().collect::<String>().parse().map_err(|_| "bad int")?));
268                    i = j;
269                    continue;
270                }
271                if c.is_alphabetic() || c == '_' || c == '$' {
272                    let mut j = i;
273                    // §38.3: '$' starts a capture token — consume it first,
274                    // then the identifier chars (prevents zero-progress loop)
275                    if cs[j] == '$' { j += 1; }
276                    while j < cs.len() && (cs[j].is_alphanumeric() || cs[j] == '_' || cs[j] == '.') { j += 1; }
277                    if j == i { return Err(format!("bad char '{c}' in expression")); }
278                    toks.push(Tok::Word(cs[i..j].iter().collect()));
279                    i = j;
280                    continue;
281                }
282                if i + 1 < cs.len() {
283                    let two: String = cs[i..i + 2].iter().collect();
284                    let op = match two.as_str() {
285                        "<=" => "<=", ">=" => ">=", "==" => "==", "!=" => "!=",
286                        _ => "",
287                    };
288                    if !op.is_empty() {
289                        toks.push(Tok::Op(match op { "<=" => "<=", ">=" => ">=", "==" => "==", _ => "!=" }));
290                        i += 2;
291                        continue;
292                    }
293                }
294                let one = match c {
295                    '+' => "+", '-' => "-", '*' => "*", '/' => "/",
296                    '<' => "<", '>' => ">", '(' => "(", ')' => ")",
297                    ',' => ",", '{' => "{", '}' => "}", ':' => ":",
298                    _ => return Err(format!("bad char '{c}' in expression")),
299                };
300                toks.push(Tok::Op(one));
301                i += 1;
302            }
303            Ok(toks)
304        }
305        struct P {
306            toks: Vec<Tok>,
307            pos: usize,
308        }
309        impl P {
310            fn peek(&self) -> Option<&Tok> { self.toks.get(self.pos) }
311            fn next(&mut self) -> Option<Tok> { let t = self.peek().cloned(); self.pos += 1; t }
312            fn atom(&mut self) -> Result<Expr, String> {
313                match self.next() {
314                    Some(Tok::Int(i)) => Ok(Expr::LitInt(i)),
315                    Some(Tok::Str(s)) => Ok(Expr::LitStr(s)),
316                    Some(Tok::Word(w)) => match w.as_str() {
317                        "true" => Ok(Expr::LitBool(true)),
318                        "false" => Ok(Expr::LitBool(false)),
319                        "not" => Ok(Expr::Not(Box::new(self.atom_add()?))),
320                        _ if w.starts_with('$') && w.len() > 1 => Ok(Expr::Capture(w[1..].to_string())),
321                        _ if w.starts_with("arg.") => Ok(Expr::Arg(w[4..].to_string())),
322                        _ if w.contains('.') && !w.starts_with('.') => {
323                            // §38.2: field access chain `q.price` — the
324                            // head segment is a state name, the rest are
325                            // record fields
326                            let mut segs = w.split('.');
327                            let head = segs.next().unwrap_or_default().to_string();
328                            let mut e = if head == "arg" {
329                                // `arg.x.y` is arg field "x.y"
330                                Expr::Arg(w[4..].to_string())
331                            } else {
332                                Expr::State(head)
333                            };
334                            for f in segs {
335                                e = Expr::Field { base: Box::new(e), name: f.to_string() };
336                            }
337                            Ok(e)
338                        }
339                        _ if self.peek().map_or(false, |t| matches!(t, Tok::Op("{"))) => {
340                            // §38.2: record literal `Bid { who: "x", price: 3 }`
341                            self.next();
342                            let mut fields: Vec<(String, Expr)> = Vec::new();
343                            loop {
344                                let fname = match self.next() {
345                                    Some(Tok::Word(w)) => w,
346                                    other => return Err(format!("bad record field near {other:?}")),
347                                };
348                                match self.next() {
349                                    Some(Tok::Op(":")) => {}
350                                    other => return Err(format!("expected ':' after record field '{fname}', got {other:?}")),
351                                }
352                                let v = self.expr()?;
353                                fields.push((fname, v));
354                                match self.next() {
355                                    Some(Tok::Op(",")) => continue,
356                                    Some(Tok::Op("}")) => break,
357                                    other => return Err(format!("bad record syntax near {other:?}")),
358                                }
359                            }
360                            Ok(Expr::RecLit { ty: w, fields })
361                        }
362                        _ if self.peek().map_or(false, |t| matches!(t, Tok::Op("("))) => {
363                            // function call
364                            self.next(); // consume (
365                            let mut args = Vec::new();
366                            if self.peek().map_or(false, |t| matches!(t, Tok::Op(")"))) {
367                                self.next();
368                            } else {
369                                loop {
370                                    args.push(self.expr()?);
371                                    match self.next() {
372                                        Some(Tok::Op(",")) => continue,
373                                        Some(Tok::Op(")")) => break,
374                                        other => return Err(format!("bad call syntax near {other:?}")),
375                                    }
376                                }
377                            }
378                            Ok(Expr::Call { name: w, args })
379                        }
380                        _ if w.chars().all(|c| c.is_alphanumeric() || c == '_')
381                            && w.chars().next().map_or(false, |c| c.is_alphabetic() || c == '_') =>
382                        {
383                            Ok(Expr::State(w))
384                        }
385                        _ => Err(format!("bad token '{w}'")),
386                    },
387                    Some(Tok::Op("(")) => {
388                        let e = self.expr()?;
389                        if self.next().map_or(false, |t| matches!(t, Tok::Op(")"))) {
390                            Ok(e)
391                        } else {
392                            Err("missing ')'".into())
393                        }
394                    },
395                    Some(Tok::Op("-")) => match self.atom()? {
396                        Expr::LitInt(i) => Ok(Expr::LitInt(-i)),
397                        other => Err(format!("cannot negate {other:?}")),
398                    },
399                    other => Err(format!("unexpected {other:?}")),
400                }
401            }
402            fn atom_mul(&mut self) -> Result<Expr, String> {
403                let mut l = self.atom()?;
404                loop {
405                    let op = match self.peek() {
406                        Some(Tok::Op("*")) => BinOp::Mul,
407                        Some(Tok::Op("/")) => BinOp::Div,
408                        _ => break,
409                    };
410                    self.next();
411                    let r = self.atom()?;
412                    l = Expr::Bin { op, l: Box::new(l), r: Box::new(r) };
413                }
414                Ok(l)
415            }
416            fn atom_add(&mut self) -> Result<Expr, String> {
417                let mut l = self.atom_mul()?;
418                loop {
419                    let op = match self.peek() {
420                        Some(Tok::Op("+")) => BinOp::Add,
421                        Some(Tok::Op("-")) => BinOp::Sub,
422                        _ => break,
423                    };
424                    self.next();
425                    let r = self.atom_mul()?;
426                    l = Expr::Bin { op, l: Box::new(l), r: Box::new(r) };
427                }
428                Ok(l)
429            }
430            fn atom_cmp(&mut self) -> Result<Expr, String> {
431                let l = self.atom_add()?;
432                let op = match self.peek() {
433                    Some(Tok::Op("<=")) => BinOp::Le,
434                    Some(Tok::Op(">=")) => BinOp::Ge,
435                    Some(Tok::Op("==")) => BinOp::Eq,
436                    Some(Tok::Op("!=")) => BinOp::Ne,
437                    Some(Tok::Op("<")) => BinOp::Lt,
438                    Some(Tok::Op(">")) => BinOp::Gt,
439                    _ => return Ok(l),
440                };
441                self.next();
442                let r = self.atom_add()?;
443                Ok(Expr::Bin { op, l: Box::new(l), r: Box::new(r) })
444            }
445            fn atom_and(&mut self) -> Result<Expr, String> {
446                let mut l = self.atom_cmp()?;
447                while self.peek().map_or(false, |t| matches!(t, Tok::Word(w) if w == "and")) {
448                    self.next();
449                    let r = self.atom_cmp()?;
450                    l = Expr::Bin { op: BinOp::And, l: Box::new(l), r: Box::new(r) };
451                }
452                Ok(l)
453            }
454            fn expr(&mut self) -> Result<Expr, String> {
455                let mut l = self.atom_and()?;
456                while self.peek().map_or(false, |t| matches!(t, Tok::Word(w) if w == "or")) {
457                    self.next();
458                    let r = self.atom_and()?;
459                    l = Expr::Bin { op: BinOp::Or, l: Box::new(l), r: Box::new(r) };
460                }
461                Ok(l)
462            }
463        }
464        let mut p = P { toks: tokenize(src)?, pos: 0 };
465        let e = p.expr()?;
466        if p.pos != p.toks.len() {
467            return Err(format!("trailing tokens in expression '{src}'"));
468        }
469        Ok(e)
470    }
471}
472
473
474#[derive(Debug, Clone, PartialEq)]
475pub enum EndWhen {
476    /// builtin: the commitment reached a terminal state
477    Builtin(String), // fulfilled | expired | breached
478    /// a declared session state is true
479    State(String),
480}
481
482#[derive(Debug, Clone, PartialEq, Default)]
483pub struct ProtocolProgram {
484    pub name: String,
485    pub version: u32,
486    pub roles: Vec<String>,
487    pub states: Vec<StateDecl>,
488    pub handlers: Vec<Handler>,
489    pub end_when: Option<EndWhen>,
490    /// §35.6: capabilities this program requires (host-gated)
491    pub capabilities: Vec<CapabilityDecl>,
492    /// §35.11: declared transport hint (stdio|http|ws|relay)
493    pub transport: Option<String>,
494    /// §35.8: max concurrent sessions (capacity model)
495    pub capacity: Option<usize>,
496    /// §35.4: abort conditions — when one becomes true, compensation runs
497    pub abort_when: Vec<Guard>,
498    /// §35.12: executable scenarios (protocol tests)
499    pub scenarios: Vec<Scenario>,
500    /// §35.3: user-defined message templates `message name = "text";`
501    pub templates: Vec<(String, String)>,
502    /// §38.1: user-defined functions `fn f(x: int) -> int { ... }`
503    pub functions: Vec<Function>,
504    /// §38.2: user-defined record types `type Quote = { price: int };`
505    pub types: BTreeMap<String, Vec<(String, String)>>,
506    /// §38.5: reusable handler fragments `handler_set name { ... }` —
507    /// spliced into a protocol by `include handler_set name;`
508    pub handler_sets: BTreeMap<String, Vec<Handler>>,
509    /// §38.10: sets made importable by `export handler_set name;` —
510    /// everything else stays private to the module file
511    pub exported_sets: Vec<String>,
512    /// §50: declared conversation phases — handlers may be gated on the
513    /// current phase (`on inform ... in <phase>`) and actions transition
514    /// with `enter <phase>;`. The FIRST declared phase is the initial one.
515    pub phases: Vec<String>,
516    /// §42: `protocol v2 extends v1;` — the base protocol declared
517    /// earlier in the same file (states/types/fns/handlers inherited,
518    /// handlers overridable by matching trigger+guard signature)
519    pub extends: Option<String>,
520    /// §42: `export type X;` / `export fn name;` — importable vocabulary
521    pub exported_types: Vec<String>,
522    pub exported_fns: Vec<String>,
523}
524
525/// §38.1: a user-defined function — pure computation over parameters and
526/// session state; parameters and locals are function-scoped.
527#[derive(Debug, Clone, PartialEq)]
528pub struct Function {
529    pub name: String,
530    pub params: Vec<(String, String)>,
531    pub ret: Option<String>,
532    /// body: `set <local> = <expr>;` + one `return <expr>;`
533    pub body: Vec<ProtocolAction>,
534    pub returned: Option<Expr>,
535}
536
537/// §35.6: capability declaration — the ONLY door to external effects.
538#[derive(Debug, Clone, PartialEq)]
539pub struct CapabilityDecl {
540    pub name: String,
541    pub alias: Option<String>,
542}
543
544/// §35.12: scenario — an executable test inside the .aclp file.
545#[derive(Debug, Clone, PartialEq)]
546pub struct Scenario {
547    pub name: String,
548    pub steps: Vec<ScenarioStep>,
549}
550
551#[derive(Debug, Clone, PartialEq)]
552pub enum ScenarioStep {
553    /// `<role> sends <perf> [pattern] to <role>;`
554    Send { from: String, performative: Performative, pattern: Option<String>, to: String },
555    /// `expect <role> sends <perf>;`
556    ExpectSend { from: String, performative: Performative },
557    /// `expect state <role>.<name>;` (true) / `== false`
558    ExpectState { role: String, name: String, value: bool },
559    /// `expect commitment <role> <status>;`
560    ExpectCommitment { role: String, status: String },
561    /// `expect log "<substring>";` — the session transcript contains it
562    ExpectLog { contains: String },
563}
564
565impl Handler {
566    /// §34: true when the trigger pattern is a content pattern `{"k": "v"}`
567    /// (as opposed to a literal `("quote")` equality pattern)
568    pub fn pattern_is_json(&self) -> bool {
569        matches!(&self.trigger, OnTrigger::Event { pattern: Some(p), .. } if p.starts_with('{'))
570    }
571}
572
573impl ProtocolProgram {
574    pub fn state_names(&self) -> Vec<&str> {
575        self.states.iter().map(|s| s.name.as_str()).collect()
576    }
577}
578
579// ---------------------------------------------------------------- parse
580
581fn perf_from_word(w: &str) -> Option<Performative> {
582    Some(match w {
583        "request" => Performative::Request,
584        "inform" => Performative::Inform,
585        "query" => Performative::Query,
586        "propose" => Performative::Propose,
587        "accept" => Performative::Accept,
588        "reject" => Performative::Reject,
589        "cancel" => Performative::Cancel,
590        "progress" => Performative::Progress,
591        "input_required" => Performative::InputRequired,
592        "failure" => Performative::Failure,
593        "delegate" => Performative::Delegate,
594        "error" => Performative::Error,
595        "hello" => Performative::Hello,
596        "bye" => Performative::Bye,
597        "retract" => Performative::Retract,
598        "subscribe" => Performative::Subscribe,
599        "unsubscribe" => Performative::Unsubscribe,
600        _ => return None,
601    })
602}
603
604/// Strip `(...)` pattern and `from <role>` from a handler head:
605/// `request("quote") from buyer` -> (`request`, Some(`"quote"`), Some(`buyer`))
606/// §38.8 helper: char vec of a string (tiny sugar for brace scanning)
607fn cs_of(s: &str) -> Vec<char> {
608    s.chars().collect()
609}
610
611/// §38.3: rewrite bare `$var` capture values inside a `{...}` content
612/// pattern into JSON string values (`"$var"`) so the pattern is valid
613/// JSON — `{"price": $p}` becomes `{"price": "$p"}`.
614fn quote_bare_captures(pattern: &str) -> String {
615    if !pattern.contains('$') {
616        return pattern.to_string();
617    }
618    let mut out = String::with_capacity(pattern.len() + 8);
619    let cs: Vec<char> = pattern.chars().collect();
620    let mut i = 0;
621    while i < cs.len() {
622        let c = cs[i];
623        out.push(c);
624        if c == ':' {
625            // skip whitespace, then capture a bare `$ident` value
626            let mut j = i + 1;
627            while j < cs.len() && cs[j].is_whitespace() { j += 1; }
628            if j < cs.len() && cs[j] == '$' {
629                let mut k = j + 1;
630                while k < cs.len() && (cs[k].is_alphanumeric() || cs[k] == '_') { k += 1; }
631                if k > j + 1 {
632                    // only when the value ends here (comma, whitespace or '}')
633                    let end_ok = k >= cs.len()
634                        || cs[k] == ','
635                        || cs[k] == '}'
636                        || cs[k].is_whitespace();
637                    if end_ok {
638                        out.push('"');
639                        out.extend(cs[j..k].iter());
640                        out.push('"');
641                        i = k - 1; // loop's i += 1 lands on k
642                    }
643                }
644            }
645        }
646        i += 1;
647    }
648    out
649}
650
651fn split_trigger(head: &str) -> (String, Option<String>, Option<String>) {
652    let (head, from) = match head.rfind(" from ") {
653        Some(i) => (head[..i].trim().to_string(), Some(head[i + 6..].trim().to_string())),
654        None => (head.trim().to_string(), None),
655    };
656    let (word, pattern) = match (head.find('('), head.find('{')) {
657        (Some(i), _) if head.ends_with(')') => {
658            (head[..i].trim().to_string(), Some(head[i..].to_string()))
659        }
660        (_, Some(i)) if head.ends_with('}') => {
661            (head[..i].trim().to_string(), Some(quote_bare_captures(&head[i..])))
662        }
663        _ => (head.trim().to_string(), None),
664    };
665    (word, pattern, from)
666}
667
668/// §35.13: parse with `include "file" with roles (a=X, b=Y);` support —
669/// the include is loaded relative to `base_dir`, roles renamed
670/// whole-word, and spliced in place of the include line.
671pub fn parse_with_includes(src: &str, base_dir: Option<&str>) -> Result<ProtocolProgram, Vec<IdlError>> {
672    parse_with_includes_depth(src, base_dir, 0)
673}
674
675fn parse_with_includes_depth(
676    src: &str,
677    base_dir: Option<&str>,
678    depth: usize,
679) -> Result<ProtocolProgram, Vec<IdlError>> {
680    let mut out_lines: Vec<String> = Vec::new();
681    let mut include_errors: Vec<String> = Vec::new();
682    for raw in src.lines() {
683        let trimmed = raw.trim();
684        if let Some(rest) = trimmed.strip_prefix("import ") {
685            // §38.10: import "mod.aclp" [as ns]; — splices only the
686            // module's EXPORTED handler sets, namespaced as ns.<set>
687            let body = rest.trim_end_matches(';').trim();
688            let (path, ns) = match body.find(" as ") {
689                Some(i) => (body[..i].trim(), Some(body[i + 4..].trim().to_string())),
690                None => (body.trim(), None),
691            };
692            let path = path.trim_matches('"').trim_matches('\'');
693            match import_module(path, ns.as_deref(), base_dir, 0) {
694                Ok(lines) => out_lines.extend(lines),
695                Err(e) => include_errors.push(e),
696            }
697            continue;
698        }
699        if let Some(rest) = trimmed.strip_prefix("include ") {
700            // `include handler_set X;` is NOT a file include — pass it
701            // through for parse()'s set-splice arm (§38.5)
702            if rest.trim_start().starts_with("handler_set ") {
703                out_lines.push(raw.to_string());
704                continue;
705            }
706            let body = rest.trim_end_matches(';');
707            // include "path" [with roles (X=R1, Y=R2)]
708            let (path_part, mapping) = match body.find(" with roles ") {
709                Some(i) => {
710                    let map_src = body[i + " with roles ".len()..]
711                        .trim()
712                        .trim_start_matches('(')
713                        .trim_end_matches(')');
714                    let mapping: Vec<(String, String)> = map_src
715                        .split(',')
716                        .filter_map(|p| {
717                            let p = p.trim();
718                            p.split_once('=')
719                                .map(|(a, b)| (b.trim().to_string(), a.trim().to_string()))
720                        })
721                        .collect();
722                    (body[..i].trim(), mapping)
723                }
724                None => (body.trim(), Vec::new()),
725            };
726            let path = path_part.trim().trim_matches('"').trim_matches('\'');
727            match expand_include(path, &mapping, base_dir) {
728                Ok(text) => out_lines.extend(text.lines().map(|l| l.to_string())),
729                Err(e) => include_errors.push(e),
730            }
731        } else {
732            out_lines.push(raw.to_string());
733        }
734    }
735    if !include_errors.is_empty() {
736        return Err(include_errors
737            .into_iter()
738            .map(|m| IdlError { line: 0, message: m })
739            .collect());
740    }
741    parse(&out_lines.join("\n"))
742}
743
744pub fn parse(src: &str) -> Result<ProtocolProgram, Vec<IdlError>> {
745    // §42: multiple `protocol` declarations in one file are only legal as
746    // an inheritance chain (`protocol v2 extends v1;`); with a single
747    // declaration the file parses exactly as before
748    let segs = split_protocol_segments(src);
749    if segs.len() <= 1 {
750        return parse_single(src);
751    }
752    let progs: Vec<ProtocolProgram> = segs
753        .iter()
754        .map(|seg| parse_single(seg))
755        .collect::<Result<_, _>>()?;
756    merge_programs(progs)
757}
758
759/// §42: split a source file into protocol segments — lines before the
760/// first `protocol` declaration join the first segment (handler_set
761/// declarations are file-level).
762fn split_protocol_segments(src: &str) -> Vec<String> {
763    let mut segs: Vec<String> = Vec::new();
764    let mut cur = String::new();
765    let mut seen_proto = false;
766    for raw in src.lines() {
767        let t = raw.trim();
768        if t.starts_with("protocol ") {
769            if seen_proto {
770                segs.push(std::mem::take(&mut cur));
771            }
772            seen_proto = true;
773        }
774        cur.push_str(raw);
775        cur.push('\n');
776    }
777    if !cur.trim().is_empty() {
778        segs.push(cur);
779    }
780    segs
781}
782
783/// §42: merge a base program into a derived one — inheritance by
784/// `extends`: states, types, functions, templates and handlers are
785/// inherited; a derived handler with the SAME trigger+guard signature
786/// overrides the base handler; handler_sets/exported sets are file-level
787/// (union across the chain).
788fn merge_programs(mut progs: Vec<ProtocolProgram>) -> Result<ProtocolProgram, Vec<IdlError>> {
789    let main = progs.pop().expect("at least one");
790    let base = match &main.extends {
791        Some(name) => match progs.iter().find(|p| &p.name == name) {
792            Some(b) => b.clone(),
793            None => {
794                return Err(vec![IdlError {
795                    line: 0,
796                    message: format!("protocol '{}' extends unknown protocol '{name}'", main.name),
797                }])
798            }
799        },
800        None if !progs.is_empty() => {
801            let prev = progs.last().unwrap();
802            return Err(vec![IdlError {
803                line: 0,
804                message: format!(
805                    "protocol '{}' follows '{}' without 'extends' (multiple protocols per file form an inheritance chain)",
806                    main.name, prev.name
807                ),
808            }]);
809        }
810        None => return Ok(main),
811    };
812    let mut out = main;
813    // roles not redeclared
814    for r in &base.roles {
815        if !out.roles.contains(r) {
816            out.roles.push(r.clone());
817        }
818    }
819    // states not redeclared
820    let have: Vec<String> = out.states.iter().map(|s| s.name.clone()).collect();
821    for st in &base.states {
822        if !have.contains(&st.name) {
823            out.states.push(st.clone());
824        }
825    }
826    // single-valued decls inherited when the derived one omits them
827    if out.end_when.is_none() {
828        out.end_when = base.end_when.clone();
829    }
830    if out.transport.is_none() {
831        out.transport = base.transport.clone();
832    }
833    if out.capacity.is_none() {
834        out.capacity = base.capacity;
835    }
836    out.abort_when.extend(base.abort_when.clone());
837    out.scenarios.extend(base.scenarios.clone());
838    // types not redeclared
839    for (k, v) in &base.types {
840        out.types.entry(k.clone()).or_insert_with(|| v.clone());
841    }
842    // functions not redeclared
843    let have_fns: Vec<String> = out.functions.iter().map(|f| f.name.clone()).collect();
844    for f in &base.functions {
845        if !have_fns.contains(&f.name) {
846            out.functions.push(f.clone());
847        }
848    }
849    // templates not redeclared
850    let have_tm: Vec<String> = out.templates.iter().map(|(n, _)| n.clone()).collect();
851    for (n, t) in &base.templates {
852        if !have_tm.contains(n) {
853            out.templates.push((n.clone(), t.clone()));
854        }
855    }
856    // handlers: base handlers first, minus overridden (same trigger+guard sig)
857    let override_sigs: Vec<String> = out.handlers.iter().map(handler_sig).collect();
858    let inherited: Vec<Handler> = base
859        .handlers
860        .iter()
861        .filter(|h| !override_sigs.contains(&handler_sig(h)))
862        .cloned()
863        .collect();
864    let n_inherited = inherited.len();
865    out.handlers = inherited.into_iter().chain(out.handlers).collect();
866    out.extends = None; // resolved
867    let _ = n_inherited;
868    Ok(out)
869}
870
871/// §42: a handler's override signature — trigger word + pattern + from + guard
872pub fn handler_sig(h: &Handler) -> String {
873    let trig = match &h.trigger {
874        OnTrigger::Event { performative, pattern, from, as_role, phase } => format!(
875            "{}|{:?}|{:?}",
876            perf_word(performative),
877            pattern,
878            from
879        ),
880        OnTrigger::Breach => "breach".into(),
881        OnTrigger::Expired => "expired".into(),
882        OnTrigger::Timer { every_ms, guard, as_role } => format!(
883            "timer|{every_ms}|{:?}|{:?}",
884            guard.as_ref().map(guard_word),
885            as_role
886        ),
887    };
888    format!("{trig}|{:?}", h.guard.as_ref().map(guard_word))
889}
890
891fn parse_single(src: &str) -> Result<ProtocolProgram, Vec<IdlError>> {
892    let mut errors = Vec::new();
893    let mut prog = ProtocolProgram::default();
894    let mut seen_protocol = false;
895    let mut handler: Option<Handler> = None;
896    let mut scenario: Option<Scenario> = None;
897    let mut func: Option<Function> = None;  // §38.1 WIP
898    // §38.5: in-progress handler_set body (name, lines, opener line, depth)
899    let mut open_set: Option<(String, Vec<String>, usize, usize)> = None;
900
901    for (idx, raw) in src.lines().enumerate() {
902        let line_no = idx + 1;
903        if raw.trim_start().starts_with("//") {
904            continue;
905        }
906        let line = match raw.find("//") {
907            Some(i) => &raw[..i],
908            None => raw,
909        }
910        .trim();
911        // §55: nested statements may contain inline blocks — split with
912        // the block-aware splitter, not raw ';'
913        let _ = ();
914        if line.is_empty() {
915            continue;
916        }
917
918        // §38.5: inside a handler_set body — collect lines until the
919        // closing brace (brace-depth aware for nested handler blocks)
920        if let Some((name, body, ln, depth)) = open_set.as_mut() {
921            let opens = line.matches('{').count();
922            let closes = line.matches('}').count();
923            *depth += opens;
924            *depth = depth.saturating_sub(closes);
925            if line.trim() == "}" && *depth <= 0 {
926                let (name, body, ln, _) = open_set.take().unwrap();
927                let mini = parse_single(&format!(
928                    "protocol __frag_{name} v1;\nroles __dummy;\n{}",
929                    body.join("\n")
930                ));
931                match mini {
932                    Ok(m) => {
933                        if prog.handler_sets.insert(name.clone(), m.handlers).is_some() {
934                            errors.push(IdlError { line: ln, message: format!("duplicate handler_set '{name}'") });
935                        }
936                    }
937                    Err(es) => {
938                        for e in es {
939                            errors.push(IdlError {
940                                line: ln,
941                                message: format!("handler_set '{name}': {}", e.message),
942                            });
943                        }
944                    }
945                }
946            } else {
947                body.push(line.to_string());
948                if *depth <= 0 {
949                    // same-line close — finalize without the brace
950                    let (name, body, ln, _) = open_set.take().unwrap();
951                    let mini = parse_single(&format!(
952                        "protocol __frag_{name} v1;\nroles __dummy;\n{}",
953                        body.join("\n")
954                    ));
955                    match mini {
956                        Ok(m) => {
957                            if prog.handler_sets.insert(name.clone(), m.handlers).is_some() {
958                                errors.push(IdlError { line: line_no, message: format!("duplicate handler_set '{name}'") });
959                            }
960                        }
961                        Err(es) => {
962                            for e in es {
963                                errors.push(IdlError {
964                                    line: ln,
965                                    message: format!("handler_set '{name}': {}", e.message),
966                                });
967                            }
968                        }
969                    }
970                }
971            }
972            continue;
973        }
974        // §38.5: handler_set opener — `handler_set name {` or inline
975        if let Some(rest) = line.strip_prefix("handler_set ") {
976            let name = rest.split('{').next().unwrap_or("").trim().to_string();
977            if name.is_empty() {
978                errors.push(IdlError { line: line_no, message: "handler_set needs a name".into() });
979            } else if line.contains('{') && line.ends_with('}') {
980                let inner = &line[line.find('{').unwrap() + 1..line.len() - 1];
981                let mini = parse_single(&format!(
982                    "protocol __frag_{name} v1;\nroles __dummy;\n{inner}"
983                ));
984                match mini {
985                    Ok(m) => {
986                        if prog.handler_sets.insert(name.clone(), m.handlers).is_some() {
987                            errors.push(IdlError { line: line_no, message: format!("duplicate handler_set '{name}'") });
988                        }
989                    }
990                    Err(es) => {
991                        for e in es {
992                            errors.push(IdlError {
993                                line: line_no,
994                                message: format!("handler_set '{name}': {}", e.message),
995                            });
996                        }
997                    }
998                }
999            } else if line.ends_with('{') {
1000                open_set = Some((name, Vec::new(), line_no, 1));
1001            } else {
1002                errors.push(IdlError { line: line_no, message: "malformed handler_set (want 'handler_set name {')".into() });
1003            }
1004            continue;
1005        }
1006        // §42: export type / export fn — importable vocabulary
1007        if let Some(rest) = line.strip_prefix("export type ") {
1008            let name = rest.trim_end_matches(';').trim().to_string();
1009            if name.is_empty() {
1010                errors.push(IdlError { line: line_no, message: "export type needs a name".into() });
1011            } else {
1012                prog.exported_types.push(name);
1013            }
1014            continue;
1015        }
1016        if let Some(rest) = line.strip_prefix("export fn ") {
1017            let name = rest.trim_end_matches(';').trim().to_string();
1018            if name.is_empty() {
1019                errors.push(IdlError { line: line_no, message: "export fn needs a name".into() });
1020            } else {
1021                prog.exported_fns.push(name);
1022            }
1023            continue;
1024        }
1025        // §38.10: mark a handler set as importable by other modules
1026        if let Some(rest) = line.strip_prefix("export handler_set ") {
1027            let name = rest.trim_end_matches(';').trim().to_string();
1028            if name.is_empty() {
1029                errors.push(IdlError { line: line_no, message: "export handler_set needs a name".into() });
1030            } else {
1031                prog.exported_sets.push(name);
1032            }
1033            continue;
1034        }
1035        // §38.5: splice a declared handler set into the current protocol
1036        if let Some(rest) = line.strip_prefix("include handler_set ") {
1037            let name = rest.trim_end_matches(';').trim().to_string();
1038            match prog.handler_sets.get(&name) {
1039                Some(hs) => prog.handlers.extend(hs.iter().cloned()),
1040                None => errors.push(IdlError {
1041                    line: line_no,
1042                    message: format!(
1043                        "unknown handler set '{name}' (declare it with handler_set before include)"
1044                    ),
1045                }),
1046            }
1047            continue;
1048        }
1049
1050        // §38.1: inside a function body — collect statements until `}`
1051        if let Some(f) = func.as_mut() {
1052            if line == "}" {
1053                let f = func.take().unwrap();
1054                if f.returned.is_none() {
1055                    errors.push(IdlError {
1056                        line: line_no,
1057                        message: format!("fn '{}' has no return statement", f.name),
1058                    });
1059                }
1060                if prog.functions.iter().any(|g| g.name == f.name) {
1061                    errors.push(IdlError {
1062                        line: line_no,
1063                        message: format!("duplicate function '{}'", f.name),
1064                    });
1065                } else {
1066                    prog.functions.push(f);
1067                }
1068                continue;
1069            }
1070            match parse_action(line) {
1071                Ok(ProtocolAction::Set { name, field, expr }) => {
1072                    if field.is_some() {
1073                        errors.push(IdlError {
1074                            line: line_no,
1075                            message: format!("field assignment '{}' not allowed inside fn", name),
1076                        });
1077                        continue;
1078                    }
1079                    f.body.push(ProtocolAction::Set { name, field, expr });
1080                }
1081                Ok(ProtocolAction::Return { expr }) => {
1082                    f.returned = Some(expr);
1083                }
1084                Ok(other) => errors.push(IdlError {
1085                    line: line_no,
1086                    message: format!("only 'set' and 'return' allowed in fn body, got {other:?}"),
1087                }),
1088                Err(e) => errors.push(IdlError { line: line_no, message: e }),
1089            }
1090            continue;
1091        }
1092
1093        // §38.1: `fn name(p1: t1, p2: t2) -> ret {`
1094        if line.starts_with("fn ") && line.ends_with('{') {
1095            let head = &line[3..line.len() - 1];
1096            let (sig, ret) = match head.split_once("->") {
1097                Some((a, b)) => (a.trim(), Some(b.trim().to_string())),
1098                None => (head.trim(), None),
1099            };
1100            let (name, params_src) = match sig.split_once('(') {
1101                Some((n, p)) => (n.trim().to_string(), p.trim_end_matches(')').trim().to_string()),
1102                None => {
1103                    errors.push(IdlError { line: line_no, message: format!("bad fn decl: '{line}'") });
1104                    continue;
1105                }
1106            };
1107            let params: Vec<(String, String)> = if params_src.is_empty() {
1108                Vec::new()
1109            } else {
1110                params_src
1111                    .split(',')
1112                    .filter_map(|p| {
1113                        let p = p.trim();
1114                        p.split_once(':').map(|(n, t)| (n.trim().to_string(), t.trim().to_string()))
1115                    })
1116                    .collect()
1117            };
1118            func = Some(Function { name, params, ret, body: Vec::new(), returned: None });
1119            continue;
1120        }
1121
1122        // §38.2: `type Name = { field: ty, ... };`
1123        if let Some(rest) = line.strip_prefix("type ") {
1124            let body = rest.trim_end_matches(';').trim();
1125            if let Some((name, fields_src)) = body.split_once('=') {
1126                let name = name.trim().to_string();
1127                let inner = fields_src.trim().trim_start_matches('{').trim_end_matches('}').trim();
1128                let fields: Vec<(String, String)> = inner
1129                    .split(',')
1130                    .filter(|f| !f.trim().is_empty())
1131                    .filter_map(|f| {
1132                        let f = f.trim();
1133                        f.split_once(':').map(|(n, t)| (n.trim().to_string(), t.trim().to_string()))
1134                    })
1135                    .collect();
1136                if fields.is_empty() || name.is_empty() {
1137                    errors.push(IdlError { line: line_no, message: format!("bad type decl: '{line}'") });
1138                } else if prog.types.insert(name.clone(), fields).is_some() {
1139                    errors.push(IdlError {
1140                        line: line_no,
1141                        message: format!("duplicate type declaration '{name}'"),
1142                    });
1143                }
1144            } else {
1145                errors.push(IdlError { line: line_no, message: format!("bad type decl: '{line}' (want 'type X = {{ f: ty }};')") });
1146            }
1147            continue;
1148        }
1149
1150        // inside a handler block: collect actions until `}`
1151        if let Some(h) = handler.as_mut() {
1152            if line == "}" {
1153                if h.actions.is_empty() {
1154                    errors.push(IdlError { line: line_no, message: "empty handler block".into() });
1155                }
1156                prog.handlers.push(handler.take().unwrap());
1157                continue;
1158            }
1159            // §35.3: inline for-block: `for x in list { act; act; }`
1160            if line.starts_with("for ") && line.ends_with('}') {
1161                match parse_for_block(line) {
1162                    Ok(a) => h.actions.push(a),
1163                    Err(e) => errors.push(IdlError { line: line_no, message: e }),
1164                }
1165                continue;
1166            }
1167            let action = match parse_action(line) {
1168                Ok(a) => a,
1169                Err(e) => {
1170                    errors.push(IdlError { line: line_no, message: e });
1171                    continue;
1172                }
1173            };
1174            h.actions.push(action);
1175            continue;
1176        }
1177
1178        if let Some(rest) = line.strip_prefix("protocol ") {
1179            let body = rest.trim_end_matches(';').trim();
1180            // §42: `protocol name vN [extends base];`
1181            let (head, extends) = match body.split_once(" extends ") {
1182                Some((h, b)) => (h.trim(), Some(b.trim().to_string())),
1183                None => (body, None),
1184            };
1185            let mut parts = head.split_whitespace();
1186            let name = parts.next().unwrap_or_default().to_string();
1187            let ver = parts
1188                .next()
1189                .and_then(|v| v.strip_prefix('v'))
1190                .and_then(|v| v.parse().ok());
1191            if name.is_empty() || ver.is_none() || parts.next().is_some() {
1192                errors.push(IdlError {
1193                    line: line_no,
1194                    message: format!("bad protocol decl: '{line}' (want 'protocol name v1 [extends base];')"),
1195                });
1196                continue;
1197            }
1198            if seen_protocol {
1199                errors.push(IdlError { line: line_no, message: "duplicate protocol declaration".into() });
1200                continue;
1201            }
1202            seen_protocol = true;
1203            prog.name = name;
1204            prog.version = ver.unwrap();
1205            prog.extends = extends;
1206            continue;
1207        }
1208        // §50: conversation phase declaration
1209        if let Some(rest) = line.strip_prefix("phase ") {
1210            let name = rest.trim_end_matches(';').trim().to_string();
1211            if name.is_empty() {
1212                errors.push(IdlError { line: line_no, message: "phase needs a name".into() });
1213            } else {
1214                prog.phases.push(name);
1215            }
1216            continue;
1217        }
1218        if let Some(rest) = line.strip_prefix("roles ") {
1219            let list = rest.trim_end_matches(';');
1220            for r in list.split(',') {
1221                let r = r.trim();
1222                if r.is_empty() {
1223                    errors.push(IdlError { line: line_no, message: "empty role name".into() });
1224                } else {
1225                    prog.roles.push(r.to_string());
1226                }
1227            }
1228            continue;
1229        }
1230        if let Some(rest) = line.strip_prefix("state ") {
1231            let body = rest.trim_end_matches(';').trim();
1232            match body.split_once(':') {
1233                Some((name, ty)) => prog.states.push(StateDecl {
1234                    name: name.trim().to_string(),
1235                    ty: Some(ty.trim().to_string()),
1236                }),
1237                None => prog.states.push(StateDecl { name: body.to_string(), ty: None }),
1238            }
1239            continue;
1240        }
1241        if let Some(rest) = line.strip_prefix("every ") {
1242            // §34: time-driven handler — `every 60s while <guard> -> act;`
1243            let (spec, arrow, sends) = match rest.split_once("->") {
1244                Some((h, s)) => (h.trim(), true, s.trim().to_string()),
1245                None => (rest.trim_end_matches('{').trim(), false, String::new()),
1246            };
1247            // peel `as <role>` BEFORE the guard split (the guard would
1248            // otherwise swallow it: 'active as a')
1249            let (spec, as_role) = match spec.rfind(" as ") {
1250                Some(i) => (spec[..i].trim(), Some(spec[i + 4..].trim().to_string())),
1251                None => (spec, None),
1252            };
1253            let (spec, guard_src) = match spec.split_once(" while ") {
1254                Some((a, g)) => (a.trim(), Some(g.trim().to_string())),
1255                None => (spec, None),
1256            };
1257            let every_ms = parse_duration(spec);
1258            let Some(every_ms) = every_ms else {
1259                errors.push(IdlError { line: line_no, message: format!("bad timer spec: '{spec}' (want e.g. '60s', '500ms')") });
1260                continue;
1261            };
1262            let guard = match guard_src.map(|g| parse_guard(&g)) {
1263                Some(Ok(g)) => Some(g),
1264                Some(Err(e)) => {
1265                    errors.push(IdlError { line: line_no, message: format!("bad guard: {e}") });
1266                    continue;
1267                }
1268                None => None,
1269            };
1270            let h = Handler { trigger: OnTrigger::Timer { every_ms, guard, as_role }, guard: None, actions: Vec::new(), line: line_no };
1271            if arrow {
1272                let stmt = sends.trim_end_matches(';').trim();
1273                match parse_action(stmt) {
1274                    Ok(a) => {
1275                        let mut hh = h;
1276                        hh.actions.push(a);
1277                        prog.handlers.push(hh);
1278                    }
1279                    Err(e) => errors.push(IdlError { line: line_no, message: e }),
1280                }
1281            } else {
1282                handler = Some(h);
1283            }
1284            continue;
1285        }
1286        if let Some(rest) = line.strip_prefix("on ") {
1287            let (head, arrow, sends) = match rest.split_once("->") {
1288                Some((h, s)) => (h.trim(), true, s.trim().to_string()),
1289                None => (rest.trim_end_matches('{').trim(), false, String::new()),
1290            };
1291            // inline block: `on X { act; act; }` — split the block body off
1292            // BEFORE trigger parsing (a content pattern's braces must not
1293            // leak into the trigger's from-clause)
1294            // inline block: `on X { act; act; }` — the final '}' closes
1295            // the BLOCK brace; find it by backward brace-matching (a
1296            // payload's '{' may appear AFTER the block opener)
1297            let block_open = if !arrow && rest.ends_with('}') && rest.contains('{') {
1298                let cs: Vec<char> = rest.chars().collect();
1299                let mut depth = 0i64;
1300                let mut open_at: Option<usize> = None;
1301                let mut i = cs.len() - 1;
1302                loop {
1303                    match cs[i] {
1304                        '}' => depth += 1,
1305                        '{' => {
1306                            depth -= 1;
1307                            if depth == 0 {
1308                                open_at = Some(i);
1309                                break;
1310                            }
1311                        }
1312                        _ => {}
1313                    }
1314                    if i == 0 {
1315                        break;
1316                    }
1317                    i -= 1;
1318                }
1319                open_at
1320            } else {
1321                None
1322            };
1323            let mut block_body: Option<String> =
1324                block_open.map(|i| cs_of(rest)[i + 1..cs_of(rest).len() - 1].iter().collect());
1325            let head: String = match block_open {
1326                Some(i) => rest[..i].trim().to_string(),
1327                None => head.to_string(),
1328            };
1329            // §50: peel `in <phase>` (conversation state gate) — outside
1330            // braces/strings, before the other peels
1331            let (head, trig_phase) = peel_phase(&head);
1332            // §43: peel `as <role>` (executor restriction for n-role) —
1333            // BEFORE the guard peel, from the END of the head
1334            let (head, as_role) = match head.rfind(" as ") {
1335                Some(i) => (head[..i].trim().to_string(), Some(head[i + 4..].trim().to_string())),
1336                None => (head, None),
1337            };
1338            // §34: peel `when <guard>` (before from-parsing)
1339            let (head, guard) = match head.rfind(" when ") {
1340                Some(i) => (head[..i].trim().to_string(), match parse_guard(head[i + 6..].trim()) {
1341                    Ok(g) => Some(g),
1342                    Err(e) => {
1343                        errors.push(IdlError { line: line_no, message: format!("bad guard: {e}") });
1344                        continue;
1345                    }
1346                }),
1347                None => (head, None),
1348            };
1349            // §38.4: alternation `on (accept | reject) from a` — expands to
1350            // one handler per alternative with identical guard and actions.
1351            // Only valid in one-line and inline-block forms.
1352            let expanded: Vec<String> = if head.starts_with('(') {
1353                match head.find(')') {
1354                    Some(close) if close > 1 => {
1355                        let alts: Vec<String> = head[1..close]
1356                            .split('|')
1357                            .map(|s| s.trim().to_string())
1358                            .filter(|s| !s.is_empty())
1359                            .collect();
1360                        let rest = head[close + 1..].trim().to_string();
1361                        if alts.len() > 1 {
1362                            alts.into_iter()
1363                                .map(|a| if rest.is_empty() { a.clone() } else { format!("{a} {rest}") })
1364                                .collect()
1365                        } else {
1366                            vec![head.to_string()]
1367                        }
1368                    }
1369                    _ => vec![head.to_string()],
1370                }
1371            } else {
1372                vec![head.to_string()]
1373            };
1374            let inline_block = block_body.is_some();
1375            if expanded.len() > 1 && !arrow && !inline_block {
1376                errors.push(IdlError {
1377                    line: line_no,
1378                    message: "alternation requires one-line or inline-block form".into(),
1379                });
1380                continue;
1381            }
1382            let mut hs: Vec<Handler> = Vec::new();
1383            for hhead in &expanded {
1384                let mut trigger = match parse_trigger_as(hhead, as_role.clone()) {
1385                    Ok(t) => t,
1386                    Err(e) => {
1387                        errors.push(IdlError { line: line_no, message: e });
1388                        continue;
1389                    }
1390                };
1391                if let OnTrigger::Event { phase, .. } = &mut trigger {
1392                    *phase = trig_phase.clone();
1393                }
1394                hs.push(Handler { trigger, guard: guard.clone(), actions: Vec::new(), line: line_no });
1395            }
1396            if hs.is_empty() {
1397                continue;
1398            }
1399            if arrow {
1400                // one-line form: `on X -> send Y;` (no block)
1401                let stmt = sends.trim_end_matches(';').trim();
1402                // §45: `on X -> <action> handle error -> <action>;` wraps
1403                // the body in a try/catch — handler-local error flow
1404                let action = match stmt.split_once(" handle error -> ") {
1405                    Some((body_part, catch_part)) => {
1406                        match (parse_action(body_part.trim()), parse_action(catch_part.trim())) {
1407                            (Ok(b), Ok(c)) => Ok(ProtocolAction::Try { body: vec![b], catch: vec![c] }),
1408                            (Err(e), _) | (_, Err(e)) => Err(e),
1409                        }
1410                    }
1411                    None => parse_action(stmt),
1412                };
1413                match action {
1414                    Ok(a) => {
1415                        for h in &mut hs {
1416                            h.actions.push(a.clone());
1417                        }
1418                    }
1419                    Err(e) => errors.push(IdlError { line: line_no, message: e }),
1420                }
1421                prog.handlers.extend(hs);
1422            } else if line.ends_with('{') {
1423                handler = Some(hs.remove(0));
1424            } else if let Some(body_src) = block_body.take() {
1425                // inline block: `on X { act; act; }` — body already split off
1426                let body = body_src;
1427                for stmt in split_stmts(&body) {
1428                    if stmt.trim().is_empty() {
1429                        continue;
1430                    }
1431                    match parse_action(stmt.trim()) {
1432                        Ok(a) => {
1433                            for hh in &mut hs {
1434                                hh.actions.push(a.clone());
1435                            }
1436                        }
1437                        Err(e) => {
1438                            errors.push(IdlError { line: line_no, message: e });
1439                            break;
1440                        }
1441                    }
1442                }
1443                for h in hs {
1444                    if !h.actions.is_empty() {
1445                        prog.handlers.push(h);
1446                    }
1447                }
1448            } else {
1449                errors.push(IdlError { line: line_no, message: format!("malformed handler: '{line}' (want 'on <event> -> <action>;' or 'on <event> {{')") });
1450            }
1451            continue;
1452        }
1453        if let Some(rest) = line.strip_prefix("message ") {
1454            let body = rest.trim_end_matches(';').trim();
1455            match body.split_once('=') {
1456                Some((name, text)) => {
1457                    let name = name.trim().to_string();
1458                    let text = text.trim().trim_matches('"').to_string();
1459                    if name.is_empty() || text.is_empty() {
1460                        errors.push(IdlError { line: line_no, message: format!("bad message template: '{line}'") });
1461                    } else {
1462                        prog.templates.push((name, text));
1463                    }
1464                }
1465                None => errors.push(IdlError { line: line_no, message: format!("bad message template: '{line}' (want 'message name = \"text\";')") }),
1466            }
1467            continue;
1468        }
1469        if let Some(rest) = line.strip_prefix("use ") {
1470            let body = rest.trim_end_matches(';').trim();
1471            let (name, alias) = match body.split_once(" as ") {
1472                Some((n, a)) => (n.trim().to_string(), Some(a.trim().to_string())),
1473                None => (body.to_string(), None),
1474            };
1475            prog.capabilities.push(CapabilityDecl { name, alias });
1476            continue;
1477        }
1478        if let Some(rest) = line.strip_prefix("transport ") {
1479            let t = rest.trim_end_matches(';').trim().to_string();
1480            if !["stdio", "http", "ws", "relay"].contains(&t.as_str()) {
1481                errors.push(IdlError {
1482                    line: line_no,
1483                    message: format!("unknown transport '{t}' (want stdio|http|ws|relay)"),
1484                });
1485            }
1486            prog.transport = Some(t);
1487            continue;
1488        }
1489        if let Some(rest) = line.strip_prefix("capacity ") {
1490            match rest.trim_end_matches(';').trim().parse::<usize>() {
1491                Ok(n) if n > 0 => prog.capacity = Some(n),
1492                _ => errors.push(IdlError { line: line_no, message: format!("bad capacity: '{line}'") }),
1493            }
1494            continue;
1495        }
1496        if let Some(rest) = line.strip_prefix("abort when ") {
1497            match parse_guard(rest.trim_end_matches(';').trim()) {
1498                Ok(g) => prog.abort_when.push(g),
1499                Err(e) => errors.push(IdlError { line: line_no, message: format!("bad abort guard: {e}") }),
1500            }
1501            continue;
1502        }
1503        if line.starts_with("scenario ") && line.ends_with('{') {
1504            scenario = Some(Scenario {
1505                name: line[8..line.len() - 1].trim().trim_matches('"').to_string(),
1506                steps: Vec::new(),
1507            });
1508            continue;
1509        }
1510        if let Some(sc) = scenario.as_mut() {
1511            if line == "}" {
1512                if sc.steps.is_empty() {
1513                    errors.push(IdlError { line: line_no, message: "empty scenario".into() });
1514                }
1515                prog.scenarios.push(scenario.take().unwrap());
1516                continue;
1517            }
1518            match parse_scenario_step(line) {
1519                Ok(st) => sc.steps.push(st),
1520                Err(e) => errors.push(IdlError { line: line_no, message: e }),
1521            }
1522            continue;
1523        }
1524        if let Some(rest) = line.strip_prefix("end when ") {
1525            let cond = rest.trim_end_matches(';').trim();
1526            prog.end_when = Some(match cond {
1527                "fulfilled" | "expired" | "breached" => EndWhen::Builtin(cond.into()),
1528                s => EndWhen::State(s.into()),
1529            });
1530            continue;
1531        }
1532        if line == "end;" {
1533            continue; // optional terminator
1534        }
1535        errors.push(IdlError { line: line_no, message: format!("unrecognized line: '{line}'") });
1536    }
1537
1538    if handler.is_some() {
1539        errors.push(IdlError { line: 0, message: "unterminated handler block (missing '}')".into() });
1540    }
1541    if scenario.is_some() {
1542        errors.push(IdlError { line: 0, message: "unterminated scenario block".into() });
1543    }
1544    if func.is_some() {
1545        errors.push(IdlError { line: 0, message: "unterminated fn block (missing '}')".into() });
1546    }
1547    if !seen_protocol {
1548        errors.push(IdlError { line: 0, message: "missing 'protocol <name> v1;' declaration".into() });
1549    }
1550    // §38.10/§42: every exported name must name a declared item
1551    for name in prog.exported_sets.clone() {
1552        if !prog.handler_sets.contains_key(&name) {
1553            errors.push(IdlError {
1554                line: 0,
1555                message: format!("export handler_set '{name}': no such handler set"),
1556            });
1557        }
1558    }
1559    for name in prog.exported_types.clone() {
1560        if !prog.types.contains_key(&name) {
1561            errors.push(IdlError {
1562                line: 0,
1563                message: format!("export type '{name}': no such type"),
1564            });
1565        }
1566    }
1567    for name in prog.exported_fns.clone() {
1568        if !prog.functions.iter().any(|f| f.name == name) {
1569            errors.push(IdlError {
1570                line: 0,
1571                message: format!("export fn '{name}': no such function"),
1572            });
1573        }
1574    }
1575    if errors.is_empty() { Ok(prog) } else { Err(errors) }
1576}
1577
1578/// §50: peel ` in <phase>` from a handler head — scans OUTSIDE braces and
1579/// string literals so a pattern like `{"m": "hello in there"}` is untouched
1580fn peel_phase(head: &str) -> (String, Option<String>) {
1581    let cs: Vec<char> = head.chars().collect();
1582    let mut depth = 0i64;
1583    let mut in_str = false;
1584    let mut i = 0;
1585    while i < cs.len() {
1586        let c = cs[i];
1587        match c {
1588            '"' => in_str = !in_str,
1589            '{' if !in_str => depth += 1,
1590            '}' if !in_str => depth -= 1,
1591            ' ' if depth == 0 && !in_str => {
1592                if i + 4 <= cs.len() && cs[i + 1] == 'i' && cs[i + 2] == 'n' && cs[i + 3] == ' ' {
1593                    let mut j = i + 4;
1594                    while j < cs.len() && (cs[j].is_alphanumeric() || cs[j] == '_') {
1595                        j += 1;
1596                    }
1597                    if j > i + 4 {
1598                        let rest: String = cs[j..].iter().collect();
1599                        if rest.trim_start().starts_with("from") || rest.trim().is_empty() {
1600                            let phase: String = cs[i + 4..j].iter().collect();
1601                            // §54: keep the REST (` from b`, ...) — only the
1602                            // `in <phase>` gate is removed
1603                            let mut head: String = cs[..i].iter().collect();
1604                            head.push_str(&rest);
1605                            return (head.trim().to_string(), Some(phase));
1606                        }
1607                    }
1608                }
1609            }
1610            _ => {}
1611        }
1612        i += 1;
1613    }
1614    (head.to_string(), None)
1615}
1616
1617/// §45: split statements on ';' at brace-depth 0 — `try { a; b; } catch { c };`
1618/// stays one statement.
1619/// §55: statement splitting that understands blocks. A `;` at depth 0
1620/// ends a statement — and so does the closing brace of an inline for or
1621/// catch block. Payload/record/pattern braces do NOT end statements, and
1622/// a try body waits for its catch before the statement is complete.
1623#[derive(PartialEq, Clone, Copy)]
1624enum BlkKind {
1625    For,
1626    TryBody,
1627    CatchBody,
1628    Payload,
1629}
1630
1631fn split_stmts(src: &str) -> Vec<String> {
1632    let mut out = Vec::new();
1633    let mut cur = String::new();
1634    let mut depth = 0i64;
1635    let mut stack: Vec<BlkKind> = Vec::new();
1636    let mut expect_catch = false;
1637    for c in src.chars() {
1638        match c {
1639            '{' => {
1640                depth += 1;
1641                cur.push(c);
1642                let kind = if expect_catch {
1643                    expect_catch = false;
1644                    BlkKind::CatchBody
1645                } else if cur.trim_start().starts_with("for ") {
1646                    BlkKind::For
1647                } else if cur.trim_start().starts_with("try ") {
1648                    BlkKind::TryBody
1649                } else {
1650                    BlkKind::Payload
1651                };
1652                stack.push(kind);
1653            }
1654            '}' => {
1655                depth -= 1;
1656                cur.push(c);
1657                match stack.pop() {
1658                    Some(BlkKind::For) | Some(BlkKind::CatchBody) if depth == 0 => {
1659                        let done = std::mem::take(&mut cur);
1660                        if !done.trim().is_empty() {
1661                            out.push(done);
1662                        }
1663                    }
1664                    Some(BlkKind::TryBody) => {
1665                        // `try { ... } catch { ... }` is ONE statement
1666                        expect_catch = true;
1667                    }
1668                    _ => {}
1669                }
1670            }
1671            ';' if depth == 0 => {
1672                let done = std::mem::take(&mut cur);
1673                if !done.trim().is_empty() {
1674                    out.push(done);
1675                }
1676            }
1677            _ => cur.push(c),
1678        }
1679    }
1680    if !cur.trim().is_empty() {
1681        out.push(cur);
1682    }
1683    out
1684}
1685
1686fn parse_trigger(head: &str) -> Result<OnTrigger, String> {
1687    parse_trigger_as(head, None)
1688}
1689
1690fn parse_trigger_as(head: &str, as_role: Option<String>) -> Result<OnTrigger, String> {
1691    let (word, pattern, from) = split_trigger(head);
1692    // §50: `on inform in quoted from a` — the phase gate lives between
1693    // the performative (and pattern) and the from-clause
1694    let (word, phase) = match word.split_once(" in ") {
1695        Some((w, ph)) => (w.trim().to_string(), Some(ph.trim().to_string())),
1696        None => (word, None),
1697    };
1698    match word.as_str() {
1699        "breach" | "expired" if from.is_some() => {
1700            Err(format!("'{word}' cannot have a 'from' role"))
1701        }
1702        "breach" => Ok(OnTrigger::Breach),
1703        "expired" => Ok(OnTrigger::Expired),
1704        w => match perf_from_word(w) {
1705            Some(p) => Ok(OnTrigger::Event { performative: p, pattern, from, as_role, phase }),
1706            None => Err(format!("unknown trigger '{word}'")),
1707        },
1708    }
1709}
1710
1711/// §35.3: `for x in list { send inform to x; set done = true; }`
1712fn parse_for_block(line: &str) -> Result<ProtocolAction, String> {
1713    let inner = line
1714        .strip_prefix("for ")
1715        .ok_or("not a for")?
1716        .trim_end_matches('}')
1717        .trim();
1718    let (head, body) = inner
1719        .split_once('{')
1720        .ok_or("for needs a block")?;
1721    let (var, over) = head
1722        .trim()
1723        .split_once(" in ")
1724        .ok_or("for needs 'for var in list'")?;
1725    let actions: Vec<ProtocolAction> = split_stmts(&body)
1726        .iter()
1727        .filter(|p| !p.trim().is_empty())
1728        .map(|p| parse_action(p.trim()))
1729        .collect::<Result<_, _>>()?;
1730    Ok(ProtocolAction::For {
1731        var: var.trim().to_string(),
1732        over: over.trim().to_string(),
1733        actions,
1734    })
1735}
1736
1737/// §35.12: one scenario step
1738fn parse_scenario_step(line: &str) -> Result<ScenarioStep, String> {
1739    let s = line.trim().trim_end_matches(';').trim();
1740    if let Some(rest) = s.strip_prefix("expect ") {
1741        if let Some(rest) = rest.strip_prefix("state ") {
1742            // expect state <role>.<name> [== <bool>]
1743            let (ref_part, val) = match rest.split_once("==") {
1744                Some((a, b)) => (a.trim(), b.trim() == "true"),
1745                None => (rest, true),
1746            };
1747            let (role, name) = ref_part
1748                .split_once('.')
1749                .ok_or("expect state needs role.name")?;
1750            return Ok(ScenarioStep::ExpectState {
1751                role: role.trim().to_string(),
1752                name: name.trim().to_string(),
1753                value: val,
1754            });
1755        }
1756        if let Some(rest) = rest.strip_prefix("log ") {
1757            let contains = rest
1758                .trim()
1759                .trim_matches('"')
1760                .to_string();
1761            return Ok(ScenarioStep::ExpectLog { contains });
1762        }
1763        if let Some(rest) = rest.strip_prefix("commitment ") {
1764            let (role, status) = rest
1765                .split_once(' ')
1766                .ok_or("expect commitment needs role status")?;
1767            return Ok(ScenarioStep::ExpectCommitment {
1768                role: role.trim().to_string(),
1769                status: status.trim().to_string(),
1770            });
1771        }
1772        // expect <role> sends <perf>
1773        let (role, perf) = rest
1774            .split_once(" sends ")
1775            .ok_or("expect sends needs 'role sends perf'")?;
1776        let p = perf_from_word(perf.trim()).ok_or(format!("unknown performative '{perf}'"))?;
1777        return Ok(ScenarioStep::ExpectSend { from: role.trim().to_string(), performative: p });
1778    }
1779    // <role> sends <perf> [pattern] to <role>
1780    let (head, to) = s.split_once(" to ").ok_or("scenario send needs 'to <role>'")?;
1781    let (from, rest) = head
1782        .split_once(" sends ")
1783        .ok_or("scenario step must be 'X sends Y to Z' or 'expect ...'")?;
1784    let rest = rest.trim();
1785    // peel an optional pattern: `request("q")` or `request {...}`
1786    let (perf_word, pattern) = match rest.find(|c| c == '(' || c == '{') {
1787        Some(i) => (rest[..i].trim(), Some(rest[i..].to_string())),
1788        None => (rest, None),
1789    };
1790    let p = perf_from_word(perf_word).ok_or(format!("unknown performative '{perf_word}'"))?;
1791    Ok(ScenarioStep::Send {
1792        from: from.trim().to_string(),
1793        performative: p,
1794        pattern,
1795        to: to.trim().to_string(),
1796    })
1797}
1798
1799fn parse_duration(spec: &str) -> Option<i64> {
1800    let spec = spec.trim();
1801    let (num, unit) = spec.split_at(spec.find(|c: char| !c.is_ascii_digit())?);
1802    let n: i64 = num.parse().ok()?;
1803    match unit {
1804        "ms" => Some(n),
1805        "s" => Some(n * 1000),
1806        "m" => Some(n * 60_000),
1807        _ => None,
1808    }
1809}
1810
1811fn parse_action(stmt: &str) -> Result<ProtocolAction, String> {
1812    let s = stmt.trim().trim_end_matches(';').trim();
1813    if s == "begin" {
1814        return Ok(ProtocolAction::Begin);
1815    }
1816    if let Some(id) = s.strip_prefix("begin ") {
1817        // §51: named commitment begin
1818        return Ok(ProtocolAction::BeginId { id: id.trim().to_string() });
1819    }
1820    if s == "fulfil" {
1821        return Ok(ProtocolAction::Fulfil);
1822    }
1823    if let Some(id) = s.strip_prefix("fulfil ") {
1824        return Ok(ProtocolAction::FulfilId { id: id.trim().to_string() });
1825    }
1826    if let Some(rest) = s.strip_prefix("retract(") {
1827        let target = rest.trim_end_matches(')').trim();
1828        if target.is_empty() {
1829            return Err("retract needs a target".into());
1830        }
1831        return Ok(ProtocolAction::Retract { target: target.trim_matches('"').to_string() });
1832    }
1833    if let Some(rest) = s.strip_prefix("set ") {
1834        let (name, expr) = rest
1835            .split_once('=')
1836            .ok_or_else(|| format!("bad set: '{s}' (want 'set x = expr')"))?;
1837        let expr = Expr::parse_expr(expr.trim())?;
1838        // `set q.price = ...` targets a record field (§38.2)
1839        let (name, field) = match name.trim().split_once('.') {
1840            Some((base, f)) => (base.trim().to_string(), Some(f.trim().to_string())),
1841            None => (name.trim().to_string(), None),
1842        };
1843        return Ok(ProtocolAction::Set { name, field, expr });
1844    }
1845    if let Some(rest) = s.strip_prefix("return ") {
1846        let expr = Expr::parse_expr(rest.trim())?;
1847        return Ok(ProtocolAction::Return { expr });
1848    }
1849    if s == "return" {
1850        return Ok(ProtocolAction::Return { expr: Expr::LitBool(true) });
1851    }
1852    if let Some(rest) = s.strip_prefix("push ") {
1853        let parts: Vec<&str> = rest.splitn(2, ',').collect();
1854        if parts.len() != 2 {
1855            return Err(format!("bad push: '{s}' (want 'push list, expr')"));
1856        }
1857        let expr = Expr::parse_expr(parts[1].trim())?;
1858        return Ok(ProtocolAction::Push { state: parts[0].trim().to_string(), expr });
1859    }
1860    if let Some(rest) = s.strip_prefix("put ") {
1861        let parts: Vec<&str> = rest.splitn(3, ',').collect();
1862        if parts.len() != 3 {
1863            return Err(format!("bad put: '{s}' (want 'put map, key, expr')"));
1864        }
1865        let expr = Expr::parse_expr(parts[2].trim())?;
1866        return Ok(ProtocolAction::Put {
1867            state: parts[0].trim().to_string(),
1868            key: parts[1].trim().trim_matches('"').to_string(),
1869            expr,
1870        });
1871    }
1872    if s == "abort" {
1873        return Ok(ProtocolAction::Abort);
1874    }
1875    if let Some(rest) = s.strip_prefix("broadcast ") {
1876        // §38.8: `broadcast propose {"task": "x"} to bidders;`
1877        let (perf_part, target) = match rest.rsplit_once(" to ") {
1878            Some((a, b)) => (a.trim(), b.trim().to_string()),
1879            None => return Err(format!("bad broadcast: '{s}' (want 'broadcast <perf> [payload] to <list_state>')")),
1880        };
1881        let (perf_w, fields) = match (perf_part.find('{'), perf_part.ends_with('}')) {
1882            (Some(i), true) => {
1883                let raw = &perf_part[i..];
1884                let map: BTreeMap<String, String> = serde_json::from_str(raw)
1885                    .map_err(|e| format!("bad broadcast payload: {e}"))?;
1886                (perf_part[..i].trim(), Some(map))
1887            }
1888            _ => (perf_part, None),
1889        };
1890        let performative = perf_from_word(perf_w)
1891            .ok_or_else(|| format!("unknown performative '{perf_w}'"))?;
1892        return Ok(ProtocolAction::Broadcast { performative, fields, to: target });
1893    }
1894    if let Some(rest) = s.strip_prefix("enter ") {
1895        // §50: conversation phase transition
1896        let phase = rest.trim_end_matches(';').trim().to_string();
1897        return Ok(ProtocolAction::Enter { phase });
1898    }
1899    if s.starts_with("for ") && s.ends_with('}') {
1900        // §55: inline for-block is a STATEMENT too (legal inside try/for)
1901        return parse_for_block(s);
1902    }
1903    if let Some(rest) = s.strip_prefix("try ") {
1904        // §45: `try { a; b; } catch { c; };` — inline form
1905        let (body_src, catch_src) = rest
1906            .split_once("} catch {")
1907            .ok_or_else(|| format!("bad try: '{s}' (want 'try {{ ... }} catch {{ ... }};')"))?;
1908        let body_inner = body_src
1909            .split_once('{')
1910            .ok_or_else(|| format!("bad try: '{s}' (missing body brace)"))?
1911            .1;
1912        let catch_inner = catch_src
1913            .trim_end_matches(';')
1914            .trim()
1915            .trim_end_matches('}')
1916            .trim();
1917        let mut body = Vec::new();
1918        for stmt in split_stmts(body_inner) {
1919            if stmt.trim().is_empty() {
1920                continue;
1921            }
1922            body.push(parse_action(stmt.trim())?);
1923        }
1924        let mut catch = Vec::new();
1925        for stmt in split_stmts(catch_inner) {
1926            if stmt.trim().is_empty() {
1927                continue;
1928            }
1929            catch.push(parse_action(stmt.trim())?);
1930        }
1931        return Ok(ProtocolAction::Try { body, catch });
1932    }
1933    if let Some(rest) = s.strip_prefix("await ") {
1934        // §44: `await 3 propose into bids within 5s as bids_ready;`
1935        let parts: Vec<&str> = rest.split_whitespace().collect();
1936        if parts.len() != 8
1937            || parts[2] != "into"
1938            || parts[4] != "within"
1939            || parts[6] != "as"
1940        {
1941            return Err(format!(
1942                "bad await: '{s}' (want 'await N <perf> into <list> within <dur> as <flag>')"
1943            ));
1944        }
1945        let count: i64 = parts[0].parse().map_err(|_| "bad await count")?;
1946        let performative =
1947            perf_from_word(parts[1]).ok_or_else(|| format!("unknown performative '{}'", parts[1]))?;
1948        let within_ms = parse_duration(parts[5]).ok_or("bad await duration")?;
1949        return Ok(ProtocolAction::Await {
1950            count,
1951            performative,
1952            into: parts[3].to_string(),
1953            within_ms,
1954            flag: parts[7].to_string(),
1955        })
1956    }
1957    if let Some(rest) = s.strip_prefix("send ") {
1958        // peel retry clause first: `retry 3 backoff 2s exp`
1959        let (rest, retry) = match rest.find(" retry ") {
1960            Some(i) => {
1961                let clause = rest[i..].trim();
1962                let head = rest[..i].trim();
1963                // parse: retry N backoff D [exp]
1964                let parts: Vec<&str> = clause.split_whitespace().collect();
1965                let retry = match parts.as_slice() {
1966                    ["retry", n, "backoff", d] => Retry {
1967                        attempts: n.parse().map_err(|_| "bad retry count")?,
1968                        backoff_ms: parse_duration(d).ok_or("bad backoff duration")?,
1969                        exponential: false,
1970                    },
1971                    ["retry", n, "backoff", d, "exp"] => Retry {
1972                        attempts: n.parse().map_err(|_| "bad retry count")?,
1973                        backoff_ms: parse_duration(d).ok_or("bad backoff duration")?,
1974                        exponential: true,
1975                    },
1976                    _ => return Err(format!("bad retry clause: '{clause}' (want 'retry N backoff D [exp]')")),
1977                };
1978                (head, Some(retry))
1979            }
1980            None => (rest, None),
1981        };
1982        let (rest, to) = match rest.find(" to ") {
1983            Some(i) => (rest[..i].trim(), Some(rest[i + 4..].trim().to_string())),
1984            None => (rest, None),
1985        };
1986        // optional payload: `send progress {"pct": "50"}`
1987        let (rest, fields) = match (rest.find('{'), rest.ends_with('}')) {
1988            (Some(i), true) => {
1989                let raw = &rest[i..];
1990                let map: BTreeMap<String, String> = serde_json::from_str(raw)
1991                    .map_err(|e| format!("bad send payload: {e}"))?;
1992                (rest[..i].trim(), Some(map))
1993            }
1994            _ => (rest, None),
1995        };
1996        let word = rest.split(|c: char| c == '(' || c == ' ' || c == '{').next().unwrap_or(rest);
1997        return match perf_from_word(word.trim()) {
1998            Some(p) => Ok(ProtocolAction::Send { performative: p, to, fields, retry }),
1999            None => Err(format!("unknown performative in send: '{word}'")),
2000        };
2001    }
2002    Err(format!("unknown statement: '{s}'"))
2003}
2004
2005// ---------------------------------------------------------------- check
2006
2007/// §38.6: static type of an expression — Some only when statically known
2008/// ("int" | "float" | "str" | "bool" | declared record type name).
2009pub fn static_ty(e: &Expr, prog: &ProtocolProgram) -> Option<String> {
2010    match e {
2011        Expr::LitInt(_) => Some("int".into()),
2012        Expr::LitStr(_) => Some("str".into()),
2013        Expr::LitBool(_) => Some("bool".into()),
2014        Expr::State(n) => prog
2015            .states
2016            .iter()
2017            .find(|s| &s.name == n)
2018            .and_then(|s| s.ty.clone()),
2019        Expr::Field { base, name } => {
2020            let bt = static_ty(base, prog)?;
2021            prog.types
2022                .get(&bt)?
2023                .iter()
2024                .find(|(f, _)| f == name)
2025                .map(|(_, t)| t.clone())
2026        }
2027        Expr::RecLit { ty, .. } => Some(ty.clone()),
2028        Expr::Call { name, .. } => prog
2029            .functions
2030            .iter()
2031            .find(|f| &f.name == name)
2032            .and_then(|f| f.ret.clone()),
2033        Expr::Not(_) => Some("bool".into()),
2034        Expr::Bin { op, l, r } => match op {
2035            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge | BinOp::Eq | BinOp::Ne
2036            | BinOp::And | BinOp::Or => Some("bool".into()),
2037            BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div => {
2038                let lt = static_ty(l, prog);
2039                let rt = static_ty(r, prog);
2040                match (lt, rt) {
2041                    (Some(a), Some(b)) if a == b => Some(a),
2042                    (Some(a), Some(b))
2043                        if (a == "int" && b == "float") || (a == "float" && b == "int") =>
2044                    {
2045                        Some("float".into())
2046                    }
2047                    _ => None,
2048                }
2049            }
2050        },
2051        Expr::Capture(_) | Expr::Arg(_) => None,
2052    }
2053}
2054
2055/// §38.6: widening rule — int widens to float, nothing else coerces.
2056fn ty_assign_ok(declared: &str, got: &str) -> bool {
2057    declared == got || (declared == "float" && got == "int")
2058}
2059
2060/// §38.6: walk assignment actions; check declared state types against
2061/// inferred expression types and record field existence (recursively
2062/// through `for` bodies).
2063fn check_action_types(
2064    prog: &ProtocolProgram,
2065    actions: &[ProtocolAction],
2066    src_line: usize,
2067    errors: &mut Vec<IdlError>,
2068) {
2069    for a in actions {
2070        match a {
2071            ProtocolAction::Set { name, field, expr } => {
2072                if let Some(f) = field {
2073                    // field write `set q.price = ...`: q must be a record
2074                    // and 'price' one of its declared fields
2075                    let declared = prog
2076                        .states
2077                        .iter()
2078                        .find(|s| &s.name == name)
2079                        .and_then(|s| s.ty.clone());
2080                    if let Some(dt) = declared {
2081                        match prog.types.get(&dt) {
2082                            Some(fields) => {
2083                                if !fields.iter().any(|(fname, _)| fname == f) {
2084                                    errors.push(IdlError {
2085                                        line: src_line,
2086                                        message: format!(
2087                                            "record '{dt}' has no field '{f}' (set {name}.{f})"
2088                                        ),
2089                                    });
2090                                }
2091                            }
2092                            None => errors.push(IdlError {
2093                                line: src_line,
2094                                message: format!(
2095                                    "'{dt}' is not a declared record type (set {name}.{f})"
2096                                ),
2097                            }),
2098                        }
2099                    }
2100                } else if let Some(dt) = prog
2101                    .states
2102                    .iter()
2103                    .find(|s| &s.name == name)
2104                    .and_then(|s| s.ty.clone())
2105                {
2106                    if let Some(gt) = static_ty(expr, prog) {
2107                        if !ty_assign_ok(&dt, &gt) {
2108                            errors.push(IdlError {
2109                                line: src_line,
2110                                message: format!(
2111                                    "type mismatch: state '{name}' is '{dt}' but expression is '{gt}'"
2112                                ),
2113                            });
2114                        }
2115                    }
2116                }
2117                check_expr_fields(prog, expr, src_line, errors);
2118            }
2119            ProtocolAction::Push { expr, .. } | ProtocolAction::Put { expr, .. } => {
2120                check_expr_fields(prog, expr, src_line, errors);
2121            }
2122            ProtocolAction::For { actions, .. } => {
2123                check_action_types(prog, actions, src_line, errors)
2124            }
2125            _ => {}
2126        }
2127    }
2128}
2129
2130/// §38.6: recursively check record field access/literals inside an expr.
2131fn check_expr_fields(prog: &ProtocolProgram, e: &Expr, src_line: usize, errors: &mut Vec<IdlError>) {
2132    match e {
2133        Expr::Field { base, name } => {
2134            if let Some(bt) = static_ty(base, prog) {
2135                match prog.types.get(&bt) {
2136                    Some(fields) => {
2137                        if !fields.iter().any(|(f, _)| f == name) {
2138                            errors.push(IdlError {
2139                                line: src_line,
2140                                message: format!("record '{bt}' has no field '{name}'"),
2141                            });
2142                        }
2143                    }
2144                    None => {
2145                        if matches!(bt.as_str(), "int" | "str" | "bool" | "float") {
2146                            errors.push(IdlError {
2147                                line: src_line,
2148                                message: format!("'{bt}' is not a record — no field '{name}'"),
2149                            });
2150                        }
2151                    }
2152                }
2153            }
2154            check_expr_fields(prog, base, src_line, errors);
2155        }
2156        Expr::Bin { l, r, .. } => {
2157            check_expr_fields(prog, l, src_line, errors);
2158            check_expr_fields(prog, r, src_line, errors);
2159        }
2160        Expr::Not(x) => check_expr_fields(prog, x, src_line, errors),
2161        Expr::Call { args, .. } => {
2162            for a in args {
2163                check_expr_fields(prog, a, src_line, errors);
2164            }
2165        }
2166        Expr::RecLit { ty, fields } => {
2167            if let Some(decl) = prog.types.get(ty) {
2168                for (f, _) in fields {
2169                    if !decl.iter().any(|(df, _)| df == f) {
2170                        errors.push(IdlError {
2171                            line: src_line,
2172                            message: format!("record '{ty}' has no field '{f}'"),
2173                        });
2174                    }
2175                }
2176            }
2177            for (_, fe) in fields {
2178                check_expr_fields(prog, fe, src_line, errors);
2179            }
2180        }
2181        _ => {}
2182    }
2183}
2184
2185/// §48: flatten NESTED actions (for bodies, try bodies and catches) —
2186/// compile-time checks must cover them, not only top-level actions
2187pub fn all_actions(actions: &[ProtocolAction]) -> Vec<&ProtocolAction> {
2188    fn go<'a>(acts: &'a [ProtocolAction], out: &mut Vec<&'a ProtocolAction>) {
2189        for a in acts {
2190            out.push(a);
2191            match a {
2192                ProtocolAction::For { actions, .. } => go(actions, out),
2193                ProtocolAction::Try { body, catch } => {
2194                    go(body, out);
2195                    go(catch, out);
2196                }
2197                _ => {}
2198            }
2199        }
2200    }
2201    let mut out = Vec::new();
2202    go(actions, &mut out);
2203    out
2204}
2205
2206/// Compile-time well-formedness — the dialogue matrix (§16) applied to the
2207/// PROGRAM, not the runtime. Returns warnings; errors abort compilation.
2208pub fn check(prog: &ProtocolProgram) -> Result<Vec<String>, Vec<IdlError>> {
2209    let mut errors = Vec::new();
2210    let mut warnings = Vec::new();
2211
2212    if prog.roles.is_empty() {
2213        errors.push(IdlError { line: 0, message: "protocol declares no roles".into() });
2214    } else {
2215        let mut seen = std::collections::BTreeSet::new();
2216        for r in &prog.roles {
2217            if !seen.insert(r.clone()) {
2218                errors.push(IdlError { line: 0, message: format!("duplicate role '{r}'") });
2219            }
2220        }
2221    }
2222    if prog.handlers.is_empty() {
2223        errors.push(IdlError { line: 0, message: "protocol declares no handlers".into() });
2224    }
2225
2226    // duplicate (trigger, pattern) handlers are ambiguous
2227    let mut sigs: BTreeMap<String, ()> = BTreeMap::new();
2228    for h in &prog.handlers {
2229        let sig = match &h.trigger {
2230            OnTrigger::Event { performative, pattern, from, as_role, phase } => {
2231                format!(
2232                    "event:{performative:?}:{pattern:?}:{from:?}:{as_role:?}:{phase:?}:guard={:?}",
2233                    h.guard.as_ref().map(|g| guard_word(g))
2234                )
2235            }
2236            OnTrigger::Timer { every_ms, guard, as_role } => {
2237                format!("timer:{every_ms}:{guard:?}:{as_role:?}")
2238            }
2239            OnTrigger::Breach => "breach".into(),
2240            OnTrigger::Expired => "expired".into(),
2241        };
2242        if sigs.insert(sig.clone(), ()).is_some() {
2243            errors.push(IdlError { line: h.line, message: format!("duplicate handler for {sig}") });
2244        }
2245    }
2246
2247    // §33/§48: every send (at ANY nesting level) must be dialogue-legal
2248    for h in &prog.handlers {
2249        for a in all_actions(&h.actions) {
2250            let out = match a {
2251                ProtocolAction::Send { performative: out, .. }
2252                | ProtocolAction::Broadcast { performative: out, .. } => *out,
2253                _ => continue,
2254            };
2255            let legal = match &h.trigger {
2256                OnTrigger::Event { performative: inp, .. } => dialogue_legal(*inp, out),
2257                // breach/expired/timer happen inside a session opened by some
2258                // request-shaped move; the send must be legal after AT
2259                // LEAST ONE plausible predecessor
2260                OnTrigger::Breach | OnTrigger::Expired | OnTrigger::Timer { .. } => [
2261                    Performative::Request,
2262                    Performative::Propose,
2263                    Performative::Delegate,
2264                ]
2265                .iter()
2266                .any(|prev| dialogue_legal(*prev, out)),
2267            };
2268            if !legal {
2269                let mut trig = match &h.trigger {
2270                    OnTrigger::Event { performative, .. } => format!("{performative:?}"),
2271                    OnTrigger::Breach => "Breach".into(),
2272                    OnTrigger::Expired => "Expired".into(),
2273                    OnTrigger::Timer { .. } => "Timer".into(),
2274                };
2275                errors.push(IdlError {
2276                    line: h.line,
2277                    message: format!(
2278                        "dialogue violation: handler on {trig} cannot send {out:?} (§16 matrix)"
2279                    ),
2280                });
2281            }
2282        }
2283    }
2284
2285    // end_when must reference a declared state or a builtin
2286    if let Some(ew) = &prog.end_when {
2287        if let EndWhen::State(s) = ew {
2288            if !prog.state_names().contains(&s.as_str()) {
2289                errors.push(IdlError {
2290                    line: 0,
2291                    message: format!("end when references undeclared state '{s}'"),
2292                });
2293            }
2294        }
2295    }
2296
2297    // ---- §50: conversation phases — triggers and enter targets must
2298    // reference declared phases
2299    let bad_phase = |name: &str, what: &str, line: usize, errors: &mut Vec<IdlError>| {
2300        if prog.phases.is_empty() {
2301            errors.push(IdlError {
2302                line,
2303                message: format!("{what} '{name}': the protocol declares no phases"),
2304            });
2305            return;
2306        }
2307        if !prog.phases.iter().any(|p| p == name) {
2308            errors.push(IdlError {
2309                line,
2310                message: format!("{what} references undeclared phase '{name}'"),
2311            });
2312        }
2313    };
2314    for h in &prog.handlers {
2315        if let OnTrigger::Event { phase: Some(ph), .. } = &h.trigger {
2316            bad_phase(ph, "trigger phase", h.line, &mut errors);
2317        }
2318        for a in all_actions(&h.actions) {
2319            if let ProtocolAction::Enter { phase } = a {
2320                bad_phase(phase, "enter", h.line, &mut errors);
2321            }
2322        }
2323    }
2324
2325    // ---- §54: phase reachability — a declared phase that is never
2326    // `enter`-ed can never host its handlers (compile WARNING; proving
2327    // cross-participant phase compatibility needs global analysis)
2328    {
2329        let entered: Vec<&str> = prog
2330            .handlers
2331            .iter()
2332            .flat_map(|h| all_actions(&h.actions))
2333            .filter_map(|a| match a {
2334                ProtocolAction::Enter { phase } => Some(phase.as_str()),
2335                _ => None,
2336            })
2337            .collect();
2338        for (i, ph) in prog.phases.iter().enumerate() {
2339            if i > 0 && !entered.contains(&ph.as_str()) {
2340                warnings.push(format!(
2341                    "phase '{ph}' is never entered — its handlers are unreachable"
2342                ));
2343            }
2344        }
2345    }
2346
2347    // ---- §47: function recursion is a compile error (no call stacks in
2348    // the runtime — a cycle would hang delivery)
2349    {
2350        let mut calls_of: BTreeMap<String, Vec<String>> = BTreeMap::new();
2351        fn collect_calls(e: &Expr, out: &mut Vec<String>) {
2352            match e {
2353                Expr::Call { name, args } => {
2354                    out.push(name.clone());
2355                    for a in args {
2356                        collect_calls(a, out);
2357                    }
2358                }
2359                Expr::Bin { l, r, .. } => {
2360                    collect_calls(l, out);
2361                    collect_calls(r, out);
2362                }
2363                Expr::Not(x) => collect_calls(x, out),
2364                Expr::Field { base, .. } => collect_calls(base, out),
2365                Expr::RecLit { fields, .. } => {
2366                    for (_, fe) in fields {
2367                        collect_calls(fe, out);
2368                    }
2369                }
2370                _ => {}
2371            }
2372        }
2373        for f in &prog.functions {
2374            let mut cs = Vec::new();
2375            for a in &f.body {
2376                if let ProtocolAction::Set { expr, .. } = a {
2377                    collect_calls(expr, &mut cs);
2378                }
2379            }
2380            if let Some(e) = &f.returned {
2381                collect_calls(e, &mut cs);
2382            }
2383            calls_of.insert(f.name.clone(), cs);
2384        }
2385        fn has_path(from: &str, target: &str, graph: &BTreeMap<String, Vec<String>>, seen: &mut Vec<String>) -> bool {
2386            if let Some(next) = graph.get(from) {
2387                for n in next {
2388                    if n == target {
2389                        return true;
2390                    }
2391                    if !seen.contains(n) {
2392                        seen.push(n.clone());
2393                        if has_path(n, target, graph, seen) {
2394                            return true;
2395                        }
2396                    }
2397                }
2398            }
2399            false
2400        }
2401        for f in &prog.functions {
2402            let mut seen = Vec::new();
2403            if has_path(&f.name, &f.name, &calls_of, &mut seen) {
2404                errors.push(IdlError {
2405                    line: 0,
2406                    message: format!("function '{}' is recursive — the runtime has no call stacks", f.name),
2407                });
2408            }
2409        }
2410    }
2411
2412    // ---- §41: state type lattice — bool|int|str|float|list|map,
2413    // list<T> / map<K,V> with valid element types, or declared records
2414    let valid_ty = |ty: &str| -> bool {
2415        match ty {
2416            "bool" | "int" | "str" | "float" | "list" | "map" => true,
2417            t if t.starts_with("list<") && t.ends_with('>') => {
2418                let e = &t[5..t.len() - 1];
2419                matches!(e, "bool" | "int" | "str" | "float") || prog.types.contains_key(e)
2420            }
2421            t if t.starts_with("map<") && t.ends_with('>') => {
2422                let inner = &t[4..t.len() - 1];
2423                let (k, v) = inner.split_once(',').unwrap_or(("str", inner));
2424                let (k, v) = (k.trim(), v.trim());
2425                (matches!(k, "str" | "int") || prog.types.contains_key(k))
2426                    && (matches!(v, "bool" | "int" | "str" | "float" | "list" | "map")
2427                        || prog.types.contains_key(v))
2428            }
2429            t => prog.types.contains_key(t),
2430        }
2431    };
2432    for st in &prog.states {
2433        if let Some(ty) = &st.ty {
2434            if !valid_ty(ty) {
2435                errors.push(IdlError {
2436                    line: 0,
2437                    message: format!(
2438                        "state '{}' has unknown type '{}' (want bool|int|str|float|list|map|list<T>|map<K,V>|declared record)",
2439                        st.name, ty
2440                    ),
2441                });
2442            }
2443        }
2444    }
2445
2446    // begin/fulfil without any Event handler is meaningless
2447    let has_event = prog
2448        .handlers
2449        .iter()
2450        .any(|h| matches!(h.trigger, OnTrigger::Event { .. }));
2451    if !has_event {
2452        warnings.push("protocol has no event handlers (nothing can arrive)".into());
2453    }
2454
2455    // ---- §34: guards reference DECLARED BOOL states ----
2456    let state_ty: BTreeMap<&str, &str> = prog
2457        .states
2458        .iter()
2459        .map(|s| (s.name.as_str(), s.ty.as_deref().unwrap_or("bool")))
2460        .collect();
2461    let mut guard_ok = |g: &Guard, what: &str, src_line: usize, errors: &mut Vec<IdlError>| {
2462        for n in g.names() {
2463            match state_ty.get(n) {
2464                None => errors.push(IdlError {
2465                    line: src_line,
2466                    message: format!("{what} references undeclared state '{n}'"),
2467                }),
2468                Some(t) if *t != "bool" => errors.push(IdlError {
2469                    line: src_line,
2470                    message: format!("{what} requires bool state '{n}', declared '{t}'"),
2471                }),
2472                _ => {}
2473            }
2474        }
2475    };
2476    for h in &prog.handlers {
2477        if let Some(g) = &h.guard {
2478            guard_ok(g, "handler guard", h.line, &mut errors);
2479        }
2480        if let OnTrigger::Timer { guard: Some(g), as_role, .. } = &h.trigger {
2481            guard_ok(g, "timer guard", h.line, &mut errors);
2482            if let Some(r) = as_role {
2483                if !prog.roles.iter().any(|x| x == r) {
2484                    errors.push(IdlError {
2485                        line: h.line,
2486                        message: format!("timer 'as {r}': undeclared role"),
2487                    });
2488                }
2489            }
2490        }
2491        // §43: event-trigger `as <role>` must name a declared role and
2492        // differ from the sender (the executor receives, it does not send)
2493        if let OnTrigger::Event { from: Some(sender), as_role: Some(r), .. } = &h.trigger {
2494            if !prog.roles.iter().any(|x| x == r) {
2495                errors.push(IdlError {
2496                    line: h.line,
2497                    message: format!("trigger 'as {r}': undeclared role"),
2498                });
2499            } else if r == sender {
2500                errors.push(IdlError {
2501                    line: h.line,
2502                    message: format!("trigger 'as {r}': executor cannot be the sender"),
2503                });
2504            }
2505        }
2506        // §41: expression guards are statically validated — undeclared
2507        // states and statically incompatible comparisons are compile errors
2508        let mut check_guard_expr = |e: &Expr, src_line: usize, errors: &mut Vec<IdlError>| {
2509            fn walk(
2510                prog: &ProtocolProgram,
2511                e: &Expr,
2512                src_line: usize,
2513                what: &str,
2514                errors: &mut Vec<IdlError>,
2515            ) {
2516                match e {
2517                    Expr::State(n) => {
2518                        if !prog.state_names().contains(&n.as_str()) {
2519                            errors.push(IdlError {
2520                                line: src_line,
2521                                message: format!("{what} references undeclared state '{n}'"),
2522                            });
2523                        }
2524                    }
2525                    Expr::Bin { op, l, r } => {
2526                        if matches!(
2527                            op,
2528                            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge | BinOp::Eq | BinOp::Ne
2529                        ) {
2530                            let lt = static_ty(l, prog);
2531                            let rt = static_ty(r, prog);
2532                            if let (Some(a), Some(b)) = (&lt, &rt) {
2533                                let compat = a == b
2534                                    || (a == "float" && b == "int")
2535                                    || (a == "int" && b == "float");
2536                                if !compat {
2537                                    errors.push(IdlError {
2538                                        line: src_line,
2539                                        message: format!(
2540                                            "{what}: comparing '{a}' with '{b}'"
2541                                        ),
2542                                    });
2543                                }
2544                            }
2545                        }
2546                        walk(prog, l, src_line, what, errors);
2547                        walk(prog, r, src_line, what, errors);
2548                    }
2549                    Expr::Not(x) => walk(prog, x, src_line, what, errors),
2550                    Expr::Call { args, .. } => {
2551                        for a in args {
2552                            walk(prog, a, src_line, what, errors);
2553                        }
2554                    }
2555                    Expr::Field { base, .. } => walk(prog, base, src_line, what, errors),
2556                    _ => {}
2557                }
2558            }
2559            walk(prog, e, src_line, "expression guard", errors);
2560        };
2561        if let Some(Guard::ExprGuard(e)) = &h.guard {
2562            check_guard_expr(e, h.line, &mut errors);
2563        }
2564        if let OnTrigger::Timer { guard: Some(Guard::ExprGuard(e)), .. } = &h.trigger {
2565            check_guard_expr(e, h.line, &mut errors);
2566        }
2567    }
2568    if let Some(EndWhen::State(sname)) = &prog.end_when {
2569        if let Some(t) = state_ty.get(sname.as_str()) {
2570            if *t != "bool" {
2571                errors.push(IdlError {
2572                    line: 0,
2573                    message: format!("end when requires bool state '{sname}', declared '{t}'"),
2574                });
2575            }
2576        }
2577    }
2578
2579    // ---- §34: n>2 protocols MUST attribute triggers and sends ----
2580    let n_roles = prog.roles.len();
2581    if n_roles > 2 {
2582        for h in &prog.handlers {
2583            if let OnTrigger::Event { from: None, .. } = &h.trigger {
2584                errors.push(IdlError {
2585                    line: h.line,
2586                    message: format!(
2587                        "{n_roles}-role protocol: trigger 'on {}' needs 'from <role>'",
2588                        match &h.trigger {
2589                            OnTrigger::Event { performative, .. } => format!("{performative:?}"),
2590                            _ => unreachable!(),
2591                        }
2592                    ),
2593                });
2594            }
2595            for a in all_actions(&h.actions) {
2596                if let ProtocolAction::Send { performative, to: None, .. } = a {
2597                    if *performative == Performative::Bye {
2598                        continue; // session terminator
2599                    }
2600                    errors.push(IdlError {
2601                        line: h.line,
2602                        message: format!(
2603                            "{n_roles}-role protocol: 'send {}' needs 'to <role>'",
2604                            format!("{performative:?}")
2605                        ),
2606                    });
2607                }
2608            }
2609        }
2610    }
2611
2612    // ---- §34: LINEARITY — every send must have a receiver ----
2613    // receiver role = explicit `to` (else counterpart in 2-role); that
2614    // role's projection must contain a handler `on <perf>` (or breach/
2615    // expired/timer counts for state events). Orphan send = compile error.
2616    let counterpart = |role: &str| -> String {
2617        prog.roles
2618            .iter()
2619            .map(|s| s.as_str())
2620            .find(|r| *r != role)
2621            .unwrap_or("")
2622            .to_string()
2623    };
2624    for h in &prog.handlers {
2625        // executors of this handler emit its sends
2626        for exec in handler_executor(prog, h) {
2627            for a in all_actions(&h.actions) {
2628                let ProtocolAction::Send { performative, to, .. } = a else { continue };
2629                if *performative == Performative::Bye {
2630                    continue; // session terminator: needs no receiver
2631                }
2632                let target = to.clone().unwrap_or_else(|| counterpart(exec));
2633                let send_fields = match a {
2634                    ProtocolAction::Send { fields, .. } => fields.clone(),
2635                    _ => None,
2636                };
2637                let mut answered = false;
2638                let mut payload_mismatch: Option<String> = None;
2639                for h2 in &prog.handlers {
2640                    if !handler_executor(prog, h2).contains(&target.as_str()) {
2641                        continue;
2642                    }
2643                    let OnTrigger::Event { performative: p2, pattern, .. } = &h2.trigger else {
2644                        continue;
2645                    };
2646                    if p2 != performative {
2647                        continue;
2648                    }
2649                    // §48: a receiving handler with a content pattern must
2650                    // be fed the keys it matches — statically verified
2651                    if let (Some(pat), Some(f)) = (pattern, &send_fields) {
2652                        if let Ok(want_map) =
2653                            serde_json::from_str::<BTreeMap<String, String>>(pat)
2654                        {
2655                            for key in want_map.keys() {
2656                                if !f.contains_key(key) {
2657                                    payload_mismatch = Some(format!(
2658                                        "'{exec}' sends {performative:?} to '{target}' without key '{key}' but the receiving handler matches {{{key}: ...}}"
2659                                    ));
2660                                }
2661                            }
2662                        }
2663                    }
2664                    answered = true;
2665                }
2666                if let Some(m) = payload_mismatch {
2667                    warnings.push(m);
2668                }
2669                if !answered {
2670                    errors.push(IdlError {
2671                        line: h.line,
2672                        message: format!(
2673                            "unanswered send: '{exec}' sends {performative:?} to '{target}' but no handler 'on {performative:?}' exists there (§34 linearity)"
2674                        ),
2675                    });
2676                }
2677            }
2678        }
2679    }
2680
2681    // ---- §35/§48: set/push/put/for targets must be declared states
2682    for h in &prog.handlers {
2683        for a in all_actions(&h.actions) {
2684            match a {
2685                ProtocolAction::Set { name, .. } | ProtocolAction::Push { state: name, .. }
2686                | ProtocolAction::Put { state: name, .. } => {
2687                    if !prog.states.iter().any(|st| &st.name == name) {
2688                        errors.push(IdlError {
2689                            line: h.line,
2690                            message: format!("'{name}' is not a declared state (set/push/put)"),
2691                        });
2692                    }
2693                }
2694                ProtocolAction::Await { count, into, flag, within_ms, .. } => {
2695                    let ty_of = |n: &str| {
2696                        prog.states
2697                            .iter()
2698                            .find(|st| st.name == n)
2699                            .and_then(|st| st.ty.clone())
2700                            .unwrap_or_default()
2701                    };
2702                    if !ty_of(into).starts_with("list") {
2703                        errors.push(IdlError {
2704                            line: h.line,
2705                            message: format!("await into '{into}': not a list state"),
2706                        });
2707                    }
2708                    if ty_of(flag) != "bool" {
2709                        errors.push(IdlError {
2710                            line: h.line,
2711                            message: format!("await flag '{flag}': not a declared bool state"),
2712                        });
2713                    }
2714                    if *count < 1 {
2715                        errors.push(IdlError {
2716                            line: h.line,
2717                            message: format!("await count {count} must be >= 1"),
2718                        });
2719                    }
2720                    if *within_ms <= 0 {
2721                        errors.push(IdlError {
2722                            line: h.line,
2723                            message: "await within must be positive".to_string(),
2724                        });
2725                    }
2726                }
2727                ProtocolAction::For { var, over, .. } => {
2728                    if !prog.states.iter().any(|st| &st.name == over) {
2729                        errors.push(IdlError {
2730                            line: h.line,
2731                            message: format!("for over '{over}': not a declared state"),
2732                        });
2733                    }
2734                    if !prog.states.iter().any(|st| &st.name == var) && !var.starts_with('$') {
2735                        warnings.push(format!(
2736                            "for var '{var}' is not a declared state — it is scoped to the loop"
2737                        ));
2738                    }
2739                }
2740                _ => {}
2741            }
2742        }
2743    }
2744
2745    // ---- §38.6: static type checks — assignments & record field access ----
2746    for h in &prog.handlers {
2747        check_action_types(prog, &h.actions, h.line, &mut errors);
2748    }
2749
2750    // ---- §34: LIVENESS — every handler can reach a terminal action ----
2751    // terminal: a handler containing `fulfil`, or one whose send is a
2752    // session-ender (bye/reject/error). Edges: handler -> handlers that
2753    // listen for its sends (in the target role). BFS from each handler.
2754    let is_terminal = |h: &Handler| {
2755        h.actions.iter().any(|a| matches!(a, ProtocolAction::Fulfil))
2756            || h.actions.iter().any(|a| matches!(
2757                a,
2758                ProtocolAction::Send { performative: Performative::Bye | Performative::Reject | Performative::Error, .. }
2759            ))
2760    };
2761    let edges = |from_h: usize| -> Vec<usize> {
2762        let mut out = Vec::new();
2763        for a in &prog.handlers[from_h].actions {
2764            let ProtocolAction::Send { performative, to, .. } = a else { continue };
2765            for (j, h2) in prog.handlers.iter().enumerate() {
2766                if j == from_h {
2767                    continue;
2768                }
2769                let listens = matches!(&h2.trigger, OnTrigger::Event { performative: p2, .. } if p2 == performative);
2770                if !listens {
2771                    continue;
2772                }
2773                // h2's executors must include the send's target role
2774                for exec in handler_executor(prog, h2) {
2775                    let target = to.clone().unwrap_or_else(|| counterpart(exec));
2776                    if handler_executor(prog, &prog.handlers[from_h]).contains(&target.as_str()) {
2777                        out.push(j);
2778                        break;
2779                    }
2780                }
2781            }
2782        }
2783        out.sort();
2784        out.dedup();
2785        out
2786    };
2787    for i in 0..prog.handlers.len() {
2788        let mut seen = std::collections::BTreeSet::new();
2789        let mut stack = vec![i];
2790        let mut reaches_terminal = is_terminal(&prog.handlers[i]);
2791        while let Some(n) = stack.pop() {
2792            for e in edges(n) {
2793                if seen.insert(e) {
2794                    if is_terminal(&prog.handlers[e]) {
2795                        reaches_terminal = true;
2796                    }
2797                    stack.push(e);
2798                }
2799            }
2800        }
2801        if !reaches_terminal {
2802            warnings.push(format!(
2803                "liveness: handler #{i} cannot reach a terminal action (fulfil/bye/reject/error) — possible deadlock"
2804            ));
2805        }
2806    }
2807
2808    if errors.is_empty() { Ok(warnings) } else { Err(errors) }
2809}
2810
2811// ---------------------------------------------------------------- pretty
2812
2813pub fn pretty(prog: &ProtocolProgram) -> String {
2814    let mut out = String::new();
2815    out.push_str(&format!("protocol {} v{};\n", prog.name, prog.version));
2816    out.push_str(&format!("roles {};\n", prog.roles.join(", ")));
2817    for s in &prog.states {
2818        match &s.ty {
2819            Some(t) => out.push_str(&format!("state {}: {};\n", s.name, t)),
2820            None => out.push_str(&format!("state {};\n", s.name)),
2821        }
2822    }
2823    for ph in &prog.phases {
2824        out.push_str(&format!("phase {ph};\n"));
2825    }
2826    for h in &prog.handlers {
2827        let mut trig = match &h.trigger {
2828            OnTrigger::Event { performative, pattern, from, as_role, phase } => {
2829                let mut t = match pattern {
2830                    Some(p) => format!("{}{}", perf_word(performative), p),
2831                    None => perf_word(performative).to_string(),
2832                };
2833                if let Some(ph) = phase {
2834                    t.push_str(&format!(" in {ph}"));
2835                }
2836                if let Some(f) = from {
2837                    t.push_str(&format!(" from {f}"));
2838                }
2839                if let Some(a) = as_role {
2840                    t.push_str(&format!(" as {a}"));
2841                }
2842                t
2843            }
2844            OnTrigger::Breach => "breach".into(),
2845            OnTrigger::Expired => "expired".into(),
2846            OnTrigger::Timer { every_ms, guard, as_role } => {
2847                let mut t = if every_ms % 60_000 == 0 {
2848                    format!("every {}m", every_ms / 60_000)
2849                } else if every_ms % 1000 == 0 {
2850                    format!("every {}s", every_ms / 1000)
2851                } else {
2852                    format!("every {}ms", every_ms)
2853                };
2854                if let Some(g) = guard {
2855                    t.push_str(&format!(" while {}", guard_word(g)));
2856                }
2857                if let Some(r) = as_role {
2858                    t.push_str(&format!(" as {r}"));
2859                }
2860                t
2861            }
2862        };
2863        if let Some(g) = &h.guard {
2864            if !matches!(h.trigger, OnTrigger::Timer { .. }) {
2865                trig.push_str(&format!(" when {}", guard_word(g)));
2866            }
2867        }
2868        if h.actions.len() == 1 {
2869            out.push_str(&format!("on {} -> {};\n", trig, action_word(&h.actions[0])));
2870        } else {
2871            out.push_str(&format!("on {} {{\n", trig));
2872            for a in &h.actions {
2873                out.push_str(&format!("  {};\n", action_word(a)));
2874            }
2875            out.push_str("}\n");
2876        }
2877    }
2878    for (n, t) in &prog.templates {
2879        out.push_str(&format!("message {n} = \"{t}\";\n"));
2880    }
2881    if let Some(t) = &prog.transport {
2882        out.push_str(&format!("transport {t};\n"));
2883    }
2884    if let Some(c) = prog.capacity {
2885        out.push_str(&format!("capacity {c};\n"));
2886    }
2887    for g in &prog.abort_when {
2888        out.push_str(&format!("abort when {};\n", guard_word(g)));
2889    }
2890    for (ty, fields) in &prog.types {
2891        let fs: Vec<String> = fields.iter().map(|(f, t)| format!("{f}: {t}")).collect();
2892        out.push_str(&format!("type {ty} = {{ {} }};\n", fs.join(", ")));
2893    }
2894    for f in &prog.functions {
2895        let params: Vec<String> = f.params.iter().map(|(n, t)| format!("{n}: {t}")).collect();
2896        let ret = f.ret.as_ref().map(|r| format!(" -> {r}")).unwrap_or_default();
2897        out.push_str(&format!("fn {}({}){} {{\n", f.name, params.join(", "), ret));
2898        for a in &f.body {
2899            out.push_str(&format!("  {};\n", action_word(a)));
2900        }
2901        if let Some(e) = &f.returned {
2902            out.push_str(&format!("  return {};\n", expr_word(e)));
2903        }
2904        out.push_str("}\n");
2905    }
2906    for (name, hs) in &prog.handler_sets {
2907        out.push_str(&format!("handler_set {name} {{\n"));
2908        for h in hs {
2909            for l in handler_to_text(h) {
2910                out.push_str(&format!("  {l}\n"));
2911            }
2912        }
2913        out.push_str("}\n");
2914    }
2915    for name in &prog.exported_sets {
2916        out.push_str(&format!("export handler_set {name};\n"));
2917    }
2918    for name in &prog.exported_types {
2919        out.push_str(&format!("export type {name};\n"));
2920    }
2921    for name in &prog.exported_fns {
2922        out.push_str(&format!("export fn {name};\n"));
2923    }
2924    for sc in &prog.scenarios {
2925        out.push_str(&format!("scenario {} {{\n", sc.name));
2926        for st in &sc.steps {
2927            let line = match st {
2928                ScenarioStep::Send { from, performative, pattern, to } => {
2929                    let p = pattern.clone().unwrap_or_default();
2930                    format!("{from} sends {}{p} to {to}", perf_word(performative))
2931                }
2932                ScenarioStep::ExpectSend { from, performative } => {
2933                    format!("expect {from} sends {}", perf_word(performative))
2934                }
2935                ScenarioStep::ExpectState { role, name, value } => {
2936                    if *value {
2937                        format!("expect state {role}.{name}")
2938                    } else {
2939                        format!("expect state {role}.{name} == false")
2940                    }
2941                }
2942                ScenarioStep::ExpectCommitment { role, status } => {
2943                    format!("expect commitment {role} {status}")
2944                }
2945                ScenarioStep::ExpectLog { contains } => {
2946                    format!("expect log \"{contains}\"")
2947                }
2948            };
2949            out.push_str(&format!("  {line};\n"));
2950        }
2951        out.push_str("}\n");
2952    }
2953    if let Some(ew) = &prog.end_when {
2954        match ew {
2955            EndWhen::Builtin(b) => out.push_str(&format!("end when {b};\n")),
2956            EndWhen::State(s) => out.push_str(&format!("end when {s};\n")),
2957        }
2958    }
2959    out
2960}
2961
2962fn perf_word(p: &Performative) -> &'static str {
2963    match p {
2964        Performative::Request => "request",
2965        Performative::Inform => "inform",
2966        Performative::Query => "query",
2967        Performative::Propose => "propose",
2968        Performative::Accept => "accept",
2969        Performative::Reject => "reject",
2970        Performative::Cancel => "cancel",
2971        Performative::Progress => "progress",
2972        Performative::InputRequired => "input_required",
2973        Performative::Failure => "failure",
2974        Performative::Delegate => "delegate",
2975        Performative::Error => "error",
2976        Performative::Hello => "hello",
2977        Performative::Bye => "bye",
2978        Performative::Retract => "retract",
2979        Performative::Subscribe => "subscribe",
2980        Performative::Unsubscribe => "unsubscribe",
2981    }
2982}
2983
2984fn guard_word(g: &Guard) -> String {
2985    match g {
2986        Guard::Atom { name, neg } => {
2987            if *neg { format!("not {name}") } else { name.clone() }
2988        }
2989        Guard::And(a, b) => format!("{} and {}", guard_word(a), guard_word(b)),
2990        Guard::Or(a, b) => format!("{} or {}", guard_word(a), guard_word(b)),
2991        // §38.3: expression guards render back as their expression
2992        Guard::ExprGuard(e) => expr_word(e),
2993    }
2994}
2995
2996fn action_word(a: &ProtocolAction) -> String {
2997    match a {
2998        ProtocolAction::Send { performative, to, fields, .. } => {
2999            // §54: the payload goes BEFORE `to` — that is the order the
3000            // send parser expects (`send X {payload} to R`)
3001            let payload = fields
3002                .as_ref()
3003                .map(|f| format!(" {}", serde_json::to_string(f).unwrap_or_default()))
3004                .unwrap_or_default();
3005            match to {
3006                Some(r) => format!("send {}{} to {}", perf_word(performative), payload, r),
3007                None => format!("send {}{}", perf_word(performative), payload),
3008            }
3009        }
3010        ProtocolAction::Begin => "begin".into(),
3011        ProtocolAction::Fulfil => "fulfil".into(),
3012        ProtocolAction::BeginId { id } => format!("begin {id}"),
3013        ProtocolAction::FulfilId { id } => format!("fulfil {id}"),
3014        ProtocolAction::Retract { target } => format!("retract({target})"),
3015        ProtocolAction::Set { name, field, expr } => format!(
3016            "set {}{} = {}",
3017            name,
3018            match field { Some(f) => format!(".{f}"), None => String::new() },
3019            expr_word(expr),
3020        ),
3021        ProtocolAction::Push { state, expr } => format!("push {}, {}", state, expr_word(expr)),
3022        ProtocolAction::Put { state, key, expr } => format!("put {}, {}, {}", state, key, expr_word(expr)),
3023        ProtocolAction::Broadcast { performative, fields, to } => format!(
3024            "broadcast {}{} to {}",
3025            perf_word(performative),
3026            fields.as_ref().map(|f| format!(" {}", serde_json::to_string(f).unwrap_or_default())).unwrap_or_default(),
3027            to
3028        ),
3029        ProtocolAction::Await { count, performative, into, within_ms, flag } => format!(
3030            "await {} {} into {} within {}ms as {}",
3031            count,
3032            perf_word(performative),
3033            into,
3034            within_ms,
3035            flag
3036        ),
3037        ProtocolAction::Enter { phase } => format!("enter {phase}"),
3038        ProtocolAction::Try { body, catch } => format!(
3039            "try {{ {} }} catch {{ {} }}",
3040            body.iter().map(action_word).collect::<Vec<_>>().join("; "),
3041            catch.iter().map(action_word).collect::<Vec<_>>().join("; ")
3042        ),
3043        ProtocolAction::For { var, over, actions } => {
3044            let inner: Vec<String> = actions.iter().map(|a| action_word(a)).collect();
3045            format!("for {} in {} {{ {} }}", var, over, inner.join("; "))
3046        }
3047        ProtocolAction::Abort => "abort".into(),
3048        ProtocolAction::Return { expr } => format!("return {}", expr_word(expr)),
3049    }
3050}
3051
3052fn expr_word(e: &Expr) -> String {
3053    match e {
3054        Expr::LitInt(i) => i.to_string(),
3055        Expr::LitStr(s) => format!("\"{s}\""),
3056        Expr::LitBool(b) => b.to_string(),
3057        Expr::State(n) => n.clone(),
3058        Expr::Capture(n) => format!("${n}"),
3059        Expr::Arg(a) => format!("arg.{a}"),
3060        Expr::Bin { op, l, r } => {
3061            let o = match op {
3062                BinOp::Add => "+", BinOp::Sub => "-", BinOp::Mul => "*", BinOp::Div => "/",
3063                BinOp::Lt => "<", BinOp::Le => "<=", BinOp::Gt => ">", BinOp::Ge => ">=",
3064                BinOp::Eq => "==", BinOp::Ne => "!=", BinOp::And => "and", BinOp::Or => "or",
3065            };
3066            format!("{} {} {}", expr_word(l), o, expr_word(r))
3067        }
3068        Expr::Not(x) => format!("not {}", expr_word(x)),
3069        Expr::Call { name, args } => {
3070            let a: Vec<String> = args.iter().map(expr_word).collect();
3071            format!("{}({})", name, a.join(", "))
3072        }
3073        Expr::Field { base, name } => format!("{}.{}", expr_word(base), name),
3074        Expr::RecLit { ty, fields } => {
3075            let f: Vec<String> = fields.iter().map(|(n, e)| format!("{}: {}", n, expr_word(e))).collect();
3076            format!("{} {{ {} }}", ty, f.join(", "))
3077        }
3078    }
3079}
3080
3081// ---------------------------------------------------------------- tests
3082
3083#[cfg(test)]
3084mod tests {
3085    use super::*;
3086
3087    const GOOD: &str = r#"
3088// supply-check protocol program — fully linear (§34): every send has a receiver
3089protocol supply_check v1;
3090roles buyer, seller;
3091state quoted: bool;
3092state paid: bool;
3093
3094// seller side
3095on request("quote") from buyer -> send propose to buyer;
3096on accept from buyer -> begin;
3097on query("status") from buyer -> send inform to buyer;
3098on breach -> send failure to buyer;
3099on expired -> send error to buyer;
3100// buyer side
3101on propose from seller -> send accept to seller;
3102on inform from seller -> send bye;
3103on failure from seller -> send bye;
3104on error from seller -> send bye;
3105
3106end when fulfilled;
3107"#;
3108
3109    #[test]
3110    fn parses_and_checks_good_program() {
3111        let p = parse(GOOD).expect("parse");
3112        assert_eq!(p.name, "supply_check");
3113        assert_eq!(p.version, 1);
3114        assert_eq!(p.roles, vec!["buyer", "seller"]);
3115        assert_eq!(p.states.len(), 2);
3116        assert_eq!(p.handlers.len(), 9); // 5 seller + 4 buyer
3117        // §16 at compile time: every send is dialogue-legal for its trigger
3118        check(&p).expect("check");
3119        // pretty roundtrip
3120        let reparsed = parse(&pretty(&p)).expect("reparse pretty");
3121        assert_eq!(reparsed, p);
3122    }
3123
3124    #[test]
3125    fn dialogue_violation_does_not_compile() {
3126        // answering a query with a request is illegal per §16
3127        let src = r#"
3128protocol bad v1;
3129roles a, b;
3130on query -> send request;
3131on request -> send bye;
3132"#;
3133        let p = parse(src).expect("parse");
3134        let errs = check(&p).expect_err("must fail");
3135        assert!(errs.iter().any(|e| e.message.contains("dialogue violation")));
3136        assert!(errs[0].message.contains("§16"));
3137    }
3138
3139    #[test]
3140    fn breach_handlers_constrained_by_plausible_predecessors() {
3141        // failure after breach is fine (legal after request)
3142        let ok = parse("protocol p v1;\nroles a,b;\non breach -> send failure;\non failure -> send bye;\n").unwrap();
3143        check(&ok).expect("failure legal after breach");
3144        // hello after breach is NOT legal after request/propose/delegate
3145        let bad = parse("protocol p v1;\nroles a,b;\non breach -> send hello;\non hello -> send bye;\n").unwrap();
3146        assert!(check(&bad).is_err());
3147    }
3148
3149    #[test]
3150    fn duplicate_handlers_rejected() {
3151        let src = r#"
3152protocol p v1;
3153roles a, b;
3154on query -> send inform;
3155on query -> send inform;
3156on inform -> send bye;
3157"#;
3158        let p = parse(src).unwrap();
3159        let errs = check(&p).expect_err("duplicate");
3160        assert!(errs.iter().any(|e| e.message.contains("duplicate handler")));
3161    }
3162
3163    #[test]
3164    fn end_when_requires_declared_state() {
3165        let src = r#"
3166protocol p v1;
3167roles a, b;
3168state done: bool;
3169on query -> send inform;
3170on inform -> begin;
3171end when nowhere;
3172"#;
3173        let p = parse(src).unwrap();
3174        let errs = check(&p).expect_err("bad end_when");
3175        assert!(errs.iter().any(|e| e.message.contains("undeclared state 'nowhere'")));
3176    }
3177
3178    #[test]
3179    fn multi_action_handler_and_retract_statement() {
3180        let src = r#"
3181protocol p v1;
3182roles a, b;
3183state announced: bool;
3184on request("job") {
3185  send propose;
3186  retract(announced);
3187}
3188on propose -> send bye;
3189"#;
3190        let p = parse(src).unwrap();
3191        assert_eq!(p.handlers[0].actions.len(), 2);
3192        assert_eq!(
3193            p.handlers[0].actions[1],
3194            ProtocolAction::Retract { target: "announced".into() }
3195        );
3196        check(&p).expect("check");
3197    }
3198
3199    #[test]
3200    fn guards_parse_and_validate() {
3201        let src = r#"
3202protocol p v1;
3203roles a, b;
3204state quoted: bool;
3205state paid: bool;
3206on accept from b when quoted -> begin;
3207on accept from b when not quoted -> send error to b;
3208on request from b when quoted and not paid -> send propose to b;
3209on error from a -> send bye;
3210on propose from a -> send bye;
3211"#;
3212        let p = parse(src).expect("parse");
3213        // guard AST shape
3214        match &p.handlers[2].guard {
3215            Some(Guard::And(l, r)) => {
3216                assert!(matches!(**l, Guard::Atom { ref name, neg: false } if name == "quoted"));
3217                assert!(matches!(**r, Guard::Atom { ref name, neg: true } if name == "paid"));
3218            }
3219            other => panic!("expected And guard, got {other:?}"),
3220        }
3221        check(&p).expect("guards reference declared bool states");
3222    }
3223
3224    #[test]
3225    fn guards_reject_undeclared_and_non_bool_states() {
3226        // undeclared state in guard
3227        let bad = parse("protocol p v1;\nroles a,b;\non accept from b when nowhere -> begin;\non error from b -> send bye;\n").unwrap();
3228        let errs = check(&bad).unwrap_err();
3229        assert!(errs.iter().any(|e| e.message.contains("undeclared state 'nowhere'")));
3230        // non-bool state in guard
3231        let bad2 = parse("protocol p v1;\nroles a,b;\nstate n: int;\non accept from b when n -> begin;\non error from b -> send bye;\n").unwrap();
3232        let errs2 = check(&bad2).unwrap_err();
3233        assert!(errs2.iter().any(|e| e.message.contains("requires bool state 'n'")));
3234    }
3235
3236    #[test]
3237    fn end_when_requires_bool_state() {
3238        let bad = parse("protocol p v1;\nroles a,b;\nstate n: int;\non query from a -> send inform to a;\non inform -> send bye;\nend when n;\n").unwrap();
3239        let errs = check(&bad).unwrap_err();
3240        assert!(errs.iter().any(|e| e.message.contains("end when requires bool state 'n'")));
3241    }
3242
3243    #[test]
3244    fn content_patterns_in_handlers() {
3245        let src = r#"
3246protocol p v1;
3247roles a, b;
3248on request {"task": "deploy*"} from b -> send propose to b;
3249on propose from a -> send bye;
3250"#;
3251        let p = parse(src).expect("content pattern parses");
3252        assert!(p.handlers[0].pattern_is_json(), "brace pattern detected");
3253        check(&p).expect("linear");
3254    }
3255
3256    #[test]
3257    fn timers_parse() {
3258        let src = r#"
3259protocol p v1;
3260roles a, b;
3261state active: bool;
3262every 60s while active as a -> send progress to b;
3263on progress from a -> send bye;
3264"#;
3265        let p = parse(src).expect("timer parses");
3266        match &p.handlers[0].trigger {
3267            OnTrigger::Timer { every_ms, guard, as_role } => {
3268                assert_eq!(*every_ms, 60_000);
3269                assert!(guard.is_some());
3270                assert_eq!(as_role.as_deref(), Some("a"));
3271            }
3272            other => panic!("expected timer, got {other:?}"),
3273        }
3274        check(&p).expect("timer program is linear");
3275    }
3276
3277    #[test]
3278    fn timer_needs_bool_guard_state() {
3279        let bad = parse("protocol p v1;\nroles a,b;\nstate n: int;\nevery 5s while n -> send progress to b;\non progress from b -> send bye;\n").unwrap();
3280        let errs = check(&bad).unwrap_err();
3281        assert!(errs.iter().any(|e| e.message.contains("timer guard requires bool state 'n'")));
3282    }
3283
3284    #[test]
3285    fn orphan_send_is_compile_error() {
3286        let src = "protocol p v1;\nroles a, b;\non query from a -> send inform to a;\n";
3287        let p = parse(src).unwrap();
3288        let errs = check(&p).unwrap_err();
3289        assert!(
3290            errs.iter().any(|e| e.message.contains("unanswered send")),
3291            "linearity must catch orphan sends, got {errs:?}"
3292        );
3293        // adding the receiver fixes it
3294        let fixed = "protocol p v1;\nroles a, b;\non query -> send inform to a;\non inform from b -> send bye;\n";
3295        let p2 = parse(fixed).unwrap();
3296        check(&p2).expect("answered send compiles");
3297    }
3298
3299    #[test]
3300    fn n_role_requires_full_attribution() {
3301        let three = "protocol t v1;\nroles a, b, c;\non query -> send inform to a;\non inform from b -> send bye;\n";
3302        let p = parse(three).unwrap();
3303        let errs = check(&p).unwrap_err();
3304        assert!(errs.iter().any(|e| e.message.contains("3-role protocol")));
3305        // fully attributed 3-role program passes the n>2 rule
3306        let ok = "protocol t v1;\nroles a, b, c;\non query from a -> send inform to b;\non inform from c -> send bye;\n";
3307        let p2 = parse(ok).unwrap();
3308        check(&p2).expect("attributed n-role compiles (n>2 projection still phase-limited)");
3309    }
3310
3311    #[test]
3312    fn liveness_warns_on_unreachable_terminal() {
3313        // request -> propose -> ??? : propose handler does only begin (no
3314        // outgoing send) — the chain cannot reach fulfil/bye/reject/error
3315        let src = "protocol p v1;\nroles a, b;\non query -> send inform to a;\non inform from b -> send bye;\non request from a -> send propose to a;\non propose from b -> begin;\n";
3316        let p = parse(src).unwrap();
3317        let warnings = check(&p).expect("compiles (warnings only)");
3318        assert!(
3319            warnings.iter().any(|w| w.contains("liveness")),
3320            "deadlock should be warned, got {warnings:?}"
3321        );
3322    }
3323
3324    #[test]
3325    fn computation_statements_parse_and_check() {
3326        let src = r#"
3327protocol p v1;
3328roles a, b;
3329state total: int;
3330state bids: list;
3331state idx: int;
3332on request from b {
3333  set total = total + 1;
3334  push bids, arg.price;
3335  put idx, "last", total;
3336  for x in bids { set total = total + len(bids); }
3337}
3338on inform from b -> send bye;
3339"#;
3340        let p = parse(src).expect("computation statements parse");
3341        check(&p).expect("targets declared");
3342    }
3343
3344    #[test]
3345    fn set_undeclared_state_is_error() {
3346        let bad = parse("protocol p v1;\nroles a,b;\non query from a { set nope = 1; }\non inform from b -> send bye;\n").unwrap();
3347        let errs = check(&bad).unwrap_err();
3348        assert!(errs.iter().any(|e| e.message.contains("'nope' is not a declared state")));
3349    }
3350
3351    #[test]
3352    fn retry_clause_parses() {
3353        let src = "protocol p v1;\nroles a, b;\non query from a -> send inform to a retry 3 backoff 2s exp;\non inform from b -> send bye;\n";
3354        let p = parse(src).unwrap();
3355        match &p.handlers[0].actions[0] {
3356            ProtocolAction::Send { retry: Some(r), .. } => {
3357                assert_eq!(r.attempts, 3);
3358                assert_eq!(r.backoff_ms, 2000);
3359                assert!(r.exponential);
3360            }
3361            other => panic!("expected retry, got {other:?}"),
3362        }
3363    }
3364
3365    #[test]
3366    fn capabilities_transport_capacity_parse() {
3367        let src = r#"
3368protocol p v1;
3369roles a, b;
3370use fs.read as reader;
3371use net.http;
3372transport relay;
3373capacity 5;
3374on query from a -> send inform to a;
3375on inform from b -> send bye;
3376"#;
3377        let p = parse(src).unwrap();
3378        assert_eq!(p.capabilities.len(), 2);
3379        assert_eq!(p.capabilities[0].alias.as_deref(), Some("reader"));
3380        assert_eq!(p.transport.as_deref(), Some("relay"));
3381        assert_eq!(p.capacity, Some(5));
3382        check(&p).expect("ok");
3383        // unknown transport
3384        assert!(parse("protocol p v1;\nroles a,b;\ntransport carrier_pigeon;\non query from a -> send inform to a;\non inform from b -> send bye;\n").is_err());
3385        assert!(parse("protocol p v1;\nroles a,b;\ntransport pigeon;\non query from a -> send inform to a;\non inform from b -> send bye;\n").is_err());
3386    }
3387
3388    #[test]
3389    fn abort_when_and_abort_statement_parse() {
3390        let src = r#"
3391protocol p v1;
3392roles a, b;
3393state quoted: bool;
3394state paid: bool;
3395abort when quoted and not paid;
3396on request from b -> send propose to b;
3397on accept from b {
3398  abort;
3399}
3400on propose from a -> send bye;
3401"#;
3402        let p = parse(src).unwrap();
3403        assert_eq!(p.abort_when.len(), 1);
3404        assert!(p.handlers.iter().any(|h| h.actions.iter().any(|a| matches!(a, ProtocolAction::Abort))));
3405        check(&p).expect("ok");
3406    }
3407
3408    #[test]
3409    fn scenarios_parse() {
3410        let src = r#"
3411protocol p v1;
3412roles a, b;
3413on query from a -> send inform to a;
3414on inform from b -> send bye;
3415
3416scenario "q&a" {
3417  a sends query to b;
3418  expect b sends inform;
3419  expect a sends bye;
3420}
3421"#;
3422        let p = parse(src).unwrap();
3423        assert_eq!(p.scenarios.len(), 1);
3424        assert_eq!(p.scenarios[0].name, "q&a");
3425        assert_eq!(p.scenarios[0].steps.len(), 3);
3426    }
3427
3428    #[test]
3429    fn message_templates_parse() {
3430        let src = "protocol p v1;\nroles a,b;\nmessage invoice = \"INVOICE {0} for {1}\";\non query from a -> send inform to a;\non inform from b -> send bye;\n";
3431        let p = parse(src).unwrap();
3432        assert_eq!(p.templates, vec![("invoice".into(), "INVOICE {0} for {1}".into())]);
3433    }
3434
3435    #[test]
3436    fn unterminated_block_and_missing_protocol() {
3437        assert!(parse("on query -> send inform;").is_err());
3438        assert!(parse("protocol p v1;\nroles a;\non query {").is_err());
3439        let e = parse("roles a;").unwrap_err();
3440        assert!(e.iter().any(|x| x.message.contains("missing 'protocol")));
3441    }
3442}
3443
3444/// expand an include: load `path` (relative to `base_dir`), rename roles
3445/// per mapping (whole-word), return its text.
3446fn expand_include(path: &str, mapping: &[(String, String)], base_dir: Option<&str>) -> Result<String, String> {
3447    let full = match base_dir {
3448        Some(d) => format!("{d}/{path}"),
3449        None => path.to_string(),
3450    };
3451    let text = std::fs::read_to_string(&full)
3452        .map_err(|e| format!("include '{path}': {e}"))?;
3453    let mut out = text;
3454    for (from, to) in mapping {
3455        // whole-word rename
3456        let pattern = format!(r"\b{}\b", regex_escape(from));
3457        out = regex_replace(&out, &pattern, to);
3458    }
3459    Ok(out)
3460}
3461
3462/// §38.10: load a module file, keep only its exported handler sets,
3463/// re-emit them as namespaced `handler_set` blocks in the importing file.
3464fn import_module(
3465    path: &str,
3466    ns: Option<&str>,
3467    base_dir: Option<&str>,
3468    depth: usize,
3469) -> Result<Vec<String>, String> {
3470    if depth > 8 {
3471        return Err(format!("import '{path}': module nesting too deep (cycle?)"));
3472    }
3473    let full = match base_dir {
3474        Some(d) => format!("{d}/{path}"),
3475        None => path.to_string(),
3476    };
3477    let text = std::fs::read_to_string(&full)
3478        .map_err(|e| format!("import '{path}': {e}"))?;
3479    let dir = std::path::Path::new(&full)
3480        .parent()
3481        .map(|p| p.to_string_lossy().to_string());
3482    let mod_prog = parse_with_includes_depth(&text, dir.as_deref(), depth + 1)
3483        .map_err(|es| {
3484            format!(
3485                "import '{path}': {}",
3486                es.iter().map(|e| e.message.clone()).collect::<Vec<_>>().join("; ")
3487            )
3488        })?;
3489    let mut out = Vec::new();
3490    // §42: exported types and functions splice under their OWN names —
3491    // they are referenced from expressions and state decls, where a
3492    // namespace prefix would not parse. Collisions are compile errors
3493    // (duplicate type/function detection in the importing file).
3494    for name in &mod_prog.exported_types {
3495        if let Some(fields) = mod_prog.types.get(name) {
3496            let fs: Vec<String> = fields
3497                .iter()
3498                .map(|(f, t)| format!("{f}: {t}"))
3499                .collect();
3500            out.push(format!("type {name} = {{ {} }};", fs.join(", ")));
3501        }
3502    }
3503    for name in &mod_prog.exported_fns {
3504        if let Some(f) = mod_prog.functions.iter().find(|f| &f.name == name) {
3505            let params: Vec<String> = f
3506                .params
3507                .iter()
3508                .map(|(n, t)| format!("{n}: {t}"))
3509                .collect();
3510            let ret = f.ret.as_ref().map(|r| format!(" -> {r}")).unwrap_or_default();
3511            let mut body = String::new();
3512            for a in &f.body {
3513                body.push_str(&format!(" {};", action_word(a)));
3514            }
3515            if let Some(e) = &f.returned {
3516                body.push_str(&format!(" return {};", expr_word(e)));
3517            }
3518            out.push(format!("fn {}({}){} {{", f.name, params.join(", "), ret));
3519            for a in &f.body {
3520                out.push(format!("  {};", action_word(a)));
3521            }
3522            if let Some(e) = &f.returned {
3523                out.push(format!("  return {};", expr_word(e)));
3524            }
3525            out.push("}".into());
3526        }
3527    }
3528    for name in &mod_prog.exported_sets {
3529        let Some(hs) = mod_prog.handler_sets.get(name) else { continue };
3530        let full_name = match ns {
3531            Some(n) => format!("{n}.{name}"),
3532            None => name.clone(),
3533        };
3534        out.push(format!("handler_set {full_name} {{"));
3535        for h in hs {
3536            for l in handler_to_text(h) {
3537                out.push(format!("  {l}"));
3538            }
3539        }
3540        out.push("}".into());
3541    }
3542    Ok(out)
3543}
3544
3545/// §38.10: render a handler back to source lines (used by module import;
3546/// captures/patterns round-trip through the same grammar).
3547fn handler_to_text(h: &Handler) -> Vec<String> {
3548    let mut head = match &h.trigger {
3549        OnTrigger::Event { performative, pattern, from, as_role, phase } => {
3550            let mut t = perf_word(performative).to_string();
3551            if let Some(p) = pattern {
3552                t.push(' ');
3553                t.push_str(p);
3554            }
3555            if let Some(ph) = phase {
3556                t.push_str(&format!(" in {ph}"));
3557            }
3558            if let Some(f) = from {
3559                t.push_str(&format!(" from {f}"));
3560            }
3561            if let Some(a) = as_role {
3562                t.push_str(&format!(" as {a}"));
3563            }
3564            t
3565        }
3566        OnTrigger::Breach => "breach".into(),
3567        OnTrigger::Expired => "expired".into(),
3568        OnTrigger::Timer { every_ms, guard, as_role } => {
3569            let mut t = if every_ms % 1000 == 0 {
3570                format!("every {}s", every_ms / 1000)
3571            } else {
3572                format!("every {}ms", every_ms)
3573            };
3574            if let Some(g) = guard {
3575                t.push_str(&format!(" while {}", guard_word(g)));
3576            }
3577            if let Some(r) = as_role {
3578                t.push_str(&format!(" as {r}"));
3579            }
3580            t
3581        }
3582    };
3583    if let Some(g) = &h.guard {
3584        head.push_str(&format!(" when {}", guard_word(g)));
3585    }
3586    if h.actions.len() == 1 {
3587        vec![format!("on {} -> {};", head, action_word(&h.actions[0]))]
3588    } else {
3589        let mut out = vec![format!("on {} {{", head)];
3590        for a in &h.actions {
3591            out.push(format!("  {};", action_word(a)));
3592        }
3593        out.push("}".into());
3594        out
3595    }
3596}
3597
3598fn regex_escape(s: &str) -> String {
3599    s.chars().map(|c| if c.is_alphanumeric() || c == '_' { c.to_string() } else { format!("\\{c}") }).collect()
3600}
3601
3602fn regex_replace(text: &str, pattern: &str, replacement: &str) -> String {
3603    // minimal whole-word replacer: split on non-word chars, rebuild
3604    let word = pattern.trim_start_matches(r"\b").trim_end_matches(r"\b");
3605    let mut out = String::new();
3606    let mut cur = String::new();
3607    for c in text.chars() {
3608        if c.is_alphanumeric() || c == '_' {
3609            cur.push(c);
3610        } else {
3611            out.push_str(if cur == word { replacement } else { &cur });
3612            out.push(c);
3613            cur.clear();
3614        }
3615    }
3616    out.push_str(if cur == word { replacement } else { &cur });
3617    out
3618}
3619
3620#[cfg(test)]
3621mod alternation_tests {
3622    use super::*;
3623
3624    // §38.4: alternation expands to one handler per alternative
3625    #[test]
3626    fn alternation_expands_handlers() {
3627        let prog = parse(
3628            "protocol p v1;\nroles a, b;\non (accept | reject) from a -> send inform to a;\non inform from b -> send bye;\n",
3629        )
3630        .unwrap();
3631        let alts: Vec<_> = prog
3632            .handlers
3633            .iter()
3634            .filter(|h| match &h.trigger {
3635                OnTrigger::Event { performative, from, .. } => {
3636                    *from == Some("a".to_string())
3637                        && matches!(performative, Performative::Accept | Performative::Reject)
3638                }
3639                _ => false,
3640            })
3641            .collect();
3642        assert_eq!(alts.len(), 2);
3643        // both handlers share the same action
3644        assert_eq!(alts[0].actions, alts[1].actions);
3645        assert!(check(&prog).is_ok());
3646    }
3647
3648    #[test]
3649    fn alternation_with_guard_expands_guard() {
3650        let prog = parse(
3651            "protocol p v1;\nroles a, b;\non (inform | query) from a when quoted -> send inform to a;\n",
3652        )
3653        .unwrap();
3654        assert_eq!(prog.handlers.len(), 2);
3655        assert!(prog.handlers[0].guard.is_some());
3656        assert_eq!(prog.handlers[0].guard, prog.handlers[1].guard);
3657    }
3658
3659    #[test]
3660    fn literal_paren_pattern_not_alternation() {
3661        // `("quote")` is a literal pattern, not an alternation (single alt)
3662        let prog = parse(
3663            "protocol p v1;\nroles a, b;\non request (\"quote\") from a -> send inform to a;\n",
3664        )
3665        .unwrap();
3666        assert_eq!(prog.handlers.len(), 1);
3667    }
3668
3669    #[test]
3670    fn alternation_block_form_rejected() {
3671        let errs = parse(
3672            "protocol p v1;\nroles a, b;\non (accept | reject) from a {\n  begin;\n}\n",
3673        )
3674        .unwrap_err();
3675        assert!(errs.iter().any(|e| e.message.contains("alternation")));
3676    }
3677}
3678
3679#[cfg(test)]
3680mod handler_set_tests {
3681    use super::*;
3682
3683    // §38.5: handler_set fragments splice into a protocol via include
3684    #[test]
3685    fn handler_set_splices_handlers() {
3686        let prog = parse(
3687            "handler_set common_failure {\non breach -> send failure to buyer;\non expired -> send error to buyer;\n}\nprotocol p v1;\nroles buyer, seller;\non request(\"quote\") from buyer -> send propose to buyer;\non propose from seller -> send accept to seller;\non accept from buyer -> begin;\non accept from seller -> send bye;\ninclude handler_set common_failure;\non failure from seller -> send bye;\non error from seller -> send bye;\n",
3688        )
3689        .unwrap();
3690        assert!(prog.handler_sets.contains_key("common_failure"));
3691        assert_eq!(prog.handler_sets["common_failure"].len(), 2);
3692        // 6 own handlers + 2 spliced
3693        assert_eq!(prog.handlers.len(), 8);
3694        assert!(check(&prog).is_ok());
3695    }
3696
3697    #[test]
3698    fn handler_set_unknown_include_errors() {
3699        let errs = parse(
3700            "protocol p v1;\nroles a, b;\non inform from a -> send inform to b;\non inform from b -> send bye;\ninclude handler_set nosuch;\n",
3701        )
3702        .unwrap_err();
3703        assert!(errs.iter().any(|e| e.message.contains("unknown handler set")));
3704    }
3705
3706    #[test]
3707    fn handler_set_roles_checked_at_include() {
3708        // the fragment references role 'ghost' which the including
3709        // protocol does not declare — check() must catch it
3710        let prog = parse(
3711            "handler_set bad {\non breach -> send failure to ghost;\n}\nprotocol p v1;\nroles a, b;\non inform from a -> send inform to b;\non inform from b -> send bye;\ninclude handler_set bad;\non breach -> send bye;\n",
3712        )
3713        .unwrap();
3714        assert!(check(&prog).is_err());
3715    }
3716
3717    #[test]
3718    fn handler_set_inline_form() {
3719        let prog = parse(
3720            "handler_set tiny { on breach -> send failure to a; }\nprotocol p v1;\nroles a, b;\non inform from a -> send inform to b;\non inform from b -> send bye;\non breach -> send bye;\ninclude handler_set tiny;\n",
3721        )
3722        .unwrap();
3723        assert_eq!(prog.handler_sets["tiny"].len(), 1);
3724        assert_eq!(prog.handlers.len(), 4);
3725    }
3726}
3727
3728#[cfg(test)]
3729mod static_type_tests {
3730    use super::*;
3731
3732    fn check_errs(src: &str) -> Vec<String> {
3733        let prog = parse(src).unwrap();
3734        check(&prog)
3735            .unwrap_err()
3736            .into_iter()
3737            .map(|e| e.message)
3738            .collect()
3739    }
3740
3741    #[test]
3742    fn set_type_mismatch_caught() {
3743        let errs = check_errs(
3744            "protocol p v1;\nroles a, b;\nstate total: int;\nstate flag: bool;\non inform from a { set total = 1 + 2; set flag = 3; set total = \"x\"; send bye; }\n",
3745        );
3746        assert!(errs.iter().any(|m| m.contains("state 'flag' is 'bool'")), "{errs:?}");
3747        assert!(errs.iter().any(|m| m.contains("state 'total' is 'int'") && m.contains("'str'")), "{errs:?}");
3748        // 1 + 2 → int → total:int OK — no error for it
3749        assert!(!errs.iter().any(|m| m.contains("'total' is 'int' but expression is 'int'")), "{errs:?}");
3750    }
3751
3752    #[test]
3753    fn arg_and_capture_stay_dynamic() {
3754        // arg.* and $captures are statically unknown — must NOT error
3755        let prog = parse(
3756            "protocol p v1;\nroles a, b;\nstate total: int;\non inform {\"amount\": $v} from a { set total = $v; send bye; }\n",
3757        )
3758        .unwrap();
3759        assert!(check(&prog).is_ok());
3760    }
3761
3762    #[test]
3763    fn record_field_access_checked() {
3764        let errs = check_errs(
3765            "type Quote = { price: int, currency: str };\nprotocol p v1;\nroles a, b;\nstate q: Quote;\nstate bad: int;\non inform from a { set q.wrong = 5; set bad = q.price + 1; set bad = q.price.nope; send bye; }\n",
3766        );
3767        assert!(errs.iter().any(|m| m.contains("'Quote' has no field 'wrong'")), "{errs:?}");
3768        assert!(!errs.iter().any(|m| m.contains("q.price + 1") || (m.contains("no field 'price'"))), "{errs:?}");
3769        assert!(errs.iter().any(|m| m.contains("no field 'nope'")), "{errs:?}");
3770    }
3771
3772    #[test]
3773    fn field_on_scalar_rejected() {
3774        let errs = check_errs(
3775            "protocol p v1;\nroles a, b;\nstate total: int;\non inform from a { set total = total.price; send bye; }\n",
3776        );
3777        assert!(errs.iter().any(|m| m.contains("not a record")), "{errs:?}");
3778    }
3779
3780    #[test]
3781    fn int_widens_to_float() {
3782        let prog = parse(
3783            "protocol p v1;\nroles a, b;\nstate r: float;\non inform from a { set r = 1 + 2; send bye; }\n",
3784        )
3785        .unwrap();
3786        assert!(check(&prog).is_ok());
3787    }
3788
3789    #[test]
3790    fn bool_expr_types_check() {
3791        let prog = parse(
3792            "protocol p v1;\nroles a, b;\nstate flag: bool;\non inform from a { set flag = 1 < 2 and not (3 == 4); send bye; }\n",
3793        )
3794        .unwrap();
3795        assert!(check(&prog).is_ok());
3796    }
3797}
3798
3799#[cfg(test)]
3800mod module_tests {
3801    use super::*;
3802
3803    fn tmpfile(tag: &str, content: &str) -> String {
3804        let p = std::env::temp_dir().join(format!("acl_mod_test_{tag}.aclp"));
3805        std::fs::write(&p, content).unwrap();
3806        p.to_string_lossy().to_string()
3807    }
3808
3809    // §38.10: only exported sets are importable, namespaced by alias
3810    #[test]
3811    fn import_namespaces_exported_sets_only() {
3812        let mod_path = tmpfile(
3813            "mod1",
3814            "handler_set pub_replies {\non breach -> send failure to buyer;\n}\nhandler_set secret {\non expired -> send error to buyer;\n}\nexport handler_set pub_replies;\nprotocol unused v1;\nroles x, y;\n",
3815        );
3816        let main = format!(
3817            "import \"{mod_path}\" as m;\nprotocol p v1;\nroles buyer, seller;\non request(\"quote\") from buyer -> send propose to buyer;\non propose from seller -> send accept to seller;\non accept from buyer -> begin;\ninclude handler_set m.pub_replies;\non failure from seller -> send bye;\non error from seller -> send bye;\n"
3818        );
3819        let prog = parse_with_includes(&main, None).unwrap();
3820        assert!(prog.handler_sets.contains_key("m.pub_replies"), "{:?}", prog.handler_sets.keys());
3821        // private set NOT imported, and un-namespaced name NOT present
3822        assert!(!prog.handler_sets.contains_key("m.secret"));
3823        assert!(!prog.handler_sets.contains_key("pub_replies"));
3824        assert_eq!(prog.handlers.len(), 6); // 5 own + 1 spliced from pub_replies
3825        assert!(check(&prog).is_ok());
3826    }
3827
3828    #[test]
3829    fn import_without_alias_collides_loudly() {
3830        let m1 = tmpfile("mod2", "handler_set shared {\non breach -> send failure to a;\n}\nexport handler_set shared;\nprotocol u1 v1;\nroles a, b;\n");
3831        let m2 = tmpfile("mod3", "handler_set shared {\non breach -> send error to a;\n}\nexport handler_set shared;\nprotocol u2 v1;\nroles a, b;\n");
3832        let main = format!(
3833            "import \"{m1}\";\nimport \"{m2}\";\nprotocol p v1;\nroles a, b;\non inform from a -> send inform to b;\non inform from b -> send bye;\non breach -> send bye;\non error -> send bye;\n"
3834        );
3835        let errs = parse_with_includes(&main, None).unwrap_err();
3836        assert!(errs.iter().any(|e| e.message.contains("duplicate handler_set")), "{errs:?}");
3837    }
3838
3839    #[test]
3840    fn export_of_unknown_set_is_error() {
3841        let errs = parse(
3842            "protocol p v1;\nroles a, b;\nexport handler_set ghost;\non inform from a -> send inform to b;\non inform from b -> send bye;\n",
3843        )
3844        .unwrap_err();
3845        assert!(errs.iter().any(|e| e.message.contains("no such handler set")));
3846    }
3847}
3848
3849#[cfg(test)]
3850mod static_validation_tests {
3851    use super::*;
3852
3853    fn errs(src: &str) -> Vec<String> {
3854        check(&parse(src).unwrap())
3855            .unwrap_err()
3856            .into_iter()
3857            .map(|e| e.message)
3858            .collect()
3859    }
3860
3861    // §41: expression guards are statically validated
3862    #[test]
3863    fn expr_guard_undeclared_state_caught() {
3864        let es = errs(
3865            "protocol p v1;\nroles a, b;\non inform from a when $p > unknow -> send bye;\non inform from b -> send bye;\n",
3866        );
3867        assert!(es.iter().any(|m| m.contains("undeclared state 'unknow'")), "{es:?}");
3868    }
3869
3870    #[test]
3871    fn expr_guard_type_mismatch_caught() {
3872        let es = errs(
3873            "protocol p v1;\nroles a, b;\nstate n: int;\non inform from a when n > \"x\" -> send bye;\non inform from b -> send bye;\n",
3874        );
3875        assert!(es.iter().any(|m| m.contains("comparing 'int' with 'str'")), "{es:?}");
3876    }
3877
3878    #[test]
3879    fn expr_guard_with_capture_ok() {
3880        let p = parse(
3881            "protocol p v1;\nroles a, b;\nstate n: int;\non inform {\"price\": $p} from a when $p > n -> send bye;\non inform from b -> send bye;\n",
3882        )
3883        .unwrap();
3884        assert!(check(&p).is_ok());
3885    }
3886
3887    // §41: state type lattice — generics and unknown types
3888    #[test]
3889    fn generic_state_types_validated() {
3890        let p = parse(
3891            "type Bid = { price: int };\nprotocol p v1;\nroles a, b;\nstate bids: list<Bid>;\nstate tally: map<str, int>;\non inform from a -> send bye;\non inform from b -> send bye;\n",
3892        )
3893        .unwrap();
3894        assert!(check(&p).is_ok());
3895        let es = errs(
3896            "protocol p v1;\nroles a, b;\nstate bids: list<Nope>;\non inform from a -> send bye;\non inform from b -> send bye;\n",
3897        );
3898        assert!(es.iter().any(|m| m.contains("unknown type 'list<Nope>'")), "{es:?}");
3899    }
3900
3901    // §41: diagnostics carry the handler's source line
3902    #[test]
3903    fn errors_carry_handler_line() {
3904        let p = parse(
3905            "protocol p v1;\nroles a, b;\non inform from a -> send inform to b;\non inform from b -> send request to a;\n",
3906        )
3907        .unwrap();
3908        let es = check(&p).unwrap_err();
3909        let dlg = es.iter().find(|e| e.message.contains("dialogue violation")).unwrap();
3910        assert_eq!(dlg.line, 4, "{es:?}");
3911    }
3912}
3913
3914#[cfg(test)]
3915mod inheritance_tests {
3916    use super::*;
3917
3918    // §42: extends inherits states/handlers; same-sig handler overrides
3919    #[test]
3920    fn extends_inherits_and_overrides() {
3921        let src = r#"
3922protocol supply_v1 v1;
3923roles buyer, seller;
3924state quoted: bool;
3925on request("quote") from buyer -> send propose to buyer;
3926on accept from buyer -> begin;
3927on breach -> send failure to buyer;
3928
3929protocol supply_v2 v1 extends supply_v1;
3930on accept from buyer -> send inform to buyer;
3931on breach -> send error to buyer;
3932on propose from seller -> send accept to seller;
3933on inform from seller -> send bye;
3934on error from seller -> send bye;
3935"#;
3936        let p = parse(src).unwrap();
3937        assert_eq!(p.name, "supply_v2");
3938        assert_eq!(p.states.len(), 1); // inherited quoted
3939        assert_eq!(p.handlers.len(), 6); // request (inherited) + 2 overrides + 3 new
3940        // the v2 accept handler OVERRODE the base's `begin`
3941        let acc: Vec<_> = p.handlers.iter().filter(|h| matches!(h.trigger, OnTrigger::Event { performative: Performative::Accept, .. })).collect();
3942        assert_eq!(acc.len(), 1);
3943        assert!(matches!(acc[0].actions[0], ProtocolAction::Send { performative: Performative::Inform, .. }));
3944        assert!(!p.handlers.iter().any(|h| h.actions.iter().any(|a| matches!(a, ProtocolAction::Begin))));
3945        assert!(check(&p).is_ok(), "{:?}", check(&p).unwrap_err());
3946    }
3947
3948    #[test]
3949    fn extends_requires_base_in_file() {
3950        let src = "protocol b v1;\nroles a, b;\non inform from a -> send inform to b;\non inform from b -> send bye;\n\nprotocol c v1 extends nosuch;\non inform from a -> send inform to b;\n";
3951        let es = parse(src).unwrap_err();
3952        assert!(es.iter().any(|e| e.message.contains("extends unknown protocol")), "{es:?}");
3953    }
3954
3955    #[test]
3956    fn second_protocol_without_extends_is_error() {
3957        let src = "protocol a v1;\nroles x, y;\non inform from x -> send inform to y;\non inform from y -> send bye;\nprotocol b v1;\nroles x, y;\non inform from x -> send inform to y;\n";
3958        let es = parse(src).unwrap_err();
3959        assert!(es.iter().any(|e| e.message.contains("without 'extends'")), "{es:?}");
3960    }
3961
3962    // §42: exported types and functions splice via import
3963    #[test]
3964    fn import_splices_exported_types_and_fns() {
3965        let mod_path = std::env::temp_dir().join("acl_voc_mod.aclp");
3966        std::fs::write(&mod_path, r#"
3967type Quote = { price: int, cur: str };
3968fn with_fee(p: int) -> int {
3969  set fee = p + 5;
3970  return fee;
3971}
3972export type Quote;
3973export fn with_fee;
3974protocol _voc v1;
3975roles x, y;
3976on inform from x -> send inform to y;
3977on inform from y -> send bye;
3978"#).unwrap();
3979        let main = format!(
3980            "import \"{}\";\nprotocol p v1;\nroles a, b;\nstate q: Quote;\non inform from a {{ set q = Quote {{ price: with_fee(10), cur: \"usd\" }}; }}\non inform from b -> send bye;\n",
3981            mod_path.to_string_lossy()
3982        );
3983        let p = parse_with_includes(&main, None).unwrap();
3984        assert!(p.types.contains_key("Quote"), "{:?}", p.types.keys());
3985        assert!(p.functions.iter().any(|f| f.name == "with_fee"));
3986        assert!(check(&p).is_ok(), "{:?}", check(&p).unwrap_err());
3987    }
3988}
3989
3990#[cfg(test)]
3991mod tooling_tests {
3992    use super::*;
3993
3994    // §47: fn recursion is a compile error (direct and mutual)
3995    #[test]
3996    fn fn_recursion_is_compile_error() {
3997        let es: Vec<String> = check(&parse(
3998            "protocol p v1;\nroles a, b;\nfn f(x: int) -> int {\nset r = f(x);\nreturn r;\n}\non inform from a -> send bye;\non inform from b -> send bye;\n",
3999        ).unwrap())
4000        .unwrap_err()
4001        .into_iter()
4002        .map(|e| e.message)
4003        .collect();
4004        assert!(es.iter().any(|m| m.contains("recursive")), "{es:?}");
4005    }
4006
4007    // §54: parse -> pretty -> parse must be a FIXPOINT for every language
4008    // feature — formatting may never invalidate a program
4009    #[test]
4010    fn pretty_roundtrip_preserves_all_features() {
4011        let src = concat!(
4012            "protocol p v1;\n",
4013            "roles a, b, c;\n",
4014            "phase start;\n",
4015            "phase work;\n",
4016            "state n: int;\n",
4017            "type Bid = { price: int };\n",
4018            "message m = \"hi\";\n",
4019            "transport http;\n",
4020            "capacity 4;\n",
4021            "abort when n > 9;\n",
4022            "fn f(x: int) -> int {\nset r = x + 1;\nreturn r;\n}\n",
4023            "on request from a as b { set n = f(2); send propose to c; }\n",
4024            "on inform {\"n\": $n} from b in work -> send inform {\"r\": \"${n}\"} to a;\n",
4025            "on propose from b as c { try { set n = n / 0; } catch { set n = 0; } }\n",
4026            "on breach -> send failure to a;\n",
4027            "on inform from a -> send bye;\n",
4028        );
4029        let p1 = parse(src).unwrap();
4030        let f1 = pretty(&p1);
4031        let p2 = parse(&f1).expect("pretty output must reparse");
4032        let f2 = pretty(&p2);
4033        assert_eq!(p1, p2, "roundtrip semantic equality");
4034        assert_eq!(f1, f2, "formatting must be IDEMPOTENT");
4035        // the formatter preserves executor attribution and phases
4036        assert!(f1.contains(" as b"), "{f1}");
4037        assert!(f1.contains("phase work;"), "{f1}");
4038        assert!(f1.contains(" in work"), "{f1}");
4039    }
4040
4041    #[test]
4042    fn non_recursive_fn_ok() {
4043        let p = parse(
4044            "protocol p v1;\nroles a, b;\nfn f(x: int) -> int {\nset r = x + 1;\nreturn r;\n}\nfn g(x: int) -> int {\nset r = f(x) * 2;\nreturn r;\n}\nstate n: int;\non inform from a { set n = g(1); send bye; }\non inform from b -> send bye;\n",
4045        )
4046        .unwrap();
4047        assert!(check(&p).is_ok());
4048    }
4049
4050    // §47: expect log parses
4051    #[test]
4052    fn expect_log_parses() {
4053        let p = parse(
4054            "protocol p v1;\nroles a, b;\nscenario s1 {\na sends inform to b;\nexpect log \"recv\";\n}\non inform from a -> send bye;\non inform from b -> send bye;\n",
4055        )
4056        .unwrap();
4057        assert!(p.scenarios.iter().any(|sc| sc.steps.iter().any(|st| matches!(st, ScenarioStep::ExpectLog { .. }))));
4058        let (passed, failed) = crate::scenario::run_all(&p);
4059        assert!(failed.is_empty(), "{failed:?}");
4060        assert_eq!(passed.len(), 1);
4061    }
4062}
4063
4064#[cfg(test)]
4065mod nested_analysis_tests {
4066    use super::*;
4067
4068    // §48: a send nested inside `for`/`try` is dialogue-checked
4069    #[test]
4070    fn nested_send_dialogue_violation_caught() {
4071        let src = "protocol p v1;\nroles a, b;\non inform from a { try { send request to b; } catch { send bye; } }\n";
4072        let p = parse(src).unwrap();
4073        let es = check(&p).unwrap_err();
4074        assert!(
4075            es.iter().any(|e| e.message.contains("dialogue violation")),
4076            "nested send escaped the dialogue check: {es:?}"
4077        );
4078    }
4079
4080    #[test]
4081    fn nested_send_linearity_caught() {
4082        let src = "protocol p v1;\nroles a, b;\nstate xs: list;\non inform from a { try { send query to b; } catch { send bye; } }\non query from b -> send bye;\non inform from b -> send bye;\n";
4083        let p = parse(src).unwrap();
4084        let es = check(&p).unwrap_err();
4085        assert!(
4086            es.iter().any(|e| e.message.contains("unanswered send") && e.message.contains("Query")),
4087            "nested send escaped linearity: {es:?}"
4088        );
4089    }
4090
4091    // §48: receiver with a content pattern fed fewer keys warns
4092    #[test]
4093    fn payload_key_mismatch_warns() {
4094        let src = "protocol p v1;\nroles a, b;\non inform {\"task\": $t} from a -> send inform {\"note\": \"ok\"} to b;\non inform {\"pct\": \"*\"} from a -> send bye;\non inform from b -> send bye;\n";
4095        let p = parse(src).unwrap();
4096        let warnings = check(&p).expect("warnings");
4097        assert!(
4098            warnings.iter().any(|w| w.contains("without key 'pct'")),
4099            "{warnings:?}"
4100        );
4101    }
4102}
4103
4104#[cfg(test)]
4105mod split_stmts_tests {
4106    use super::*;
4107
4108    #[test]
4109    fn split_stmts_handles_nested_for() {
4110        let body = r#" push items, "p1"; push items, "p2"; for it in items { send inform {"i": "${it}"} to a; } set x = x / 0; "#;
4111        let stmts = split_stmts(body);
4112        assert_eq!(stmts.len(), 4, "{stmts:?}");
4113        let f = stmts[2].trim();
4114        assert!(f.starts_with("for it in items") && f.ends_with('}'), "{f:?}");
4115        assert_eq!(stmts[3].trim(), "set x = x / 0");
4116    }
4117}