Skip to main content

bynk_syntax/
ast.rs

1//! Abstract syntax tree types for Bynk v0 (spec §9.2).
2
3use crate::span::Span;
4
5/// An identifier with its source span.
6#[derive(Debug, Clone)]
7pub struct Ident {
8    pub name: String,
9    pub span: Span,
10}
11
12/// Comment trivia attached to a declaration or statement (v1.1 LSP spec
13/// §3.5). The parser collects line comments from the token stream and
14/// attaches them to nearby AST nodes so the formatter can re-emit them.
15///
16/// - `leading` holds comments that appear immediately above the node,
17///   ordered top-to-bottom: each a `--` line, or an orphaned `---` doc block
18///   (see [`Comment`]). Above a unit-level declaration it also records where a
19///   blank line separated them ([`Comment::Blank`]).
20/// - `trailing` holds a single comment that appears on the same source
21///   line as the node's final token (e.g. `expr  -- note`).
22#[derive(Debug, Clone, Default)]
23pub struct Trivia {
24    pub leading: Vec<Comment>,
25    pub trailing: Option<String>,
26}
27
28/// #3067: the comments inside a list literal `[a, b, c]` (and, #3110, a call's
29/// arguments or a record literal's fields). `items` runs parallel
30/// to the elements: the comments above each, and the one at the end of its line.
31/// `closing` holds those before the `]`. Boxed and absent (`None`) when the list
32/// carries no comment, which keeps `ExprKind` small.
33#[derive(Debug, Clone, Default)]
34pub struct ListTrivia {
35    pub items: Vec<Trivia>,
36    pub closing: Vec<Comment>,
37}
38
39/// One entry of comment trivia.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub enum Comment {
42    /// A `--` line comment: the text after the marker, with its original
43    /// inline whitespace preserved.
44    Line(String),
45    /// #1756: a doc (a `---` block, or since #1888 a run of `--|` lines) that
46    /// attaches to no declaration (a blank line separates it from the next
47    /// one, or nothing follows it). The parser warns
48    /// `bynk.parse.orphan_doc_block` and keeps the block here, so the formatter
49    /// can print it where it was. Its content is normalised as an attached
50    /// doc's is.
51    OrphanDoc(Doc),
52    /// #1884: a blank line after a `--` comment, before the next comment or
53    /// the declaration. Recorded only where canonical style sets declarations
54    /// apart with blank lines: in the leading and closing comments of a
55    /// unit-level declaration (an item, a `uses`/`consumes`/`exports` clause,
56    /// the unit header), and of a service's sections and handlers or an agent's
57    /// invariants, transitions and handlers. There it keeps a comment that is
58    /// separated from the declaration below from reading as describing it.
59    /// Elsewhere (statements, record fields, capability ops, policy fields,
60    /// store fields) style has no blank lines, so the parser drops it. Several
61    /// blank lines are one entry.
62    Blank,
63}
64
65/// #1888: a documentation comment as written: its normalised text and the
66/// form it was written in. Every `documentation` field holds one. It derefs to
67/// its text, so a reader that only wants the Markdown treats it as a `str`;
68/// only the formatter reads [`Doc::form`], to print each doc in the form its
69/// author chose (DECISION F: it never converts between them).
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Doc {
72    /// The Markdown text: a `---` block's content with its common indent
73    /// stripped, or the `--|` lines' text joined with newlines.
74    pub text: String,
75    pub form: DocForm,
76}
77
78/// #1888: which of the two doc forms a [`Doc`] was written in.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
80pub enum DocForm {
81    /// A `---` fenced block (ADR 0188; matched-length fences since #1885).
82    #[default]
83    Block,
84    /// One or more consecutive `--|` lines.
85    Lines,
86}
87
88impl Doc {
89    pub fn new(text: impl Into<String>, form: DocForm) -> Self {
90        Self {
91            text: text.into(),
92            form,
93        }
94    }
95
96    pub fn as_str(&self) -> &str {
97        &self.text
98    }
99}
100
101impl std::ops::Deref for Doc {
102    type Target = str;
103    fn deref(&self) -> &str {
104        &self.text
105    }
106}
107
108/// A doc built from bare text is a `---` block, the form every doc had before
109/// #1888.
110impl From<String> for Doc {
111    fn from(text: String) -> Self {
112        Self::new(text, DocForm::Block)
113    }
114}
115
116impl From<&str> for Doc {
117    fn from(text: &str) -> Self {
118        Self::new(text, DocForm::Block)
119    }
120}
121
122impl std::fmt::Display for Doc {
123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124        f.write_str(&self.text)
125    }
126}
127
128impl Trivia {
129    pub fn is_empty(&self) -> bool {
130        self.leading.is_empty() && self.trailing.is_none()
131    }
132}
133
134/// A whole parsed commons source file.
135///
136/// In v0.3 a commons may be split across multiple files in a directory; the
137/// resolver merges them into one logical commons. Each parsed AST instance
138/// represents the contribution from a single source file.
139#[derive(Debug, Clone)]
140pub struct Commons {
141    pub name: QualifiedName,
142    pub items: Vec<CommonsItem>,
143    /// `uses` clauses declared in this file.
144    pub uses: Vec<UsesDecl>,
145    /// Optional documentation block attached to the commons declaration.
146    pub documentation: Option<Doc>,
147    /// Surface form of the file: brace-delimited body or headerless fragment.
148    pub form: CommonsForm,
149    pub span: Span,
150    /// Trivia attached to the commons declaration itself — leading comments
151    /// before the `commons` keyword and a trailing comment after the header
152    /// or closing brace.
153    pub trivia: Trivia,
154    /// Comments appearing after the last item but before the file ends
155    /// (or the closing brace, for brace form). One entry per `--` line.
156    pub trailing_comments: Vec<Comment>,
157}
158
159/// The two surface forms in which a commons body may be parsed (v0.3 §3.1).
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum CommonsForm {
162    /// `commons name { ... }`
163    Brace,
164    /// `commons name` followed by top-level declarations to EOF.
165    Fragment,
166}
167
168/// A `uses other.commons` declaration (v0.3 §3.3).
169#[derive(Debug, Clone)]
170pub struct UsesDecl {
171    pub target: QualifiedName,
172    pub span: Span,
173    pub trivia: Trivia,
174    /// A blank line separated this header line's leading comment from the
175    /// line above (#2893). The formatter keeps it, so the comment still reads
176    /// as belonging to this line. Never set without a leading comment.
177    pub blank_before: bool,
178}
179
180/// A whole parsed context source file (v0.4 §3.1).
181///
182/// Contexts are the architectural-layer declaration kind. Like commons, a
183/// context may be split across multiple files in a directory.
184#[derive(Debug, Clone)]
185pub struct Context {
186    pub name: QualifiedName,
187    pub items: Vec<CommonsItem>,
188    /// `uses` clauses declared in this file.
189    pub uses: Vec<UsesDecl>,
190    /// `consumes` clauses declared in this file.
191    pub consumes: Vec<ConsumesDecl>,
192    /// `exports` clauses declared in this file.
193    pub exports: Vec<ExportsDecl>,
194    /// Optional documentation block attached to the context declaration.
195    pub documentation: Option<Doc>,
196    /// Surface form of the file: brace-delimited body or headerless fragment.
197    pub form: CommonsForm,
198    pub span: Span,
199    /// Trivia attached to the context declaration itself — leading comments
200    /// before the `context` keyword.
201    pub trivia: Trivia,
202    /// Comments appearing after the last item but before the file ends
203    /// (or the closing brace, for brace form). One entry per `--` line.
204    pub trailing_comments: Vec<Comment>,
205    /// State-migrations S3 (#2248): `removed agent Old` declarations. Kept
206    /// beside `items` rather than as a `CommonsItem`: they declare a class's
207    /// *absence* (its stored data is deleted), so nothing that walks the
208    /// unit's items has anything to do with them.
209    pub removed_agents: Vec<RemovedAgentDecl>,
210}
211
212/// `removed agent Old` (state-migrations S3, #2248): the agent class `Old`
213/// is gone, and its stored data is deleted through an `exports` tombstone.
214#[derive(Debug, Clone)]
215pub struct RemovedAgentDecl {
216    /// The contextual `removed` keyword.
217    pub keyword: Span,
218    pub name: Ident,
219    pub documentation: Option<Doc>,
220    pub span: Span,
221    pub trivia: Trivia,
222}
223
224/// A `consumes other.context` declaration (v0.4 §3.2). May optionally carry
225/// an alias introduced by `consumes other.context as Alias` (v0.6 §3.1).
226#[derive(Debug, Clone)]
227pub struct ConsumesDecl {
228    pub target: QualifiedName,
229    pub alias: Option<Ident>,
230    /// v0.17: `consumes U { Cap, … }` — selected capabilities flattened into
231    /// the consumer's local capability namespace under their bare names (§3.3).
232    /// `None` for the whole-unit forms; `Some` (possibly empty) for the braced
233    /// form. Mutually exclusive with `alias`.
234    pub selected: Option<Vec<ConsumesItem>>,
235    pub span: Span,
236    pub trivia: Trivia,
237    /// A blank line separated this header line's leading comment from the
238    /// line above (#2893). The formatter keeps it, so the comment still reads
239    /// as belonging to this line. Never set without a leading comment.
240    pub blank_before: bool,
241}
242
243/// One name in a braced `consumes U { … }` list: a capability or exported type,
244/// optionally renamed for this context with `Name as Alias` (#2887).
245#[derive(Debug, Clone)]
246pub struct ConsumesItem {
247    pub name: Ident,
248    /// `Digest as CryptoDigest`: the exported type is in scope here only as the
249    /// alias, which sidesteps a clash with a local or `uses` type of that name.
250    pub alias: Option<Ident>,
251}
252
253/// An `exports visibility { names }` clause (v0.4 §3.3) or, v0.15, an
254/// `exports capability { names }` clause.
255#[derive(Debug, Clone)]
256pub struct ExportsDecl {
257    pub kind: ExportKind,
258    pub names: Vec<ExportName>,
259    pub span: Span,
260    pub trivia: Trivia,
261    /// A blank line separated this header line's leading comment from the
262    /// line above (#2893). The formatter keeps it, so the comment still reads
263    /// as belonging to this line. Never set without a leading comment.
264    pub blank_before: bool,
265    /// #1797: comments before the closing `}`.
266    pub trailing_comments: Vec<Comment>,
267}
268
269/// One name in an `exports` list, with its comments (#1797).
270#[derive(Debug, Clone)]
271pub struct ExportName {
272    pub name: Ident,
273    /// #1797: comments above the name and at the end of its line. A comment
274    /// on the list's `{` line leads the first name.
275    pub trivia: Trivia,
276}
277
278/// What an `exports` clause exposes: types (with a visibility) or, v0.15,
279/// capabilities offered for cross-context consumption.
280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub enum ExportKind {
282    /// `exports opaque { ... }` / `exports transparent { ... }` — type exports.
283    Type(Visibility),
284    /// `exports capability { ... }` — capabilities offered to consumers (v0.15).
285    Capability,
286}
287
288/// Visibility level for an exports clause (v0.4 §3.3).
289#[derive(Debug, Clone, Copy, PartialEq, Eq)]
290pub enum Visibility {
291    /// Token-only outside the context: hold, pass, compare; no inspect, no construct.
292    Opaque,
293    /// Readable shape outside the context: inspect fields, match variants; no construct.
294    Transparent,
295}
296
297/// An `adapter qualified.name { … }` declaration (v0.17 §3.1). An adapter
298/// co-locates a capability contract with a non-Bynk binding: it may declare
299/// capabilities, the boundary types they reference, inline pure helper
300/// `type`/`fn` (and `uses`), external (bodiless) providers, `exports
301/// capability`, and exactly one `binding` clause. It may *not* declare
302/// services, agents, or bodied providers. Like commons/contexts it may be
303/// split across files in a directory.
304#[derive(Debug, Clone)]
305pub struct AdapterDecl {
306    pub name: QualifiedName,
307    pub items: Vec<CommonsItem>,
308    /// `uses` clauses declared in this file (pure-vocabulary mixin; allowed
309    /// because helpers cannot pierce containment — spec [DECISION B]).
310    pub uses: Vec<UsesDecl>,
311    /// `exports capability { … }` clauses (adapters export capabilities and
312    /// boundary types, never services).
313    pub exports: Vec<ExportsDecl>,
314    /// v0.18: `consumes U { Cap, … }` clauses — adapter-to-adapter capability
315    /// dependencies (spec §4.5, \[N\]). Braced form only; adapter targets only
316    /// (both enforced semantically, not in the parser).
317    pub consumes: Vec<ConsumesDecl>,
318    /// The `binding "<module>" requires { … }` clause, if present. Required
319    /// when the adapter declares any external provider (`bynk.adapter.no_binding`).
320    pub binding: Option<BindingDecl>,
321    pub documentation: Option<Doc>,
322    pub form: CommonsForm,
323    pub span: Span,
324    pub trivia: Trivia,
325    pub trailing_comments: Vec<Comment>,
326}
327
328/// A `binding "<module>" [includes [ … ]] requires { "pkg": "range", … }` clause inside an
329/// adapter (v0.17 §3.5). `module` is the TypeScript module supplying the
330/// adapter's external provider symbols, resolved relative to the adapter's
331/// source file. `requires` declares npm dependencies folded into the
332/// generated `package.json`.
333#[derive(Debug, Clone)]
334pub struct BindingDecl {
335    /// The module path as written (the string-literal contents, no quotes).
336    pub module: String,
337    pub module_span: Span,
338    /// #2321: the `includes ["./x.wasm", …]` files shipped beside the binding,
339    /// as written (string-literal contents, no quotes) with their spans.
340    pub includes: Vec<IncludeEntry>,
341    pub requires: Vec<RequiresDep>,
342    pub span: Span,
343    pub trivia: Trivia,
344}
345
346/// One path in a binding's `includes [ … ]` list (#2321).
347#[derive(Debug, Clone)]
348pub struct IncludeEntry {
349    pub path: String,
350    pub span: Span,
351}
352
353/// One `"pkg": "range"` entry in a binding's `requires { … }` map.
354#[derive(Debug, Clone)]
355pub struct RequiresDep {
356    pub package: String,
357    pub range: String,
358    pub span: Span,
359}
360
361/// Either a commons or a context — the two declaration kinds at the file
362/// level (v0.4 §3.1). v0.7 adds the test declaration kind; v0.17 the adapter.
363#[derive(Debug, Clone)]
364pub enum SourceUnit {
365    Commons(Commons),
366    Context(Context),
367    Suite(SuiteDecl),
368    /// v0.17: an `adapter` unit — the host boundary (capability contract +
369    /// external binding).
370    Adapter(AdapterDecl),
371}
372
373impl SourceUnit {
374    pub fn name(&self) -> &QualifiedName {
375        match self {
376            SourceUnit::Commons(c) => &c.name,
377            SourceUnit::Context(c) => &c.name,
378            SourceUnit::Suite(t) => &t.target,
379            SourceUnit::Adapter(a) => &a.name,
380        }
381    }
382
383    pub fn span(&self) -> Span {
384        match self {
385            SourceUnit::Commons(c) => c.span,
386            SourceUnit::Context(c) => c.span,
387            SourceUnit::Suite(t) => t.span,
388            SourceUnit::Adapter(a) => a.span,
389        }
390    }
391
392    /// The doc-block above this file's unit header, if it carries one. For a
393    /// `commons`/`context`/`adapter` this is the unit's *module doc* (#1885);
394    /// for a `suite` it is the suite's own doc.
395    pub fn documentation(&self) -> Option<&str> {
396        match self {
397            SourceUnit::Commons(c) => c.documentation.as_deref(),
398            SourceUnit::Context(c) => c.documentation.as_deref(),
399            SourceUnit::Suite(t) => t.documentation.as_deref(),
400            SourceUnit::Adapter(a) => a.documentation.as_deref(),
401        }
402    }
403
404    /// The doc-block above this file's unit header when it carries prose:
405    /// [`SourceUnit::documentation`], with an empty or all-whitespace block
406    /// treated as absent. This is what "a file carries a module doc" means
407    /// for the one-module-doc-per-unit rule and for the tooling that shows the
408    /// doc (#1885): an empty `---`/`---` pair documents nothing, so it neither
409    /// counts against the rule nor shadows a sibling file's real doc.
410    pub fn module_doc(&self) -> Option<&str> {
411        self.documentation().filter(|d| !d.trim().is_empty())
412    }
413
414    pub fn kind_name(&self) -> &'static str {
415        match self {
416            SourceUnit::Commons(_) => "commons",
417            SourceUnit::Context(_) => "context",
418            SourceUnit::Suite(_) => "suite",
419            SourceUnit::Adapter(_) => "adapter",
420        }
421    }
422}
423
424/// A `test <qualified-name> { ... }` declaration (v0.7 §3.1).
425///
426/// A test targets a commons or context by qualified name and bundles a set of
427/// test cases plus optional mock declarations. As with commons and contexts, a
428/// test may be split across multiple files (fragment form).
429#[derive(Debug, Clone)]
430pub struct SuiteDecl {
431    /// The targeted commons or context.
432    pub target: QualifiedName,
433    /// `uses` clauses brought in by this test fragment.
434    pub uses: Vec<UsesDecl>,
435    /// #3536: `consumes` clauses of this suite file. Imports are per file: a
436    /// name from another unit (a type, a capability) is in scope in a suite
437    /// file only if its own `consumes` brings it in; the suite's target's
438    /// clauses are not inherited.
439    pub consumes: Vec<ConsumesDecl>,
440    /// v0.118: suite-scoped `stub` clauses — per-seam provider overrides
441    /// applied to every case (a case-scoped `stub` takes precedence). Formerly
442    /// the punned `provides` stub; renamed to `stub` in the keyword-hygiene
443    /// batch (#548).
444    pub stubs: Vec<StubClause>,
445    /// #2134: suite-scoped `env { … }` clauses — the variables and secrets
446    /// every participant sees, for every case (a case's own `env` layers over
447    /// them name by name).
448    pub envs: Vec<EnvClause>,
449    /// The individual test cases.
450    pub cases: Vec<Case>,
451    /// v0.114: generative `property` blocks (testing track slice 2).
452    pub properties: Vec<PropertyDecl>,
453    /// #2841: `fixture name = "fixtures/…"` declarations — project files whose
454    /// text is a `String` constant in this suite's cases, never deployed.
455    pub fixtures: Vec<FixtureDecl>,
456    /// #2834: suite-local helper `fn`s — pure, private to this suite, called
457    /// from its `case` and `property` bodies and emitted only into test output.
458    pub fns: Vec<FnDecl>,
459    /// #3066: suite-local `type` declarations — private to this suite, usable by
460    /// its cases, properties and helpers, emitted only into test output.
461    pub types: Vec<TypeDecl>,
462    /// #3066: suite-local `const` declarations — static values private to this
463    /// suite, with the same initialiser rules as a unit's constants.
464    pub consts: Vec<ConstDecl>,
465    /// v0.118: the suite-level tier default (`suite … as integration`). `None`
466    /// means the `unit` default; a `case`'s own tier overrides it. A `property`
467    /// ignores a suite tier (tiers are a `case`-only affordance).
468    pub tier: Option<TestTier>,
469    /// Surface form: brace-delimited body or headerless fragment.
470    pub form: CommonsForm,
471    /// Optional documentation block attached to the test declaration.
472    pub documentation: Option<Doc>,
473    pub span: Span,
474    pub trivia: Trivia,
475    pub trailing_comments: Vec<Comment>,
476}
477
478/// v0.118: the tier a `case` runs at (testing track slice 6, ADR 0153). One
479/// body promoted across the testing pyramid; `unit` is the default and elided.
480#[derive(Debug, Clone, Copy, PartialEq, Eq)]
481pub enum TestTier {
482    /// Collaborators stubbed (the default).
483    Unit,
484    /// Real collaborators within one context, no serialisation wire.
485    Integration,
486    /// Contexts wired across the real serialise → JSON → deserialise boundary.
487    System,
488}
489
490impl TestTier {
491    pub fn as_str(self) -> &'static str {
492        match self {
493            TestTier::Unit => "unit",
494            TestTier::Integration => "integration",
495            TestTier::System => "system",
496        }
497    }
498}
499
500/// v0.118: a per-seam provider override `stub Cap.method(<args>) returns <v>
501/// | fails` (testing track slice 6, ADR 0154; keyword `stub` since #548).
502/// Substitutes one capability method's provision under test; the right-hand
503/// side is a value or a fault, never a computed body.
504#[derive(Debug, Clone)]
505pub struct StubClause {
506    /// The capability being overridden (a consumed seam of the unit).
507    pub capability: Ident,
508    /// The overridden method.
509    pub method: Ident,
510    /// One argument pattern per parameter (`_` or a value the arg must equal).
511    pub args: Vec<ArgPattern>,
512    /// The provision: a value, a fault, a per-call sequence, or none at all.
513    pub rhs: StubRhs,
514    /// #2683: `returns <v> after <d>` — the call completes only once the
515    /// harness clock has advanced by `d` from the call. Only on `returns`.
516    pub after: Option<Expr>,
517    pub documentation: Option<Doc>,
518    pub span: Span,
519    pub trivia: Trivia,
520}
521
522/// #2134: a suite- or case-scoped `env { NAME = "value" … }` clause — the
523/// variables and secrets a suite's participants see (ADR for #2134). `env` is
524/// contextual: a keyword only at the head of a suite or case body member.
525#[derive(Debug, Clone)]
526pub struct EnvClause {
527    /// The entries, in source order.
528    pub entries: Vec<EnvEntry>,
529    pub documentation: Option<Doc>,
530    pub span: Span,
531    pub trivia: Trivia,
532}
533
534/// #2134: one `NAME = <value>` entry of an [`EnvClause`]. The value is parsed
535/// as an expression; the checker requires a `String` literal.
536#[derive(Debug, Clone)]
537pub struct EnvEntry {
538    pub name: Ident,
539    pub value: Expr,
540    pub span: Span,
541}
542
543/// v0.118: one argument pattern in a `stub` call pattern. Patterns for the
544/// same method are tried top-to-bottom, first match wins.
545#[derive(Debug, Clone)]
546pub enum ArgPattern {
547    /// `_` — matches any argument.
548    Any(Span),
549    /// A value the recorded argument must equal (a literal or pure value expr).
550    Value(Expr),
551}
552
553/// v0.118: the right-hand side of a `stub` clause.
554#[derive(Debug, Clone)]
555pub enum StubRhs {
556    /// `returns <value>` — a single success value, repeated for every call.
557    Returns(Expr),
558    /// `fails` — inject a capability fault (Principle 3).
559    Fails(Span),
560    /// `returns each [<outcome>, …]` — one outcome per call, in order; the last
561    /// outcome repeats once the sequence is exhausted (DECISION V).
562    ReturnsEach(Vec<SeqOutcome>, Span),
563    /// #2683: `never` — the call never completes. It exists to test a
564    /// `within` against an effect that does not finish.
565    Never(Span),
566}
567
568impl StubRhs {
569    pub fn span(&self) -> Span {
570        match self {
571            StubRhs::Returns(e) => e.span,
572            StubRhs::Fails(s) => *s,
573            StubRhs::ReturnsEach(_, s) => *s,
574            StubRhs::Never(s) => *s,
575        }
576    }
577}
578
579/// v0.118: one outcome in a sequenced (`returns each`) `stub`.
580#[derive(Debug, Clone)]
581pub enum SeqOutcome {
582    /// A success value.
583    Value(Expr),
584    /// A fault.
585    Fails(Span),
586}
587
588/// A `case "name" [as <tier>] { [stub …] body }` block inside a suite
589/// (v0.7 §3.3; v0.118 adds the tier clause and case-scoped stubs).
590#[derive(Debug, Clone)]
591pub struct Case {
592    /// The test name, taken from the string literal.
593    pub name: String,
594    /// The span of the string literal — used for diagnostics and runtime
595    /// failure reports.
596    pub name_span: Span,
597    /// v0.118: the case's own tier, if written (`as integration` / `as system`).
598    /// `None` means inherit the suite default (itself `unit` when unset).
599    pub tier: Option<TestTier>,
600    /// v0.118: case-scoped `stub` clauses (override the suite's, and the
601    /// tier default).
602    pub stubs: Vec<StubClause>,
603    /// #2134: case-scoped `env { … }` clauses, layered over the suite's.
604    pub envs: Vec<EnvClause>,
605    pub body: Block,
606    pub documentation: Option<Doc>,
607    pub span: Span,
608    pub trivia: Trivia,
609}
610
611/// A `property "name" { for all <bindings> [where <pred>] { body } }` block
612/// inside a suite (v0.114, testing track slice 2, ADR 0149). The generative
613/// sibling of [`Case`]: the runner draws inhabitants of each binding's type from
614/// its refinement domain and evaluates the body's `expect`s over them.
615#[derive(Debug, Clone)]
616pub struct PropertyDecl {
617    /// The property name, taken from the string literal.
618    pub name: String,
619    /// The span of the string literal — used for diagnostics and reports.
620    pub name_span: Span,
621    /// The `for all` binder: the generated bindings, an optional `where` filter,
622    /// and the predicate body.
623    pub forall: ForAll,
624    pub documentation: Option<Doc>,
625    pub span: Span,
626    pub trivia: Trivia,
627}
628
629/// The `for all x: T, … [where <pred>] { … }` binder inside a [`PropertyDecl`].
630#[derive(Debug, Clone)]
631pub struct ForAll {
632    /// The generated bindings, `x: T` (one or more).
633    pub bindings: Vec<ForAllBinding>,
634    /// An optional `where <pred>` filter (a pure `Bool`) applied to generated
635    /// tuples before the body runs.
636    pub where_pred: Option<Expr>,
637    /// The body — one or more statements, typically `expect`s.
638    pub body: Block,
639    pub span: Span,
640}
641
642/// One `for all` binding: `name: T`, where the runner generates inhabitants of
643/// `T` from its refinements.
644#[derive(Debug, Clone)]
645pub struct ForAllBinding {
646    pub name: Ident,
647    pub type_ref: TypeRef,
648}
649
650/// A capability reference in a `given` clause (v0.15 §3.2). A bare name is a
651/// local capability (`given Cap`); a dotted name refers to a capability a
652/// consumed context provides (`given B.Cap` / `given Alias.Cap`).
653#[derive(Debug, Clone)]
654pub struct CapRef {
655    /// `None` for a local capability; `Some(prefix)` for a cross-context
656    /// reference where `prefix` is a consumed-context qualified name or alias.
657    pub context: Option<QualifiedName>,
658    /// The capability's simple name (also the local deps key).
659    pub name: Ident,
660    pub span: Span,
661}
662
663impl CapRef {
664    /// The local deps key / capability simple name (e.g. `Clock`).
665    pub fn key(&self) -> &str {
666        &self.name.name
667    }
668
669    /// True when this references a capability provided by a consumed context.
670    pub fn is_cross_context(&self) -> bool {
671        self.context.is_some()
672    }
673
674    /// How the reference is written: `Cap`, or `B.Cap` for a consumed context's.
675    pub fn display_name(&self) -> String {
676        match self.prefix() {
677            Some(p) => format!("{p}.{}", self.key()),
678            None => self.key().to_string(),
679        }
680    }
681
682    /// The cross-context prefix (consumed-context qualified name or alias) as
683    /// a dotted string, if any.
684    pub fn prefix(&self) -> Option<String> {
685        self.context.as_ref().map(|q| q.joined())
686    }
687}
688
689/// A dotted name like `fitness.units`.
690#[derive(Debug, Clone)]
691pub struct QualifiedName {
692    pub parts: Vec<Ident>,
693    pub span: Span,
694}
695
696impl QualifiedName {
697    pub fn joined(&self) -> String {
698        self.parts
699            .iter()
700            .map(|p| p.name.as_str())
701            .collect::<Vec<_>>()
702            .join(".")
703    }
704}
705
706// Finding #31 shrank `Expr`/`ExprKind` enough that clippy's variance check
707// between this enum's smallest and largest variants (`Service`/`Actor` vs.
708// `Type`/`Fn`) now crosses its threshold — a pre-existing size profile made
709// newly visible, not something #31 itself is scoped to fix. Boxing
710// `ServiceDecl`/`ActorDecl` here is a separate, unscoped refactor (its own
711// blast radius across every `CommonsItem::Service`/`Actor` construction and
712// match site) left for a future finding.
713#[allow(clippy::large_enum_variant)]
714#[derive(Debug, Clone)]
715pub enum CommonsItem {
716    Type(TypeDecl),
717    Fn(FnDecl),
718    /// `capability Name { fn op(...) -> T ... }` (v0.5; contexts only).
719    Capability(CapabilityDecl),
720    /// `provides Cap = ProviderName { fn op(...) -> T { ... } ... }` (v0.5).
721    Provider(ProviderDecl),
722    /// `service Name { on call(...) -> T { ... } ... }` (v0.5).
723    Service(ServiceDecl),
724    /// `agent Name { key id: T; state { ... }; on call ... }` (v0.5).
725    Agent(AgentDecl),
726    /// `actor Name { auth = Scheme, identity = T }` (v0.45). A nominal boundary
727    /// contract consumed by a handler's `by` clause; not a runnable entity.
728    Actor(ActorDecl),
729    /// `messages <tag> @reference { "code" => "template" ... }` — a message
730    /// bundle for one locale. Commons-only (checker-enforced, not grammar);
731    /// legal syntactically wherever any `CommonsItem` is, per the existing
732    /// `Service`/`Agent`-in-`adapter` precedent.
733    Messages(MessagesDecl),
734    /// `event Name = { fields }` (Events track, slice 0, spine #936).
735    /// Context-only (checker-enforced, not grammar) — the mirror image of
736    /// `Messages`' commons-only restriction, same mechanism.
737    Event(EventDecl),
738    /// `asset name = "path"` (#1883, slice 1a). A static file the platform
739    /// serves beside the Worker. Context or commons ([DECISION G]); an
740    /// adapter is rejected by the checker, not the grammar, like `Event`.
741    Asset(AssetDecl),
742    /// `embed name = "path"` (#2387, slice 1). A project file's text as a
743    /// `String` constant. Context or commons; an adapter is rejected by the
744    /// checker, not the grammar, like `Asset`.
745    Embed(EmbedDecl),
746    /// `const Name: Type = <static expression>` (#2617). A named value of
747    /// the declared type, usable wherever an expression of that type is.
748    /// Context or commons; an adapter is rejected by the checker, not the
749    /// grammar, like `Embed`.
750    Const(ConstDecl),
751}
752
753impl CommonsItem {
754    /// The declaring identifier, when the item is named by one. `Messages` is
755    /// the sole `None`: its locale tag is a `LocaleTag` string literal
756    /// (`"pt-BR"`), not an identifier, and synthesising an `Ident` from it
757    /// would be a lie any identifier-shaped consumer (rename, go-to-def) would
758    /// eventually surface.
759    pub fn name(&self) -> Option<&Ident> {
760        match self {
761            CommonsItem::Type(t) => Some(&t.name),
762            CommonsItem::Fn(f) => Some(f.name.ident()),
763            CommonsItem::Capability(c) => Some(&c.name),
764            CommonsItem::Provider(p) => Some(&p.provider_name),
765            CommonsItem::Service(s) => Some(&s.name),
766            CommonsItem::Agent(a) => Some(&a.name),
767            CommonsItem::Actor(a) => Some(&a.name),
768            CommonsItem::Messages(_) => None,
769            CommonsItem::Event(e) => Some(&e.name),
770            CommonsItem::Asset(a) => Some(&a.name),
771            CommonsItem::Embed(e) => Some(&e.name),
772            CommonsItem::Const(c) => Some(&c.name),
773        }
774    }
775
776    /// #2618: the span of the item's `private` modifier, when it has one.
777    /// Only the kinds that may carry the modifier (`fn`, `type`, `messages`,
778    /// `asset`, `embed`, `const`) ever answer `Some`.
779    pub fn private_span(&self) -> Option<Span> {
780        match self {
781            CommonsItem::Type(t) => t.private,
782            CommonsItem::Fn(f) => f.private,
783            CommonsItem::Messages(m) => m.private,
784            CommonsItem::Asset(a) => a.private,
785            CommonsItem::Embed(e) => e.private,
786            CommonsItem::Const(c) => c.private,
787            CommonsItem::Capability(_)
788            | CommonsItem::Provider(_)
789            | CommonsItem::Service(_)
790            | CommonsItem::Agent(_)
791            | CommonsItem::Actor(_)
792            | CommonsItem::Event(_) => None,
793        }
794    }
795
796    /// #2618: is the item unit-private?
797    pub fn is_private(&self) -> bool {
798        self.private_span().is_some()
799    }
800
801    /// The whole declaration's span, from its first token to its last.
802    pub fn span(&self) -> Span {
803        match self {
804            CommonsItem::Type(t) => t.span,
805            CommonsItem::Fn(f) => f.span,
806            CommonsItem::Capability(c) => c.span,
807            CommonsItem::Provider(p) => p.span,
808            CommonsItem::Service(s) => s.span,
809            CommonsItem::Agent(a) => a.span,
810            CommonsItem::Actor(a) => a.span,
811            CommonsItem::Messages(m) => m.span,
812            CommonsItem::Event(e) => e.span,
813            CommonsItem::Asset(a) => a.span,
814            CommonsItem::Embed(e) => e.span,
815            CommonsItem::Const(c) => c.span,
816        }
817    }
818
819    /// The `service` declaration, when the item is one.
820    pub fn as_service(&self) -> Option<&ServiceDecl> {
821        match self {
822            CommonsItem::Service(s) => Some(s),
823            CommonsItem::Type(_)
824            | CommonsItem::Fn(_)
825            | CommonsItem::Capability(_)
826            | CommonsItem::Provider(_)
827            | CommonsItem::Agent(_)
828            | CommonsItem::Actor(_)
829            | CommonsItem::Messages(_)
830            | CommonsItem::Event(_)
831            | CommonsItem::Asset(_)
832            | CommonsItem::Embed(_)
833            | CommonsItem::Const(_) => None,
834        }
835    }
836
837    /// The `agent` declaration, when the item is one.
838    pub fn as_agent(&self) -> Option<&AgentDecl> {
839        match self {
840            CommonsItem::Agent(a) => Some(a),
841            CommonsItem::Type(_)
842            | CommonsItem::Fn(_)
843            | CommonsItem::Capability(_)
844            | CommonsItem::Provider(_)
845            | CommonsItem::Service(_)
846            | CommonsItem::Actor(_)
847            | CommonsItem::Messages(_)
848            | CommonsItem::Event(_)
849            | CommonsItem::Asset(_)
850            | CommonsItem::Embed(_)
851            | CommonsItem::Const(_) => None,
852        }
853    }
854
855    /// The `capability` declaration, when the item is one.
856    pub fn as_capability(&self) -> Option<&CapabilityDecl> {
857        match self {
858            CommonsItem::Capability(c) => Some(c),
859            CommonsItem::Type(_)
860            | CommonsItem::Fn(_)
861            | CommonsItem::Provider(_)
862            | CommonsItem::Service(_)
863            | CommonsItem::Agent(_)
864            | CommonsItem::Actor(_)
865            | CommonsItem::Messages(_)
866            | CommonsItem::Event(_)
867            | CommonsItem::Asset(_)
868            | CommonsItem::Embed(_)
869            | CommonsItem::Const(_) => None,
870        }
871    }
872
873    /// The `actor` declaration, when the item is one.
874    pub fn as_actor(&self) -> Option<&ActorDecl> {
875        match self {
876            CommonsItem::Actor(a) => Some(a),
877            CommonsItem::Type(_)
878            | CommonsItem::Fn(_)
879            | CommonsItem::Capability(_)
880            | CommonsItem::Provider(_)
881            | CommonsItem::Service(_)
882            | CommonsItem::Agent(_)
883            | CommonsItem::Messages(_)
884            | CommonsItem::Event(_)
885            | CommonsItem::Asset(_)
886            | CommonsItem::Embed(_)
887            | CommonsItem::Const(_) => None,
888        }
889    }
890
891    /// The `messages` block, when the item is one.
892    pub fn as_messages(&self) -> Option<&MessagesDecl> {
893        match self {
894            CommonsItem::Messages(m) => Some(m),
895            CommonsItem::Type(_)
896            | CommonsItem::Fn(_)
897            | CommonsItem::Capability(_)
898            | CommonsItem::Provider(_)
899            | CommonsItem::Service(_)
900            | CommonsItem::Agent(_)
901            | CommonsItem::Actor(_)
902            | CommonsItem::Event(_)
903            | CommonsItem::Asset(_)
904            | CommonsItem::Embed(_)
905            | CommonsItem::Const(_) => None,
906        }
907    }
908
909    /// The handlers the item declares: a service's or an agent's, and none for
910    /// any other kind.
911    pub fn handlers(&self) -> &[Handler] {
912        match self {
913            CommonsItem::Service(s) => &s.handlers,
914            CommonsItem::Agent(a) => &a.handlers,
915            CommonsItem::Type(_)
916            | CommonsItem::Fn(_)
917            | CommonsItem::Capability(_)
918            | CommonsItem::Provider(_)
919            | CommonsItem::Actor(_)
920            | CommonsItem::Messages(_)
921            | CommonsItem::Event(_)
922            | CommonsItem::Asset(_)
923            | CommonsItem::Embed(_)
924            | CommonsItem::Const(_) => &[],
925        }
926    }
927}
928
929/// `asset name = "path"` (#1883, slice 1a): one static file, served by the
930/// platform at a content-hashed URL and never reaching the Worker, so public
931/// by construction. `name` is a value of the built-in type `Asset`
932/// ([DECISION H]), whose `.url` is that URL.
933///
934/// `path` is the literal's value with escapes applied, relative to the
935/// project root. The checker rejects a path that is absolute or contains a
936/// `..` segment (`bynk.asset.unsafe_path`) or names a file outside the
937/// project's `assets/` folder (`bynk.asset.outside_assets_dir`), and one
938/// whose file does not exist there (`bynk.asset.missing_file`).
939#[derive(Debug, Clone)]
940pub struct AssetDecl {
941    pub name: Ident,
942    pub path: String,
943    pub path_span: Span,
944    /// `at "/favicon.ico"` (#1883, slice 2, [DECISION C]): a fixed URL path
945    /// to serve the file at, for clients that fetch a file by name without
946    /// reading a page (`favicon.ico`, `robots.txt`). `None` serves it at a
947    /// content-hashed path under `/_assets/`. With its span, for diagnostics.
948    pub at: Option<(String, Span)>,
949    pub documentation: Option<Doc>,
950    /// #2618: the span of a leading `private` modifier, when the declaration
951    /// is unit-private: visible across its own unit's files (and to that
952    /// unit's suites), never through `uses`. `None` is the default, public.
953    pub private: Option<Span>,
954    pub span: Span,
955    pub trivia: Trivia,
956}
957
958/// `embed name = "path"` (#2387, slice 1): one project file whose text is the
959/// value of `name`, a `String` constant compiled into the code. Unlike an
960/// [`AssetDecl`] it is never served, so it is private and comes from the
961/// project's `embeds/` folder rather than `assets/`.
962///
963/// `path` is the literal's value with escapes applied, relative to the
964/// project root. The checker rejects a path that is absolute or contains a
965/// `..` segment (`bynk.embed.unsafe_path`) or names a file outside the
966/// project's `embeds/` folder (`bynk.embed.outside_embeds_dir`).
967#[derive(Debug, Clone)]
968pub struct EmbedDecl {
969    pub name: Ident,
970    pub path: String,
971    pub path_span: Span,
972    pub documentation: Option<Doc>,
973    /// #2618: the span of a leading `private` modifier, when the declaration
974    /// is unit-private: visible across its own unit's files (and to that
975    /// unit's suites), never through `uses`. `None` is the default, public.
976    pub private: Option<Span>,
977    pub span: Span,
978    pub trivia: Trivia,
979}
980
981/// `fixture name = "path"` (#2841): a project file's text as a `String`
982/// constant visible to the declaring suite's `case` and `property` bodies. A
983/// fixture is test-only: its text goes into test output, never into a deployable.
984///
985/// `path` is the literal's value with escapes applied, relative to the project
986/// root. The checker rejects a path that is absolute or contains a `..` segment
987/// (`bynk.fixture.unsafe_path`) or names a file outside the project's
988/// `fixtures/` folder (`bynk.fixture.outside_fixtures_dir`).
989#[derive(Debug, Clone)]
990pub struct FixtureDecl {
991    pub name: Ident,
992    pub path: String,
993    pub path_span: Span,
994    pub documentation: Option<Doc>,
995    pub span: Span,
996    pub trivia: Trivia,
997}
998
999/// `const Name: Type = <static expression>` (#2617): a named value, typed by
1000/// its required annotation `ty`. The initialiser `init` is a *static
1001/// expression* (ADR 0004) or a reference to another constant; the checker
1002/// rejects anything else (`bynk.resolve.bad_const_initialiser`), a name that
1003/// is not upper-camel (`bynk.resolve.const_name_case`) and constants whose
1004/// initialisers refer to each other in a cycle (`bynk.resolve.const_cycle`).
1005/// Emitted as an exported, hoisted TypeScript function that caches the value;
1006/// each reference is a call.
1007#[derive(Debug, Clone)]
1008pub struct ConstDecl {
1009    pub name: Ident,
1010    pub ty: TypeRef,
1011    pub init: Expr,
1012    pub documentation: Option<Doc>,
1013    /// The span of a leading `private` modifier, when the constant is
1014    /// unit-private: visible across its own unit's files (and to that unit's
1015    /// suites), never through `uses`. `None` is the default, public.
1016    pub private: Option<Span>,
1017    pub span: Span,
1018    pub trivia: Trivia,
1019}
1020
1021/// One locale's message bundle (v0.222+): `messages "<tag>" @reference { ... }`.
1022/// `tag` is a `LocaleTag` string literal (like an entry's `code`/`template`);
1023/// its refinement (`bynk.locale.types`) is checked by `check_messages_bundles`,
1024/// which reports `bynk.messages.invalid_locale_tag` for a tag the pattern
1025/// rejects.
1026#[derive(Debug, Clone)]
1027pub struct MessagesDecl {
1028    pub tag: String,
1029    pub tag_span: Span,
1030    /// Every `@`-annotation attached to this block. The parser stays
1031    /// permissive (zero or more, same as `store` field annotations); cardinality
1032    /// (exactly one `@reference` per bundle, counted across every `Messages`
1033    /// item in the commons) is a checker concern, not a parse error.
1034    pub annotations: Vec<Annotation>,
1035    pub entries: Vec<MessageEntry>,
1036    pub documentation: Option<Doc>,
1037    /// #2618: the span of a leading `private` modifier, when the declaration
1038    /// is unit-private: visible across its own unit's files (and to that
1039    /// unit's suites), never through `uses`. `None` is the default, public.
1040    pub private: Option<Span>,
1041    pub span: Span,
1042    pub trivia: Trivia,
1043}
1044
1045/// One `"code" => "template"` entry inside a `messages` block. Both sides are
1046/// plain string literals — a template's `{name}` placeholders are resolved by
1047/// a compile-time string scan during lowering, not parsed as expressions.
1048#[derive(Debug, Clone)]
1049pub struct MessageEntry {
1050    pub code: String,
1051    pub code_span: Span,
1052    pub template: String,
1053    pub template_span: Span,
1054    pub span: Span,
1055    /// #1888: the doc above the entry, in either form.
1056    pub documentation: Option<Doc>,
1057}
1058
1059/// A capability declaration (v0.5 §3.3). Capabilities are interface-like
1060/// contracts for external dependencies, used inside contexts. They may only
1061/// appear inside a `context` declaration.
1062#[derive(Debug, Clone)]
1063pub struct CapabilityDecl {
1064    pub name: Ident,
1065    /// Empty for a derived capability ([`CapabilityDecl::derived`]), whose
1066    /// operations are its base's; the checker resolves them.
1067    pub ops: Vec<CapabilityOp>,
1068    /// Standard-library S4a (#1966): `capability Sessions = Kv @option(…)`, a
1069    /// distinct instance of a platform capability the unit consumes. `None` for
1070    /// the braced `capability X { fn … }` form.
1071    pub derived: Option<DerivedCapability>,
1072    pub documentation: Option<Doc>,
1073    pub span: Span,
1074    /// #1756: comments before the closing `}`, an orphaned doc block among
1075    /// them, so the formatter keeps them.
1076    pub trailing_comments: Vec<Comment>,
1077    pub trivia: Trivia,
1078}
1079
1080/// The `= Base @option(…)*` of a derived capability (S4a, #1966): a new
1081/// capability name whose operations are those of `base`, a platform capability
1082/// the unit selects with `consumes U { Base }`, provided by the platform
1083/// adapter's own provider bound to this instance.
1084#[derive(Debug, Clone)]
1085pub struct DerivedCapability {
1086    /// The base capability, by its flattened (bare) name.
1087    pub base: Ident,
1088    /// Creation options for the instance, checked against the base kind's
1089    /// closed set.
1090    pub annotations: Vec<Annotation>,
1091}
1092
1093/// One operation in a capability (signature only; no body).
1094#[derive(Debug, Clone)]
1095pub struct CapabilityOp {
1096    pub name: Ident,
1097    /// #926: `[T, …]` type parameters on the op itself; empty for a
1098    /// non-generic op. Resolved only from an explicit type argument at the
1099    /// call site (`Cap.op[Some](…)`) — never inferred.
1100    pub type_params: Vec<TypeParam>,
1101    pub params: Vec<Param>,
1102    pub return_type: TypeRef,
1103    /// Typed capability reads (#3458): `@name(arg)` annotations after the
1104    /// return type. Internal to the standard library: the checker refuses any
1105    /// outside a first-party unit (`bynk.generics.internal_op_annotation`).
1106    pub annotations: Vec<Annotation>,
1107    pub documentation: Option<Doc>,
1108    pub span: Span,
1109    pub trivia: Trivia,
1110}
1111
1112/// A provider declaration (v0.5 §3.4). Supplies an implementation for a
1113/// capability.
1114#[derive(Debug, Clone)]
1115pub struct ProviderDecl {
1116    /// The capability being implemented.
1117    pub capability: Ident,
1118    /// The provider's identifier (used in tests/config to select impls).
1119    pub provider_name: Ident,
1120    /// v0.12: capabilities this provider depends on (`provides X = Impl given
1121    /// Y, Z { … }`). The provider's operation bodies may use these. v0.15:
1122    /// a dependency may be a cross-context capability (`given B.Cap`).
1123    pub given: Vec<CapRef>,
1124    pub ops: Vec<ProviderOp>,
1125    /// v0.17: an *external* provider — `provides Cap = Name` with **no** brace
1126    /// block — inside an adapter, supplied by the adapter's binding rather than
1127    /// a Bynk body. When `true`, `ops` is empty and the emitter produces no
1128    /// class. The absence of the brace block (not an empty one) is the signal.
1129    pub external: bool,
1130    pub documentation: Option<Doc>,
1131    pub span: Span,
1132    pub trivia: Trivia,
1133}
1134
1135/// One operation in a provider (signature plus body).
1136#[derive(Debug, Clone)]
1137pub struct ProviderOp {
1138    pub name: Ident,
1139    pub params: Vec<Param>,
1140    pub return_type: TypeRef,
1141    pub body: Block,
1142    pub span: Span,
1143    pub trivia: Trivia,
1144}
1145
1146/// A service declaration (v0.5 §3.5). Services are the boundary interface
1147/// of a context.
1148#[derive(Debug, Clone)]
1149pub struct ServiceDecl {
1150    pub name: Ident,
1151    /// The protocol the service conforms to, from the `from <protocol>` header
1152    /// clause (v0.44). `Call` when there is no clause.
1153    pub protocol: ServiceProtocol,
1154    /// The optional service-level `by` default (v0.155) — a `by <Actor>` clause on
1155    /// the service header, `service Api from http by v: Visitor { … }`. Every
1156    /// handler that omits its own `by` inherits this one (injected by the
1157    /// normalization pass). `None` when absent — handlers then fall back to the
1158    /// per-protocol default actor (HTTP/WebSocket have none, so `by` stays
1159    /// mandatory there). The "public / bearer-authed" fact is usually a service
1160    /// fact, so this removes the per-handler repetition.
1161    pub default_by: Option<ByClause>,
1162    /// The optional service-level `given` default (v0.155) — a `given C1, C2`
1163    /// clause on the service header, following the `by` default. Every handler
1164    /// that declares no `given` of its own inherits this list. Empty when absent.
1165    pub default_given: Vec<CapRef>,
1166    /// The optional cross-origin (CORS) policy (v0.131, ADR 0159) — a `cors { }`
1167    /// section in the service body, only meaningful on a `from http` service.
1168    /// `None` when absent (same-origin default, byte-for-byte unchanged output).
1169    pub cors: Option<CorsPolicy>,
1170    /// The optional security-headers policy (v0.141, ADR 0164) — a `security { }`
1171    /// section in the service body, only meaningful on a `from http` service.
1172    /// `None` when absent, but unlike `cors` the *absence* still stamps the safe
1173    /// defaults (`nosniff` on) — the emitter synthesises a default policy for every
1174    /// `from http` service, so `None` here means "defaults", not "no headers".
1175    pub security: Option<SecurityPolicy>,
1176    /// The optional request-body-size policy (v0.142, ADR 0165) — a `limits { }`
1177    /// section in the service body, only meaningful on a `from http` service. It
1178    /// declares a per-service `maxBody` ceiling (in bytes) for the service's
1179    /// body-taking routes; a route may override it with `@limit(maxBody: …)`.
1180    /// `None` when absent (no cap — byte-for-byte unchanged output, the opt-in
1181    /// CORS posture, not the `security` default-on posture).
1182    pub limits: Option<LimitsPolicy>,
1183    /// The optional response-JSON policy (#2858) — a `json { options: plain }`
1184    /// section in the service body, only meaningful on a `from http` service.
1185    /// `None` (or `options: tagged`) keeps Bynk's tagged `Option` encoding in
1186    /// response bodies, byte-for-byte unchanged; a route's `@json(options:)`
1187    /// overrides it.
1188    pub json: Option<JsonPolicy>,
1189    pub handlers: Vec<Handler>,
1190    pub documentation: Option<Doc>,
1191    pub span: Span,
1192    /// #1756: comments before the closing `}`, an orphaned doc block among
1193    /// them, so the formatter keeps them.
1194    pub trailing_comments: Vec<Comment>,
1195    pub trivia: Trivia,
1196}
1197
1198/// A cross-origin resource-sharing policy on a `from http` service (v0.131,
1199/// ADR 0159): the `cors { }` section in the service body. Parsed leniently as a
1200/// list of `name: value` fields (the grammar accepts any field name — an unknown
1201/// one is a checker diagnostic, per the `@`-annotation precedent, ADR 0111), and
1202/// interpreted through the typed accessors below.
1203///
1204/// `Access-Control-Allow-Methods` is deliberately **not** a field — it is derived
1205/// from the service's routes at emit time (the routes already enumerate the
1206/// methods; a restated list would drift). Likewise `Allow-Headers` defaults to
1207/// `content-type` (+ `Authorization` when a Bearer route exists) and is only
1208/// stored here when the author overrides it.
1209#[derive(Debug, Clone)]
1210pub struct CorsPolicy {
1211    /// The `cors { }` fields as written, in source order. Field names are
1212    /// validated against the closed set (`origins`/`headers`/`credentials`/
1213    /// `maxAge`) by the checker, not the parser.
1214    pub fields: Vec<CorsField>,
1215    pub span: Span,
1216    /// #1786: comments before the closing `}`, an orphaned doc block among
1217    /// them.
1218    pub trailing_comments: Vec<Comment>,
1219    pub trivia: Trivia,
1220}
1221
1222/// One `name: value` field inside a `cors { }` policy (v0.131).
1223#[derive(Debug, Clone)]
1224pub struct CorsField {
1225    pub name: Ident,
1226    pub value: Expr,
1227    pub span: Span,
1228    /// #1786: the field's own comments, above it and at the end of its line.
1229    pub trivia: Trivia,
1230}
1231
1232impl CorsPolicy {
1233    /// The raw value expression for a field, by name (the last one wins if a
1234    /// field is repeated — the checker flags the duplicate separately).
1235    pub fn field(&self, name: &str) -> Option<&Expr> {
1236        self.fields
1237            .iter()
1238            .rev()
1239            .find(|f| f.name.name == name)
1240            .map(|f| &f.value)
1241    }
1242
1243    /// The allowed origins — the string literals of the `origins:` list. An
1244    /// absent or malformed field yields an empty list (the checker has already
1245    /// reported the shape error; the emitter fails closed on an empty list).
1246    pub fn origins(&self) -> Vec<String> {
1247        Self::str_list(self.field("origins")).unwrap_or_default()
1248    }
1249
1250    /// `true` iff `origins` is exactly the wildcard `["*"]`.
1251    pub fn is_wildcard(&self) -> bool {
1252        let os = self.origins();
1253        os.len() == 1 && os[0] == "*"
1254    }
1255
1256    /// Whether credentialed requests are allowed (`credentials: true`); defaults
1257    /// to `false` when the field is absent.
1258    pub fn credentials(&self) -> bool {
1259        matches!(
1260            self.field("credentials").map(|e| &e.kind),
1261            Some(ExprKind::BoolLit(true))
1262        )
1263    }
1264
1265    /// The explicit `Access-Control-Allow-Headers` override, if the author gave
1266    /// a `headers:` list; `None` leaves the emitter to apply its smart default.
1267    pub fn allow_headers(&self) -> Option<Vec<String>> {
1268        self.field("headers").and_then(Self::str_list_of)
1269    }
1270
1271    /// The `Access-Control-Max-Age` in whole seconds, if a `maxAge:` duration was
1272    /// given; `None` leaves the header off (the browser default).
1273    pub fn max_age_secs(&self) -> Option<i64> {
1274        match self.field("maxAge").map(|e| &e.kind) {
1275            Some(ExprKind::DurationLit { millis, .. }) => Some(millis / 1_000),
1276            _ => None,
1277        }
1278    }
1279
1280    /// Interpret an expression as a list of string literals, if it is one.
1281    fn str_list(expr: Option<&Expr>) -> Option<Vec<String>> {
1282        expr.and_then(Self::str_list_of)
1283    }
1284
1285    fn str_list_of(expr: &Expr) -> Option<Vec<String>> {
1286        match &expr.kind {
1287            ExprKind::ListLit(items, ..) => items
1288                .iter()
1289                .map(|e| match &e.kind {
1290                    ExprKind::StrLit(s) => Some(s.clone()),
1291                    _ => None,
1292                })
1293                .collect(),
1294            _ => None,
1295        }
1296    }
1297}
1298
1299/// A security-headers policy on a `from http` service (v0.141, ADR 0164): the
1300/// `security { }` section in the service body. Parsed leniently as a list of
1301/// `name: value` fields (an unknown one is a checker diagnostic, per the CORS /
1302/// `@`-annotation precedent) and interpreted through the typed accessors below.
1303///
1304/// The closed set is `nosniff` (a `Bool`, default `true` — stamps
1305/// `X-Content-Type-Options: nosniff`) and `hsts` (a positive `Duration`, opt-in —
1306/// stamps `Strict-Transport-Security: max-age=…`). Unlike `cors`, the *safe*
1307/// header is on by default: a `from http` service with no `security { }` still
1308/// stamps `nosniff`, because a security header you have to remember to switch on
1309/// is the one you forget (ADR 0164 DECISION A).
1310#[derive(Debug, Clone)]
1311pub struct SecurityPolicy {
1312    /// The `security { }` fields as written, in source order. Field names are
1313    /// validated against the closed set (`hsts`/`nosniff`) by the checker, not
1314    /// the parser.
1315    pub fields: Vec<SecurityField>,
1316    pub span: Span,
1317    /// #1786: comments before the closing `}`, an orphaned doc block among
1318    /// them.
1319    pub trailing_comments: Vec<Comment>,
1320    pub trivia: Trivia,
1321}
1322
1323/// One `name: value` field inside a `security { }` policy (v0.141).
1324#[derive(Debug, Clone)]
1325pub struct SecurityField {
1326    pub name: Ident,
1327    pub value: Expr,
1328    pub span: Span,
1329    /// #1786: the field's own comments, above it and at the end of its line.
1330    pub trivia: Trivia,
1331}
1332
1333impl SecurityPolicy {
1334    /// The raw value expression for a field, by name (the last one wins if a
1335    /// field is repeated — the checker flags the duplicate separately).
1336    pub fn field(&self, name: &str) -> Option<&Expr> {
1337        self.fields
1338            .iter()
1339            .rev()
1340            .find(|f| f.name.name == name)
1341            .map(|f| &f.value)
1342    }
1343
1344    /// Whether `X-Content-Type-Options: nosniff` is stamped. Defaults to `true`
1345    /// (the safe default, ADR 0164 DECISION A); only an explicit `nosniff: false`
1346    /// opts out. A malformed value has already been reported by the checker; it
1347    /// falls back to the safe default here.
1348    pub fn nosniff(&self) -> bool {
1349        !matches!(
1350            self.field("nosniff").map(|e| &e.kind),
1351            Some(ExprKind::BoolLit(false))
1352        )
1353    }
1354
1355    /// The `Strict-Transport-Security` `max-age` in whole seconds, if the author
1356    /// opted in with an `hsts:` duration; `None` leaves HSTS off (the default —
1357    /// HSTS pins the browser to HTTPS and is a deliberate opt-in, DECISION A).
1358    pub fn hsts_max_age_secs(&self) -> Option<i64> {
1359        match self.field("hsts").map(|e| &e.kind) {
1360            Some(ExprKind::DurationLit { millis, .. }) => Some(millis / 1_000),
1361            _ => None,
1362        }
1363    }
1364}
1365
1366/// A request-body-size policy on a `from http` service (v0.142, ADR 0165): the
1367/// `limits { }` section in the service body. Parsed leniently as a list of
1368/// `name: value` fields (an unknown one is a checker diagnostic, per the CORS /
1369/// `security` / `@`-annotation precedent) and interpreted through the typed
1370/// accessor below.
1371///
1372/// The closed set is `maxBody` — a positive `Int` byte count (there is no byte
1373/// `Size` literal yet; a `1.mb`-style literal is a named follow-on, the
1374/// `Duration` playbook). Unlike `security`, this is opt-in: a service with no
1375/// `limits { }` (and no route `@limit`) has no cap and emits byte-for-byte
1376/// unchanged output (ADR 0165 DECISION E — the CORS posture).
1377#[derive(Debug, Clone)]
1378pub struct LimitsPolicy {
1379    /// The `limits { }` fields as written, in source order. Field names are
1380    /// validated against the closed set (`maxBody`) by the checker, not the
1381    /// parser.
1382    pub fields: Vec<LimitsField>,
1383    pub span: Span,
1384    /// #1786: comments before the closing `}`, an orphaned doc block among
1385    /// them.
1386    pub trailing_comments: Vec<Comment>,
1387    pub trivia: Trivia,
1388}
1389
1390/// One `name: value` field inside a `limits { }` policy (v0.142).
1391#[derive(Debug, Clone)]
1392pub struct LimitsField {
1393    pub name: Ident,
1394    pub value: Expr,
1395    pub span: Span,
1396    /// #1786: the field's own comments, above it and at the end of its line.
1397    pub trivia: Trivia,
1398}
1399
1400impl LimitsPolicy {
1401    /// The raw value expression for a field, by name (the last one wins if a
1402    /// field is repeated — the checker flags the duplicate separately).
1403    pub fn field(&self, name: &str) -> Option<&Expr> {
1404        self.fields
1405            .iter()
1406            .rev()
1407            .find(|f| f.name.name == name)
1408            .map(|f| &f.value)
1409    }
1410
1411    /// The service-wide maximum request-body size in bytes, if the author gave a
1412    /// positive `maxBody:` `Int` literal; `None` leaves the service without a
1413    /// default cap. A malformed or non-positive value has already been reported
1414    /// by the checker; it falls back to `None` here (no cap).
1415    pub fn max_body(&self) -> Option<i64> {
1416        match self.field("maxBody").map(|e| &e.kind) {
1417            Some(ExprKind::IntLit { value, .. }) if *value > 0 => Some(*value),
1418            _ => None,
1419        }
1420    }
1421
1422    /// #3276: the service-wide per-file ceiling of a `@multipart` route, in bytes
1423    /// (`maxFile:`); `None` leaves a file part bounded by the body cap alone.
1424    pub fn max_file(&self) -> Option<i64> {
1425        match self.field("maxFile").map(|e| &e.kind) {
1426            Some(ExprKind::IntLit { value, .. }) if *value > 0 => Some(*value),
1427            _ => None,
1428        }
1429    }
1430
1431    /// #3276: the service-wide ceiling on the parts of one `@multipart` request
1432    /// (`maxParts:`); `None` takes [`DEFAULT_MAX_PARTS`].
1433    pub fn max_parts(&self) -> Option<i64> {
1434        match self.field("maxParts").map(|e| &e.kind) {
1435            Some(ExprKind::IntLit { value, .. }) if *value > 0 => Some(*value),
1436            _ => None,
1437        }
1438    }
1439}
1440
1441/// #3276: the parts a `@multipart` request may carry when no `maxParts` says
1442/// otherwise.
1443pub const DEFAULT_MAX_PARTS: i64 = 64;
1444
1445/// How an `Option` is written in an HTTP response body (#2858).
1446#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1447pub enum JsonOptions {
1448    /// Bynk's tagged form: `{"kind": "Some", "value": v}` / `{"kind": "None"}`.
1449    #[default]
1450    Tagged,
1451    /// Plain JSON: `Some(v)` is `v` and `None` is `null`.
1452    Plain,
1453}
1454
1455impl JsonOptions {
1456    /// Read a bare `tagged` / `plain` identifier, the value of `options:`.
1457    pub fn from_expr(e: &Expr) -> Option<JsonOptions> {
1458        match &e.kind {
1459            ExprKind::Ident(n) if n.name == "tagged" => Some(JsonOptions::Tagged),
1460            ExprKind::Ident(n) if n.name == "plain" => Some(JsonOptions::Plain),
1461            _ => None,
1462        }
1463    }
1464}
1465
1466/// A response-JSON policy on a `from http` service (#2858): the
1467/// `json { }` section in the service body. Parsed leniently as a list of
1468/// `name: value` fields (as `limits { }`); the closed set is `options`, whose
1469/// value is the bare identifier `tagged` or `plain`.
1470#[derive(Debug, Clone)]
1471pub struct JsonPolicy {
1472    pub fields: Vec<JsonField>,
1473    pub span: Span,
1474    pub trailing_comments: Vec<Comment>,
1475    pub trivia: Trivia,
1476}
1477
1478/// One `name: value` field inside a `json { }` policy.
1479#[derive(Debug, Clone)]
1480pub struct JsonField {
1481    pub name: Ident,
1482    pub value: Expr,
1483    pub span: Span,
1484    pub trivia: Trivia,
1485}
1486
1487impl JsonPolicy {
1488    pub fn field(&self, name: &str) -> Option<&Expr> {
1489        self.fields
1490            .iter()
1491            .rev()
1492            .find(|f| f.name.name == name)
1493            .map(|f| &f.value)
1494    }
1495
1496    /// The service-wide `options:` mode; a malformed value (already reported by
1497    /// the checker) reads as the default, tagged.
1498    pub fn options(&self) -> JsonOptions {
1499        self.field("options")
1500            .and_then(JsonOptions::from_expr)
1501            .unwrap_or_default()
1502    }
1503}
1504
1505/// The mode a route's response body is written in: its own `@json(options:)`
1506/// wins over the service's `json { options: }`, which wins over the tagged
1507/// default.
1508pub fn effective_json_options(service: Option<&JsonPolicy>, h: &Handler) -> JsonOptions {
1509    h.json_options()
1510        .or_else(|| service.map(JsonPolicy::options))
1511        .unwrap_or_default()
1512}
1513
1514/// The protocol a service conforms to — declared on the header via
1515/// `from <protocol>` (v0.44). `Call` is the default (no `from` clause): a
1516/// contract-mediated internal-RPC surface, not a wire protocol. Multi-endpoint
1517/// protocols (`Http`, `Cron`) carry no binding — the endpoint lives on each
1518/// handler; single-binding `Queue` carries its queue name.
1519#[derive(Debug, Clone)]
1520pub enum ServiceProtocol {
1521    /// No `from` clause: the service holds `on call` handlers only.
1522    Call,
1523    /// `from http` — many routes; each handler is `on <Method>("route")`.
1524    Http,
1525    /// `from cron` — many schedules; each handler is `on schedule("expr")`.
1526    Cron,
1527    /// `from queue("name")` — one bound queue; handlers are `on message(...)`.
1528    Queue { name: String },
1529    /// `from websocket(in: ClientFrame, out: ServerFrame)` — a held WebSocket
1530    /// connection (v0.103, real-time track slice 3). `in_type` is the inbound
1531    /// frame type (client→server, decoded and routed as typed agent messages);
1532    /// `out_type` is the server→client frame type the held `Connection[out_type]`
1533    /// carries. The service holds exactly one `on open` handler (edge auth via
1534    /// `by`, then transfer of the connection to an agent).
1535    WebSocket { in_type: TypeRef, out_type: TypeRef },
1536    /// `from Events(E)` or `from Events(E { field: value, .. })`, optionally
1537    /// followed by `via schema(N)` — a subscriber to event type `E`,
1538    /// optionally filtered by a structural payload pattern (Events track,
1539    /// slice 0 spine #936; the pattern is slice 1) and/or the envelope's
1540    /// `schemaVersion` (slice 4). `Events`, capitalised, is matched as plain
1541    /// `Ident` text the same way `websocket` is — it names the `Events`
1542    /// capability directly (every first-party capability is already an
1543    /// unreserved PascalCase identifier), not a built-in type name, so no
1544    /// lexer reservation. `pattern` and `schema_dispatch` are independent:
1545    /// a service may carry either, both, or neither.
1546    Events {
1547        event_type: TypeRef,
1548        pattern: Option<EventPattern>,
1549        schema_dispatch: Option<SchemaDispatch>,
1550    },
1551    /// `from email("[email protected]")` or `from email("*@shop.example")` —
1552    /// inbound email (#3328, ADR 0079's seventh member). `address` is the
1553    /// literal recipient address this service claims, or `*@domain` for the
1554    /// domain's catch-all. `email` is a contextual identifier, matched as plain
1555    /// `Ident` text the way `websocket` is, so no lexer reservation. The
1556    /// service's handler is `on message(mail: InboundEmail) ->
1557    /// Effect[EmailVerdict]`.
1558    Email { address: String },
1559}
1560
1561/// An agent declaration (v0.5 §3.6). Agents are state-bearing entities
1562/// with their own handlers.
1563#[derive(Debug, Clone)]
1564pub struct AgentDecl {
1565    pub name: Ident,
1566    /// State-migrations S3 (#2248): `agent New replaces Old` — the class
1567    /// `Old` is renamed to this one, its stored data moving with it.
1568    pub replaces: Option<Ident>,
1569    /// `key id: Type` — the identifier-typed value identifying instances.
1570    pub key_name: Ident,
1571    pub key_type: TypeRef,
1572    /// #1788: comments above the `key` line and at its end. A comment on the
1573    /// agent's `{` line leads the key too.
1574    pub key_trivia: Trivia,
1575    /// `store` fields (v0.81, storage track) — each an access-pattern slot of a
1576    /// declared storage kind (`Cell`/`Map`/…). The successor to the removed
1577    /// `state { }` record (ADR 0108); every agent declares its state this way.
1578    pub store_fields: Vec<StoreField>,
1579    /// Invariants (v0.80 §14) — universally-quantified predicates over the
1580    /// agent's `store` fields. The phase sits between the fields and the
1581    /// handlers; each is checked against the state staged by a handler's writes
1582    /// before it commits.
1583    pub invariants: Vec<Invariant>,
1584    /// Step invariants (v0.116 §, testing track slice 4) — named predicates over
1585    /// the pre-/post-commit state *pair* (`old`/`new`), checked at the commit
1586    /// boundary beside [`invariants`], from the second commit onward. Widen the
1587    /// invariant subject from a snapshot to a step (ADR 0144 — one predicate
1588    /// surface).
1589    ///
1590    /// [`invariants`]: AgentDecl::invariants
1591    pub transitions: Vec<Transition>,
1592    /// State-migrations S2 (#2224, track §3.3): `migrate from N (old: T) { … }`
1593    /// steps, each carrying a stored record from lock version `N` to the
1594    /// current shape. Declared in the phase beside invariants and transitions.
1595    pub migrations: Vec<MigrateDecl>,
1596    pub handlers: Vec<Handler>,
1597    pub documentation: Option<Doc>,
1598    pub span: Span,
1599    /// #1756: comments before the closing `}`, an orphaned doc block among
1600    /// them, so the formatter keeps them.
1601    pub trailing_comments: Vec<Comment>,
1602    pub trivia: Trivia,
1603}
1604
1605/// A migration step (state-migrations S2, #2224): `migrate from N (old: T) {
1606/// … }`. `old` names a record type declaring the version-`N` fields the step
1607/// reads; the body assigns current `store` fields with record-literal
1608/// semantics (each at most once, order-free, a bare field reads its carried
1609/// value) and acknowledges removed or uncovered fields with `drop`.
1610#[derive(Debug, Clone)]
1611pub struct MigrateDecl {
1612    /// The `migrate` keyword.
1613    pub keyword: Span,
1614    /// The lock version `N` this step reads, and its literal's span.
1615    pub from: i64,
1616    pub from_span: Span,
1617    /// `(old: T)` — absent for a step that reads nothing.
1618    pub old: Option<MigrateOld>,
1619    pub items: Vec<MigrateItem>,
1620    /// #1756-style: comments before the body's closing `}`.
1621    pub trailing_comments: Vec<Comment>,
1622    pub documentation: Option<Doc>,
1623    pub span: Span,
1624    pub trivia: Trivia,
1625}
1626
1627/// A step's `(old: T)` parameter.
1628#[derive(Debug, Clone)]
1629pub struct MigrateOld {
1630    pub name: Ident,
1631    pub type_ref: TypeRef,
1632}
1633
1634/// One item of a migration step's body.
1635// A step holds a handful of items, so the size gap between `Let`/`Assign` and
1636// the small `Drop` costs nothing worth boxing every consumer's match for.
1637#[allow(clippy::large_enum_variant)]
1638#[derive(Debug, Clone)]
1639pub enum MigrateItem {
1640    /// `let x = e` — a pure local binding, visible to later items.
1641    Let(LetStmt),
1642    /// `f := e` — the current `store` field `f` takes `e`.
1643    Assign(AssignStmt),
1644    /// `drop f` — the stored value of `f` is discarded on purpose.
1645    Drop(MigrateDrop),
1646}
1647
1648/// `drop f` inside a migration step.
1649#[derive(Debug, Clone)]
1650pub struct MigrateDrop {
1651    pub keyword: Span,
1652    pub field: Ident,
1653    pub span: Span,
1654    pub trivia: Trivia,
1655}
1656
1657/// A `store` field (v0.81, storage track). Each is an access-pattern slot of a
1658/// declared storage kind: `store <name>: <Kind>[…] [@annotations] [= <init>]`.
1659/// The kind and its element type are carried as an ordinary [`TypeRef`]
1660/// (`Cell[Int]`, `Map[K, V]`); the checker restricts which heads are storage
1661/// kinds. Access-pattern annotations (`@indexed`, …) parse into [`annotations`]
1662/// (v0.85, ADR 0111); the checker validates them against the closed registry.
1663///
1664/// [`annotations`]: StoreField::annotations
1665#[derive(Debug, Clone)]
1666pub struct StoreField {
1667    pub name: Ident,
1668    /// The storage kind and its element type(s): `Cell[Int]`, `Map[K, V]`. A
1669    /// dedicated [`StoreKind`] rather than a [`TypeRef`] — storage kinds are not
1670    /// value types, and the checker dispatches kind-aware operations on the head.
1671    pub kind: StoreKind,
1672    /// Storage annotations on the field (v0.85, ADR 0111): `@ttl(5.minutes)`,
1673    /// `@indexed(by: orderId)`. Parsed in declaration order (after the kind,
1674    /// before the initialiser); the checker validates names against the closed
1675    /// registry and gates each to the slice that implements it.
1676    pub annotations: Vec<Annotation>,
1677    /// The fresh-key initial value (`= expr`), if given — same disposition as a
1678    /// `state` field's initialiser (ADRs 0003/0004 carry forward).
1679    pub init: Option<Expr>,
1680    pub documentation: Option<Doc>,
1681    pub span: Span,
1682    pub trivia: Trivia,
1683}
1684
1685/// A storage annotation on a `store` field (v0.85, storage track; ADR 0111):
1686/// `@<name>(<args>)`. The `name` is matched against the closed registry
1687/// (`@indexed`/`@ttl`/`@retain`/`@bounded`) by the checker; the grammar accepts
1688/// any identifier so an unknown name is a checker diagnostic, not a parse error.
1689/// Arguments are compile-time metadata, restricted to literals (and the `by:`
1690/// field-name labels of `@indexed`) by the checker per ADR 0111 D4.
1691#[derive(Debug, Clone)]
1692pub struct Annotation {
1693    pub name: Ident,
1694    pub args: Vec<AnnotationArg>,
1695    pub span: Span,
1696}
1697
1698/// A single annotation argument (v0.85; ADR 0111): an optional `label:` followed
1699/// by a value expression — `by: orderId` (labelled) or `5.minutes` (positional).
1700/// The value is parsed as an ordinary [`Expr`] so the duration-literal form
1701/// (`5.minutes`, landing with the `Duration` slice) needs no special grammar;
1702/// the checker restricts it to a literal where the annotation is functional.
1703#[derive(Debug, Clone)]
1704pub struct AnnotationArg {
1705    pub label: Option<Ident>,
1706    pub value: Expr,
1707    pub span: Span,
1708    /// #3445: set when `value` is the literal a bare constant reference
1709    /// resolved to (`annotation_consts`), not text the author wrote. `value`
1710    /// keeps the reference's span, so a diagnostic points where the author can
1711    /// act; this names the constant and where it is declared.
1712    pub from_const: Option<ConstRef>,
1713}
1714
1715/// #3445: the constant an annotation argument named before the resolution pass
1716/// replaced it with the literal it denotes.
1717#[derive(Debug, Clone)]
1718pub struct ConstRef {
1719    /// The reference as written (its span is the argument's).
1720    pub name: Ident,
1721    /// The span of the constant's declaration, when it is in the same file as
1722    /// the reference (a span is an offset into one file); `None` for a constant
1723    /// from a sibling file or a used commons.
1724    pub decl_span: Option<Span>,
1725}
1726
1727/// A storage kind applied to its element type(s) (v0.81): `Cell[Int]`,
1728/// `Map[ReservationId, Reservation]`. The `head` is the kind name (`Cell`,
1729/// `Map`, `Set`, `Log`, `Queue`, `Cache`); the checker validates it against the
1730/// closed catalogue. Element types are ordinary [`TypeRef`]s. Refined element
1731/// types (`Cell[Int where NonNegative]`) ride a later slice (parse_type_ref does
1732/// not yet accept an inline refinement in type-argument position).
1733#[derive(Debug, Clone)]
1734pub struct StoreKind {
1735    pub head: Ident,
1736    pub args: Vec<TypeRef>,
1737    pub span: Span,
1738}
1739
1740/// An agent invariant (v0.80 §14). A named predicate over the agent's state
1741/// fields that must hold of every committed state; a commit that would violate
1742/// it faults (`InvariantViolation`) before the state is persisted. The
1743/// predicate references state fields by bare name, mirroring the design-notes
1744/// worked examples (`status == Paid implies paymentRef.isSome()`).
1745#[derive(Debug, Clone)]
1746pub struct Invariant {
1747    pub name: Ident,
1748    /// The predicate expression — an ordinary `Bool`-typed expression over the
1749    /// state fields, plus `implies` and `is`. The parsed-predicate-on-a-
1750    /// declaration shape mirrors [`ActorRefinement::predicate`].
1751    pub predicate: Expr,
1752    pub documentation: Option<Doc>,
1753    pub span: Span,
1754    pub trivia: Trivia,
1755}
1756
1757/// An agent step invariant (v0.116 §, testing track slice 4). A named predicate
1758/// over the *pair* of committed states — the pre-commit `old` and the proposed
1759/// `new`, each the agent's state record — that must hold of every state move; a
1760/// commit that would violate it faults (`InvariantViolation`) before the state is
1761/// persisted, exactly as a snapshot [`Invariant`] does. Widens the invariant
1762/// subject from a snapshot to a step (ADR 0144 — one predicate surface); the
1763/// predicate reuses the invariant surface (`implies`/`is`/pure methods) with
1764/// `old`/`new` bound contextually (`old.status is Paid implies new.status is
1765/// Paid`).
1766#[derive(Debug, Clone)]
1767pub struct Transition {
1768    pub name: Ident,
1769    /// The predicate expression — an ordinary `Bool`-typed expression over the
1770    /// `old` and `new` state records, with `implies`/`is` and pure methods,
1771    /// mirroring [`Invariant`].
1772    pub predicate: Expr,
1773    pub documentation: Option<Doc>,
1774    pub span: Span,
1775    pub trivia: Trivia,
1776}
1777
1778/// A function contract clause (v0.115 §, testing track slice 3). A named
1779/// predicate on a `fn` signature — a `requires` (precondition) or `ensures`
1780/// (postcondition). A contract is the invariant predicate attached to a
1781/// function (ADR 0144 — one predicate surface): the predicate is a pure `Bool`
1782/// expression over the parameters (`requires`) or the parameters plus `result`
1783/// (`ensures`), with `implies`/`is` and pure methods, mirroring [`Invariant`].
1784/// The name rides the failure report and the redundant-test dedup.
1785#[derive(Debug, Clone)]
1786pub struct Contract {
1787    pub name: Ident,
1788    /// The predicate expression — an ordinary `Bool`-typed expression over the
1789    /// parameters (and, for an `ensures`, the contextual `result` binding).
1790    pub predicate: Expr,
1791    pub span: Span,
1792}
1793
1794/// An actor declaration (v0.45 §3.7). An actor is a nominal *contract type*
1795/// describing an external party at a boundary — not a runnable entity. A
1796/// handler consumes an actor on its `by` clause; the boundary verifies the
1797/// declared `auth` scheme and mints a sealed identity (`name.identity`).
1798#[derive(Debug, Clone)]
1799pub struct ActorDecl {
1800    pub name: Ident,
1801    /// The authentication scheme from `auth = <Scheme>`, stored as the raw
1802    /// identifier. The checker classifies it: `None`/`Internal`/`Bearer` are
1803    /// admitted; `Signature` is reserved-and-rejected
1804    /// (`bynk.actor.scheme_unsupported`); anything else is
1805    /// `bynk.actor.unknown_scheme`. `None` for the refinement form.
1806    pub auth: Option<Ident>,
1807    /// The scheme's keyed config from `auth = Scheme(key = value, …)` (v0.47
1808    /// `Bearer(secret = "…")`; v0.51 generalised for `Signature(secret, header,
1809    /// timestamp?, tolerance?)`). Empty for schemes/forms with no config. The
1810    /// checker validates which keys each scheme requires/allows.
1811    pub auth_config: Vec<SchemeArg>,
1812    /// The optional identity type from `, identity = <T>`. Absent ⇒ the
1813    /// scheme default (`()` for `None`; a sealed `CallerId` for the `Internal`
1814    /// `on call` channel, `()` for other `Internal` channels).
1815    pub identity: Option<TypeRef>,
1816    /// The refinement form `actor Admin = Base where <predicate>` — narrows a
1817    /// base actor by an authorisation claim (ADR 0091). The predicate is parsed
1818    /// as a full expression; a static-semantics rule restricts it to the closed
1819    /// actor-claim catalogue (`hasClaim`/`claimEquals` over a `Bearer` base;
1820    /// `bynk.actor.refinement_predicate_unsupported` / `…_base_unsupported`).
1821    pub refinement: Option<ActorRefinement>,
1822    pub documentation: Option<Doc>,
1823    pub span: Span,
1824    pub trivia: Trivia,
1825    /// #1797: comments above the `auth` entry and at the end of its line. A
1826    /// comment on the actor's `{` line leads `auth` too. Empty for the
1827    /// refinement form.
1828    pub auth_trivia: Trivia,
1829    /// #1797: comments above the `identity` entry and at the end of its line.
1830    /// Empty when there is no `identity`.
1831    pub identity_trivia: Trivia,
1832    /// #1797: comments before the actor body's closing `}`.
1833    pub trailing_comments: Vec<Comment>,
1834}
1835
1836impl ActorDecl {
1837    /// The value of a scheme config arg by key, if present (e.g. `secret`,
1838    /// `header`).
1839    pub fn scheme_arg(&self, key: &str) -> Option<&SchemeArg> {
1840        self.auth_config.iter().find(|a| a.key.name == key)
1841    }
1842}
1843
1844/// One `key = value` argument in a scheme config (`Scheme(key = value, …)`).
1845#[derive(Debug, Clone)]
1846pub struct SchemeArg {
1847    pub key: Ident,
1848    pub value: SchemeArgValue,
1849    /// Span of the value, for diagnostics.
1850    pub span: Span,
1851}
1852
1853/// A scheme config arg value — a string literal, an integer, a duration
1854/// literal (`12.hours`, #3386) or a bare identifier (`sameSite = Lax`, #3386).
1855#[derive(Debug, Clone)]
1856pub enum SchemeArgValue {
1857    Str(String),
1858    Int(i64),
1859    /// A duration literal as written: the magnitude, its unit, and the
1860    /// resolved milliseconds.
1861    Duration {
1862        value: i64,
1863        unit: DurationUnit,
1864        millis: i64,
1865    },
1866    /// A bare identifier naming one of a closed set of variants.
1867    Ident(String),
1868}
1869
1870impl SchemeArgValue {
1871    pub fn as_str(&self) -> Option<&str> {
1872        match self {
1873            SchemeArgValue::Str(s) => Some(s),
1874            _ => None,
1875        }
1876    }
1877    pub fn as_int(&self) -> Option<i64> {
1878        match self {
1879            SchemeArgValue::Int(n) => Some(*n),
1880            _ => None,
1881        }
1882    }
1883    /// The duration in milliseconds, for a duration literal.
1884    pub fn as_duration_millis(&self) -> Option<i64> {
1885        match self {
1886            SchemeArgValue::Duration { millis, .. } => Some(*millis),
1887            _ => None,
1888        }
1889    }
1890    /// The identifier, for a bare-identifier value.
1891    pub fn as_ident(&self) -> Option<&str> {
1892        match self {
1893            SchemeArgValue::Ident(s) => Some(s),
1894            _ => None,
1895        }
1896    }
1897}
1898
1899/// The reserved refinement form `actor Admin = User where <predicate>` (Q3).
1900/// Parsed in Foundations so the grammar is fixed; admission is a later slice.
1901#[derive(Debug, Clone)]
1902pub struct ActorRefinement {
1903    /// The base actor being refined.
1904    pub base: Ident,
1905    /// The `where` predicate. Parsed but not yet checked.
1906    pub predicate: Expr,
1907    pub span: Span,
1908}
1909
1910/// The `by (<binder>:)? <Actor>` clause on a handler (v0.45; binder optional in
1911/// v0.50). Names the actor contract the handler consumes; when a `binder` is
1912/// given, the verified identity binds to it and is read as `binder.identity`.
1913/// Omitting the binder (`by <Actor>`) declares-and-verifies the contract without
1914/// capturing the identity — for anonymous or verify-and-discard handlers. Sits
1915/// after the protocol config and before the parameters.
1916#[derive(Debug, Clone)]
1917pub struct ByClause {
1918    /// The identity binder, if the handler consumes the identity. `None` for the
1919    /// binder-less `by <Actor>` form. Required when `actors` names more than one
1920    /// (a sum is resolved by matching on the bound actor).
1921    pub binder: Option<Ident>,
1922    /// The actor contract(s) referenced — each a local actor decl or a prelude
1923    /// actor. A single name is the ordinary single-actor handler; more than one
1924    /// (`by who: A | B`, v0.52) is an **ordered sum of peer actors** resolved
1925    /// first-wins, the body matching on the resolved actor. Always non-empty.
1926    pub actors: Vec<Ident>,
1927    pub span: Span,
1928}
1929
1930impl ByClause {
1931    /// The first (and, for a single-actor handler, only) actor contract named.
1932    pub fn primary(&self) -> &Ident {
1933        &self.actors[0]
1934    }
1935    /// Whether this `by` clause names an ordered sum of peer actors (`A | B`).
1936    pub fn is_sum(&self) -> bool {
1937        self.actors.len() > 1
1938    }
1939}
1940
1941/// v0.182 (testing-the-boundary Slice A, #664): a call-site actor clause on a
1942/// test-body `let x <- <service address> by <Actor>(<identity>)`. Distinct from
1943/// [`ByClause`] (the handler/header form): the *declaration* names which actor
1944/// may call and binds the verified identity, whereas the *call site* names the
1945/// actor the case is acting as and supplies the identity value. A unit-identity
1946/// actor (`Visitor`, and cron/queue's internal actors) carries no `identity`.
1947#[derive(Debug, Clone)]
1948pub struct CallSiteActor {
1949    /// The actor the case acts as — a local actor decl or a prelude actor.
1950    pub actor: Ident,
1951    /// The supplied identity value (`"bob"` in `by User("bob")`), or `None` for a
1952    /// unit-identity actor written `by Visitor` with no argument.
1953    pub identity: Option<Box<Expr>>,
1954    /// #2380 (L5): the verified-token claims an `Oidc` actor's handler reads
1955    /// (`by Workload("id", TokenClaims.of([…]))`), at the in-process tiers.
1956    pub claims: Option<Box<Expr>>,
1957    /// An id of this clause's own (1A.33), allocated from the expression counter so the
1958    /// checker can record what the principal resolves to beside the call's own callees.
1959    pub id: ExprId,
1960    pub span: Span,
1961}
1962
1963/// A handler block — `on call(args) -> T given C1, C2 { body }`.
1964/// Used by both services and agents.
1965#[derive(Debug, Clone)]
1966pub struct Handler {
1967    pub kind: HandlerKind,
1968    /// Handler-position annotations (v0.140, ADR 0163): `@cache(maxAge: 5.minutes)`
1969    /// written immediately before `on <METHOD>(…)`. Reuses the [`Annotation`] AST
1970    /// shared with `store` fields (ADR 0111); the grammar accepts any `@name(args)`
1971    /// so an unknown name is a project-validation diagnostic, not a parse error. The
1972    /// first handler-position annotation surface — empty for every handler that
1973    /// carries none.
1974    pub annotations: Vec<Annotation>,
1975    /// For agent handlers, the method-style handler name (e.g.
1976    /// `on call addItem(...)`). For service handlers, this is None (just
1977    /// `on call(...)`).
1978    pub method_name: Option<Ident>,
1979    /// The `by <binder>: <Actor>` clause (v0.45), if present. Service handlers
1980    /// only; an absent clause inherits the protocol's default actor.
1981    pub by_clause: Option<ByClause>,
1982    pub params: Vec<Param>,
1983    pub return_type: TypeRef,
1984    pub given: Vec<CapRef>,
1985    pub body: Block,
1986    pub documentation: Option<Doc>,
1987    pub span: Span,
1988    pub trivia: Trivia,
1989}
1990
1991impl Handler {
1992    /// The handler's own `@limit(maxBody:)` byte cap, if it carries a well-formed
1993    /// one (ADR 0165). The checker rejects a malformed `@limit`, so a bad value
1994    /// reads as no cap here.
1995    pub fn limit_max_body(&self) -> Option<i64> {
1996        let ann = self.annotations.iter().find(|a| a.name.name == "limit")?;
1997        ann.args
1998            .iter()
1999            .find_map(|arg| match (&arg.label, &arg.value.kind) {
2000                (Some(l), ExprKind::IntLit { value, .. }) if l.name == "maxBody" && *value > 0 => {
2001                    Some(*value)
2002                }
2003                _ => None,
2004            })
2005    }
2006
2007    /// #3276: the handler's own `@limit(maxFile:)` per-file byte cap, if any.
2008    pub fn limit_max_file(&self) -> Option<i64> {
2009        self.limit_int_arg("maxFile")
2010    }
2011
2012    /// #3276: the handler's own `@limit(maxParts:)` part-count cap, if any.
2013    pub fn limit_max_parts(&self) -> Option<i64> {
2014        self.limit_int_arg("maxParts")
2015    }
2016
2017    fn limit_int_arg(&self, name: &str) -> Option<i64> {
2018        let ann = self.annotations.iter().find(|a| a.name.name == "limit")?;
2019        ann.args
2020            .iter()
2021            .find_map(|arg| match (&arg.label, &arg.value.kind) {
2022                (Some(l), ExprKind::IntLit { value, .. }) if l.name == name && *value > 0 => {
2023                    Some(*value)
2024                }
2025                _ => None,
2026            })
2027    }
2028
2029    /// The handler's own `@json(options:)` mode, if it carries a well-formed one
2030    /// (#2858). The checker rejects a malformed `@json`, so a bad value reads as
2031    /// no override here.
2032    pub fn json_options(&self) -> Option<JsonOptions> {
2033        let ann = self.annotations.iter().find(|a| a.name.name == "json")?;
2034        ann.args.iter().find_map(|arg| match &arg.label {
2035            Some(l) if l.name == "options" => JsonOptions::from_expr(&arg.value),
2036            _ => None,
2037        })
2038    }
2039
2040    /// The media type a `@raw(contentType:)` handler declares: `Some` marks the
2041    /// handler's `body: Bytes` as the raw request body (request-side counterpart of
2042    /// ADR 0143). `"*/*"` accepts any content type. A malformed `@raw` is a checker
2043    /// error, so a missing or non-literal `contentType` reads as not raw here.
2044    pub fn raw_content_type(&self) -> Option<&str> {
2045        let ann = self.annotations.iter().find(|a| a.name.name == "raw")?;
2046        ann.args
2047            .iter()
2048            .find_map(|arg| match (&arg.label, &arg.value.kind) {
2049                (Some(l), ExprKind::StrLit(s)) if l.name == "contentType" && is_media_type(s) => {
2050                    Some(s.as_str())
2051                }
2052                _ => None,
2053            })
2054    }
2055}
2056
2057/// Whether `s` is a media type a `@raw(contentType:)` may declare: `type/subtype`
2058/// of RFC 7230 token characters, or the wildcard `*/*`. Parameters (`; charset=…`)
2059/// are not part of the declaration.
2060pub fn is_media_type(s: &str) -> bool {
2061    fn token(t: &str) -> bool {
2062        !t.is_empty()
2063            && t.bytes()
2064                .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
2065    }
2066    s == "*/*"
2067        || s.split_once('/')
2068            .is_some_and(|(t, sub)| token(t) && token(sub) && t != "*" && sub != "*")
2069}
2070
2071/// `Hash` (P8.5, #1516): a `HandlerKind` value is a body-free, span-free
2072/// discriminant, added so a `DefId`-keyed handler identity could carry it
2073/// (`bynk-check`'s former `queries::HandlerDefId`, deleted by #1537 — kept
2074/// here because the derive is harmless, and a rebuild against ADR 0417's
2075/// shape would need it again). Purely additive; no existing
2076/// caller matches on hashing behaviour.
2077#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2078pub enum HandlerKind {
2079    /// `on call(...)` — typed RPC (the only kind in v0.5).
2080    Call,
2081    /// `on http METHOD "path"` — external-facing HTTP route (v0.9).
2082    Http { method: HttpMethod, path: String },
2083    /// `on cron "expr"` — scheduled task; `expr` is a 5-field cron
2084    /// expression (v0.10a).
2085    Cron { expr: String },
2086    /// `on message(m: T)` — a message off the service's bound queue. The queue
2087    /// binding lives on the service's `ServiceProtocol::Queue` (v0.44).
2088    Message,
2089    /// `on open ...` — the WebSocket upgrade handler (v0.103, real-time track
2090    /// slice 3). Exactly one per `from websocket` service; carries a mandatory
2091    /// `by` clause (edge auth) and receives a fresh owned `Connection[out]`.
2092    Open,
2093    /// `on close ...` — the WebSocket close handler (v0.106, real-time track slice
2094    /// 3b-iii). Optional, ≤1 per `from websocket` service; runs when the socket
2095    /// closes. Like `on open`, edge-authenticated (`by`), with the identity/params
2096    /// recovered from the socket attachment (set at `on open`). (A `from websocket`
2097    /// `on message` reuses [`HandlerKind::Message`], disambiguated by the protocol.)
2098    Close,
2099    /// `on event(e: E)` — one emission of a `from Events(E)` service's
2100    /// subscribed event type (Events track, slice 0, spine #936). No
2101    /// envelope parameter yet (slice 2). `event`, like `message`/`open`/
2102    /// `close`/`schedule`, is matched by plain ident text at the fixed
2103    /// position right after `on`, with no lexer reservation — an ordinary
2104    /// identifier everywhere else in the grammar.
2105    Event,
2106    /// `on rejected(why: BoundaryRejection)` — renders the router's own
2107    /// rejections (`400`, `405`, `413`, `415`) of a `from http` service in the
2108    /// service's shape, keeping their status (#2341, decision C). At most one
2109    /// per service; no `by`, no `given`.
2110    Rejected,
2111}
2112
2113/// HTTP methods supported by `on http` handlers (v0.9).
2114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2115pub enum HttpMethod {
2116    Get,
2117    Post,
2118    Put,
2119    Patch,
2120    Delete,
2121}
2122
2123impl HttpMethod {
2124    pub fn as_str(self) -> &'static str {
2125        match self {
2126            HttpMethod::Get => "GET",
2127            HttpMethod::Post => "POST",
2128            HttpMethod::Put => "PUT",
2129            HttpMethod::Patch => "PATCH",
2130            HttpMethod::Delete => "DELETE",
2131        }
2132    }
2133
2134    pub fn from_ident(s: &str) -> Option<HttpMethod> {
2135        match s {
2136            "GET" => Some(HttpMethod::Get),
2137            "POST" => Some(HttpMethod::Post),
2138            "PUT" => Some(HttpMethod::Put),
2139            "PATCH" => Some(HttpMethod::Patch),
2140            "DELETE" => Some(HttpMethod::Delete),
2141            _ => None,
2142        }
2143    }
2144
2145    /// True if this method conventionally has no request body.
2146    pub fn forbids_body(self) -> bool {
2147        matches!(self, HttpMethod::Get | HttpMethod::Delete)
2148    }
2149}
2150
2151/// Payload shape of an `HttpResult[T]` variant (v0.9 §3.3).
2152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2153pub enum HttpVariantPayload {
2154    /// No payload (e.g. `NoContent`, `Unauthorized`).
2155    None,
2156    /// Carries a value of the `HttpResult` type parameter `T`.
2157    Value,
2158    /// Carries a `String` message (e.g. `BadRequest`, `Conflict`).
2159    Message,
2160    /// Carries a `String` target URL, emitted as a `Location` header — the
2161    /// redirect variants (`Found`, `SeeOther`, `PermanentRedirect`, …).
2162    Location,
2163    /// Carries a `Stream[String]`, emitted as an SSE (`text/event-stream`)
2164    /// streaming body — the `Streaming` (200) variant (v0.101, real-time track
2165    /// slice 1).
2166    Streamed,
2167    /// Carries `(body: Bytes, contentType: String)` — the author-owned raw body
2168    /// written straight into the response with the declared `content-type` and
2169    /// **no codec** (the typed-wire guarantee is deliberately off). The `Raw`
2170    /// (200) variant (v0.111), the first two-argument payload shape, and
2171    /// `RawCreated` (201, #2403).
2172    Raw,
2173    /// Carries `(body: Bytes, contentType: String, etag: String)` — a raw body
2174    /// with the handler's own entity tag, sent as the response's `ETag` and
2175    /// validated at run time. The `RawTagged` (200) variant (caching raw
2176    /// responses), for a body too large to hash or a validator the handler has
2177    /// for free (a content hash, an object store's `etag`).
2178    RawTagged,
2179    /// Carries `(body: Stream[Bytes], contentType: String)` — a raw body
2180    /// streamed into the response as its chunks arrive, with no codec and no
2181    /// validator: the bytes can't be hashed without buffering them. The
2182    /// `RawStreamed` (200) variant (K-streams, #2623). Its status is sent
2183    /// before the first chunk, so a fault mid-body aborts the response.
2184    RawStreamed,
2185    /// Carries `(status: ErrorStatus, body: Bytes, contentType: String)` — an
2186    /// error status the author chooses, with an author-owned body and no codec
2187    /// (#2341, L4). The `RawError` variant; `status` is one of the vocabulary's
2188    /// 4xx/5xx variant names ([`error_status`]), resolved at compile time.
2189    RawError,
2190}
2191
2192/// One variant of the built-in `HttpResult[T]` sum (v0.9 §3.3).
2193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2194pub struct HttpVariant {
2195    pub name: &'static str,
2196    pub payload: HttpVariantPayload,
2197    pub status: u16,
2198}
2199
2200/// All `HttpResult[T]` variants, in declaration order (ascending status). The
2201/// vocabulary tracks the common, modern HTTP status codes (RFC 9110): success
2202/// and created/accepted (`Value`), redirects carrying a `Location` URL, and
2203/// the client/server failures that handlers routinely return (`Message` when
2204/// an explanation helps the caller, `None` for self-describing statuses).
2205pub const HTTP_VARIANTS: &[HttpVariant] = &[
2206    // ── 2xx success ──────────────────────────────────────────────────────
2207    HttpVariant {
2208        name: "Ok",
2209        payload: HttpVariantPayload::Value,
2210        status: 200,
2211    },
2212    // v0.101 (real-time track slice 1): a 200 whose body is a streamed
2213    // `Stream[String]`, SSE-framed. Status precedes the body, so streaming is
2214    // 200-only — pre-stream failures are ordinary variants returned instead.
2215    HttpVariant {
2216        name: "Streaming",
2217        payload: HttpVariantPayload::Streamed,
2218        status: 200,
2219    },
2220    // v0.111: a 200 whose body is an author-owned `Bytes` written straight into
2221    // the response with the declared `content-type` — no codec runs. 200-only,
2222    // like `Streaming`: it serves service-tier raw bodies (`robots.txt`,
2223    // `sitemap.xml`, feeds, a QR PNG), not custom-status error pages.
2224    HttpVariant {
2225        name: "Raw",
2226        payload: HttpVariantPayload::Raw,
2227        status: 200,
2228    },
2229    // Caching raw responses: a `Raw` body plus the handler-supplied entity tag
2230    // its `ETag` carries. A separate variant, so every `Raw(…)` call is unchanged.
2231    HttpVariant {
2232        name: "RawTagged",
2233        payload: HttpVariantPayload::RawTagged,
2234        status: 200,
2235    },
2236    // K-streams (#2623): a `Raw` body streamed as a `Stream[Bytes]`, chunk by
2237    // chunk, for a body too large to buffer. 200-only, like `Streaming`: the
2238    // status is sent before the body.
2239    HttpVariant {
2240        name: "RawStreamed",
2241        payload: HttpVariantPayload::RawStreamed,
2242        status: 200,
2243    },
2244    // #2403 (L6): a `Raw` body answered `201` — for an external contract that
2245    // fixes the bytes of a creation's answer. `Raw`'s payload shape, so every
2246    // `Raw` check, binding and emit arm covers it; no validator (a 201 answers a
2247    // write and is not cached).
2248    HttpVariant {
2249        name: "RawCreated",
2250        payload: HttpVariantPayload::Raw,
2251        status: 201,
2252    },
2253    HttpVariant {
2254        name: "Created",
2255        payload: HttpVariantPayload::Value,
2256        status: 201,
2257    },
2258    HttpVariant {
2259        name: "Accepted",
2260        payload: HttpVariantPayload::Value,
2261        status: 202,
2262    },
2263    HttpVariant {
2264        name: "NoContent",
2265        payload: HttpVariantPayload::None,
2266        status: 204,
2267    },
2268    // ── 3xx redirection (carry a `Location` URL) ─────────────────────────
2269    HttpVariant {
2270        name: "MovedPermanently",
2271        payload: HttpVariantPayload::Location,
2272        status: 301,
2273    },
2274    HttpVariant {
2275        name: "Found",
2276        payload: HttpVariantPayload::Location,
2277        status: 302,
2278    },
2279    HttpVariant {
2280        name: "SeeOther",
2281        payload: HttpVariantPayload::Location,
2282        status: 303,
2283    },
2284    HttpVariant {
2285        name: "TemporaryRedirect",
2286        payload: HttpVariantPayload::Location,
2287        status: 307,
2288    },
2289    HttpVariant {
2290        name: "PermanentRedirect",
2291        payload: HttpVariantPayload::Location,
2292        status: 308,
2293    },
2294    // ── 4xx client error ─────────────────────────────────────────────────
2295    HttpVariant {
2296        name: "BadRequest",
2297        payload: HttpVariantPayload::Message,
2298        status: 400,
2299    },
2300    HttpVariant {
2301        name: "Unauthorized",
2302        payload: HttpVariantPayload::None,
2303        status: 401,
2304    },
2305    HttpVariant {
2306        name: "Forbidden",
2307        payload: HttpVariantPayload::None,
2308        status: 403,
2309    },
2310    HttpVariant {
2311        name: "NotFound",
2312        payload: HttpVariantPayload::None,
2313        status: 404,
2314    },
2315    HttpVariant {
2316        name: "MethodNotAllowed",
2317        payload: HttpVariantPayload::None,
2318        status: 405,
2319    },
2320    HttpVariant {
2321        name: "NotAcceptable",
2322        payload: HttpVariantPayload::None,
2323        status: 406,
2324    },
2325    HttpVariant {
2326        name: "RequestTimeout",
2327        payload: HttpVariantPayload::None,
2328        status: 408,
2329    },
2330    HttpVariant {
2331        name: "Conflict",
2332        payload: HttpVariantPayload::Message,
2333        status: 409,
2334    },
2335    HttpVariant {
2336        name: "Gone",
2337        payload: HttpVariantPayload::None,
2338        status: 410,
2339    },
2340    HttpVariant {
2341        name: "LengthRequired",
2342        payload: HttpVariantPayload::None,
2343        status: 411,
2344    },
2345    HttpVariant {
2346        name: "PayloadTooLarge",
2347        payload: HttpVariantPayload::Message,
2348        status: 413,
2349    },
2350    HttpVariant {
2351        name: "UnsupportedMediaType",
2352        payload: HttpVariantPayload::Message,
2353        status: 415,
2354    },
2355    HttpVariant {
2356        name: "UnprocessableEntity",
2357        payload: HttpVariantPayload::Message,
2358        status: 422,
2359    },
2360    HttpVariant {
2361        name: "TooManyRequests",
2362        payload: HttpVariantPayload::Message,
2363        status: 429,
2364    },
2365    HttpVariant {
2366        name: "UnavailableForLegalReasons",
2367        payload: HttpVariantPayload::Message,
2368        status: 451,
2369    },
2370    // ── 5xx server error ─────────────────────────────────────────────────
2371    HttpVariant {
2372        name: "ServerError",
2373        payload: HttpVariantPayload::Message,
2374        status: 500,
2375    },
2376    HttpVariant {
2377        name: "NotImplemented",
2378        payload: HttpVariantPayload::Message,
2379        status: 501,
2380    },
2381    HttpVariant {
2382        name: "BadGateway",
2383        payload: HttpVariantPayload::Message,
2384        status: 502,
2385    },
2386    HttpVariant {
2387        name: "ServiceUnavailable",
2388        payload: HttpVariantPayload::Message,
2389        status: 503,
2390    },
2391    HttpVariant {
2392        name: "GatewayTimeout",
2393        payload: HttpVariantPayload::Message,
2394        status: 504,
2395    },
2396    // #2341 (L4): an error status the author chooses, with an author-owned
2397    // body — the form for an external API's error contract. Its status is
2398    // its first argument, so the row's own is [`AUTHOR_CHOSEN_STATUS`].
2399    HttpVariant {
2400        name: "RawError",
2401        payload: HttpVariantPayload::RawError,
2402        status: AUTHOR_CHOSEN_STATUS,
2403    },
2404];
2405
2406/// The `status` of an [`HttpVariant`] whose status is chosen per construction
2407/// (`RawError`, #2341) rather than fixed by the variant.
2408pub const AUTHOR_CHOSEN_STATUS: u16 = 0;
2409
2410/// The status an `ErrorStatus` name stands for in `RawError`'s first argument
2411/// (#2341, L4): one of the vocabulary's own 4xx/5xx variant names
2412/// (`Forbidden` → 403). `None` for any other name.
2413pub fn error_status(name: &str) -> Option<u16> {
2414    HTTP_VARIANTS
2415        .iter()
2416        .find(|v| v.name == name && (400..600).contains(&v.status))
2417        .map(|v| v.status)
2418}
2419
2420/// Find an `HttpResult[T]` variant by name. Returns the variant info or
2421/// `None` if the name doesn't match.
2422pub fn http_variant(name: &str) -> Option<HttpVariant> {
2423    HTTP_VARIANTS.iter().copied().find(|v| v.name == name)
2424}
2425
2426/// #2341 (L4): the status a `RawError`'s first argument names — a bare 4xx/5xx
2427/// variant name (`Forbidden`) or one qualified by `ErrorStatus`
2428/// (`ErrorStatus.Forbidden`). `None` for any other expression.
2429pub fn raw_error_status(arg: &Expr) -> Option<u16> {
2430    match &arg.kind {
2431        ExprKind::Ident(id) => error_status(&id.name),
2432        ExprKind::FieldAccess { receiver, field } => match &receiver.kind {
2433            ExprKind::Ident(r) if r.name == "ErrorStatus" => error_status(&field.name),
2434            _ => None,
2435        },
2436        _ => None,
2437    }
2438}
2439
2440/// A `Decimal` rounding mode (#2622) — the closed set `round`/`div` accept.
2441/// Written `RoundingMode.HalfEven`; read syntactically at that argument (it is
2442/// not a first-class value in this slice), so it lowers to its name.
2443#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2444pub enum RoundingMode {
2445    /// Toward zero (truncate).
2446    Down,
2447    /// Away from zero.
2448    Up,
2449    /// Toward negative infinity.
2450    Floor,
2451    /// Toward positive infinity.
2452    Ceiling,
2453    /// To nearest; a tie goes away from zero.
2454    HalfUp,
2455    /// To nearest; a tie goes toward zero.
2456    HalfDown,
2457    /// To nearest; a tie goes to the even neighbour (banker's rounding).
2458    HalfEven,
2459}
2460
2461impl RoundingMode {
2462    pub const ALL: [RoundingMode; 7] = [
2463        RoundingMode::Down,
2464        RoundingMode::Up,
2465        RoundingMode::Floor,
2466        RoundingMode::Ceiling,
2467        RoundingMode::HalfUp,
2468        RoundingMode::HalfDown,
2469        RoundingMode::HalfEven,
2470    ];
2471
2472    pub fn name(self) -> &'static str {
2473        match self {
2474            RoundingMode::Down => "Down",
2475            RoundingMode::Up => "Up",
2476            RoundingMode::Floor => "Floor",
2477            RoundingMode::Ceiling => "Ceiling",
2478            RoundingMode::HalfUp => "HalfUp",
2479            RoundingMode::HalfDown => "HalfDown",
2480            RoundingMode::HalfEven => "HalfEven",
2481        }
2482    }
2483
2484    pub fn from_name(name: &str) -> Option<Self> {
2485        Self::ALL.into_iter().find(|m| m.name() == name)
2486    }
2487}
2488
2489/// #2622: the rounding mode a `Decimal` `round`/`div` argument names —
2490/// `RoundingMode.HalfEven`. `None` for any other expression.
2491pub fn rounding_mode(arg: &Expr) -> Option<RoundingMode> {
2492    match &arg.kind {
2493        ExprKind::FieldAccess { receiver, field } => match &receiver.kind {
2494            ExprKind::Ident(r) if r.name == "RoundingMode" => RoundingMode::from_name(&field.name),
2495            _ => None,
2496        },
2497        _ => None,
2498    }
2499}
2500
2501/// Payload shape of a `QueueResult` variant (v0.44). Non-generic — a verdict
2502/// carries no value; `Retry` carries a `String` reason for the log path.
2503#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2504pub enum QueueVariantPayload {
2505    /// No payload (`Ack`).
2506    None,
2507    /// Carries a `String` reason (`Retry`).
2508    Message,
2509}
2510
2511/// One variant of the built-in `QueueResult` sum (v0.44).
2512#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2513pub struct QueueVariant {
2514    pub name: &'static str,
2515    pub payload: QueueVariantPayload,
2516}
2517
2518/// All `QueueResult` variants, in declaration order. `Ack` confirms the
2519/// message; `Retry` redelivers it, carrying a reason for observability.
2520pub const QUEUE_VARIANTS: &[QueueVariant] = &[
2521    QueueVariant {
2522        name: "Ack",
2523        payload: QueueVariantPayload::None,
2524    },
2525    QueueVariant {
2526        name: "Retry",
2527        payload: QueueVariantPayload::Message,
2528    },
2529];
2530
2531/// Find a `QueueResult` variant by name.
2532pub fn queue_variant(name: &str) -> Option<QueueVariant> {
2533    QUEUE_VARIANTS.iter().copied().find(|v| v.name == name)
2534}
2535
2536#[derive(Debug, Clone)]
2537pub struct TypeDecl {
2538    pub name: Ident,
2539    /// `[T, U]` type parameters (v0.157, ADR 0183): empty for a non-generic
2540    /// type. A generic *record* type (`type Paginated[T] = { … }`) is the only
2541    /// generic body accepted; the checker rejects type parameters on refined /
2542    /// opaque / sum bodies. Mirrors [`FnDecl::type_params`].
2543    pub type_params: Vec<TypeParam>,
2544    pub body: TypeBody,
2545    /// `derives Ord` (constrained-generics slice 1): the constraints the type
2546    /// opts into, in source order. Empty when there is no clause. `Eq`, `Key` and
2547    /// `Codable` are automatic, so `Ord` is the only name the checker admits.
2548    pub derives: Vec<Ident>,
2549    /// The span of the `derives` keyword, when there is a clause.
2550    pub derives_kw: Option<Span>,
2551    /// Documentation block attached to this declaration (v0.3).
2552    pub documentation: Option<Doc>,
2553    /// #2618: the span of a leading `private` modifier, when the declaration
2554    /// is unit-private: visible across its own unit's files (and to that
2555    /// unit's suites), never through `uses`. `None` is the default, public.
2556    pub private: Option<Span>,
2557    pub span: Span,
2558    pub trivia: Trivia,
2559}
2560
2561/// `event Name = { fields }` — a typed fact a context may emit and other
2562/// contexts' subscriber services may receive (Events track, slice 0, spine
2563/// #936). Record body only in slice 0 — pattern refinement (subscription
2564/// side, slice 1) and default-valued fields for additive versioning (slice
2565/// 3a) both extend a record body, so nothing here forecloses them. An
2566/// optional `@schema(N)` annotation (slice 3b) asserts the event's current
2567/// wire schema version, embedded into `env.schemaVersion` at emission — see
2568/// [`EventDecl::schema_version`]. Legal only inside a `context` —
2569/// checker-enforced (`bynk.event.outside_context`), not grammar, mirroring
2570/// how `capability`/`provides` are commons-rejected at the parser while
2571/// `event` instead follows `messages`' precedent (ADR 0272) of parsing
2572/// uniformly and letting the checker place it, since unlike
2573/// `capability`/`provides` an `event` has no meaning to reject early inside
2574/// an `adapter` either.
2575#[derive(Debug, Clone)]
2576pub struct EventDecl {
2577    pub name: Ident,
2578    /// Every `@`-annotation attached to this declaration. The parser stays
2579    /// permissive (zero or more, same as `store` field / `messages`
2580    /// annotations); the closed registry (today: `@schema` alone) and its
2581    /// argument shape are a checker concern (`bynk.event.unknown_annotation`
2582    /// / `bynk.event.bad_schema_version`), not a parse error.
2583    pub annotations: Vec<Annotation>,
2584    pub body: RecordBody,
2585    /// Documentation block attached to this declaration.
2586    pub documentation: Option<Doc>,
2587    pub span: Span,
2588    pub trivia: Trivia,
2589}
2590
2591impl EventDecl {
2592    /// A synthetic `TypeDecl` with this event's name and record body, so an
2593    /// event registers into the ordinary `types` symbol table and reuses
2594    /// every existing type-reference/exports/consumes/construction check —
2595    /// no non-generic type parameters, no separate resolution path. Callers
2596    /// that need to know a name is specifically an *event* (owner-only
2597    /// emission, `from Events(E)`/`Events.emit[E]`'s "must be an event, not
2598    /// just any type" gate) track that separately, alongside this.
2599    ///
2600    /// Deliberately lossy: a `TypeDecl` has no `annotations`, so `@schema(N)`
2601    /// does not survive this conversion. Nothing downstream of this
2602    /// synthesis needs the event's schema version — only the emitter's own
2603    /// `Events.emit` lowering does, and it reads [`EventDecl::schema_version`]
2604    /// directly off the real declaration instead.
2605    pub fn as_type_decl(&self) -> TypeDecl {
2606        TypeDecl {
2607            derives: Vec::new(),
2608            derives_kw: None,
2609            name: self.name.clone(),
2610            type_params: Vec::new(),
2611            body: TypeBody::Record(self.body.clone()),
2612            documentation: self.documentation.clone(),
2613            span: self.span,
2614            trivia: self.trivia.clone(),
2615            private: None,
2616        }
2617    }
2618
2619    /// This event's declared wire schema version (Events slice 3b, #978):
2620    /// the positive `Int` literal argument of its sole `@schema(N)`
2621    /// annotation, or `1` if the annotation is absent — identical to every
2622    /// event's behaviour before this annotation existed. A malformed
2623    /// `@schema` (non-positive, non-literal, wrong arity, labelled, or
2624    /// duplicated) has already been reported by the checker
2625    /// (`bynk.event.bad_schema_version`); this falls back to `1` rather than
2626    /// re-deriving that diagnostic.
2627    pub fn schema_version(&self) -> i64 {
2628        self.annotations
2629            .iter()
2630            .find(|a| a.name.name == "schema")
2631            .and_then(|a| a.args.first())
2632            .and_then(|arg| match &arg.value.kind {
2633                ExprKind::IntLit { value, .. } if *value > 0 => Some(*value),
2634                _ => None,
2635            })
2636            .unwrap_or(1)
2637    }
2638}
2639
2640/// The structural filter on a `from Events(E { field: value, .. })`
2641/// subscription header (Events track, slice 1, spine #936) — deliver-and-filter:
2642/// every emission still reaches the fan-out mechanism, and the subscriber's
2643/// own generated handler evaluates this as a boolean guard before running the
2644/// body. Deliberately **not** a [`Pattern`] — an event is a plain record, not
2645/// a sum, so it has no tag for [`Pattern::Variant`] to test; extending the
2646/// shared `Pattern` enum to fit would touch parser/checker/emitter/fmt/
2647/// tree-sitter/LSP sites and drag in match-exhaustiveness semantics a
2648/// delivery filter does not need. This amends
2649/// [ADR 0286](../decisions/0286-events-pattern-dispatch-deliver-and-filter.md)'s
2650/// "no bespoke matching engine is introduced for Events" claim; its
2651/// deliver-and-filter decision is unchanged. No static narrowing: a matching
2652/// handler body still sees its parameter at its own declared type, never
2653/// narrowed to a listed field's specific value (deferred — narrowing needs a
2654/// singleton-variant type the checker does not have, and waits on the
2655/// refinement-propagation design question `design/bynk-type-system.md`
2656/// §2.5.4 names as still open).
2657#[derive(Debug, Clone)]
2658pub struct EventPattern {
2659    /// The listed fields, in source order. Never empty — a pattern with no
2660    /// fields has no shape (`from Events(E)`, no braces, is the pattern-less
2661    /// form; `from Events(E { })` is a parse error pointing at it).
2662    pub fields: Vec<EventPatternField>,
2663    /// The span of the required trailing `..` — every listed field leaves
2664    /// the rest of the record's fields unconstrained, and that must be
2665    /// written explicitly rather than implied.
2666    pub rest_span: Span,
2667    pub span: Span,
2668}
2669
2670/// One `name: value` entry in an [`EventPattern`].
2671#[derive(Debug, Clone)]
2672pub struct EventPatternField {
2673    pub name: Ident,
2674    pub value: EventPatternValue,
2675    pub span: Span,
2676}
2677
2678/// The value a pattern field is matched against. A closed set, mirroring
2679/// [`Pattern::Literal`]'s closed literal kinds plus a nullary sum-variant
2680/// reference — no nested record sub-patterns in v1 (slice 1 filters on
2681/// top-level fields only).
2682#[derive(Debug, Clone)]
2683pub enum EventPatternValue {
2684    /// An `Int`/`String`/`Bool` literal — matches the field by value equality.
2685    Literal {
2686        value: LiteralValue,
2687        /// The literal as written (`-1_000`), digit separators kept; `None`
2688        /// for a pattern built without source. Only the formatter reads it,
2689        /// and it sits outside `value` so the duplicate-arm check ignores it.
2690        text: Option<String>,
2691        span: Span,
2692    },
2693    /// A nullary sum-type variant, optionally qualified: `Region.Domestic` or
2694    /// bare `Domestic` — both resolve against the field's declared sum type.
2695    /// A variant that carries a payload is rejected (`bynk.event.
2696    /// pattern_variant_payload`): testing only the tag while ignoring a
2697    /// payload would silently over-broaden the filter.
2698    Variant {
2699        /// `Some(Region)` for the qualified form, `None` for bare.
2700        type_name: Option<Ident>,
2701        variant: Ident,
2702        span: Span,
2703    },
2704}
2705
2706impl EventPattern {
2707    pub fn span(&self) -> Span {
2708        self.span
2709    }
2710}
2711
2712impl EventPatternValue {
2713    pub fn span(&self) -> Span {
2714        match self {
2715            EventPatternValue::Literal { span, .. } => *span,
2716            EventPatternValue::Variant { span, .. } => *span,
2717        }
2718    }
2719}
2720
2721/// A `via schema(...)` dispatch clause on a `from Events(...)` header
2722/// (Events track, slice 4, spine #936): filters delivery by the envelope's
2723/// `schemaVersion`, parallel to [`EventPattern`] but matched against the
2724/// envelope rather than the payload, and written after the `Events(...)`
2725/// header's closing `)` rather than inside it. Delivery is still
2726/// deliver-and-filter (unchanged from slice 1's ADR 0286): the fan-out
2727/// mechanism delivers every emission to every subscriber regardless, and
2728/// this becomes one more independently-evaluated runtime guard in the
2729/// subscriber's own generated handler — no cross-subscriber ambiguity
2730/// check (two sibling subscribers with the same or overlapping version
2731/// coverage are both legal, undiagnosed).
2732#[derive(Debug, Clone)]
2733pub struct SchemaDispatch {
2734    pub pattern: SchemaVersionPattern,
2735    pub span: Span,
2736}
2737
2738/// The pattern a `via schema(...)` clause matches `env.schemaVersion`
2739/// against: a literal, an inclusive integer range, or `_`. Mirrors
2740/// `@schema(N)`'s own permissive-parse-then-checker-validate split (a
2741/// non-positive bound is a checker error, not a parse error, for the same
2742/// diagnostic style). The range is the same [`IntRange`] a match pattern uses
2743/// (events slice 4b, #990, with patterns slice 5, #2699).
2744#[derive(Debug, Clone)]
2745pub enum SchemaVersionPattern {
2746    Literal(i64),
2747    /// `via schema(2..4)`, `(2..)`, `(..4)`; bounds are inclusive.
2748    Range(IntRange),
2749    /// `via schema(_)`: any version, the same as omitting the clause.
2750    Wildcard,
2751}
2752
2753/// The right-hand side of a `type` declaration. In v0/v0.1 only the
2754/// `Refined` variant existed; v0.2 adds records and sums; v0.3 adds opaque.
2755#[derive(Debug, Clone)]
2756pub enum TypeBody {
2757    /// Refined base type: `BaseType where refinement`.
2758    Refined {
2759        base: BaseType,
2760        base_span: Span,
2761        refinement: Option<Refinement>,
2762    },
2763    /// Record type: `{ field: T where ..., ... }`.
2764    Record(RecordBody),
2765    /// Sum type: pipe-form variants or `enum { ... }` shorthand.
2766    Sum(SumBody),
2767    /// Opaque base type: `opaque BaseType (where refinement)?` (v0.3 §3.4).
2768    /// Identity is nominal; the base type is hidden outside the defining commons.
2769    Opaque {
2770        base: BaseType,
2771        base_span: Span,
2772        refinement: Option<Refinement>,
2773    },
2774}
2775
2776/// Body of a record-type declaration (v0.2 §3.1).
2777#[derive(Debug, Clone)]
2778pub struct RecordBody {
2779    pub fields: Vec<RecordField>,
2780    pub span: Span,
2781    /// #1788: comments before the closing `}`.
2782    pub trailing_comments: Vec<Comment>,
2783}
2784
2785/// One field of a record type declaration. Each field may carry inline
2786/// refinement, which is enforced at construction time on the field's value.
2787#[derive(Debug, Clone)]
2788pub struct RecordField {
2789    /// #3343: annotations before the field (`@name("__Host-sid") sid: …`), the
2790    /// external name a request record's key has when it is not an identifier.
2791    pub annotations: Vec<Annotation>,
2792    pub name: Ident,
2793    pub type_ref: TypeRef,
2794    pub refinement: Option<Refinement>,
2795    /// v0.11: an optional initial-value expression. Only meaningful on agent
2796    /// `state` fields (the field's fresh-key value); ignored / rejected on
2797    /// record-type fields by the checker.
2798    pub init: Option<Expr>,
2799    pub span: Span,
2800    /// #1888: the doc above the field, in either form. Hover, completion and
2801    /// the documentation page show it.
2802    pub documentation: Option<Doc>,
2803    /// #1788: comments above the field and at the end of its line.
2804    pub trivia: Trivia,
2805}
2806
2807impl RecordField {
2808    /// #3343: the key `@name("…")` gives this field on an HTTP request (a cookie,
2809    /// a query key, a form field), `None` when it reads under its own name. The
2810    /// checker refuses a `@name` that is not exactly one string literal.
2811    pub fn wire_name(&self) -> Option<String> {
2812        self.annotations
2813            .iter()
2814            .find(|a| a.name.name == "name")
2815            .and_then(|a| match a.args.as_slice() {
2816                [arg] => match &arg.value.kind {
2817                    ExprKind::StrLit(s) => Some(s.clone()),
2818                    _ => None,
2819                },
2820                _ => None,
2821            })
2822    }
2823}
2824
2825/// Body of a sum-type declaration (v0.2 §3.2).
2826#[derive(Debug, Clone)]
2827pub struct SumBody {
2828    pub variants: Vec<Variant>,
2829    /// v0.154 (ADR 0178): declared error embeddings — `embeds E as V, …` after
2830    /// the variants. Each says "an `E` value auto-wraps into variant `V`", which
2831    /// the `?` operator uses to convert a cross-context error without a manual
2832    /// `.mapErr`. Empty for a sum with no embeddings.
2833    pub embeds: Vec<EmbedsClause>,
2834    pub span: Span,
2835    /// #1794: comments before the closing `}` of an `enum { … }` body, or, in
2836    /// the pipe form, on their own lines between the last variant and its
2837    /// `embeds` clause.
2838    pub trailing_comments: Vec<Comment>,
2839}
2840
2841/// One `embeds <source_type> as <variant>` mapping in a sum body (v0.154, ADR
2842/// 0178). Declares that a value of `source_type` can be auto-wrapped into the
2843/// named single-payload `variant` of the enclosing sum.
2844#[derive(Debug, Clone)]
2845pub struct EmbedsClause {
2846    pub source_type: TypeRef,
2847    pub variant: Ident,
2848    pub span: Span,
2849}
2850
2851/// One variant of a sum type. Variants may have payload fields; a
2852/// payload-less variant is a simple tag.
2853#[derive(Debug, Clone)]
2854pub struct Variant {
2855    pub name: Ident,
2856    pub payload: Vec<VariantField>,
2857    pub span: Span,
2858    /// #1888: the doc above the variant, in either form.
2859    pub documentation: Option<Doc>,
2860    /// #1794: comments above the variant and at the end of its line. A comment
2861    /// on an `enum {` line leads the first variant, and so does one on the `=`
2862    /// line of a pipe-form sum. The last pipe-form variant's end-of-line
2863    /// comment is the type's own trailing comment unless an `embeds` clause
2864    /// follows it.
2865    pub trivia: Trivia,
2866}
2867
2868/// One payload field of a sum variant. Variant payload fields use named
2869/// declarations like record fields, but do not carry refinement in v0.2.
2870#[derive(Debug, Clone)]
2871pub struct VariantField {
2872    pub name: Ident,
2873    pub type_ref: TypeRef,
2874    pub span: Span,
2875    /// #1888: the doc above the payload field, in either form.
2876    pub documentation: Option<Doc>,
2877}
2878
2879#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
2880pub enum BaseType {
2881    Int,
2882    String,
2883    Bool,
2884    Float,
2885    /// `Duration` (v0.86, ADR 0112) — a span of time, a distinct base type
2886    /// erased to TS `number` carrying milliseconds (the `Clock` unit). Modelled
2887    /// on `Float`: Bynk-side-only, no implicit `Int` coercion (save the one
2888    /// sanctioned clock-math mix).
2889    Duration,
2890    /// `Instant` (v0.90, ADR 0114) — an absolute point in time, a distinct base
2891    /// type erased to TS `number` carrying Unix epoch milliseconds (the
2892    /// `Clock` unit). No literal (minted by `Clock.now()`); arithmetic composes
2893    /// with `Duration` (`Instant ± Duration -> Instant`, `Instant − Instant ->
2894    /// Duration`). Supersedes ADR 0112 D4's `Int`↔`Duration` clock-math mix.
2895    Instant,
2896    /// `Bytes` (v0.110, ADR 0142) — an immutable finite octet sequence, the
2897    /// seventh base type. Unlike its neighbours it does **not** erase to TS
2898    /// `number`: a `Bytes` lowers to a `Uint8Array`. No source literal
2899    /// (constructed via `Bytes.fromUtf8`/`fromBase64`/`empty`); `==` compares
2900    /// by content (real emitter codegen, not host `===`); wires as a base64
2901    /// JSON string; not `Map`-keyable and not orderable.
2902    Bytes,
2903    /// `Decimal` (#2622) — an exact base-10 number: an arbitrary-precision
2904    /// integer coefficient with a non-negative scale. Like `Bytes` it does not
2905    /// erase to a JS primitive (it lowers to a frozen `{ coefficient, scale }`
2906    /// object over `BigInt`); `==`/`<` compare by numeric value; it wires as a
2907    /// canonical JSON string (`"1.20"`).
2908    Decimal,
2909}
2910
2911impl BaseType {
2912    pub fn name(self) -> &'static str {
2913        match self {
2914            BaseType::Int => "Int",
2915            BaseType::String => "String",
2916            BaseType::Bool => "Bool",
2917            BaseType::Float => "Float",
2918            BaseType::Duration => "Duration",
2919            BaseType::Instant => "Instant",
2920            BaseType::Bytes => "Bytes",
2921            BaseType::Decimal => "Decimal",
2922        }
2923    }
2924
2925    /// The base type written `name`, or `None` for anything else.
2926    pub fn from_name(name: &str) -> Option<Self> {
2927        Some(match name {
2928            "Int" => BaseType::Int,
2929            "String" => BaseType::String,
2930            "Bool" => BaseType::Bool,
2931            "Float" => BaseType::Float,
2932            "Duration" => BaseType::Duration,
2933            "Instant" => BaseType::Instant,
2934            "Bytes" => BaseType::Bytes,
2935            "Decimal" => BaseType::Decimal,
2936            _ => return None,
2937        })
2938    }
2939}
2940
2941/// A `Duration` literal unit (v0.86, ADR 0112) — the closed set of suffixes in a
2942/// `<int>.<unit>` literal. Each maps to a fixed millisecond factor (`Duration`
2943/// erases to `Int` milliseconds).
2944#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2945pub enum DurationUnit {
2946    Milliseconds,
2947    Seconds,
2948    Minutes,
2949    Hours,
2950    Days,
2951}
2952
2953/// Which spelling of a [`DurationUnit`] a literal used: `hour` or `hours`.
2954#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2955pub enum UnitForm {
2956    Singular,
2957    Plural,
2958}
2959
2960impl DurationUnit {
2961    /// Every unit, in ascending size.
2962    pub const ALL: [DurationUnit; 5] = [
2963        DurationUnit::Milliseconds,
2964        DurationUnit::Seconds,
2965        DurationUnit::Minutes,
2966        DurationUnit::Hours,
2967        DurationUnit::Days,
2968    ];
2969
2970    /// Resolve a unit name (`minutes`, `minute`) to its variant and the form it
2971    /// was written in, or `None` if it is not one of the closed set (#3947).
2972    /// Used by the parser to recognise an `<int>.<unit>` literal.
2973    pub fn from_name(name: &str) -> Option<(Self, UnitForm)> {
2974        Self::ALL.into_iter().find_map(|u| {
2975            if u.name() == name {
2976                Some((u, UnitForm::Plural))
2977            } else if u.singular_name() == name {
2978                Some((u, UnitForm::Singular))
2979            } else {
2980                None
2981            }
2982        })
2983    }
2984
2985    /// The plural unit name (`hours`), the one written with every number but `1`.
2986    pub fn name(self) -> &'static str {
2987        match self {
2988            DurationUnit::Milliseconds => "milliseconds",
2989            DurationUnit::Seconds => "seconds",
2990            DurationUnit::Minutes => "minutes",
2991            DurationUnit::Hours => "hours",
2992            DurationUnit::Days => "days",
2993        }
2994    }
2995
2996    /// The singular unit name (`hour`), the one written with `1`.
2997    pub fn singular_name(self) -> &'static str {
2998        match self {
2999            DurationUnit::Milliseconds => "millisecond",
3000            DurationUnit::Seconds => "second",
3001            DurationUnit::Minutes => "minute",
3002            DurationUnit::Hours => "hour",
3003            DurationUnit::Days => "day",
3004        }
3005    }
3006
3007    /// The unit name that agrees with `value`: singular for `1`, plural otherwise.
3008    pub fn name_for(self, value: i64) -> &'static str {
3009        if value == 1 {
3010            self.singular_name()
3011        } else {
3012            self.name()
3013        }
3014    }
3015
3016    /// The unit's value in milliseconds.
3017    pub fn millis(self) -> i64 {
3018        match self {
3019            DurationUnit::Milliseconds => 1,
3020            DurationUnit::Seconds => 1_000,
3021            DurationUnit::Minutes => 60_000,
3022            DurationUnit::Hours => 3_600_000,
3023            DurationUnit::Days => 86_400_000,
3024        }
3025    }
3026}
3027
3028/// An integer refinement bound (v0.40, ADR 0073): the parsed value plus the
3029/// bound's source span (covering a leading `-`). Value-only beyond the span —
3030/// ints have one canonical printed form, so the formatter stays idempotent
3031/// without a stored lexeme. The span backs the `InRange`-swap quick-fix.
3032#[derive(Debug, Clone)]
3033pub struct IntBound {
3034    pub value: i64,
3035    /// The bound as written (`-20_000`), digit separators kept (#2993). Only
3036    /// the formatter reads it; `value` is what the checker uses.
3037    pub lexeme: String,
3038    pub span: Span,
3039}
3040
3041/// A float refinement bound (v0.21): the parsed value plus the signed source
3042/// lexeme (for byte-stable emission). v0.40 (ADR 0073): also the source span,
3043/// for the `InRange`-swap quick-fix.
3044#[derive(Debug, Clone)]
3045pub struct FloatBound {
3046    pub value: f64,
3047    pub lexeme: String,
3048    pub span: Span,
3049}
3050
3051/// A decimal refinement bound (#2622): `InRange(0.00d, 100.00d)`. The
3052/// coefficient keeps any leading `-`; the lexeme is the signed source text.
3053#[derive(Debug, Clone)]
3054pub struct DecimalBound {
3055    pub coef: String,
3056    pub scale: u32,
3057    pub lexeme: String,
3058    pub span: Span,
3059}
3060
3061#[derive(Debug, Clone)]
3062pub struct Refinement {
3063    pub predicates: Vec<RefinementPred>,
3064    /// #2686: `@…` annotations after a type declaration's or record field's
3065    /// refinement. Only `@example(<literal>)` is meaningful (the checker
3066    /// matches the name); empty everywhere else. Not part of the predicates,
3067    /// so contracts and emitted code never see it.
3068    pub annotations: Vec<Annotation>,
3069    pub span: Span,
3070}
3071
3072/// #3946: whether `T.of(value)` is total, returning `T` rather than
3073/// `Result[T, ValidationError]`. True for a named type (`type Id = Int`): not
3074/// opaque, and a refinement with no predicates (annotations alone are not a
3075/// predicate). `Float` is the exception: its finite-number check is part of
3076/// the type (ADR 0040), so a `Float` named type stays fallible.
3077pub fn of_is_total(base: BaseType, refinement: Option<&Refinement>, opaque: bool) -> bool {
3078    !opaque && base != BaseType::Float && refinement.is_none_or(|r| r.predicates.is_empty())
3079}
3080
3081#[derive(Debug, Clone)]
3082pub struct RefinementPred {
3083    pub kind: PredKind,
3084    /// The integer argument of `MinLength`/`MaxLength`/`Length` as written
3085    /// (`1_000`), digit separators kept (#2993); `None` for other predicates
3086    /// and for a predicate built without source. Only the formatter reads it.
3087    pub arg_text: Option<String>,
3088    pub span: Span,
3089}
3090
3091#[derive(Debug, Clone)]
3092pub enum PredKind {
3093    Matches(String),
3094    InRange(IntBound, IntBound),
3095    /// `InRange` with float bounds (v0.21) — a separate variant so every
3096    /// `Int` refinement path stays untouched. Bounds keep their source
3097    /// lexemes (including any sign) so emitted runtime checks are
3098    /// byte-stable.
3099    InRangeF(FloatBound, FloatBound),
3100    /// `InRange` with decimal bounds (#2622): `InRange(0.00d, 100.00d)`.
3101    InRangeD(DecimalBound, DecimalBound),
3102    MinLength(i64),
3103    MaxLength(i64),
3104    Length(i64),
3105    NonNegative,
3106    Positive,
3107    NonEmpty,
3108    /// #2867: a `String` that is a real calendar date, exactly `YYYY-MM-DD`
3109    /// (years 0000-9999). The same date rule `Instant.fromIso` applies.
3110    IsoDate,
3111    /// #3873: a `String` that is a valid Cloudflare cron schedule
3112    /// ([`crate::cron::is_cron_expression`]).
3113    Cron,
3114}
3115
3116/// #2867: is `s` exactly `YYYY-MM-DD` and a date that exists? The one
3117/// compile-time statement of the rule `IsoDate` enforces; the runtime's
3118/// `__bynkIsIsoDate` (`bynk-emit/runtime/src/time.ts`) is its TypeScript twin
3119/// and shares the calendar with `Instant.fromIso`.
3120pub fn is_iso_date(s: &str) -> bool {
3121    let b = s.as_bytes();
3122    if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
3123        return false;
3124    }
3125    let digits = |r: std::ops::Range<usize>| -> Option<u32> {
3126        let part = &b[r];
3127        if part.iter().all(u8::is_ascii_digit) {
3128            Some(part.iter().fold(0, |n, d| n * 10 + u32::from(d - b'0')))
3129        } else {
3130            None
3131        }
3132    };
3133    let (Some(year), Some(month), Some(day)) = (digits(0..4), digits(5..7), digits(8..10)) else {
3134        return false;
3135    };
3136    let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
3137    let days = match month {
3138        2 if leap => 29,
3139        2 => 28,
3140        4 | 6 | 9 | 11 => 30,
3141        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
3142        _ => return false,
3143    };
3144    (1..=days).contains(&day)
3145}
3146
3147impl PredKind {
3148    pub fn name(&self) -> &'static str {
3149        match self {
3150            PredKind::Matches(_) => "Matches",
3151            PredKind::InRange(..) | PredKind::InRangeF(..) | PredKind::InRangeD(..) => "InRange",
3152            PredKind::MinLength(_) => "MinLength",
3153            PredKind::MaxLength(_) => "MaxLength",
3154            PredKind::Length(_) => "Length",
3155            PredKind::NonNegative => "NonNegative",
3156            PredKind::Positive => "Positive",
3157            PredKind::NonEmpty => "NonEmpty",
3158            PredKind::IsoDate => "IsoDate",
3159            PredKind::Cron => "Cron",
3160        }
3161    }
3162}
3163
3164/// #1651: the order a refinement's predicates are **checked** in at runtime:
3165/// every `Matches` after every other predicate, and otherwise source order.
3166///
3167/// A `Matches` pattern may take time polynomial in the input's length, and a
3168/// `MaxLength`/`Length` bound is what caps it (`bynk.types.polynomial_regex_capped`),
3169/// so the length checks must run first wherever the author wrote them. The order
3170/// is observable only in which failure a value failing several predicates
3171/// reports. Every runtime check site (`.of`, the boundary codec, `is`) and the
3172/// checker's compile-time literal check use this order, so they agree. The
3173/// canonical form a contract fingerprint hashes sorts its own copy and is
3174/// unaffected.
3175pub fn in_check_order<T>(preds: &[T], kind: impl Fn(&T) -> &PredKind) -> Vec<&T> {
3176    let (regex, rest): (Vec<&T>, Vec<&T>) = preds
3177        .iter()
3178        .partition(|p| matches!(kind(p), PredKind::Matches(_)));
3179    rest.into_iter().chain(regex).collect()
3180}
3181
3182/// A function type parameter (v0.20a, `fn name[A, B](…)`). A struct rather
3183/// than a bare Ident so the ADR-0028 "bound-capable" promise is a later field
3184/// addition, not a representation change.
3185#[derive(Debug, Clone)]
3186pub struct TypeParam {
3187    pub name: Ident,
3188    /// Declared constraints, `T: C1 + C2` (constrained-generics slice 0). Empty
3189    /// for an unbounded parameter. Slice 0 admits only `Eq`; the checker
3190    /// reports any other name as `bynk.generics.unknown_constraint`.
3191    pub bounds: Vec<Ident>,
3192    pub span: Span,
3193}
3194
3195/// One `A: C1 + C2` entry of a method's `where` clause (constrained-generics
3196/// slice 0): bounds a type parameter the method does not declare itself — the
3197/// receiver type's (`fn Box.has(self, x: A) -> Bool where A: Eq`).
3198#[derive(Debug, Clone)]
3199pub struct WhereBound {
3200    pub param: Ident,
3201    pub bounds: Vec<Ident>,
3202    pub span: Span,
3203}
3204
3205/// A lambda expression (v0.20a): `(params) => expr` or `(params) => { … }`.
3206/// `=>` is the value arrow (shared with `match`); param annotations are
3207/// optional where an expected function type supplies them.
3208#[derive(Debug, Clone)]
3209pub struct LambdaExpr {
3210    pub params: Vec<LambdaParam>,
3211    pub body: Box<Expr>,
3212    pub span: Span,
3213    /// #2712: whether the author wrote the body as a `{ … }` block. Only read
3214    /// when a parameter is a pattern, whose desugaring wraps the body in a block
3215    /// either way; the formatter needs the source form back.
3216    pub block_body: bool,
3217}
3218
3219/// A lambda parameter. A separate type from [`Param`] because its annotation
3220/// is optional — `Param.type_ref` stays mandatory at every signature site.
3221#[derive(Debug, Clone)]
3222pub struct LambdaParam {
3223    pub name: Ident,
3224    pub type_ref: Option<TypeRef>,
3225    pub span: Span,
3226    /// #2712: the irrefutable record pattern the author wrote in place of a name
3227    /// — `(Item { qty, .. }) => …`. `name` is then the hidden
3228    /// `__lambdaArg<offset>` (empty span, at the pattern), `type_ref` is `None`,
3229    /// and the lambda's body is already desugared to
3230    /// `{ let <pattern> = __lambdaArg<offset>; <body> }` through the `else`-less
3231    /// `let` (ADR 0484, #2654). The pattern is kept here for the checker (the
3232    /// parameter's type comes from its name) and to print the source form back.
3233    pub pattern: Option<Pattern>,
3234}
3235
3236/// #2712: the prefix of every hidden lambda-parameter binder. See
3237/// [`LambdaParam::pattern`]; like [`LET_ELSE_BINDER_PREFIX`] it cannot collide
3238/// with a user identifier.
3239pub const LAMBDA_ARG_BINDER_PREFIX: &str = "__lambdaArg";
3240
3241/// #2896: the prefix of the hidden name a wildcard lambda parameter (`_`) is
3242/// given — `__wild<offset>`, with an empty span at the `_`. The parameter takes
3243/// its type from the expected function type like a named one; the unique name
3244/// keeps `(_, _) => …` from emitting duplicate TS identifiers, and no user
3245/// identifier can spell it, so nothing in the body can refer to it.
3246pub const LAMBDA_WILDCARD_PREFIX: &str = "__wild";
3247
3248impl LambdaParam {
3249    /// #2896: whether this is a `_` parameter. Keyed on the hidden prefix,
3250    /// which no user identifier can start with (identifiers do not begin with
3251    /// `_`); any new generated name must not reuse `__wild`.
3252    pub fn is_wildcard(&self) -> bool {
3253        self.pattern.is_none() && self.name.name.starts_with(LAMBDA_WILDCARD_PREFIX)
3254    }
3255}
3256
3257#[derive(Debug, Clone)]
3258pub struct FnDecl {
3259    /// v0.20a: `[A, B]` type parameters; empty for non-generic functions.
3260    pub type_params: Vec<TypeParam>,
3261    /// Free function or method (`TypeName.methodName`). See [`FnName`].
3262    pub name: FnName,
3263    pub params: Vec<Param>,
3264    pub return_type: TypeRef,
3265    /// #2868: `given C1, C2` on a context-level function, parsed straight after
3266    /// the return type: the capabilities the body may use, and that every
3267    /// caller must itself have in scope. Empty when absent.
3268    pub given: Vec<CapRef>,
3269    /// `where A: Eq, …`, parsed between the return type and the contract
3270    /// clauses; empty when absent. Bounds receiver type parameters (and may
3271    /// restate the method's own).
3272    pub where_bounds: Vec<WhereBound>,
3273    /// v0.115: preconditions (`requires <name>: <pred>`), parsed between the
3274    /// return type and the body. A contract clause is the invariant predicate
3275    /// attached to a function (ADR 0144 — one predicate surface); `requires`
3276    /// scopes over the parameters only.
3277    pub requires: Vec<Contract>,
3278    /// v0.115: postconditions (`ensures <name>: <pred>`). Scopes over the
3279    /// parameters *and* `result`, the contextual binding for the return value.
3280    pub ensures: Vec<Contract>,
3281    pub body: Block,
3282    /// True when the first parameter is the special `self` parameter. Only
3283    /// valid for method declarations.
3284    pub has_self: bool,
3285    /// Documentation block attached to this declaration (v0.3).
3286    pub documentation: Option<Doc>,
3287    /// #2618: the span of a leading `private` modifier, when the declaration
3288    /// is unit-private: visible across its own unit's files (and to that
3289    /// unit's suites), never through `uses`. `None` is the default, public.
3290    pub private: Option<Span>,
3291    pub span: Span,
3292    pub trivia: Trivia,
3293}
3294
3295/// A function-declaration name: either a free function `f` or a method
3296/// `T.method` (v0.2 §3.6).
3297#[derive(Debug, Clone)]
3298pub enum FnName {
3299    /// `fn name(...)` — a free function.
3300    Free(Ident),
3301    /// `fn TypeName.methodName(...)` — a method attached to a type.
3302    Method {
3303        type_name: Ident,
3304        method_name: Ident,
3305    },
3306}
3307
3308impl FnName {
3309    /// The function's short name for diagnostics. For methods returns the
3310    /// method portion only; the type prefix is recovered via `type_name`.
3311    pub fn ident(&self) -> &Ident {
3312        match self {
3313            FnName::Free(id) => id,
3314            FnName::Method { method_name, .. } => method_name,
3315        }
3316    }
3317
3318    /// For methods, the attached type's identifier; `None` for free fns.
3319    pub fn type_name(&self) -> Option<&Ident> {
3320        match self {
3321            FnName::Free(_) => None,
3322            FnName::Method { type_name, .. } => Some(type_name),
3323        }
3324    }
3325
3326    /// The displayed full name (e.g., `Money.add` or `parseSku`).
3327    pub fn display(&self) -> String {
3328        match self {
3329            FnName::Free(id) => id.name.clone(),
3330            FnName::Method {
3331                type_name,
3332                method_name,
3333            } => format!("{}.{}", type_name.name, method_name.name),
3334        }
3335    }
3336}
3337
3338/// A brace-delimited block of statements ending in a tail expression
3339/// whose value is the block's value (spec v0.1 §3.1).
3340#[derive(Debug, Clone)]
3341pub struct Block {
3342    pub statements: Vec<Statement>,
3343    pub tail: Box<Expr>,
3344    pub span: Span,
3345    /// Line comments that appear between the last statement (or the
3346    /// opening brace) and the tail expression. Preserved here because
3347    /// expressions do not carry trivia in v1.1.
3348    pub tail_leading_comments: Vec<Comment>,
3349    /// `true` when the block was written with no explicit tail expression and
3350    /// the parser synthesised a `()` (unit) tail (v0.146, ADR 0170). The tail
3351    /// is a real `ExprKind::UnitLit` either way; this flag records that it was
3352    /// *implicit* so the formatter can omit it (Bynk has no statement
3353    /// terminator, so a printed `()` would re-attach to the last statement on
3354    /// re-parse — `x` `()` → `x()`). The parser re-derives the implicit unit
3355    /// tail, so omitting it is loss-free.
3356    pub implicit_tail: bool,
3357}
3358
3359impl Block {
3360    /// Whether this block is a synthesised empty unit block — no statements and
3361    /// an *implicit* `()` tail (v0.146, ADR 0170). This is exactly the shape the
3362    /// parser inserts for an `if` with no `else` branch, so both the checker
3363    /// (gating the else-less form to unit) and the formatter (omitting the
3364    /// synthetic `else { () }`) recognise it here.
3365    pub fn is_synth_unit(&self) -> bool {
3366        self.statements.is_empty()
3367            && self.implicit_tail
3368            && matches!(self.tail.kind, ExprKind::UnitLit)
3369    }
3370}
3371
3372/// Block-level statement.
3373#[derive(Debug, Clone)]
3374pub enum Statement {
3375    /// `let name (: T)? = expr` — pure binding (v0.1).
3376    Let(LetStmt),
3377    /// `let name (: T)? <- expr` — effectful binding (v0.5).
3378    EffectLet(LetStmt),
3379    /// `expect expr` — verify a Bool predicate at test runtime (v0.7; renamed
3380    /// from `assert` in v0.112). Only valid inside test case bodies.
3381    Expect(ExpectStmt),
3382    /// `do expr` — an effect-performing expression statement (v0.146, ADR 0170).
3383    /// Runs an `Effect[T]` and discards its result — the binder-free sugar for
3384    /// `let _ <- expr`. Legal only in an effectful body; the operand MUST be an
3385    /// `Effect[T]` whose `T` is not a `Result` (a `Result` keeps the explicit
3386    /// `let _ <- e`, so dropping an `Err` stays visible; amended by #3436).
3387    Do(DoStmt),
3388    /// `name := expr` — a `Cell` store write (v0.81, storage track). The
3389    /// unconditional write form; `.update(fn)` (a method call) is the
3390    /// read-modify-write form. ADR 0108.
3391    Assign(AssignStmt),
3392    /// `advance Clock by <Duration>` — move the harness clock forward
3393    /// (#2137, end-to-end testing track §3.4). `advance` is contextual: it
3394    /// opens a statement only before `<Ident> by`. Only valid in a `case` body.
3395    Advance(AdvanceStmt),
3396    /// `par { let a <- e1  let b <- e2 }` — a concurrent binding block (#2640,
3397    /// concurrent-effects slice 0). `par` is contextual: it opens a statement
3398    /// only before `{`. The parser admits any statements inside; the checker
3399    /// accepts only `let x <- e` and `do e`.
3400    Par(ParStmt),
3401}
3402
3403impl Statement {
3404    pub fn span(&self) -> Span {
3405        match self {
3406            Statement::Let(l) | Statement::EffectLet(l) => l.span,
3407            Statement::Expect(a) => a.span,
3408            Statement::Do(d) => d.span,
3409            Statement::Assign(a) => a.span,
3410            Statement::Advance(a) => a.span,
3411            Statement::Par(p) => p.span,
3412        }
3413    }
3414}
3415
3416/// #2640: a `par { … }` block. `statements` is what the author wrote between
3417/// the braces, unvalidated: the checker rejects every form but the effectful
3418/// `let` and `do` (`bynk.par.invalid_statement`), so the editor still sees the
3419/// rejected statement in place.
3420#[derive(Debug, Clone)]
3421pub struct ParStmt {
3422    /// The contextual `par` keyword.
3423    pub keyword: Span,
3424    pub statements: Vec<Statement>,
3425    /// Comments between the last statement and the closing `}`.
3426    pub closing_comments: Vec<Comment>,
3427    pub span: Span,
3428    pub trivia: Trivia,
3429}
3430
3431/// #2137: `advance <Cap> by <amount>` — moves the case's harness clock forward
3432/// by a `Duration`. `cap` must be `Clock` (the checker refuses any other).
3433#[derive(Debug, Clone)]
3434pub struct AdvanceStmt {
3435    /// The contextual `advance` keyword.
3436    pub keyword: Span,
3437    /// The capability whose time moves (`Clock`).
3438    pub cap: Ident,
3439    /// The `Duration` to move it by.
3440    pub amount: Expr,
3441    pub span: Span,
3442    pub trivia: Trivia,
3443}
3444
3445/// #2842: the `matches snapshot "<name>"` tail of an `expect`. `matches` and
3446/// `snapshot` are contextual words, matched by text like `faults`.
3447#[derive(Debug, Clone)]
3448pub struct SnapshotClause {
3449    /// The snapshot's name (the literal's text), unique within its case.
3450    pub name: String,
3451    /// The `matches` keyword through the closing quote of the name.
3452    pub span: Span,
3453    /// The name literal.
3454    pub name_span: Span,
3455}
3456
3457#[derive(Debug, Clone)]
3458pub struct ExpectStmt {
3459    pub value: Expr,
3460    /// #2842: `expect <value> matches snapshot "<name>"` compares `value`'s
3461    /// canonical JSON to a stored snapshot instead of asserting a `Bool`. `None`
3462    /// for every other `expect`.
3463    pub snapshot: Option<SnapshotClause>,
3464    pub span: Span,
3465    pub trivia: Trivia,
3466}
3467
3468/// `name := expr` — a `Cell` store write (v0.81, storage track). `target` is the
3469/// `Cell` field being written (a bare name for now; the checker resolves it to a
3470/// `store` field). `value` is the new value.
3471#[derive(Debug, Clone)]
3472pub struct AssignStmt {
3473    pub target: Ident,
3474    pub value: Expr,
3475    pub span: Span,
3476    pub trivia: Trivia,
3477}
3478
3479#[derive(Debug, Clone)]
3480pub struct LetStmt {
3481    pub name: Ident,
3482    pub type_annot: Option<TypeRef>,
3483    pub value: Expr,
3484    /// v0.182 (#664): the call-site `by <Actor>(<identity>)` clause on an
3485    /// `EffectLet` whose value addresses a test service handler. `None` on a pure
3486    /// `Let` (the `by` is parsed only in the `<-` arm) and on an effect-let with
3487    /// no principal.
3488    pub principal: Option<CallSiteActor>,
3489    /// #2010: set when this binding is the hidden one a `let <pattern> … else …`
3490    /// statement desugars into. `None` for every binding the author wrote.
3491    pub let_else: Option<LetElse>,
3492    pub span: Span,
3493    pub trivia: Trivia,
3494}
3495
3496/// #2010: what remains of a `let <pattern> <- e else …` (or `= e else …`)
3497/// statement once the parser has desugared it.
3498///
3499/// The parser rewrites `let P <- e else E` followed by the rest of the block
3500/// into a hidden binding, `let __letElse<offset> <- e`, and a `match` on it as
3501/// the block's tail: `P => { rest of the block }` first, then either
3502/// `_ => E` (an `else` block) or the `else match` arms. Everything downstream
3503/// (checker, emitter, editor) sees only that ordinary `match`. This marker,
3504/// carried on the hidden binding, is what lets the formatter print the sugar
3505/// back and the checker word its diagnostics in the author's terms.
3506#[derive(Debug, Clone)]
3507pub struct LetElse {
3508    /// Whether the `else` was a block or a `match { arms }`.
3509    pub form: LetElseForm,
3510    /// The `else` keyword (empty, at the end of the statement, for [`LetElseForm::Plain`]).
3511    pub else_span: Span,
3512    /// #2654: for a record pattern, the source ranges whose deletion leaves the
3513    /// `else`-less form — any parentheses around the pattern, and the `else`
3514    /// clause with the space before it. Empty for every other pattern, and for
3515    /// the plain form.
3516    pub remove_else: Vec<Span>,
3517}
3518
3519/// #2010: the spellings of a `let … else` fallback (and, #2654, its absence).
3520#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3521pub enum LetElseForm {
3522    /// `else { … }` — desugared to a trailing `_ => { … }` arm.
3523    Block,
3524    /// `else match { arms }` — the arms follow the pattern's arm unchanged.
3525    Match,
3526    /// No `else` at all (#2654): an irrefutable record pattern, `let Item { sku, .. } = e`,
3527    /// desugared to a one-arm `match`. `else_span` is then empty, at the end of
3528    /// the statement.
3529    Plain,
3530}
3531
3532/// #2010: the prefix of every hidden `let … else` binding. User identifiers
3533/// start with a letter (the lexer's `Ident` rule), so no user name can collide
3534/// with it, and the emitter already treats `__`-prefixed names as its own.
3535pub const LET_ELSE_BINDER_PREFIX: &str = "__letElse";
3536
3537impl Expr {
3538    /// #2010: whether this is the `match` a `let <pattern> … else …` was
3539    /// desugared into — one whose scrutinee is the hidden binder. It is not an
3540    /// expression the author wrote, so source-level tools (refactorings,
3541    /// diagnostics) treat it as the statement it came from.
3542    pub fn is_let_else_match(&self) -> bool {
3543        matches!(
3544            &self.kind,
3545            ExprKind::Match { discriminant, .. }
3546                if matches!(&discriminant.kind, ExprKind::Ident(i) if i.name.starts_with(LET_ELSE_BINDER_PREFIX))
3547        )
3548    }
3549}
3550
3551/// #2010: whether `name` is a binding the compiler generated rather than one
3552/// the author wrote. Editor surfaces (inlay hints, locals, symbols) skip these.
3553pub fn is_generated_binding(name: &str) -> bool {
3554    name.starts_with("__")
3555}
3556
3557/// `do expr` — an effect-performing expression statement (v0.146, ADR 0170).
3558/// `value` is the awaited effect, which MUST be an `Effect[T]` with `T` not a `Result`.
3559#[derive(Debug, Clone)]
3560pub struct DoStmt {
3561    pub value: Expr,
3562    pub span: Span,
3563    pub trivia: Trivia,
3564}
3565
3566#[derive(Debug, Clone)]
3567pub struct Param {
3568    pub name: Ident,
3569    pub type_ref: TypeRef,
3570    pub span: Span,
3571}
3572
3573#[derive(Debug, Clone)]
3574pub enum TypeRef {
3575    Base(BaseType, Span),
3576    Named(Ident),
3577    /// `Result[T, E]` — the built-in generic Result type (v0.1).
3578    Result(Box<TypeRef>, Box<TypeRef>, Span),
3579    /// `Option[T]` — the built-in generic Option type (v0.2).
3580    Option(Box<TypeRef>, Span),
3581    /// `Effect[T]` — the built-in generic Effect type (v0.5).
3582    Effect(Box<TypeRef>, Span),
3583    /// `HttpResult[T]` — the built-in HTTP-result sum (v0.9).
3584    HttpResult(Box<TypeRef>, Span),
3585    /// `QueueResult` — the built-in queue verdict sum (`Ack | Retry`),
3586    /// non-generic; the required return of a queue handler (v0.44).
3587    QueueResult(Span),
3588    /// `Asset` — a static file declared by `asset name = "path"` (#1883,
3589    /// slice 1a, [DECISION H]). Non-generic, like `QueueResult`; its one
3590    /// field is `.url : String`.
3591    Asset(Span),
3592    /// `RequestHeaders` (#2341, decision A) — an HTTP handler's read-only view
3593    /// of the request's headers, the type of its `headers` parameter.
3594    /// Non-generic and opaque: `get`, `bearer`, `clientIp`. Never stored or
3595    /// sent (it has no wire form).
3596    RequestHeaders(Span),
3597    /// `RequestQuery` (#2854, decision B) — an HTTP handler's read-only view
3598    /// of the request's query string, the type of its `query` parameter when
3599    /// it wants raw access: `get`, `all`, `params`. Never stored or sent.
3600    RequestQuery(Span),
3601    /// `RequestCookies` (#3277, decision A) — an HTTP handler's read-only view
3602    /// of the request's `Cookie` header, the type of its `cookies` parameter
3603    /// when it wants raw access (a prefixed name such as `__Host-sid`): `get`,
3604    /// `all`, `names`. Never stored or sent.
3605    RequestCookies(Span),
3606    /// `TokenClaims` (#2380, L5) — the verified claims of an `Oidc` actor's
3607    /// token, read through its binder (`who.claims`). Read-only, never stored
3608    /// or sent.
3609    TokenClaims(Span),
3610    /// `BoundaryRejection` (#2341, decision C) — why the router refused a
3611    /// request before any handler ran; the type of an `on rejected` handler's
3612    /// parameter. Opaque here (its variants are matched, never built). Never
3613    /// stored or sent.
3614    BoundaryRejection(Span),
3615    /// `List[T]` — the built-in generic immutable list type (v0.20b).
3616    List(Box<TypeRef>, Span),
3617    /// `Map[K, V]` — the built-in generic immutable map type (v0.20b).
3618    /// Keys are confined to `Key` types
3619    /// (`bynk.types.not_keyable`).
3620    Map(Box<TypeRef>, Box<TypeRef>, Span),
3621    /// `Set[T]` — the built-in generic immutable set type (standard-library
3622    /// K6a, #2596). Insertion-ordered like `Map`; elements are confined to the
3623    /// `Map`-key rule (`bynk.types.not_keyable`).
3624    Set(Box<TypeRef>, Span),
3625    /// `Query[T]` — the built-in lazy storage-read description (v0.91, ADR 0115).
3626    /// Nameable in a pure helper's return type; non-storable and non-boundary
3627    /// (like `Effect`/`Fn`).
3628    Query(Box<TypeRef>, Span),
3629    /// `Stream[T]` — the value-over-time primitive (v0.100, real-time track
3630    /// slice 0). A lazy, pull-shaped sequence produced over time; non-storable
3631    /// and non-boundary (like `Query`/`Effect`/`Fn`).
3632    Stream(Box<TypeRef>, Span),
3633    /// `Connection[F]` — a held WebSocket connection (v0.102, real-time track
3634    /// slice 2). `F` is the server→client frame type. A `Held` resource:
3635    /// non-serialisable, non-boundary, and governed by the linearity discipline
3636    /// (§2.9); storable only in `Cell[Option[Connection]]` / `Map[K, Connection]`.
3637    Connection(Box<TypeRef>, Span),
3638    /// `History[Agent]` — a generated, driven call-history of an agent (v0.119,
3639    /// testing track slice 7, ADR 0155). A test-only generator, legal only in
3640    /// `for all` binding position inside a `property`; it is not a value type,
3641    /// so it never resolves in a field/param/return position. The bound subject
3642    /// behaves as an ordinary `List[Step]`.
3643    History(Box<TypeRef>, Span),
3644    /// `ValidationError` — the built-in error type used by refined-type
3645    /// constructors (v0.1).
3646    ValidationError(Span),
3647    /// `DecodeError` — the built-in JSON-decode error type (v0.22b). A
3648    /// uniform record (`kind`/`path`/`message`, all `String`) the codec
3649    /// maps `BoundaryError` variants and parse failures into.
3650    DecodeError(Span),
3651    /// `()` — the unit type (v0.5).
3652    Unit(Span),
3653    /// `A -> B` / `(A, B) -> C` / `() -> B` — a function type (v0.20a).
3654    /// Right-associative; effectful iff the return type is `Effect[_]`
3655    /// (the structural rule). Confined to non-boundary positions
3656    /// (`bynk.types.function_at_boundary`).
3657    Fn(Vec<TypeRef>, Box<TypeRef>, Span),
3658    /// `Name[Arg, …]` — an application of a user-declared generic type
3659    /// (v0.157, ADR 0183). `name` is a user type name (never a built-in
3660    /// generic, which each have a dedicated variant above). Arity and the
3661    /// existence of the referenced type are checked in the resolver.
3662    App {
3663        name: Ident,
3664        args: Vec<TypeRef>,
3665        span: Span,
3666    },
3667}
3668
3669impl TypeRef {
3670    pub fn span(&self) -> Span {
3671        match self {
3672            TypeRef::Base(_, s) => *s,
3673            TypeRef::Named(id) => id.span,
3674            TypeRef::Result(_, _, s) => *s,
3675            TypeRef::Option(_, s) => *s,
3676            TypeRef::Effect(_, s) => *s,
3677            TypeRef::HttpResult(_, s) => *s,
3678            TypeRef::QueueResult(s) => *s,
3679            TypeRef::Asset(s) => *s,
3680            TypeRef::RequestHeaders(s) => *s,
3681            TypeRef::RequestQuery(s) => *s,
3682            TypeRef::RequestCookies(s) => *s,
3683            TypeRef::TokenClaims(s) => *s,
3684            TypeRef::BoundaryRejection(s) => *s,
3685            TypeRef::List(_, s) => *s,
3686            TypeRef::Map(_, _, s) => *s,
3687            TypeRef::Set(_, s) => *s,
3688            TypeRef::Query(_, s) => *s,
3689            TypeRef::Stream(_, s) => *s,
3690            TypeRef::Connection(_, s) => *s,
3691            TypeRef::History(_, s) => *s,
3692            TypeRef::ValidationError(s) => *s,
3693            TypeRef::DecodeError(s) => *s,
3694            TypeRef::Unit(s) => *s,
3695            TypeRef::Fn(_, _, s) => *s,
3696            TypeRef::App { span, .. } => *span,
3697        }
3698    }
3699}
3700
3701/// K-streams (#2623): where `t` reaches a `Stream`, as the chain of fields it
3702/// is reached through (`["Bundle.download", "Download.body"]`), or `None`. A
3703/// bare `Stream` (or one inside a wrapper) is the empty chain. A record or sum
3704/// may carry a stream; such a type is then non-boundary like the stream
3705/// itself, and this is the walk every boundary check uses to find it. It
3706/// follows named and applied types into their declarations (a generic
3707/// record's own fields too, so `Wrap[T] = { s: Stream[T] }` is found through
3708/// `Wrap[Int]`), but not into a function type, which is rejected at a
3709/// boundary on its own. Terminates via the `visited` set.
3710pub fn stream_path(
3711    t: &TypeRef,
3712    types: &std::collections::HashMap<String, std::sync::Arc<TypeDecl>>,
3713) -> Option<Vec<String>> {
3714    fn walk(
3715        t: &TypeRef,
3716        types: &std::collections::HashMap<String, std::sync::Arc<TypeDecl>>,
3717        visited: &mut std::collections::HashSet<String>,
3718    ) -> Option<Vec<String>> {
3719        match t {
3720            TypeRef::Stream(..) => Some(Vec::new()),
3721            TypeRef::Named(id) => named(&id.name, types, visited),
3722            TypeRef::App { name, args, .. } => named(&name.name, types, visited)
3723                .or_else(|| args.iter().find_map(|a| walk(a, types, visited))),
3724            TypeRef::Option(a, _)
3725            | TypeRef::List(a, _)
3726            | TypeRef::Set(a, _)
3727            | TypeRef::Effect(a, _)
3728            | TypeRef::HttpResult(a, _)
3729            | TypeRef::Query(a, _)
3730            | TypeRef::Connection(a, _)
3731            | TypeRef::History(a, _) => walk(a, types, visited),
3732            TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
3733                walk(a, types, visited).or_else(|| walk(b, types, visited))
3734            }
3735            TypeRef::Fn(..)
3736            | TypeRef::Base(..)
3737            | TypeRef::QueueResult(_)
3738            | TypeRef::Asset(_)
3739            | TypeRef::RequestHeaders(_)
3740            | TypeRef::RequestQuery(_)
3741            | TypeRef::RequestCookies(_)
3742            | TypeRef::TokenClaims(_)
3743            | TypeRef::BoundaryRejection(_)
3744            | TypeRef::ValidationError(_)
3745            | TypeRef::DecodeError(_)
3746            | TypeRef::Unit(_) => None,
3747        }
3748    }
3749    fn named(
3750        name: &str,
3751        types: &std::collections::HashMap<String, std::sync::Arc<TypeDecl>>,
3752        visited: &mut std::collections::HashSet<String>,
3753    ) -> Option<Vec<String>> {
3754        if !visited.insert(name.to_string()) {
3755            return None;
3756        }
3757        let decl = types.get(name)?;
3758        let fields: Vec<(String, &TypeRef)> = match &decl.body {
3759            TypeBody::Record(r) => r
3760                .fields
3761                .iter()
3762                .map(|f| (format!("{name}.{}", f.name.name), &f.type_ref))
3763                .collect(),
3764            TypeBody::Sum(s) => s
3765                .variants
3766                .iter()
3767                .flat_map(|v| {
3768                    v.payload.iter().map(move |p| {
3769                        (
3770                            format!("{name}.{}.{}", v.name.name, p.name.name),
3771                            &p.type_ref,
3772                        )
3773                    })
3774                })
3775                .collect(),
3776            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => Vec::new(),
3777        };
3778        fields.into_iter().find_map(|(at, t)| {
3779            walk(t, types, visited).map(|mut rest| {
3780                rest.insert(0, at);
3781                rest
3782            })
3783        })
3784    }
3785    walk(t, types, &mut std::collections::HashSet::new())
3786}
3787
3788/// K-streams (#2623): whether the named type `name` carries a `Stream` in a
3789/// field, at any depth ([`stream_path`]). Such a type has no codec.
3790pub fn type_carries_stream(
3791    name: &str,
3792    types: &std::collections::HashMap<String, std::sync::Arc<TypeDecl>>,
3793) -> bool {
3794    stream_path(
3795        &TypeRef::Named(Ident {
3796            name: name.to_string(),
3797            span: Span::default(),
3798        }),
3799        types,
3800    )
3801    .is_some()
3802}
3803
3804/// Every type name a type mentions (heads of applications and named types,
3805/// descending through wrappers and generic arguments), pushed onto `out`.
3806fn heads(t: &TypeRef, out: &mut Vec<String>) {
3807    match t {
3808        TypeRef::Named(id) => out.push(id.name.clone()),
3809        TypeRef::App {
3810            name: app_name,
3811            args,
3812            ..
3813        } => {
3814            out.push(app_name.name.clone());
3815            for a in args {
3816                heads(a, out);
3817            }
3818        }
3819        TypeRef::Option(a, _)
3820        | TypeRef::List(a, _)
3821        | TypeRef::Set(a, _)
3822        | TypeRef::Effect(a, _)
3823        | TypeRef::HttpResult(a, _)
3824        | TypeRef::Query(a, _)
3825        | TypeRef::Stream(a, _)
3826        | TypeRef::Connection(a, _)
3827        | TypeRef::History(a, _) => heads(a, out),
3828        TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
3829            heads(a, out);
3830            heads(b, out);
3831        }
3832        TypeRef::Fn(ps, r, _) => {
3833            for p in ps {
3834                heads(p, out);
3835            }
3836            heads(r, out);
3837        }
3838        TypeRef::Base(..)
3839        | TypeRef::QueueResult(_)
3840        | TypeRef::Asset(_)
3841        | TypeRef::RequestHeaders(_)
3842        | TypeRef::RequestQuery(_)
3843        | TypeRef::RequestCookies(_)
3844        | TypeRef::TokenClaims(_)
3845        | TypeRef::BoundaryRejection(_)
3846        | TypeRef::ValidationError(_)
3847        | TypeRef::DecodeError(_)
3848        | TypeRef::Unit(_) => {}
3849    }
3850}
3851fn body_heads(decl: &TypeDecl, out: &mut Vec<String>) {
3852    match &decl.body {
3853        TypeBody::Record(r) => {
3854            for f in &r.fields {
3855                heads(&f.type_ref, out);
3856            }
3857        }
3858        TypeBody::Sum(s) => {
3859            for v in &s.variants {
3860                for p in &v.payload {
3861                    heads(&p.type_ref, out);
3862                }
3863            }
3864        }
3865        TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
3866    }
3867}
3868
3869/// Whether type `to` is reachable from the body of type `from`, following every
3870/// named / applied head. Terminates via a `visited` set.
3871fn type_reaches(
3872    from: &str,
3873    to: &str,
3874    types: &std::collections::HashMap<String, std::sync::Arc<TypeDecl>>,
3875) -> bool {
3876    let Some(root) = types.get(from) else {
3877        return false;
3878    };
3879    let mut visited: std::collections::HashSet<String> = std::collections::HashSet::new();
3880    let mut stack: Vec<String> = Vec::new();
3881    body_heads(root, &mut stack);
3882    while let Some(n) = stack.pop() {
3883        if n == to {
3884            return true;
3885        }
3886        if !visited.insert(n.clone()) {
3887            continue;
3888        }
3889        if let Some(decl) = types.get(&n) {
3890            body_heads(decl, &mut stack);
3891        }
3892    }
3893    false
3894}
3895
3896/// v0.174 (#592): does the generic record type `name` transitively contain a
3897/// reference to itself — through any field-type path, including collection and
3898/// `Option` wrappers, sum-variant payloads, and generic type arguments? Such a
3899/// type has no finite set of monomorphised boundary codecs: uniform recursion
3900/// (`Node[T] = { next: Option[Node[T]] }`) would need a self-referential codec
3901/// chain the per-instantiation model does not yet generate, and polymorphic
3902/// recursion (`Weird[T] = { next: Option[Weird[List[T]]] }`) an unbounded set of
3903/// instantiations. A recursive generic declares and works in memory; it is
3904/// refused only where a codec is required
3905/// (`bynk.generics.recursive_generic_at_boundary`, found by
3906/// [`recursive_generic_path`]), and polymorphic recursion is refused at its
3907/// declaration (`bynk.generics.polymorphic_recursion`, found by
3908/// [`polymorphic_recursion_edges`]).
3909///
3910/// Detection is reachability over the type-containment graph: `name` is
3911/// recursive iff it is reachable from its own body, following every named /
3912/// applied head and descending into every wrapper, map/result pair, function
3913/// position, and generic argument. Terminates via the `visited` set.
3914pub fn generic_record_is_recursive(
3915    name: &str,
3916    types: &std::collections::HashMap<String, std::sync::Arc<TypeDecl>>,
3917) -> bool {
3918    type_reaches(name, name, types)
3919}
3920
3921/// #3192: a recursive generic type reached from some type, and how.
3922#[derive(Debug, Clone, PartialEq, Eq)]
3923pub struct RecursiveGenericPath {
3924    /// The recursive generic declaration's name.
3925    pub name: String,
3926    /// `"record"` or `"sum"`, from the declaration.
3927    pub noun: &'static str,
3928    /// The field chain the generic is reached through from the type asked
3929    /// about (`["Holder.t"]`); empty when the type is itself an application of
3930    /// the recursive generic.
3931    pub path: Vec<String>,
3932}
3933
3934/// #3192: where `t` reaches an application of a recursive generic type
3935/// ([`generic_record_is_recursive`]), as the field chain it is reached through.
3936/// A recursive generic declares and works in memory but has no codec yet, so
3937/// every position that serialises uses this walk. It follows named and applied
3938/// types into their declarations, as [`stream_path`] does, so a record that
3939/// merely *contains* `Tree[Int]` is found where the record is used. It does not
3940/// enter a function type, which is refused at a boundary on its own. Terminates
3941/// via the `visited` set.
3942pub fn recursive_generic_path(
3943    t: &TypeRef,
3944    types: &std::collections::HashMap<String, std::sync::Arc<TypeDecl>>,
3945) -> Option<RecursiveGenericPath> {
3946    fn walk(
3947        t: &TypeRef,
3948        types: &std::collections::HashMap<String, std::sync::Arc<TypeDecl>>,
3949        visited: &mut std::collections::HashSet<String>,
3950    ) -> Option<RecursiveGenericPath> {
3951        match t {
3952            TypeRef::App { name, args, .. } => {
3953                if types
3954                    .get(&name.name)
3955                    .is_some_and(|d| !d.type_params.is_empty())
3956                    && generic_record_is_recursive(&name.name, types)
3957                {
3958                    return Some(RecursiveGenericPath {
3959                        noun: match types.get(&name.name).map(|d| &d.body) {
3960                            Some(TypeBody::Sum(_)) => "sum",
3961                            _ => "record",
3962                        },
3963                        name: name.name.clone(),
3964                        path: Vec::new(),
3965                    });
3966                }
3967                named(&name.name, types, visited)
3968                    .or_else(|| args.iter().find_map(|a| walk(a, types, visited)))
3969            }
3970            TypeRef::Named(id) => named(&id.name, types, visited),
3971            TypeRef::Option(a, _)
3972            | TypeRef::List(a, _)
3973            | TypeRef::Set(a, _)
3974            | TypeRef::Effect(a, _)
3975            | TypeRef::HttpResult(a, _)
3976            | TypeRef::Query(a, _)
3977            | TypeRef::Connection(a, _)
3978            | TypeRef::History(a, _) => walk(a, types, visited),
3979            TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
3980                walk(a, types, visited).or_else(|| walk(b, types, visited))
3981            }
3982            TypeRef::Stream(..)
3983            | TypeRef::Fn(..)
3984            | TypeRef::Base(..)
3985            | TypeRef::QueueResult(_)
3986            | TypeRef::Asset(_)
3987            | TypeRef::RequestHeaders(_)
3988            | TypeRef::RequestQuery(_)
3989            | TypeRef::RequestCookies(_)
3990            | TypeRef::TokenClaims(_)
3991            | TypeRef::BoundaryRejection(_)
3992            | TypeRef::ValidationError(_)
3993            | TypeRef::DecodeError(_)
3994            | TypeRef::Unit(_) => None,
3995        }
3996    }
3997    fn named(
3998        name: &str,
3999        types: &std::collections::HashMap<String, std::sync::Arc<TypeDecl>>,
4000        visited: &mut std::collections::HashSet<String>,
4001    ) -> Option<RecursiveGenericPath> {
4002        if !visited.insert(name.to_string()) {
4003            return None;
4004        }
4005        let decl = types.get(name)?;
4006        let fields: Vec<(String, &TypeRef)> = match &decl.body {
4007            TypeBody::Record(r) => r
4008                .fields
4009                .iter()
4010                .map(|f| (format!("{name}.{}", f.name.name), &f.type_ref))
4011                .collect(),
4012            TypeBody::Sum(s) => s
4013                .variants
4014                .iter()
4015                .flat_map(|v| {
4016                    v.payload.iter().map(move |p| {
4017                        (
4018                            format!("{name}.{}.{}", v.name.name, p.name.name),
4019                            &p.type_ref,
4020                        )
4021                    })
4022                })
4023                .collect(),
4024            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => Vec::new(),
4025        };
4026        fields.into_iter().find_map(|(at, t)| {
4027            walk(t, types, visited).map(|mut rest| {
4028                rest.path.insert(0, at);
4029                rest
4030            })
4031        })
4032    }
4033    walk(t, types, &mut std::collections::HashSet::new())
4034}
4035
4036/// #3192: the recursive edges of generic type `decl` that are not *uniform*,
4037/// as `(callee, span)`. A recursive edge is an application, in the body, of a
4038/// generic that reaches `decl` again (`decl` itself, or a mutually recursive
4039/// partner); it is uniform when its arguments are exactly `decl`'s own type
4040/// parameters, in order. Anything else (`Weird[List[T]]` inside `Weird[T]`,
4041/// `Pair[B, A]` inside `Pair[A, B]`) is polymorphic recursion, which generates
4042/// an unbounded set of instantiations and is refused at the declaration
4043/// (`bynk.generics.polymorphic_recursion`). Conservative by design.
4044pub fn polymorphic_recursion_edges(
4045    decl: &TypeDecl,
4046    types: &std::collections::HashMap<String, std::sync::Arc<TypeDecl>>,
4047) -> Vec<(String, Span)> {
4048    fn apps<'a>(t: &'a TypeRef, out: &mut Vec<(&'a Ident, &'a [TypeRef], Span)>) {
4049        match t {
4050            TypeRef::App { name, args, span } => {
4051                out.push((name, args, *span));
4052                for a in args {
4053                    apps(a, out);
4054                }
4055            }
4056            TypeRef::Option(a, _)
4057            | TypeRef::List(a, _)
4058            | TypeRef::Set(a, _)
4059            | TypeRef::Effect(a, _)
4060            | TypeRef::HttpResult(a, _)
4061            | TypeRef::Query(a, _)
4062            | TypeRef::Stream(a, _)
4063            | TypeRef::Connection(a, _)
4064            | TypeRef::History(a, _) => apps(a, out),
4065            TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
4066                apps(a, out);
4067                apps(b, out);
4068            }
4069            TypeRef::Fn(ps, r, _) => {
4070                for p in ps {
4071                    apps(p, out);
4072                }
4073                apps(r, out);
4074            }
4075            TypeRef::Named(_)
4076            | TypeRef::Base(..)
4077            | TypeRef::QueueResult(_)
4078            | TypeRef::Asset(_)
4079            | TypeRef::RequestHeaders(_)
4080            | TypeRef::RequestQuery(_)
4081            | TypeRef::RequestCookies(_)
4082            | TypeRef::TokenClaims(_)
4083            | TypeRef::BoundaryRejection(_)
4084            | TypeRef::ValidationError(_)
4085            | TypeRef::DecodeError(_)
4086            | TypeRef::Unit(_) => {}
4087        }
4088    }
4089    if decl.type_params.is_empty() || !generic_record_is_recursive(&decl.name.name, types) {
4090        return Vec::new();
4091    }
4092    let mut found = Vec::new();
4093    match &decl.body {
4094        TypeBody::Record(r) => {
4095            for f in &r.fields {
4096                apps(&f.type_ref, &mut found);
4097            }
4098        }
4099        TypeBody::Sum(s) => {
4100            for v in &s.variants {
4101                for p in &v.payload {
4102                    apps(&p.type_ref, &mut found);
4103                }
4104            }
4105        }
4106        TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
4107    }
4108    found
4109        .into_iter()
4110        .filter(|(callee, args, _)| {
4111            if !type_reaches(&callee.name, &decl.name.name, types) {
4112                return false;
4113            }
4114            if callee.name == decl.name.name {
4115                // A self-reference passes the parameters through unchanged.
4116                return !(args.len() == decl.type_params.len()
4117                    && args
4118                        .iter()
4119                        .zip(&decl.type_params)
4120                        .all(|(a, p)| matches!(a, TypeRef::Named(id) if id.name == p.name.name)));
4121            }
4122            // A mutually recursive partner (of any arity) may be applied to the
4123            // declaration's own parameters or to types that mention none: each
4124            // argument then comes from a finite set, so only finitely many
4125            // instantiations are reachable. Anything that wraps a parameter
4126            // (`List[T]`) grows without bound.
4127            !args.iter().all(|a| {
4128                let mut names = Vec::new();
4129                heads(a, &mut names);
4130                match a {
4131                    TypeRef::Named(id) => {
4132                        decl.type_params.iter().any(|p| p.name.name == id.name)
4133                            || !names
4134                                .iter()
4135                                .any(|n| decl.type_params.iter().any(|p| &p.name.name == n))
4136                    }
4137                    _ => !names
4138                        .iter()
4139                        .any(|n| decl.type_params.iter().any(|p| &p.name.name == n)),
4140                }
4141            })
4142        })
4143        .map(|(callee, _, span)| (callee.name.clone(), span))
4144        .collect()
4145}
4146
4147/// T3.4 (R2.4): a node's identity, independent of position — allocated once,
4148/// monotonically, per expression the parser constructs (`Parser::alloc_expr_id`
4149/// in `bynk-syntax/src/parser.rs`). Never derived from a `Span`, so two
4150/// expressions occupying the same byte range (a synthetic node, a
4151/// zero-width span) never collide the way a span-keyed side table could.
4152#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
4153pub struct ExprId(pub u32);
4154
4155impl ExprId {
4156    /// Reserved for `Expr` nodes built outside the parser — after checking,
4157    /// during emission — that are never looked up in a checker-populated
4158    /// `expr_types`/`expr_ty` table (they are lowered directly, from
4159    /// already-typed sub-expressions they wrap or splice). A lookup against
4160    /// this id is a bug: the node was never checked and has no recorded
4161    /// type of its own.
4162    pub const SYNTHETIC: ExprId = ExprId(u32::MAX);
4163}
4164
4165#[derive(Debug, Clone)]
4166pub struct Expr {
4167    pub id: ExprId,
4168    pub kind: ExprKind,
4169    pub span: Span,
4170}
4171
4172/// Finding #31: `Expr` sets the size of every expression node in the
4173/// program — `ExprKind::Observation`'s payload and `ExprKind::Is`'s pattern
4174/// field are boxed specifically to keep it small (176 bytes unboxed, 128
4175/// boxed, measured on this target). Pinned so the next large variant added
4176/// to `ExprKind` is a compile error here rather than a silent regression.
4177/// T3.4: `id: ExprId` adds 4 bytes (padded); the budget is unchanged, so this
4178/// still fits.
4179/// T3.4 (R2.4): `id: ExprId` is a deliberate 8-byte increase (128 → 136,
4180/// alignment-padded from 4), not a silent regression — the ceiling moves
4181/// with it, once, here, so the next *accidental* growth still trips this
4182/// assertion rather than hiding under slack headroom.
4183/// T3.5 (R2.2): `file: FileId` on `Span` is a deliberate increase (136 → 160
4184/// — `Span` itself grows from 16 to 24 bytes with alignment padding, and
4185/// `ExprKind`'s largest variant carries more than one `Span`), not a silent
4186/// regression — the ceiling moves with it, once, here, exactly as T3.4 did
4187/// for `id: ExprId`.
4188const _: () = assert!(std::mem::size_of::<Expr>() <= 160);
4189
4190impl ExprKind {
4191    /// Construct an `IntLit` for a *synthesized* integer — one the compiler
4192    /// invents rather than reading from source (a default `1`, a computed bound).
4193    /// The lexeme is the canonical decimal form (no separators). Source-parsed
4194    /// literals keep their as-written lexeme instead (v0.142, ADR 0166).
4195    pub fn int_lit(value: i64) -> ExprKind {
4196        ExprKind::IntLit {
4197            value,
4198            lexeme: value.to_string(),
4199        }
4200    }
4201
4202    /// The link of a plain access chain (`a`, `a.b`, `(a.b).c`) this expression is, if it
4203    /// is one: a root name, a field read off an inner expression, or a bracketed inner
4204    /// expression. Every other expression is not part of a chain.
4205    ///
4206    /// The emitter asks this to decide whether a receiver is a repeatable, side-effect-free
4207    /// lvalue it can name more than once; they follow the links inwards through
4208    /// [`ChainLink::Field`] and [`ChainLink::Paren`] until a root, or a non-link, ends the walk.
4209    pub fn chain_link(&self) -> Option<ChainLink<'_>> {
4210        match self {
4211            ExprKind::Ident(id) => Some(ChainLink::Root(id)),
4212            ExprKind::FieldAccess { receiver, field } => Some(ChainLink::Field { receiver, field }),
4213            ExprKind::Paren(inner) => Some(ChainLink::Paren(inner)),
4214            ExprKind::IntLit { .. }
4215            | ExprKind::FloatLit { .. }
4216            | ExprKind::DecimalLit { .. }
4217            | ExprKind::DurationLit { .. }
4218            | ExprKind::StrLit(..)
4219            | ExprKind::InterpStr(..)
4220            | ExprKind::BoolLit(..)
4221            | ExprKind::Call { .. }
4222            | ExprKind::Lambda(..)
4223            | ExprKind::BinOp(..)
4224            | ExprKind::UnaryOp(..)
4225            | ExprKind::Block(..)
4226            | ExprKind::If { .. }
4227            | ExprKind::Ok(..)
4228            | ExprKind::Err(..)
4229            | ExprKind::Question(..)
4230            | ExprKind::RecordConstruction { .. }
4231            | ExprKind::MethodCall { .. }
4232            | ExprKind::Match { .. }
4233            | ExprKind::Is { .. }
4234            | ExprKind::Some(..)
4235            | ExprKind::None
4236            | ExprKind::UnitLit
4237            | ExprKind::RecordSpread { .. }
4238            | ExprKind::EffectPure(..)
4239            | ExprKind::Expect(..)
4240            | ExprKind::Val { .. }
4241            | ExprKind::Wire(..)
4242            | ExprKind::ListLit(..)
4243            | ExprKind::Observation(..)
4244            | ExprKind::Faults(..)
4245            | ExprKind::Trace { .. } => None,
4246        }
4247    }
4248
4249    /// The compile-time number or string a refined type may admit as a literal, with
4250    /// its sign: an integer, float, decimal or string literal, or a negated number
4251    /// (`-3`). The checker folds the sign in its own constant reading, so a lowering
4252    /// that routes the literal through `unsafe` must see the negated form as one
4253    /// literal. Every other expression, a negated string included, is not one.
4254    pub fn refinable_literal(&self) -> Option<RefinableLiteral<'_>> {
4255        match self {
4256            ExprKind::StrLit(s) => Some(RefinableLiteral::Str(s)),
4257            ExprKind::UnaryOp(op, inner) => match op {
4258                UnaryOp::Neg => inner.kind.number_literal(true),
4259                UnaryOp::Not => None,
4260            },
4261            ExprKind::IntLit { .. } | ExprKind::FloatLit { .. } | ExprKind::DecimalLit { .. } => {
4262                self.number_literal(false)
4263            }
4264            ExprKind::DurationLit { .. }
4265            | ExprKind::InterpStr(..)
4266            | ExprKind::BoolLit(..)
4267            | ExprKind::Ident(..)
4268            | ExprKind::Call { .. }
4269            | ExprKind::Lambda(..)
4270            | ExprKind::BinOp(..)
4271            | ExprKind::Paren(..)
4272            | ExprKind::Block(..)
4273            | ExprKind::If { .. }
4274            | ExprKind::Ok(..)
4275            | ExprKind::Err(..)
4276            | ExprKind::Question(..)
4277            | ExprKind::RecordConstruction { .. }
4278            | ExprKind::FieldAccess { .. }
4279            | ExprKind::MethodCall { .. }
4280            | ExprKind::Match { .. }
4281            | ExprKind::Is { .. }
4282            | ExprKind::Some(..)
4283            | ExprKind::None
4284            | ExprKind::UnitLit
4285            | ExprKind::RecordSpread { .. }
4286            | ExprKind::EffectPure(..)
4287            | ExprKind::Expect(..)
4288            | ExprKind::Val { .. }
4289            | ExprKind::Wire(..)
4290            | ExprKind::ListLit(..)
4291            | ExprKind::Observation(..)
4292            | ExprKind::Faults(..)
4293            | ExprKind::Trace { .. } => None,
4294        }
4295    }
4296
4297    /// An integer, float or decimal literal, read with the given sign.
4298    fn number_literal(&self, negated: bool) -> Option<RefinableLiteral<'_>> {
4299        match self {
4300            ExprKind::IntLit { value, .. } => Some(RefinableLiteral::Int {
4301                value: *value,
4302                negated,
4303            }),
4304            ExprKind::FloatLit { lexeme, .. } => Some(RefinableLiteral::Float { lexeme, negated }),
4305            ExprKind::DecimalLit { coef, scale, .. } => Some(RefinableLiteral::Decimal {
4306                coef,
4307                scale: *scale,
4308                negated,
4309            }),
4310            ExprKind::DurationLit { .. }
4311            | ExprKind::StrLit(..)
4312            | ExprKind::InterpStr(..)
4313            | ExprKind::BoolLit(..)
4314            | ExprKind::Ident(..)
4315            | ExprKind::Call { .. }
4316            | ExprKind::Lambda(..)
4317            | ExprKind::BinOp(..)
4318            | ExprKind::UnaryOp(..)
4319            | ExprKind::Paren(..)
4320            | ExprKind::Block(..)
4321            | ExprKind::If { .. }
4322            | ExprKind::Ok(..)
4323            | ExprKind::Err(..)
4324            | ExprKind::Question(..)
4325            | ExprKind::RecordConstruction { .. }
4326            | ExprKind::FieldAccess { .. }
4327            | ExprKind::MethodCall { .. }
4328            | ExprKind::Match { .. }
4329            | ExprKind::Is { .. }
4330            | ExprKind::Some(..)
4331            | ExprKind::None
4332            | ExprKind::UnitLit
4333            | ExprKind::RecordSpread { .. }
4334            | ExprKind::EffectPure(..)
4335            | ExprKind::Expect(..)
4336            | ExprKind::Val { .. }
4337            | ExprKind::Wire(..)
4338            | ExprKind::ListLit(..)
4339            | ExprKind::Observation(..)
4340            | ExprKind::Faults(..)
4341            | ExprKind::Trace { .. } => None,
4342        }
4343    }
4344
4345    /// The two expressions that choose between branches, `match` and `if`: the shape of
4346    /// each, or `None` for any other expression. The emitter writes a tail `match` or
4347    /// `if` as statements rather than as an expression, and asks this where it decides.
4348    pub fn branching(&self) -> Option<Branching<'_>> {
4349        match self {
4350            ExprKind::Match { discriminant, arms } => Some(Branching::Match { discriminant, arms }),
4351            ExprKind::If {
4352                cond,
4353                then_block,
4354                else_block,
4355            } => Some(Branching::If {
4356                cond,
4357                then_block,
4358                else_block,
4359            }),
4360            ExprKind::IntLit { .. }
4361            | ExprKind::FloatLit { .. }
4362            | ExprKind::DecimalLit { .. }
4363            | ExprKind::DurationLit { .. }
4364            | ExprKind::StrLit(..)
4365            | ExprKind::InterpStr(..)
4366            | ExprKind::BoolLit(..)
4367            | ExprKind::Ident(..)
4368            | ExprKind::Call { .. }
4369            | ExprKind::Lambda(..)
4370            | ExprKind::BinOp(..)
4371            | ExprKind::UnaryOp(..)
4372            | ExprKind::Paren(..)
4373            | ExprKind::Block(..)
4374            | ExprKind::Ok(..)
4375            | ExprKind::Err(..)
4376            | ExprKind::Question(..)
4377            | ExprKind::RecordConstruction { .. }
4378            | ExprKind::FieldAccess { .. }
4379            | ExprKind::MethodCall { .. }
4380            | ExprKind::Is { .. }
4381            | ExprKind::Some(..)
4382            | ExprKind::None
4383            | ExprKind::UnitLit
4384            | ExprKind::RecordSpread { .. }
4385            | ExprKind::EffectPure(..)
4386            | ExprKind::Expect(..)
4387            | ExprKind::Val { .. }
4388            | ExprKind::Wire(..)
4389            | ExprKind::ListLit(..)
4390            | ExprKind::Observation(..)
4391            | ExprKind::Faults(..)
4392            | ExprKind::Trace { .. } => None,
4393        }
4394    }
4395}
4396
4397/// A branching expression, as [`ExprKind::branching`] reads it.
4398#[derive(Debug, Clone, Copy)]
4399pub enum Branching<'a> {
4400    /// `match discriminant { arms }`.
4401    Match {
4402        discriminant: &'a Expr,
4403        arms: &'a [MatchArm],
4404    },
4405    /// `if cond { then_block } else { else_block }`.
4406    If {
4407        cond: &'a Expr,
4408        then_block: &'a Block,
4409        else_block: &'a Block,
4410    },
4411}
4412
4413/// A literal [`ExprKind::refinable_literal`] reads: its data, borrowed from the expression.
4414#[derive(Debug, Clone, Copy, PartialEq)]
4415pub enum RefinableLiteral<'a> {
4416    /// An integer literal; `negated` when written `-n`.
4417    Int { value: i64, negated: bool },
4418    /// A float literal, as its source lexeme; `negated` when written `-x`.
4419    Float { lexeme: &'a str, negated: bool },
4420    /// A decimal literal's coefficient digits and scale; `negated` when written `-d`.
4421    Decimal {
4422        coef: &'a str,
4423        scale: u32,
4424        negated: bool,
4425    },
4426    /// A string literal's value.
4427    Str(&'a str),
4428}
4429
4430/// One link of a plain access chain, as [`ExprKind::chain_link`] reads it.
4431#[derive(Debug, Clone, Copy)]
4432pub enum ChainLink<'a> {
4433    /// The name the chain starts at.
4434    Root(&'a Ident),
4435    /// `receiver.field`: the chain continues in `receiver`.
4436    Field {
4437        receiver: &'a Expr,
4438        field: &'a Ident,
4439    },
4440    /// `(inner)`: the chain continues in `inner`.
4441    Paren(&'a Expr),
4442}
4443
4444#[derive(Debug, Clone)]
4445pub enum ExprKind {
4446    /// An integer literal (typed `Int`). The lexeme is kept alongside the parsed
4447    /// value (v0.142, ADR 0166) so formatting is byte-stable: an author's `_`
4448    /// digit separators (`1_048_576`) survive a round-trip, mirroring the
4449    /// `FloatLit` treatment. The value is separator-free; emission lowers the
4450    /// value, so emitted output is unaffected.
4451    IntLit {
4452        value: i64,
4453        lexeme: String,
4454    },
4455    /// A float literal (v0.21). The lexeme is kept alongside the parsed
4456    /// value so emission and formatting are byte-stable (`1e10` must not
4457    /// normalise to `10000000000`).
4458    FloatLit {
4459        value: f64,
4460        lexeme: String,
4461    },
4462    /// A decimal literal (#2622): `1.20d`, `5d`. Typed `Decimal`; the scale is
4463    /// the number of fraction digits as written, so `1.20d` keeps scale 2.
4464    DecimalLit {
4465        /// The coefficient: the digits with the `.` and `_` separators removed
4466        /// (`120` for `1.20d`), as an arbitrary-precision base-10 string.
4467        coef: String,
4468        /// The number of fraction digits as written (`2` for `1.20d`).
4469        scale: u32,
4470        /// The lexeme as written, `d` suffix included (formatting is verbatim).
4471        lexeme: String,
4472    },
4473    /// A duration literal `<int>.<unit>` (v0.86, ADR 0112): `5.minutes`,
4474    /// `30.days`. The parser recognises the `IntLit . <unit>` shape and records
4475    /// the magnitude, the unit, and the resolved milliseconds (the value the
4476    /// emitter lowers to). Typed `Duration`.
4477    DurationLit {
4478        /// The integer magnitude as written (`5` in `5.minutes`).
4479        value: i64,
4480        /// The unit name (`minutes`), one of the closed set.
4481        unit: DurationUnit,
4482        /// The value in milliseconds — `value * unit factor`.
4483        millis: i64,
4484    },
4485    StrLit(String),
4486    /// An interpolated string `"… \(expr) …"` (v0.43, ADR 0075). Chunks and
4487    /// holes alternate. A plain `"…"` with no holes stays [`ExprKind::StrLit`],
4488    /// so existing code and the emitter/formatter fast-path are untouched.
4489    InterpStr(Vec<InterpPart>),
4490    BoolLit(bool),
4491    Ident(Ident),
4492    Call {
4493        name: Ident,
4494        /// v0.20a: explicit type arguments (`name[T](…)`); empty when absent.
4495        type_args: Vec<TypeRef>,
4496        args: Vec<Expr>,
4497        /// #3110: the comments between the arguments; `None` when there are none.
4498        trivia: Option<Box<ListTrivia>>,
4499    },
4500    /// A lambda (v0.20a). See [`LambdaExpr`].
4501    Lambda(LambdaExpr),
4502    BinOp(BinOp, Box<Expr>, Box<Expr>),
4503    UnaryOp(UnaryOp, Box<Expr>),
4504    Paren(Box<Expr>),
4505    /// `{ stmts; expr }` — block expression (v0.1).
4506    Block(Block),
4507    /// `if cond { then } else { else }` (v0.1).
4508    If {
4509        cond: Box<Expr>,
4510        then_block: Box<Block>,
4511        else_block: Box<Block>,
4512    },
4513    /// `Ok(value)` — Result success constructor (v0.1).
4514    Ok(Box<Expr>),
4515    /// `Err(error)` — Result failure constructor (v0.1).
4516    Err(Box<Expr>),
4517    /// `expr?` — propagation operator (v0.1).
4518    Question(Box<Expr>),
4519    /// `TypeName { field: value, ... }` — record construction (v0.2).
4520    RecordConstruction {
4521        type_name: Ident,
4522        fields: Vec<FieldInit>,
4523        /// #3110: the comments between the fields; `None` when there are none.
4524        trivia: Option<Box<ListTrivia>>,
4525    },
4526    /// `receiver.field` — field access on a record value (v0.2). v0.3 adds
4527    /// `.raw` on opaque types within the defining commons.
4528    FieldAccess {
4529        receiver: Box<Expr>,
4530        field: Ident,
4531    },
4532    /// `receiver.method(args)` — instance method call (v0.2). The
4533    /// resolver determines the receiver's type and looks up the method.
4534    MethodCall {
4535        receiver: Box<Expr>,
4536        method: Ident,
4537        /// v0.22b: explicit type arguments on a qualified static
4538        /// (`Json.decode[T](…)`); empty when absent. The same-line-`[`
4539        /// rule applies as for `Call` type application (0039).
4540        type_args: Vec<TypeRef>,
4541        args: Vec<Expr>,
4542        /// #3110: the comments between the arguments; `None` when there are none.
4543        trivia: Option<Box<ListTrivia>>,
4544    },
4545    /// `match disc { arm+ }` — pattern matching (v0.2).
4546    Match {
4547        discriminant: Box<Expr>,
4548        arms: Vec<MatchArm>,
4549    },
4550    /// `expr is pattern` — pattern test, returns Bool (v0.2).
4551    ///
4552    /// `pattern` is boxed (finding #31): `Pattern`'s `Variant` case carries two
4553    /// `Ident`s plus a `Vec`, inlining it into every `ExprKind` sets the size
4554    /// of every expression node in the program for the one variant that
4555    /// tests a pattern.
4556    Is {
4557        value: Box<Expr>,
4558        pattern: Box<Pattern>,
4559    },
4560    /// `Some(value)` — Option Some constructor (v0.2).
4561    Some(Box<Expr>),
4562    /// `None` — Option None constructor (v0.2).
4563    None,
4564    /// `()` — unit literal (v0.5).
4565    UnitLit,
4566    /// `TypeName { ...base, field: value, ... }` or `{ ...base, ... }` —
4567    /// record spread expression (v0.5).
4568    RecordSpread {
4569        /// Optional type prefix (`TypeName { ...base }`). Absent for the
4570        /// bare form used inside `commit`.
4571        type_name: Option<Ident>,
4572        /// The base record being spread.
4573        base: Box<Expr>,
4574        /// Field overrides (always full `name: value` form — never shorthand).
4575        overrides: Vec<FieldInit>,
4576        /// #3110: the comments between the items — the `...base` spread first,
4577        /// then each override; `None` when there are none.
4578        trivia: Option<Box<ListTrivia>>,
4579    },
4580    /// `Effect.pure(value)` — wrap a synchronous value into `Effect[T]`
4581    /// (v0.5). Recognised in the parser as a special-form.
4582    EffectPure(Box<Expr>),
4583    /// `expect expr` — expectation as an expression of type `()` (v0.9.1;
4584    /// renamed from `assert` in v0.112). Valid only inside test bodies. Evaluates
4585    /// `expr` (must be Bool); if false, the surrounding test case fails.
4586    Expect(Box<Expr>),
4587    /// `Val[T]`, `Val[T](args)` — test-context value construction (v0.9.4).
4588    /// `args` is empty for the bare form and holds the pin arguments for
4589    /// `Val[T](...)`. The record-override form `Val[T] { ... }` is not yet
4590    /// parsed. Valid only inside test bodies; has type `T`.
4591    Val {
4592        type_ref: TypeRef,
4593        args: Vec<Expr>,
4594        /// #3110: the comments between the arguments; `None` when there are none.
4595        trivia: Option<Box<ListTrivia>>,
4596    },
4597    /// `Wire(<String>)` — a raw, pre-validation argument to a `system`-tier
4598    /// service address (testing-the-boundary Slice C). The inner expression is a
4599    /// `String` carrying the wire form the boundary will receive *unvalidated* —
4600    /// a body's JSON text or a path segment — so a case can drive the router with
4601    /// input the type system forbids and observe the rejection. Legal only at
4602    /// `system` (there is no wire at `unit`); the router validates it, so no
4603    /// refined value is ever minted from a `Wire` (ADR 0182 untouched).
4604    Wire(Box<Expr>),
4605    /// `[a, b, c]` — list literal (v0.20b). An empty `[]` requires an
4606    /// expected type (`bynk.types.uninferable_element_type`).
4607    ListLit(Vec<Expr>, Option<Box<ListTrivia>>),
4608    /// An observation over a consumed capability's recorded calls (v0.117,
4609    /// testing track slice 5). The direct subject of an `expect` in a `case`
4610    /// body — `expect Cap.op called once with <pred>`, `expect Cap.op never
4611    /// called`, `expect A.op before B.op`. Types as `Bool` (the claim about the
4612    /// recorded trace), lowered to a boolean over the recorded log.
4613    /// Boxed (finding #31): at ~160 bytes, `ObservationExpr` inlined here set
4614    /// the size of every `ExprKind` for the one variant that records a
4615    /// capability-call observation.
4616    Observation(Box<ObservationExpr>),
4617    /// `<call> faults` — the claim that an effectful call **faults** (#1706).
4618    /// The direct subject of an `expect` in a `case` body —
4619    /// `expect quote.call("GBP") faults`. The claim's `call` is the call
4620    /// itself, an `Effect[_]` the claim awaits; the claim types as `Bool` and
4621    /// holds when awaiting the call throws (a capability fault, an injected
4622    /// `stub … fails`, an invariant violation) rather than returning a value.
4623    /// A fault is untyped and uncatchable by the caller, so this is a test's
4624    /// observation of the fault, not a handler for it: no production code can
4625    /// write it.
4626    ///
4627    /// #1812: the claim may carry a call-site principal (`expect
4628    /// api.POST(…) by User("bob") faults`), so an identity-carrying handler's
4629    /// fault path is testable; see [`FaultsExpr`]. Boxed, as `Observation` is,
4630    /// so the principal does not widen every `ExprKind`.
4631    Faults(Box<FaultsExpr>),
4632    /// `trace(Cap.op)` — the bound-trace escape hatch (v0.117, testing track
4633    /// slice 5). Yields the recorded calls of `Cap.op` as a `List[<CallRecord>]`
4634    /// (a synthetic record of the operation's parameters), asserted over with the
4635    /// ordinary value surface. Test-body-only, like [`ExprKind::Val`].
4636    Trace {
4637        cap: Ident,
4638        op: Ident,
4639    },
4640}
4641
4642/// Every directly-nested sub-expression of `e` — the **total** child
4643/// iterator. The match is exhaustive (no `_` arm), so adding an [`ExprKind`]
4644/// variant is a compile error here rather than a silently incomplete walk —
4645/// the trap the checker's three hand-rolled partial walkers each fell into
4646/// (block statements and match-arm bodies were skipped, so e.g. the `:=`
4647/// self-reference rule was bypassable through a match arm).
4648///
4649/// Exhaustive over [`ExprKind`] *and* over the expressions each variant holds
4650/// (#1760: match-arm guards were once missed, and every walk built on this one
4651/// missed them with it).
4652///
4653/// Descends one level: block *statements* and the tail, match-arm guards and
4654/// bodies, lambda bodies, interpolation holes, record-field values, and
4655/// observation predicates are all children. Callers recurse for a deep walk.
4656pub fn expr_children(e: &Expr) -> Vec<&Expr> {
4657    fn block_children<'a>(b: &'a Block, out: &mut Vec<&'a Expr>) {
4658        for s in &b.statements {
4659            statement_exprs(s, out);
4660        }
4661        out.push(&b.tail);
4662    }
4663    let mut out = Vec::new();
4664    match &e.kind {
4665        ExprKind::IntLit { .. }
4666        | ExprKind::FloatLit { .. }
4667        | ExprKind::DecimalLit { .. }
4668        | ExprKind::DurationLit { .. }
4669        | ExprKind::StrLit(_)
4670        | ExprKind::BoolLit(_)
4671        | ExprKind::Ident(_)
4672        | ExprKind::None
4673        | ExprKind::UnitLit
4674        | ExprKind::Trace { .. } => {}
4675        ExprKind::InterpStr(parts) => {
4676            for p in parts {
4677                if let InterpPart::Hole(h) = p {
4678                    out.push(h.as_ref());
4679                }
4680            }
4681        }
4682        ExprKind::Call { args, .. } | ExprKind::Val { args, .. } | ExprKind::ListLit(args, ..) => {
4683            out.extend(args.iter())
4684        }
4685        ExprKind::Wire(inner) => out.push(inner.as_ref()),
4686        ExprKind::Lambda(l) => out.push(l.body.as_ref()),
4687        ExprKind::BinOp(_, l, r) => {
4688            out.push(l.as_ref());
4689            out.push(r.as_ref());
4690        }
4691        ExprKind::UnaryOp(_, inner)
4692        | ExprKind::Paren(inner)
4693        | ExprKind::Ok(inner)
4694        | ExprKind::Err(inner)
4695        | ExprKind::Question(inner)
4696        | ExprKind::Some(inner)
4697        | ExprKind::EffectPure(inner)
4698        | ExprKind::Expect(inner) => out.push(inner.as_ref()),
4699        ExprKind::Faults(f) => {
4700            // #1812: a call-site principal's identity is evaluated first, as
4701            // an argument to the claimed call — the same order as an
4702            // effect-let's in `statement_exprs`.
4703            if let Some(identity) = f.principal.as_ref().and_then(|p| p.identity.as_deref()) {
4704                out.push(identity);
4705            }
4706            if let Some(claims) = f.principal.as_ref().and_then(|p| p.claims.as_deref()) {
4707                out.push(claims);
4708            }
4709            out.push(&f.call);
4710        }
4711        ExprKind::Block(b) => block_children(b, &mut out),
4712        ExprKind::If {
4713            cond,
4714            then_block,
4715            else_block,
4716        } => {
4717            out.push(cond.as_ref());
4718            block_children(then_block, &mut out);
4719            block_children(else_block, &mut out);
4720        }
4721        ExprKind::RecordConstruction { fields, .. } => {
4722            out.extend(fields.iter().filter_map(|f| f.value.as_ref()));
4723        }
4724        ExprKind::FieldAccess { receiver, .. } => out.push(receiver.as_ref()),
4725        ExprKind::MethodCall { receiver, args, .. } => {
4726            out.push(receiver.as_ref());
4727            out.extend(args.iter());
4728        }
4729        ExprKind::Match { discriminant, arms } => {
4730            out.push(discriminant.as_ref());
4731            for arm in arms {
4732                // #1760: the guard, in evaluation order before the body. It is
4733                // an ordinary expression, checked like any other.
4734                if let Some(guard) = &arm.guard {
4735                    out.push(guard);
4736                }
4737                match &arm.body {
4738                    MatchBody::Expr(e) => out.push(e),
4739                    MatchBody::Block(b) => block_children(b, &mut out),
4740                }
4741            }
4742        }
4743        ExprKind::Is { value, .. } => out.push(value.as_ref()),
4744        ExprKind::RecordSpread {
4745            base, overrides, ..
4746        } => {
4747            out.push(base.as_ref());
4748            out.extend(overrides.iter().filter_map(|f| f.value.as_ref()));
4749        }
4750        ExprKind::Observation(obs) => match &obs.matcher {
4751            ObservationMatcher::Called { count, with_pred } => {
4752                if let Some(c) = count {
4753                    out.push(c.as_ref());
4754                }
4755                if let Some(p) = with_pred {
4756                    out.push(p.as_ref());
4757                }
4758            }
4759            ObservationMatcher::NeverCalled | ObservationMatcher::Before { .. } => {}
4760        },
4761    }
4762    out
4763}
4764
4765/// The expressions directly contained in a statement — the statement half of
4766/// [`expr_children`]'s total walk. Exhaustive over [`Statement`] for the same
4767/// reason, and over each statement's expressions: a `let`'s call-site
4768/// principal identity included.
4769pub fn statement_exprs<'a>(s: &'a Statement, out: &mut Vec<&'a Expr>) {
4770    match s {
4771        Statement::Let(l) | Statement::EffectLet(l) => {
4772            // #1766 review: a call-site principal's identity (`by User(who)`)
4773            // is a full expression. It is evaluated first, as an argument to
4774            // the addressed call.
4775            if let Some(identity) = l.principal.as_ref().and_then(|p| p.identity.as_deref()) {
4776                out.push(identity);
4777            }
4778            if let Some(claims) = l.principal.as_ref().and_then(|p| p.claims.as_deref()) {
4779                out.push(claims);
4780            }
4781            out.push(&l.value)
4782        }
4783        Statement::Expect(a) => out.push(&a.value),
4784        Statement::Do(d) => out.push(&d.value),
4785        Statement::Assign(a) => out.push(&a.value),
4786        Statement::Advance(a) => out.push(&a.amount),
4787        Statement::Par(p) => p.statements.iter().for_each(|s| statement_exprs(s, out)),
4788    }
4789}
4790
4791/// A fault claim, `<call> [by <Actor>(<identity>)] faults` (#1706, #1812).
4792/// `call` is the effectful call the claim awaits; `principal` is the optional
4793/// call-site `by` clause, read exactly as on an effect-let (`let r <- call by
4794/// User("bob")`): it supplies the identity the addressed handler reads.
4795#[derive(Debug, Clone)]
4796pub struct FaultsExpr {
4797    pub call: Expr,
4798    pub principal: Option<CallSiteActor>,
4799}
4800
4801/// An observation of a capability operation's recorded calls (v0.117, testing
4802/// track slice 5). `cap`/`op` name the seam (`Logger.log`); `matcher` is the
4803/// claim about the recorded calls.
4804#[derive(Debug, Clone)]
4805pub struct ObservationExpr {
4806    pub cap: Ident,
4807    pub op: Ident,
4808    pub matcher: ObservationMatcher,
4809}
4810
4811/// The claim an [`ObservationExpr`] makes about a seam's recorded calls (v0.117).
4812#[derive(Debug, Clone)]
4813pub enum ObservationMatcher {
4814    /// `called` [`once` | `<n> times`]? [`with` `<pred>`]?. `count` is `None`
4815    /// for a bare `called` (at least one); `Some(expr)` is the exact-count claim
4816    /// (a literal; `once` desugars to `1`). `with_pred` matches a call whose
4817    /// arguments (in scope by the operation's parameter names) satisfy it.
4818    Called {
4819        count: Option<Box<Expr>>,
4820        with_pred: Option<Box<Expr>>,
4821    },
4822    /// `never called` — zero calls.
4823    NeverCalled,
4824    /// `before Cap.op` — the first call of the subject precedes the first call
4825    /// of the named operation (both must have occurred).
4826    Before { cap: Ident, op: Ident },
4827}
4828
4829/// One part of an interpolated string (v0.43, ADR 0075). An
4830/// [`ExprKind::InterpStr`] holds an alternating run of these.
4831#[derive(Debug, Clone)]
4832pub enum InterpPart {
4833    /// Literal text between holes, with escapes already resolved.
4834    Chunk(String),
4835    /// An interpolated expression `\(expr)`. Type-checked by the hole rule
4836    /// (base scalars only; see the checker) and lowered into a template-
4837    /// literal `${…}` slot.
4838    Hole(Box<Expr>),
4839}
4840
4841/// One field-initialiser inside a record construction expression:
4842/// either `name: expr` or the shorthand `name` (which requires a binding
4843/// of the same name in scope and uses its value).
4844#[derive(Debug, Clone)]
4845pub struct FieldInit {
4846    pub name: Ident,
4847    /// `None` means shorthand — the field's value is the same-named binding.
4848    pub value: Option<Expr>,
4849    pub span: Span,
4850}
4851
4852/// One arm of a `match` expression: `pattern => body` or, with a guard,
4853/// `pattern if guard => body` (guard added in the nested-patterns increment,
4854/// ADR 0169). A guarded arm matches only when the pattern matches **and** the
4855/// `Bool` guard evaluates true; it never contributes to exhaustiveness.
4856#[derive(Debug, Clone)]
4857pub struct MatchArm {
4858    pub pattern: Pattern,
4859    /// Optional `if <Bool-expr>` guard between the pattern and `=>`.
4860    pub guard: Option<Expr>,
4861    pub body: MatchBody,
4862    pub span: Span,
4863}
4864
4865/// The right-hand side of a match arm — either a single expression or
4866/// a block.
4867#[derive(Debug, Clone)]
4868pub enum MatchBody {
4869    Expr(Expr),
4870    Block(Block),
4871}
4872
4873impl MatchBody {
4874    pub fn span(&self) -> Span {
4875        match self {
4876            MatchBody::Expr(e) => e.span,
4877            MatchBody::Block(b) => b.span,
4878        }
4879    }
4880}
4881
4882/// A pattern (v0.2 §3.8). Patterns appear in `match` arms and as the
4883/// right-hand side of the `is` operator.
4884#[derive(Debug, Clone)]
4885pub enum Pattern {
4886    /// `_` — matches any value, no bindings.
4887    Wildcard(Span),
4888    /// A lowercase identifier — binds the whole value to `name` and matches
4889    /// anything (ADR 0169). At the top of a `match` arm it binds the scrutinee
4890    /// (`n if n > 0 => …`); inside a payload position it binds the field
4891    /// (`Some(user)`). The uppercase-led counterpart is a nullary [`Pattern::Variant`].
4892    Binding(Ident),
4893    /// A literal pattern — `31`, `"english"`, `true` (v0.130 §2.3.4). Matches a
4894    /// primitive scrutinee (`Int`/`String`/`Bool`) by value equality. The
4895    /// admitted set mirrors ADR 0001's closed literal set (integers — including
4896    /// a leading unary minus — strings, and booleans); `Float`/`()` are not
4897    /// admitted as patterns.
4898    Literal {
4899        value: LiteralValue,
4900        /// The literal as written (`-1_000`), digit separators kept; `None`
4901        /// for a pattern built without source. Only the formatter reads it,
4902        /// and it sits outside `value` so the duplicate-arm check ignores it.
4903        text: Option<String>,
4904        span: Span,
4905    },
4906    /// `lo..hi`, `lo..` or `..hi` — an inclusive integer range (patterns track,
4907    /// slice 5, #2699). Matches an `Int` scrutinee by comparison. Binds nothing.
4908    /// The one production `via schema(...)` shares ([`SchemaVersionPattern::Range`]).
4909    Range(IntRange),
4910    /// `Variant` or `Variant(bindings)` or `TypeName.Variant(bindings)`. Each
4911    /// payload binding is itself a [`Pattern`] (ADR 0169), so payloads nest:
4912    /// `Some(Ok(x))`, `Err(PollClosed)`.
4913    Variant {
4914        /// Optional qualifier: `TypeName.Variant`.
4915        type_name: Option<Ident>,
4916        /// The variant name.
4917        variant: Ident,
4918        /// Payload bindings (empty for nullary variants).
4919        bindings: Vec<PatternBinding>,
4920        span: Span,
4921    },
4922    /// `TypeName { f1, f2: pattern, .. }` — a record pattern (patterns track,
4923    /// slice 1, #2641). Always open: unlisted fields are ignored, and the
4924    /// trailing `..` is mandatory so that adding a field to the record never
4925    /// breaks a pattern. A field with no sub-pattern (`f`) binds the field to a
4926    /// local of the same name; `f: p` matches the field against `p`.
4927    Record {
4928        /// The record type's name — required, and never carries type
4929        /// arguments (a generic record's come from the scrutinee).
4930        type_name: Ident,
4931        /// The listed fields, in source order. `None` is the shorthand `f`.
4932        fields: Vec<(Ident, Option<Pattern>)>,
4933        /// The span of the mandatory trailing `..`.
4934        rest_span: Span,
4935        span: Span,
4936    },
4937    /// `[p₁, …, pₙ]` or `[p₁, …, pₙ, ..]` / `[p₁, …, pₙ, ..rest]` — a list
4938    /// pattern (patterns track, slice 4, #2680). Without `rest` it matches a
4939    /// list of exactly `n` elements, element `i` against `pᵢ`; with `rest` it
4940    /// matches `n` or more, and a named rest binds the remaining elements.
4941    List {
4942        elems: Vec<Pattern>,
4943        rest: Option<ListRest>,
4944        span: Span,
4945    },
4946    /// `p 'where' refinement-predicate` — a refinement guard on a pattern
4947    /// (#472). Matches when `inner` matches *and* the scrutinee satisfies
4948    /// `predicate` at runtime. v1 admits only `Wildcard` as `inner` (no
4949    /// binding form yet); refutable — never counts toward exhaustiveness or
4950    /// as a catch-all arm, the same treatment as an `if` guard (§2.3.4).
4951    Refined {
4952        inner: Box<Pattern>,
4953        predicate: Refinement,
4954        span: Span,
4955    },
4956    /// `p₁ | p₂ | … | pₙ` — an or-pattern (#474 §2.3.4): matches if any
4957    /// alternative matches. Left-associative `|`, flattened by the parser's
4958    /// chain fold into one `Vec` — an alternative is always a leaf
4959    /// (`Wildcard`/`Binding`/`Literal`/`Variant`), never itself an `Or`
4960    /// (there is no parenthesized-pattern syntax to nest one inside another).
4961    /// Well-typedness (checked, not parsed): every alternative binds the same
4962    /// set of names, a name shared across alternatives has the same type
4963    /// (including refinement) in each, and every alternative matches the same
4964    /// value type.
4965    Or(Vec<Pattern>, Span),
4966}
4967
4968/// An inclusive integer range, `lo..hi`, `lo..` or `..hi` (patterns track,
4969/// slice 5, #2699; events slice 4b, #990): the one production a match pattern
4970/// and a `via schema(...)` clause share. At least one bound is present — a bare
4971/// `..` is the rest marker, never a range. Each bound is an optionally negative
4972/// `Int` literal, parsed permissively: whether it is in range and whether
4973/// `lo <= hi` are checker questions.
4974#[derive(Debug, Clone, PartialEq, Eq)]
4975pub struct IntRange {
4976    pub lo: Option<i64>,
4977    pub hi: Option<i64>,
4978    /// The low bound as written (`-1_000`), digit separators kept; `None` when
4979    /// `lo` is. Only the formatter reads it; a range built without source
4980    /// (a suggested fix) leaves it `None` and prints from the value.
4981    pub lo_text: Option<String>,
4982    /// The high bound as written; see `lo_text`.
4983    pub hi_text: Option<String>,
4984    pub span: Span,
4985}
4986
4987impl IntRange {
4988    /// As [`IntRange::describe`], but each bound keeps its source spelling
4989    /// (`1_000..2_000`), so formatting does not drop digit separators.
4990    pub fn describe_source(&self) -> String {
4991        let lo = match (&self.lo_text, self.lo) {
4992            (Some(t), _) => t.clone(),
4993            (None, Some(n)) => n.to_string(),
4994            (None, None) => String::new(),
4995        };
4996        let hi = match (&self.hi_text, self.hi) {
4997            (Some(t), _) => t.clone(),
4998            (None, Some(n)) => n.to_string(),
4999            (None, None) => String::new(),
5000        };
5001        format!("{lo}..{hi}")
5002    }
5003
5004    /// The range as written, `0..9`, `18..` or `..-1`; the form the formatter
5005    /// prints and diagnostics quote.
5006    pub fn describe(&self) -> String {
5007        let lo = self.lo.map(|n| n.to_string()).unwrap_or_default();
5008        let hi = self.hi.map(|n| n.to_string()).unwrap_or_default();
5009        format!("{lo}..{hi}")
5010    }
5011}
5012
5013/// The trailing `..` of a list pattern, with the optional name that binds the
5014/// remaining elements (`..rest`).
5015#[derive(Debug, Clone)]
5016pub struct ListRest {
5017    pub binder: Option<Ident>,
5018    /// The span of the `..` token.
5019    pub span: Span,
5020}
5021
5022/// The value carried by a [`Pattern::Literal`]. A closed set (ADR 0001):
5023/// integer, string, and boolean. Kept distinct from [`ExprKind`] so patterns
5024/// carry only what they can actually match, and so it is `Eq`/`Hash` for the
5025/// duplicate-arm check.
5026#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5027pub enum LiteralValue {
5028    Int(i64),
5029    Str(String),
5030    Bool(bool),
5031}
5032
5033impl LiteralValue {
5034    /// A human-readable rendering for diagnostics (`31`, `"english"`, `true`).
5035    pub fn describe(&self) -> String {
5036        match self {
5037            LiteralValue::Int(n) => n.to_string(),
5038            LiteralValue::Str(s) => format!("{s:?}"),
5039            LiteralValue::Bool(b) => b.to_string(),
5040        }
5041    }
5042}
5043
5044impl Pattern {
5045    pub fn span(&self) -> Span {
5046        match self {
5047            Pattern::Wildcard(s) => *s,
5048            Pattern::Binding(id) => id.span,
5049            Pattern::Literal { span, .. } => *span,
5050            Pattern::Range(r) => r.span,
5051            Pattern::Variant { span, .. } => *span,
5052            Pattern::Record { span, .. } => *span,
5053            Pattern::List { span, .. } => *span,
5054            Pattern::Refined { span, .. } => *span,
5055            Pattern::Or(_, span) => *span,
5056        }
5057    }
5058
5059    /// Every identifier this pattern binds into scope, recursively (`_` and
5060    /// nullary variants bind nothing). Used by the resolver and the checker to
5061    /// populate an arm's scope, and by the guard to see the arm's bindings.
5062    ///
5063    /// For [`Pattern::Or`] this returns the *first* alternative's names — the
5064    /// checker separately verifies (#474 Rule 1) that every alternative binds
5065    /// the same set, so this is a defensive default when that rule is
5066    /// violated, not a semantic choice among alternatives.
5067    pub fn bound_names(&self) -> Vec<&Ident> {
5068        match self {
5069            Pattern::Wildcard(_) | Pattern::Literal { .. } | Pattern::Range(_) => Vec::new(),
5070            Pattern::Binding(id) => vec![id],
5071            Pattern::Variant { bindings, .. } => bindings
5072                .iter()
5073                .flat_map(|b| b.pattern().bound_names())
5074                .collect(),
5075            Pattern::Record { fields, .. } => fields
5076                .iter()
5077                .flat_map(|(name, sub)| match sub {
5078                    Some(p) => p.bound_names(),
5079                    None => vec![name],
5080                })
5081                .collect(),
5082            Pattern::List { elems, rest, .. } => elems
5083                .iter()
5084                .flat_map(Pattern::bound_names)
5085                .chain(rest.iter().filter_map(|r| r.binder.as_ref()))
5086                .collect(),
5087            Pattern::Refined { inner, .. } => inner.bound_names(),
5088            Pattern::Or(alts, _) => alts.first().map(Pattern::bound_names).unwrap_or_default(),
5089        }
5090    }
5091
5092    /// True when this pattern matches every value and binds nothing — a bare
5093    /// `_`. A [`Pattern::Binding`] also matches everything but *does* bind, so it
5094    /// is not a pure wildcard.
5095    pub fn is_wildcard(&self) -> bool {
5096        matches!(self, Pattern::Wildcard(_))
5097    }
5098
5099    /// True when this pattern matches every value (a `_` or a name binding),
5100    /// i.e. it is irrefutable and covers the position for exhaustiveness. An
5101    /// [`Pattern::Or`] is irrefutable when any alternative is — `_` in any
5102    /// position already makes the whole pattern match everything.
5103    pub fn is_irrefutable(&self) -> bool {
5104        match self {
5105            Pattern::Wildcard(_) | Pattern::Binding(_) => true,
5106            Pattern::Or(alts, _) => alts.iter().any(Pattern::is_irrefutable),
5107            Pattern::Record { fields, .. } => fields
5108                .iter()
5109                .all(|(_, sub)| sub.as_ref().is_none_or(Pattern::is_irrefutable)),
5110            // `[..]` and `[..rest]` match every list; any fixed length does not.
5111            Pattern::List { elems, rest, .. } => elems.is_empty() && rest.is_some(),
5112            _ => false,
5113        }
5114    }
5115}
5116
5117/// A single binding inside a variant pattern. Two surface forms:
5118/// `pattern` (positional — match the i-th payload field) and
5119/// `fieldName: pattern` (named — match the named payload field). The matched
5120/// sub-`pattern` is a full [`Pattern`] (ADR 0169), so a plain `name` is a
5121/// [`Pattern::Binding`], `_` a [`Pattern::Wildcard`], and `Ok(x)` a nested
5122/// [`Pattern::Variant`].
5123#[derive(Debug, Clone)]
5124pub struct PatternBinding {
5125    /// Source form: positional or named.
5126    pub kind: PatternBindingKind,
5127    pub span: Span,
5128}
5129
5130#[derive(Debug, Clone)]
5131pub enum PatternBindingKind {
5132    /// `pattern` (e.g. `x`, `_`, `Ok(v)`): match the payload field at this position.
5133    Positional { pattern: Pattern },
5134    /// `field: pattern`: match the named payload field against `pattern`.
5135    Named { field: Ident, pattern: Pattern },
5136}
5137
5138impl PatternBinding {
5139    /// The sub-pattern this binding matches its payload field against.
5140    pub fn pattern(&self) -> &Pattern {
5141        match &self.kind {
5142            PatternBindingKind::Positional { pattern } => pattern,
5143            PatternBindingKind::Named { pattern, .. } => pattern,
5144        }
5145    }
5146
5147    /// True when this binding discards its field (`_` or `field: _`) — a pure
5148    /// wildcard sub-pattern that binds nothing.
5149    pub fn is_wildcard(&self) -> bool {
5150        self.pattern().is_wildcard()
5151    }
5152}
5153
5154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5155pub enum BinOp {
5156    /// `P implies Q` — logical implication (v0.80). Desugars to `!P || Q`; sits
5157    /// at the lowest precedence (below `||`). Reads directionally (P → Q).
5158    Implies,
5159    Or,
5160    And,
5161    Eq,
5162    NotEq,
5163    Lt,
5164    LtEq,
5165    Gt,
5166    GtEq,
5167    Add,
5168    Sub,
5169    Mul,
5170    Div,
5171}
5172
5173impl BinOp {
5174    pub fn name(self) -> &'static str {
5175        match self {
5176            BinOp::Implies => "implies",
5177            BinOp::Or => "||",
5178            BinOp::And => "&&",
5179            BinOp::Eq => "==",
5180            BinOp::NotEq => "!=",
5181            BinOp::Lt => "<",
5182            BinOp::LtEq => "<=",
5183            BinOp::Gt => ">",
5184            BinOp::GtEq => ">=",
5185            BinOp::Add => "+",
5186            BinOp::Sub => "-",
5187            BinOp::Mul => "*",
5188            BinOp::Div => "/",
5189        }
5190    }
5191}
5192
5193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5194pub enum UnaryOp {
5195    Neg,
5196    Not,
5197}
5198
5199impl UnaryOp {
5200    pub fn name(self) -> &'static str {
5201        match self {
5202            UnaryOp::Neg => "-",
5203            UnaryOp::Not => "!",
5204        }
5205    }
5206}
5207
5208#[cfg(test)]
5209mod size_tests {
5210    use super::*;
5211
5212    /// Finding #31: boxing `ExprKind::Observation`'s payload and
5213    /// `ExprKind::Is`'s pattern field took `Expr` from 176 to 128 bytes on
5214    /// this target (the module-level `const _` assertion is the real pin;
5215    /// this test just makes the before/after concrete and fails loudly if a
5216    /// future change silently regresses the win rather than tripping the
5217    /// `<= 128` ceiling by enough to notice).
5218    #[test]
5219    fn expr_is_smaller_than_before_the_boxing() {
5220        assert!(
5221            std::mem::size_of::<Expr>() < 176,
5222            "Expr should be smaller than its pre-#31 size of 176 bytes"
5223        );
5224    }
5225}
5226
5227#[cfg(test)]
5228mod expr_children_tests {
5229    use super::*;
5230
5231    /// #1760: a match arm's guard is a child, between the discriminant and
5232    /// the arm's body, in evaluation order.
5233    #[test]
5234    fn a_match_arms_guard_is_a_child_in_evaluation_order() {
5235        let source = "commons d\n\nfn f(n: Int, lim: Int) -> Int {\n  match n {\n    k if k > lim => 1\n    _ => 0\n  }\n}\n";
5236        let tokens = crate::lexer::tokenize(source).unwrap();
5237        let units = crate::parser::parse_units(&tokens, source).unwrap();
5238        let SourceUnit::Commons(c) = &units[0] else {
5239            panic!("a commons");
5240        };
5241        let CommonsItem::Fn(f) = &c.items[0] else {
5242            panic!("a fn");
5243        };
5244        let ExprKind::Match { .. } = &f.body.tail.kind else {
5245            panic!("a match tail");
5246        };
5247        let children: Vec<&str> = expr_children(&f.body.tail)
5248            .into_iter()
5249            .map(|e| &source[e.span.start..e.span.end])
5250            .collect();
5251        assert_eq!(children, ["n", "k > lim", "1", "0"]);
5252    }
5253
5254    /// #1766 review: a `let`'s call-site principal identity is a statement
5255    /// expression, before the value it addresses.
5256    #[test]
5257    fn a_principal_identity_is_a_statement_expression() {
5258        let source = "suite demo.s {\n  case \"c\" {\n    let who = \"alice\"\n    let item <- api.get() by User(who)\n    expect item\n  }\n}\n";
5259        let tokens = crate::lexer::tokenize(source).unwrap();
5260        let units = crate::parser::parse_units(&tokens, source).unwrap();
5261        let SourceUnit::Suite(t) = &units[0] else {
5262            panic!("a suite");
5263        };
5264        let mut exprs = Vec::new();
5265        statement_exprs(&t.cases[0].body.statements[1], &mut exprs);
5266        let texts: Vec<&str> = exprs
5267            .into_iter()
5268            .map(|e| &source[e.span.start..e.span.end])
5269            .collect();
5270        assert_eq!(texts, ["who", "api.get()"]);
5271    }
5272}
5273
5274/// #1832: [`expr_children`] and [`statement_exprs`] reach every child slot of
5275/// every expression, so every walk built on them does too.
5276///
5277/// The guard is in two parts:
5278///
5279/// - **An oracle that cannot fall behind the AST.** [`oracle_children`] and
5280///   [`oracle_statement`] destructure every field of every `ExprKind` variant
5281///   and of every expression-bearing struct with no `..`, so adding a variant
5282///   or a field anywhere an expression can hide is a compile error here until
5283///   the oracle names the new slot.
5284/// - **A program that uses every slot.** [`COVERAGE`] is parsed (never
5285///   checked, so it only has to be syntactically valid), and two tests run
5286///   over it: every slot the oracle knows is used at least once, and at every
5287///   node `expr_children`/`statement_exprs` return exactly the oracle's
5288///   children. A new slot therefore fails the first test until the program
5289///   uses it, and the second until `expr_children` walks it.
5290///
5291/// The hand-rolled walks that cannot be built on `expr_children` (they carry
5292/// scopes, ownership or position) are tested where they live (#1832's
5293/// triage: the resolver, structure, linearity, effects and emit walks).
5294#[cfg(test)]
5295mod slot_coverage_tests {
5296    use super::*;
5297    use std::collections::BTreeSet;
5298
5299    /// Every slot, used at least once. `p` is a commons for the production
5300    /// forms; the suite holds the test-only ones (`Val`, `Wire`,
5301    /// observations, `faults`, `trace`, call-site principals).
5302    const COVERAGE: &str = r#"commons p
5303
5304fn f(x: Int) -> Int {
5305  let a = "s \(x) t"
5306  let b = g(x)
5307  let c = (y) => y
5308  let d = x + 1
5309  let e = -x
5310  let h = (x)
5311  let i = (z) => {
5312    let q = z
5313    q
5314  }
5315  let j = if x > 0 {
5316    let q = 1
5317    q
5318  } else {
5319    let w = 2
5320    w
5321  }
5322  let k = Ok(x)
5323  let l = Err(x)
5324  let n = r?
5325  let o = Some(x)
5326  let u = R { a: x }
5327  let v = r.a
5328  let w = r.m(x)
5329  let y = match x {
5330    z if z > 0 => z
5331    0 => expect x
5332    _ => {
5333      let s = 1
5334      s
5335    }
5336  }
5337  let aa = x is Some(v)
5338  let bb = R { ...r, a: x }
5339  let cc = Effect.pure(x)
5340  let dd = [x]
5341  do L.log(x).detach()
5342  do s.put(x)
5343  cell := x
5344  x
5345}
5346"#;
5347
5348    const COVERAGE_SUITE: &str = r#"suite p {
5349  case "c" {
5350    let who = "alice"
5351    let a <- api.get(x) by User(who)
5352    let b = Val[T](x)
5353    let c = Wire(x)
5354    expect L.log called 2 times with msg == x
5355    expect box.call() faults
5356    expect api.post(x) by User(who) faults
5357    let t = trace(L.log)
5358    expect x
5359  }
5360}
5361"#;
5362
5363    type Slots<'a> = Vec<(&'static str, &'a Expr)>;
5364
5365    fn oracle_block<'a>(owner: &'static str, b: &'a Block, out: &mut Slots<'a>) {
5366        let Block {
5367            statements,
5368            tail,
5369            span: _,
5370            tail_leading_comments: _,
5371            implicit_tail: _,
5372        } = b;
5373        for s in statements {
5374            for (slot, e) in oracle_statement(s) {
5375                out.push((slot, e));
5376            }
5377        }
5378        out.push((owner, tail));
5379    }
5380
5381    /// A statement's expressions, each tagged with its slot.
5382    fn oracle_statement(s: &Statement) -> Slots<'_> {
5383        fn let_slots<'a>(kind: &'static str, l: &'a LetStmt, out: &mut Slots<'a>) {
5384            let LetStmt {
5385                name: _,
5386                type_annot: _,
5387                value,
5388                principal,
5389                let_else: _,
5390                span: _,
5391                trivia: _,
5392            } = l;
5393            if let Some(CallSiteActor {
5394                actor: _,
5395                identity,
5396                claims: _,
5397                id: _,
5398                span: _,
5399            }) = principal
5400                && let Some(identity) = identity
5401            {
5402                out.push((
5403                    if kind == "let" {
5404                        "let.identity"
5405                    } else {
5406                        "let<-.identity"
5407                    },
5408                    identity,
5409                ));
5410            }
5411            out.push((
5412                if kind == "let" {
5413                    "let.value"
5414                } else {
5415                    "let<-.value"
5416                },
5417                value,
5418            ));
5419        }
5420        let mut out = Vec::new();
5421        match s {
5422            Statement::Let(l) => let_slots("let", l, &mut out),
5423            Statement::EffectLet(l) => let_slots("let<-", l, &mut out),
5424            Statement::Expect(ExpectStmt {
5425                value,
5426                snapshot: _,
5427                span: _,
5428                trivia: _,
5429            }) => out.push(("expect.value", value)),
5430            Statement::Do(DoStmt {
5431                value,
5432                span: _,
5433                trivia: _,
5434            }) => out.push(("do.value", value)),
5435            Statement::Assign(AssignStmt {
5436                target: _,
5437                value,
5438                span: _,
5439                trivia: _,
5440            }) => out.push(("assign.value", value)),
5441            Statement::Advance(AdvanceStmt {
5442                keyword: _,
5443                cap: _,
5444                amount,
5445                span: _,
5446                trivia: _,
5447            }) => out.push(("advance.amount", amount)),
5448            Statement::Par(ParStmt {
5449                keyword: _,
5450                statements,
5451                closing_comments: _,
5452                span: _,
5453                trivia: _,
5454            }) => {
5455                for s in statements {
5456                    for (slot, e) in oracle_statement(s) {
5457                        out.push((slot, e));
5458                    }
5459                }
5460            }
5461        }
5462        out
5463    }
5464
5465    /// An expression's children, each tagged with its slot.
5466    fn oracle_children(e: &Expr) -> Slots<'_> {
5467        let Expr {
5468            id: _,
5469            kind,
5470            span: _,
5471        } = e;
5472        let mut out = Vec::new();
5473        match kind {
5474            ExprKind::IntLit {
5475                value: _,
5476                lexeme: _,
5477            }
5478            | ExprKind::FloatLit {
5479                value: _,
5480                lexeme: _,
5481            }
5482            | ExprKind::DecimalLit {
5483                coef: _,
5484                scale: _,
5485                lexeme: _,
5486            }
5487            | ExprKind::DurationLit {
5488                value: _,
5489                unit: _,
5490                millis: _,
5491            }
5492            | ExprKind::StrLit(_)
5493            | ExprKind::BoolLit(_)
5494            | ExprKind::Ident(_)
5495            | ExprKind::None
5496            | ExprKind::UnitLit
5497            | ExprKind::Trace { cap: _, op: _ } => {}
5498            ExprKind::InterpStr(parts) => {
5499                for p in parts {
5500                    match p {
5501                        InterpPart::Chunk(_) => {}
5502                        InterpPart::Hole(h) => out.push(("interp.hole", h.as_ref())),
5503                    }
5504                }
5505            }
5506            ExprKind::Call {
5507                name: _,
5508                type_args: _,
5509                args,
5510                ..
5511            } => args.iter().for_each(|a| out.push(("call.arg", a))),
5512            ExprKind::Lambda(LambdaExpr {
5513                params: _,
5514                body,
5515                span: _,
5516                block_body: _,
5517            }) => out.push(("lambda.body", body)),
5518            ExprKind::BinOp(_, l, r) => {
5519                out.push(("binop.left", l));
5520                out.push(("binop.right", r));
5521            }
5522            ExprKind::UnaryOp(_, x) => out.push(("unary.operand", x)),
5523            ExprKind::Paren(x) => out.push(("paren.inner", x)),
5524            ExprKind::Block(b) => oracle_block("block.tail", b, &mut out),
5525            ExprKind::If {
5526                cond,
5527                then_block,
5528                else_block,
5529            } => {
5530                out.push(("if.cond", cond));
5531                oracle_block("if.then.tail", then_block, &mut out);
5532                oracle_block("if.else.tail", else_block, &mut out);
5533            }
5534            ExprKind::Ok(x) => out.push(("ok.inner", x)),
5535            ExprKind::Err(x) => out.push(("err.inner", x)),
5536            ExprKind::Question(x) => out.push(("question.inner", x)),
5537            ExprKind::RecordConstruction {
5538                type_name: _,
5539                fields,
5540                ..
5541            } => {
5542                for FieldInit {
5543                    name: _,
5544                    value,
5545                    span: _,
5546                } in fields
5547                {
5548                    if let Some(v) = value {
5549                        out.push(("record.field", v));
5550                    }
5551                }
5552            }
5553            ExprKind::FieldAccess { receiver, field: _ } => out.push(("field.receiver", receiver)),
5554            ExprKind::MethodCall {
5555                receiver,
5556                method: _,
5557                type_args: _,
5558                args,
5559                ..
5560            } => {
5561                out.push(("method.receiver", receiver));
5562                args.iter().for_each(|a| out.push(("method.arg", a)));
5563            }
5564            ExprKind::Match { discriminant, arms } => {
5565                out.push(("match.discriminant", discriminant));
5566                for MatchArm {
5567                    pattern: _,
5568                    guard,
5569                    body,
5570                    span: _,
5571                } in arms
5572                {
5573                    if let Some(g) = guard {
5574                        out.push(("match.guard", g));
5575                    }
5576                    match body {
5577                        MatchBody::Expr(x) => out.push(("match.body", x)),
5578                        MatchBody::Block(b) => oracle_block("match.block.tail", b, &mut out),
5579                    }
5580                }
5581            }
5582            ExprKind::Is { value, pattern: _ } => out.push(("is.value", value)),
5583            ExprKind::Some(x) => out.push(("some.inner", x)),
5584            ExprKind::RecordSpread {
5585                type_name: _,
5586                base,
5587                overrides,
5588                ..
5589            } => {
5590                out.push(("spread.base", base));
5591                for FieldInit {
5592                    name: _,
5593                    value,
5594                    span: _,
5595                } in overrides
5596                {
5597                    if let Some(v) = value {
5598                        out.push(("spread.override", v));
5599                    }
5600                }
5601            }
5602            ExprKind::EffectPure(x) => out.push(("effect_pure.inner", x)),
5603            ExprKind::Expect(x) => out.push(("expect_expr.inner", x)),
5604            ExprKind::Val {
5605                type_ref: _, args, ..
5606            } => args.iter().for_each(|a| out.push(("val.arg", a))),
5607            ExprKind::Wire(x) => out.push(("wire.inner", x)),
5608            ExprKind::ListLit(items, ..) => items.iter().for_each(|i| out.push(("list.item", i))),
5609            ExprKind::Observation(obs) => {
5610                let ObservationExpr {
5611                    cap: _,
5612                    op: _,
5613                    matcher,
5614                } = obs.as_ref();
5615                match matcher {
5616                    ObservationMatcher::Called { count, with_pred } => {
5617                        if let Some(c) = count {
5618                            out.push(("observation.count", c));
5619                        }
5620                        if let Some(p) = with_pred {
5621                            out.push(("observation.with", p));
5622                        }
5623                    }
5624                    ObservationMatcher::NeverCalled
5625                    | ObservationMatcher::Before { cap: _, op: _ } => {}
5626                }
5627            }
5628            ExprKind::Faults(f) => {
5629                let FaultsExpr { call, principal } = f.as_ref();
5630                if let Some(CallSiteActor {
5631                    actor: _,
5632                    identity,
5633                    claims: _,
5634                    id: _,
5635                    span: _,
5636                }) = principal
5637                    && let Some(identity) = identity
5638                {
5639                    out.push(("faults.identity", identity));
5640                }
5641                out.push(("faults.inner", call));
5642            }
5643        }
5644        out
5645    }
5646
5647    /// Every slot [`oracle_children`] and [`oracle_statement`] can name.
5648    const ALL_SLOTS: &[&str] = &[
5649        "interp.hole",
5650        "call.arg",
5651        "lambda.body",
5652        "binop.left",
5653        "binop.right",
5654        "unary.operand",
5655        "paren.inner",
5656        "block.tail",
5657        "if.cond",
5658        "if.then.tail",
5659        "if.else.tail",
5660        "ok.inner",
5661        "err.inner",
5662        "question.inner",
5663        "record.field",
5664        "field.receiver",
5665        "method.receiver",
5666        "method.arg",
5667        "match.discriminant",
5668        "match.guard",
5669        "match.body",
5670        "match.block.tail",
5671        "is.value",
5672        "some.inner",
5673        "spread.base",
5674        "spread.override",
5675        "effect_pure.inner",
5676        "expect_expr.inner",
5677        "val.arg",
5678        "wire.inner",
5679        "list.item",
5680        "observation.count",
5681        "observation.with",
5682        "faults.identity",
5683        "faults.inner",
5684        "let.value",
5685        "let<-.value",
5686        "let<-.identity",
5687        "expect.value",
5688        "do.value",
5689        "assign.value",
5690    ];
5691
5692    /// Every top-level block of the coverage program: fn bodies and case
5693    /// bodies.
5694    fn bodies(units: &[SourceUnit]) -> Vec<&Block> {
5695        let mut out = Vec::new();
5696        for u in units {
5697            match u {
5698                SourceUnit::Commons(c) => {
5699                    for item in &c.items {
5700                        if let CommonsItem::Fn(f) = item {
5701                            out.push(&f.body);
5702                        }
5703                    }
5704                }
5705                SourceUnit::Suite(t) => out.extend(t.cases.iter().map(|c| &c.body)),
5706                _ => {}
5707            }
5708        }
5709        out
5710    }
5711
5712    fn parse(source: &str) -> Vec<SourceUnit> {
5713        let tokens = crate::lexer::tokenize(source).expect("lex");
5714        crate::parser::parse_units(&tokens, source).expect("the coverage program parses")
5715    }
5716
5717    /// Visit every expression under `b` through the oracle, depth first.
5718    fn visit<'a>(b: &'a Block, f: &mut impl FnMut(&'a Expr)) {
5719        fn go<'a>(e: &'a Expr, f: &mut impl FnMut(&'a Expr)) {
5720            f(e);
5721            for (_, c) in oracle_children(e) {
5722                go(c, f);
5723            }
5724        }
5725        let mut top = Vec::new();
5726        oracle_block("body.tail", b, &mut top);
5727        for (_, e) in top {
5728            go(e, f);
5729        }
5730    }
5731
5732    #[test]
5733    fn the_coverage_program_uses_every_slot() {
5734        let mut used = BTreeSet::new();
5735        for source in [COVERAGE, COVERAGE_SUITE] {
5736            let units = parse(source);
5737            for b in bodies(&units) {
5738                for s in &b.statements {
5739                    used.extend(oracle_statement(s).into_iter().map(|(slot, _)| slot));
5740                }
5741                visit(b, &mut |e| {
5742                    used.extend(oracle_children(e).into_iter().map(|(slot, _)| slot));
5743                    if let ExprKind::Block(b) = &e.kind {
5744                        for s in &b.statements {
5745                            used.extend(oracle_statement(s).into_iter().map(|(slot, _)| slot));
5746                        }
5747                    }
5748                });
5749            }
5750        }
5751        let missing: Vec<&str> = ALL_SLOTS
5752            .iter()
5753            .copied()
5754            .filter(|s| !used.contains(s))
5755            .collect();
5756        let unknown: Vec<&str> = used
5757            .iter()
5758            .copied()
5759            .filter(|s| !ALL_SLOTS.contains(s))
5760            .collect();
5761        assert!(
5762            missing.is_empty() && unknown.is_empty(),
5763            "slots the coverage program never uses: {missing:?}; slots missing from ALL_SLOTS: {unknown:?}"
5764        );
5765    }
5766
5767    #[test]
5768    fn expr_children_returns_exactly_the_oracle_s_children_at_every_node() {
5769        let key = |e: &Expr| (e.span.start, e.span.end, e.id);
5770        let mut checked = 0;
5771        for source in [COVERAGE, COVERAGE_SUITE] {
5772            let units = parse(source);
5773            for b in bodies(&units) {
5774                for s in &b.statements {
5775                    let mut got = Vec::new();
5776                    statement_exprs(s, &mut got);
5777                    let got: Vec<_> = got.into_iter().map(key).collect();
5778                    let want: Vec<_> = oracle_statement(s)
5779                        .into_iter()
5780                        .map(|(_, e)| key(e))
5781                        .collect();
5782                    assert_eq!(got, want, "statement_exprs at {:?}", s.span());
5783                }
5784                visit(b, &mut |e| {
5785                    let got: Vec<_> = expr_children(e).into_iter().map(key).collect();
5786                    let want: Vec<_> = oracle_children(e)
5787                        .into_iter()
5788                        .map(|(_, c)| key(c))
5789                        .collect();
5790                    assert_eq!(
5791                        got,
5792                        want,
5793                        "expr_children of `{}`",
5794                        &source[e.span.start..e.span.end]
5795                    );
5796                    checked += 1;
5797                });
5798            }
5799        }
5800        assert!(checked > 50, "only {checked} nodes checked");
5801    }
5802}
5803
5804#[cfg(test)]
5805mod stream_path_tests {
5806    use super::*;
5807
5808    fn types(source: &str) -> std::collections::HashMap<String, std::sync::Arc<TypeDecl>> {
5809        let tokens = crate::lexer::tokenize(source).unwrap();
5810        let units = crate::parser::parse_units(&tokens, source).unwrap();
5811        let SourceUnit::Commons(c) = &units[0] else {
5812            panic!("a commons");
5813        };
5814        c.items
5815            .iter()
5816            .filter_map(|i| match i {
5817                CommonsItem::Type(t) => Some((t.name.name.clone(), std::sync::Arc::new(t.clone()))),
5818                _ => None,
5819            })
5820            .collect()
5821    }
5822
5823    fn named(name: &str) -> TypeRef {
5824        TypeRef::Named(Ident {
5825            name: name.to_string(),
5826            span: Span::default(),
5827        })
5828    }
5829
5830    /// K-streams (#2623): the chain of fields a stream is reached through,
5831    /// across records, sums and a generic record's own fields, terminating on
5832    /// a recursive type.
5833    #[test]
5834    fn the_stream_path_names_each_field_it_passes_through() {
5835        let t = types(
5836            "commons d\n\
5837             type Download = { contentType: String, body: Stream[Bytes] }\n\
5838             type Shelf = { name: String, latest: Option[Download] }\n\
5839             type Pick = | Got(d: Download) | Nothing\n\
5840             type Wrap[T] = { s: Stream[T] }\n\
5841             type Tree = { kids: List[Tree], n: Int }\n\
5842             type Plain = { n: Int }\n",
5843        );
5844        let path = |n: &str| stream_path(&named(n), &t);
5845        assert_eq!(path("Download"), Some(vec!["Download.body".to_string()]));
5846        assert_eq!(
5847            path("Shelf"),
5848            Some(vec![
5849                "Shelf.latest".to_string(),
5850                "Download.body".to_string()
5851            ])
5852        );
5853        assert_eq!(
5854            path("Pick"),
5855            Some(vec!["Pick.Got.d".to_string(), "Download.body".to_string()])
5856        );
5857        assert_eq!(path("Wrap"), Some(vec!["Wrap.s".to_string()]));
5858        assert_eq!(path("Tree"), None);
5859        assert_eq!(path("Plain"), None);
5860        assert!(type_carries_stream("Shelf", &t));
5861        assert!(!type_carries_stream("Tree", &t));
5862    }
5863
5864    /// #2867: the calendar rule at its edges.
5865    #[test]
5866    fn is_iso_date_decides_the_calendar() {
5867        for ok in [
5868            "2026-11-03",
5869            "2028-02-29",
5870            "2000-02-29",
5871            "0000-01-01",
5872            "9999-12-31",
5873            "2026-04-30",
5874            "2026-12-31",
5875            "2400-02-29",
5876        ] {
5877            assert!(is_iso_date(ok), "{ok}");
5878        }
5879        for bad in [
5880            "2026-02-30",
5881            "2026-02-29",
5882            "1900-02-29",
5883            "2100-02-29",
5884            "2026-04-31",
5885            "2026-13-01",
5886            "2026-00-10",
5887            "2026-01-00",
5888            "2026-1-1",
5889            "yesterday",
5890            "",
5891            "2026-11-03 ",
5892            "20261103",
5893            "2026/11/03",
5894            "+2026-11-03",
5895            "2026-11-03T00:00:00Z",
5896            "2026-11-03",
5897            "2026-+1-03",
5898        ] {
5899            assert!(!is_iso_date(bad), "{bad:?}");
5900        }
5901    }
5902}
5903
5904#[cfg(test)]
5905mod commons_item_accessor_tests {
5906    use super::*;
5907
5908    /// Parses `src` as a commons and returns its items in source order.
5909    fn items(src: &str) -> Vec<CommonsItem> {
5910        let tokens = crate::lexer::tokenize(src).expect("tokenize");
5911        match crate::parser::parse_unit(&tokens, src).expect("parse") {
5912            SourceUnit::Commons(c) => c.items,
5913            SourceUnit::Context(c) => c.items,
5914            _ => panic!("expected a commons or a context"),
5915        }
5916    }
5917
5918    /// One item of each kind an accessor distinguishes, in a context so that
5919    /// services and agents parse.
5920    const SRC: &str = r#"context shop
5921
5922type Id = { n: Int }
5923
5924capability Clock {
5925  fn now() -> Effect[Int]
5926}
5927
5928service greeter {
5929  on call(name: String) -> Effect[String] by Caller {
5930    Effect.pure(name)
5931  }
5932}
5933
5934agent Counter {
5935  key id: String
5936  store hits: Cell[Int]
5937  on call bump() -> Effect[()] {
5938    Effect.pure(())
5939  }
5940}
5941"#;
5942
5943    #[test]
5944    fn each_accessor_answers_for_its_own_kind_only() {
5945        let items = items(SRC);
5946        let kinds: Vec<(bool, bool, bool, bool, usize)> = items
5947            .iter()
5948            .map(|i| {
5949                (
5950                    i.as_service().is_some(),
5951                    i.as_agent().is_some(),
5952                    i.as_capability().is_some(),
5953                    i.as_messages().is_some(),
5954                    i.handlers().len(),
5955                )
5956            })
5957            .collect();
5958        assert_eq!(
5959            kinds,
5960            vec![
5961                (false, false, false, false, 0), // type
5962                (false, false, true, false, 0),  // capability
5963                (true, false, false, false, 1),  // service
5964                (false, true, false, false, 1),  // agent
5965            ]
5966        );
5967    }
5968
5969    #[test]
5970    fn an_actor_answers_as_actor_and_nothing_else() {
5971        let items = items(
5972            r#"context a
5973
5974type UserId = String
5975
5976actor Participant { auth = Bearer(secret = "AUTH_SECRET"), identity = UserId }
5977"#,
5978        );
5979        let actors: Vec<bool> = items.iter().map(|i| i.as_actor().is_some()).collect();
5980        assert_eq!(actors, vec![false, true]);
5981        assert!(items[1].as_service().is_none() && items[1].as_capability().is_none());
5982    }
5983
5984    #[test]
5985    fn a_messages_block_answers_as_messages_and_nothing_else() {
5986        let items = items(
5987            r#"commons m
5988
5989messages "en" @reference {
5990  "a" => "b"
5991}
5992"#,
5993        );
5994        assert_eq!(items.len(), 1);
5995        assert!(items[0].as_messages().is_some());
5996        assert!(items[0].as_service().is_none() && items[0].as_agent().is_none());
5997        assert!(items[0].as_capability().is_none() && items[0].handlers().is_empty());
5998    }
5999}
6000
6001/// [`ExprKind::chain_link`] answers for the three chain links and `None` for every other
6002/// expression.
6003#[cfg(test)]
6004mod expr_kind_accessor_tests {
6005    use super::*;
6006
6007    fn expr(kind: ExprKind) -> Expr {
6008        Expr {
6009            id: ExprId::SYNTHETIC,
6010            kind,
6011            span: Span::new(0, 0),
6012        }
6013    }
6014
6015    fn ident(name: &str) -> Ident {
6016        Ident {
6017            name: name.to_string(),
6018            span: Span::new(0, 0),
6019        }
6020    }
6021
6022    #[test]
6023    fn a_name_a_field_read_and_a_bracket_are_links() {
6024        let root = ExprKind::Ident(ident("a"));
6025        assert!(matches!(
6026            root.chain_link(),
6027            Some(ChainLink::Root(id)) if id.name == "a"
6028        ));
6029        let field = ExprKind::FieldAccess {
6030            receiver: Box::new(expr(ExprKind::Ident(ident("a")))),
6031            field: ident("b"),
6032        };
6033        assert!(matches!(
6034            field.chain_link(),
6035            Some(ChainLink::Field { receiver, field }) if field.name == "b"
6036                && matches!(&receiver.kind, ExprKind::Ident(id) if id.name == "a")
6037        ));
6038        let paren = ExprKind::Paren(Box::new(expr(ExprKind::Ident(ident("a")))));
6039        assert!(matches!(paren.chain_link(), Some(ChainLink::Paren(_))));
6040    }
6041
6042    #[test]
6043    fn nothing_else_is_a_link() {
6044        let inner = || Box::new(expr(ExprKind::Ident(ident("a"))));
6045        for kind in [
6046            ExprKind::int_lit(1),
6047            ExprKind::StrLit("s".to_string()),
6048            ExprKind::BoolLit(true),
6049            ExprKind::None,
6050            ExprKind::UnitLit,
6051            ExprKind::Some(inner()),
6052            ExprKind::Ok(inner()),
6053            ExprKind::Question(inner()),
6054            ExprKind::UnaryOp(UnaryOp::Neg, inner()),
6055            ExprKind::BinOp(BinOp::Add, inner(), inner()),
6056        ] {
6057            assert!(kind.chain_link().is_none(), "{kind:?}");
6058        }
6059    }
6060
6061    #[test]
6062    fn refinable_literal_reads_numbers_strings_and_negated_numbers() {
6063        let neg = |k: ExprKind| ExprKind::UnaryOp(UnaryOp::Neg, Box::new(expr(k)));
6064        let float = || ExprKind::FloatLit {
6065            value: 1.5,
6066            lexeme: "1.5".to_string(),
6067        };
6068        let decimal = || ExprKind::DecimalLit {
6069            coef: "125".to_string(),
6070            scale: 2,
6071            lexeme: "1.25".to_string(),
6072        };
6073        assert_eq!(
6074            ExprKind::int_lit(7).refinable_literal(),
6075            Some(RefinableLiteral::Int {
6076                value: 7,
6077                negated: false
6078            })
6079        );
6080        assert_eq!(
6081            neg(ExprKind::int_lit(7)).refinable_literal(),
6082            Some(RefinableLiteral::Int {
6083                value: 7,
6084                negated: true
6085            })
6086        );
6087        assert_eq!(
6088            float().refinable_literal(),
6089            Some(RefinableLiteral::Float {
6090                lexeme: "1.5",
6091                negated: false
6092            })
6093        );
6094        assert_eq!(
6095            neg(float()).refinable_literal(),
6096            Some(RefinableLiteral::Float {
6097                lexeme: "1.5",
6098                negated: true
6099            })
6100        );
6101        assert_eq!(
6102            decimal().refinable_literal(),
6103            Some(RefinableLiteral::Decimal {
6104                coef: "125",
6105                scale: 2,
6106                negated: false
6107            })
6108        );
6109        assert_eq!(
6110            neg(decimal()).refinable_literal(),
6111            Some(RefinableLiteral::Decimal {
6112                coef: "125",
6113                scale: 2,
6114                negated: true
6115            })
6116        );
6117        assert_eq!(
6118            ExprKind::StrLit("s".to_string()).refinable_literal(),
6119            Some(RefinableLiteral::Str("s"))
6120        );
6121    }
6122
6123    #[test]
6124    fn refinable_literal_refuses_the_rest() {
6125        let inner = || Box::new(expr(ExprKind::int_lit(1)));
6126        for kind in [
6127            // A negated string, a `not`, and a doubly negated number are not literals.
6128            ExprKind::UnaryOp(
6129                UnaryOp::Neg,
6130                Box::new(expr(ExprKind::StrLit("s".to_string()))),
6131            ),
6132            ExprKind::UnaryOp(UnaryOp::Not, inner()),
6133            ExprKind::UnaryOp(
6134                UnaryOp::Neg,
6135                Box::new(expr(ExprKind::UnaryOp(UnaryOp::Neg, inner()))),
6136            ),
6137            ExprKind::BoolLit(true),
6138            ExprKind::UnitLit,
6139            ExprKind::None,
6140            ExprKind::Ident(ident("a")),
6141            ExprKind::Paren(inner()),
6142            ExprKind::Some(inner()),
6143        ] {
6144            assert!(kind.refinable_literal().is_none(), "{kind:?}");
6145        }
6146    }
6147
6148    fn block(tail: ExprKind) -> Block {
6149        Block {
6150            statements: Vec::new(),
6151            tail: Box::new(expr(tail)),
6152            span: Span::new(0, 0),
6153            tail_leading_comments: Vec::new(),
6154            implicit_tail: false,
6155        }
6156    }
6157
6158    #[test]
6159    fn branching_reads_match_and_if_and_nothing_else() {
6160        let scrutinee = || Box::new(expr(ExprKind::Ident(ident("x"))));
6161        let if_kind = ExprKind::If {
6162            cond: scrutinee(),
6163            then_block: Box::new(block(ExprKind::int_lit(1))),
6164            else_block: Box::new(block(ExprKind::int_lit(2))),
6165        };
6166        assert!(matches!(
6167            if_kind.branching(),
6168            Some(Branching::If { cond, .. }) if matches!(&cond.kind, ExprKind::Ident(_))
6169        ));
6170        let match_kind = ExprKind::Match {
6171            discriminant: scrutinee(),
6172            arms: Vec::new(),
6173        };
6174        assert!(matches!(
6175            match_kind.branching(),
6176            Some(Branching::Match { arms, .. }) if arms.is_empty()
6177        ));
6178        for kind in [
6179            ExprKind::Block(block(ExprKind::int_lit(1))),
6180            ExprKind::Paren(scrutinee()),
6181            ExprKind::Is {
6182                value: scrutinee(),
6183                pattern: Box::new(Pattern::Wildcard(Span::new(0, 0))),
6184            },
6185            ExprKind::Ident(ident("x")),
6186            ExprKind::None,
6187        ] {
6188            assert!(kind.branching().is_none(), "{kind:?}");
6189        }
6190    }
6191}