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 entry is the body of one `--` line
18///   (the text after the marker, with its original inline whitespace
19///   preserved).
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<String>,
25    pub trailing: Option<String>,
26}
27
28impl Trivia {
29    pub fn is_empty(&self) -> bool {
30        self.leading.is_empty() && self.trailing.is_none()
31    }
32}
33
34/// A whole parsed commons source file.
35///
36/// In v0.3 a commons may be split across multiple files in a directory; the
37/// resolver merges them into one logical commons. Each parsed AST instance
38/// represents the contribution from a single source file.
39#[derive(Debug, Clone)]
40pub struct Commons {
41    pub name: QualifiedName,
42    pub items: Vec<CommonsItem>,
43    /// `uses` clauses declared in this file.
44    pub uses: Vec<UsesDecl>,
45    /// Optional documentation block attached to the commons declaration.
46    pub documentation: Option<String>,
47    /// Surface form of the file: brace-delimited body or headerless fragment.
48    pub form: CommonsForm,
49    pub span: Span,
50    /// Trivia attached to the commons declaration itself — leading comments
51    /// before the `commons` keyword and a trailing comment after the header
52    /// or closing brace.
53    pub trivia: Trivia,
54    /// Comments appearing after the last item but before the file ends
55    /// (or the closing brace, for brace form). One entry per `--` line.
56    pub trailing_comments: Vec<String>,
57}
58
59/// The two surface forms in which a commons body may be parsed (v0.3 §3.1).
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum CommonsForm {
62    /// `commons name { ... }`
63    Brace,
64    /// `commons name` followed by top-level declarations to EOF.
65    Fragment,
66}
67
68/// A `uses other.commons` declaration (v0.3 §3.3).
69#[derive(Debug, Clone)]
70pub struct UsesDecl {
71    pub target: QualifiedName,
72    pub span: Span,
73    pub trivia: Trivia,
74}
75
76/// A whole parsed context source file (v0.4 §3.1).
77///
78/// Contexts are the architectural-layer declaration kind. Like commons, a
79/// context may be split across multiple files in a directory.
80#[derive(Debug, Clone)]
81pub struct Context {
82    pub name: QualifiedName,
83    pub items: Vec<CommonsItem>,
84    /// `uses` clauses declared in this file.
85    pub uses: Vec<UsesDecl>,
86    /// `consumes` clauses declared in this file.
87    pub consumes: Vec<ConsumesDecl>,
88    /// `exports` clauses declared in this file.
89    pub exports: Vec<ExportsDecl>,
90    /// Optional documentation block attached to the context declaration.
91    pub documentation: Option<String>,
92    /// Surface form of the file: brace-delimited body or headerless fragment.
93    pub form: CommonsForm,
94    pub span: Span,
95    /// Trivia attached to the context declaration itself — leading comments
96    /// before the `context` keyword.
97    pub trivia: Trivia,
98    /// Comments appearing after the last item but before the file ends
99    /// (or the closing brace, for brace form). One entry per `--` line.
100    pub trailing_comments: Vec<String>,
101}
102
103/// A `consumes other.context` declaration (v0.4 §3.2). May optionally carry
104/// an alias introduced by `consumes other.context as Alias` (v0.6 §3.1).
105#[derive(Debug, Clone)]
106pub struct ConsumesDecl {
107    pub target: QualifiedName,
108    pub alias: Option<Ident>,
109    /// v0.17: `consumes U { Cap, … }` — selected capabilities flattened into
110    /// the consumer's local capability namespace under their bare names (§3.3).
111    /// `None` for the whole-unit forms; `Some` (possibly empty) for the braced
112    /// form. Mutually exclusive with `alias`.
113    pub selected: Option<Vec<Ident>>,
114    pub span: Span,
115    pub trivia: Trivia,
116}
117
118/// An `exports visibility { names }` clause (v0.4 §3.3) or, v0.15, an
119/// `exports capability { names }` clause.
120#[derive(Debug, Clone)]
121pub struct ExportsDecl {
122    pub kind: ExportKind,
123    pub names: Vec<Ident>,
124    pub span: Span,
125    pub trivia: Trivia,
126}
127
128/// What an `exports` clause exposes: types (with a visibility) or, v0.15,
129/// capabilities offered for cross-context consumption.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum ExportKind {
132    /// `exports opaque { ... }` / `exports transparent { ... }` — type exports.
133    Type(Visibility),
134    /// `exports capability { ... }` — capabilities offered to consumers (v0.15).
135    Capability,
136}
137
138/// Visibility level for an exports clause (v0.4 §3.3).
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum Visibility {
141    /// Token-only outside the context: hold, pass, compare; no inspect, no construct.
142    Opaque,
143    /// Readable shape outside the context: inspect fields, match variants; no construct.
144    Transparent,
145}
146
147/// An `adapter qualified.name { … }` declaration (v0.17 §3.1). An adapter
148/// co-locates a capability contract with a non-Bynk binding: it may declare
149/// capabilities, the boundary types they reference, inline pure helper
150/// `type`/`fn` (and `uses`), external (bodiless) providers, `exports
151/// capability`, and exactly one `binding` clause. It may *not* declare
152/// services, agents, or bodied providers. Like commons/contexts it may be
153/// split across files in a directory.
154#[derive(Debug, Clone)]
155pub struct AdapterDecl {
156    pub name: QualifiedName,
157    pub items: Vec<CommonsItem>,
158    /// `uses` clauses declared in this file (pure-vocabulary mixin; allowed
159    /// because helpers cannot pierce containment — spec [DECISION B]).
160    pub uses: Vec<UsesDecl>,
161    /// `exports capability { … }` clauses (adapters export capabilities and
162    /// boundary types, never services).
163    pub exports: Vec<ExportsDecl>,
164    /// v0.18: `consumes U { Cap, … }` clauses — adapter-to-adapter capability
165    /// dependencies (spec §4.5, \[N\]). Braced form only; adapter targets only
166    /// (both enforced semantically, not in the parser).
167    pub consumes: Vec<ConsumesDecl>,
168    /// The `binding "<module>" requires { … }` clause, if present. Required
169    /// when the adapter declares any external provider (`bynk.adapter.no_binding`).
170    pub binding: Option<BindingDecl>,
171    pub documentation: Option<String>,
172    pub form: CommonsForm,
173    pub span: Span,
174    pub trivia: Trivia,
175    pub trailing_comments: Vec<String>,
176}
177
178/// A `binding "<module>" requires { "pkg": "range", … }` clause inside an
179/// adapter (v0.17 §3.5). `module` is the TypeScript module supplying the
180/// adapter's external provider symbols, resolved relative to the adapter's
181/// source file. `requires` declares npm dependencies folded into the
182/// generated `package.json`.
183#[derive(Debug, Clone)]
184pub struct BindingDecl {
185    /// The module path as written (the string-literal contents, no quotes).
186    pub module: String,
187    pub module_span: Span,
188    pub requires: Vec<RequiresDep>,
189    pub span: Span,
190    pub trivia: Trivia,
191}
192
193/// One `"pkg": "range"` entry in a binding's `requires { … }` map.
194#[derive(Debug, Clone)]
195pub struct RequiresDep {
196    pub package: String,
197    pub range: String,
198    pub span: Span,
199}
200
201/// Either a commons or a context — the two declaration kinds at the file
202/// level (v0.4 §3.1). v0.7 adds the test declaration kind; v0.17 the adapter.
203#[derive(Debug, Clone)]
204pub enum SourceUnit {
205    Commons(Commons),
206    Context(Context),
207    Suite(SuiteDecl),
208    /// v0.17: an `adapter` unit — the host boundary (capability contract +
209    /// external binding).
210    Adapter(AdapterDecl),
211}
212
213impl SourceUnit {
214    pub fn name(&self) -> &QualifiedName {
215        match self {
216            SourceUnit::Commons(c) => &c.name,
217            SourceUnit::Context(c) => &c.name,
218            SourceUnit::Suite(t) => &t.target,
219            SourceUnit::Adapter(a) => &a.name,
220        }
221    }
222
223    pub fn span(&self) -> Span {
224        match self {
225            SourceUnit::Commons(c) => c.span,
226            SourceUnit::Context(c) => c.span,
227            SourceUnit::Suite(t) => t.span,
228            SourceUnit::Adapter(a) => a.span,
229        }
230    }
231
232    pub fn kind_name(&self) -> &'static str {
233        match self {
234            SourceUnit::Commons(_) => "commons",
235            SourceUnit::Context(_) => "context",
236            SourceUnit::Suite(_) => "suite",
237            SourceUnit::Adapter(_) => "adapter",
238        }
239    }
240}
241
242/// A `test <qualified-name> { ... }` declaration (v0.7 §3.1).
243///
244/// A test targets a commons or context by qualified name and bundles a set of
245/// test cases plus optional mock declarations. As with commons and contexts, a
246/// test may be split across multiple files (fragment form).
247#[derive(Debug, Clone)]
248pub struct SuiteDecl {
249    /// The targeted commons or context.
250    pub target: QualifiedName,
251    /// `uses` clauses brought in by this test fragment.
252    pub uses: Vec<UsesDecl>,
253    /// v0.118: suite-scoped `stub` clauses — per-seam provider overrides
254    /// applied to every case (a case-scoped `stub` takes precedence). Formerly
255    /// the punned `provides` stub; renamed to `stub` in the keyword-hygiene
256    /// batch (#548).
257    pub stubs: Vec<StubClause>,
258    /// The individual test cases.
259    pub cases: Vec<Case>,
260    /// v0.114: generative `property` blocks (testing track slice 2).
261    pub properties: Vec<PropertyDecl>,
262    /// v0.118: the suite-level tier default (`suite … as integration`). `None`
263    /// means the `unit` default; a `case`'s own tier overrides it. A `property`
264    /// ignores a suite tier (tiers are a `case`-only affordance).
265    pub tier: Option<TestTier>,
266    /// Surface form: brace-delimited body or headerless fragment.
267    pub form: CommonsForm,
268    /// Optional documentation block attached to the test declaration.
269    pub documentation: Option<String>,
270    pub span: Span,
271    pub trivia: Trivia,
272    pub trailing_comments: Vec<String>,
273}
274
275/// v0.118: the tier a `case` runs at (testing track slice 6, ADR 0153). One
276/// body promoted across the testing pyramid; `unit` is the default and elided.
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub enum TestTier {
279    /// Collaborators stubbed (the default).
280    Unit,
281    /// Real collaborators within one context, no serialisation wire.
282    Integration,
283    /// Contexts wired across the real serialise → JSON → deserialise boundary.
284    System,
285}
286
287impl TestTier {
288    pub fn as_str(self) -> &'static str {
289        match self {
290            TestTier::Unit => "unit",
291            TestTier::Integration => "integration",
292            TestTier::System => "system",
293        }
294    }
295}
296
297/// v0.118: a per-seam provider override `stub Cap.method(<args>) returns <v>
298/// | fails` (testing track slice 6, ADR 0154; keyword `stub` since #548).
299/// Substitutes one capability method's provision under test; the right-hand
300/// side is a value or a fault, never a computed body.
301#[derive(Debug, Clone)]
302pub struct StubClause {
303    /// The capability being overridden (a consumed seam of the unit).
304    pub capability: Ident,
305    /// The overridden method.
306    pub method: Ident,
307    /// One argument pattern per parameter (`_` or a value the arg must equal).
308    pub args: Vec<ArgPattern>,
309    /// The provision: a value, a fault, or a per-call sequence.
310    pub rhs: StubRhs,
311    pub documentation: Option<String>,
312    pub span: Span,
313    pub trivia: Trivia,
314}
315
316/// v0.118: one argument pattern in a `stub` call pattern. Patterns for the
317/// same method are tried top-to-bottom, first match wins.
318#[derive(Debug, Clone)]
319pub enum ArgPattern {
320    /// `_` — matches any argument.
321    Any(Span),
322    /// A value the recorded argument must equal (a literal or pure value expr).
323    Value(Expr),
324}
325
326/// v0.118: the right-hand side of a `stub` clause.
327#[derive(Debug, Clone)]
328pub enum StubRhs {
329    /// `returns <value>` — a single success value, repeated for every call.
330    Returns(Expr),
331    /// `fails` — inject a capability fault (Principle 3).
332    Fails(Span),
333    /// `returns each [<outcome>, …]` — one outcome per call, in order; the last
334    /// outcome repeats once the sequence is exhausted (DECISION V).
335    ReturnsEach(Vec<SeqOutcome>, Span),
336}
337
338impl StubRhs {
339    pub fn span(&self) -> Span {
340        match self {
341            StubRhs::Returns(e) => e.span,
342            StubRhs::Fails(s) => *s,
343            StubRhs::ReturnsEach(_, s) => *s,
344        }
345    }
346}
347
348/// v0.118: one outcome in a sequenced (`returns each`) `stub`.
349#[derive(Debug, Clone)]
350pub enum SeqOutcome {
351    /// A success value.
352    Value(Expr),
353    /// A fault.
354    Fails(Span),
355}
356
357/// A `case "name" [as <tier>] { [stub …] body }` block inside a suite
358/// (v0.7 §3.3; v0.118 adds the tier clause and case-scoped stubs).
359#[derive(Debug, Clone)]
360pub struct Case {
361    /// The test name, taken from the string literal.
362    pub name: String,
363    /// The span of the string literal — used for diagnostics and runtime
364    /// failure reports.
365    pub name_span: Span,
366    /// v0.118: the case's own tier, if written (`as integration` / `as system`).
367    /// `None` means inherit the suite default (itself `unit` when unset).
368    pub tier: Option<TestTier>,
369    /// v0.118: case-scoped `stub` clauses (override the suite's, and the
370    /// tier default).
371    pub stubs: Vec<StubClause>,
372    pub body: Block,
373    pub documentation: Option<String>,
374    pub span: Span,
375    pub trivia: Trivia,
376}
377
378/// A `property "name" { for all <bindings> [where <pred>] { body } }` block
379/// inside a suite (v0.114, testing track slice 2, ADR 0149). The generative
380/// sibling of [`Case`]: the runner draws inhabitants of each binding's type from
381/// its refinement domain and evaluates the body's `expect`s over them.
382#[derive(Debug, Clone)]
383pub struct PropertyDecl {
384    /// The property name, taken from the string literal.
385    pub name: String,
386    /// The span of the string literal — used for diagnostics and reports.
387    pub name_span: Span,
388    /// The `for all` binder: the generated bindings, an optional `where` filter,
389    /// and the predicate body.
390    pub forall: ForAll,
391    pub documentation: Option<String>,
392    pub span: Span,
393    pub trivia: Trivia,
394}
395
396/// The `for all x: T, … [where <pred>] { … }` binder inside a [`PropertyDecl`].
397#[derive(Debug, Clone)]
398pub struct ForAll {
399    /// The generated bindings, `x: T` (one or more).
400    pub bindings: Vec<ForAllBinding>,
401    /// An optional `where <pred>` filter (a pure `Bool`) applied to generated
402    /// tuples before the body runs.
403    pub where_pred: Option<Expr>,
404    /// The body — one or more statements, typically `expect`s.
405    pub body: Block,
406    pub span: Span,
407}
408
409/// One `for all` binding: `name: T`, where the runner generates inhabitants of
410/// `T` from its refinements.
411#[derive(Debug, Clone)]
412pub struct ForAllBinding {
413    pub name: Ident,
414    pub type_ref: TypeRef,
415}
416
417/// A capability reference in a `given` clause (v0.15 §3.2). A bare name is a
418/// local capability (`given Cap`); a dotted name refers to a capability a
419/// consumed context provides (`given B.Cap` / `given Alias.Cap`).
420#[derive(Debug, Clone)]
421pub struct CapRef {
422    /// `None` for a local capability; `Some(prefix)` for a cross-context
423    /// reference where `prefix` is a consumed-context qualified name or alias.
424    pub context: Option<QualifiedName>,
425    /// The capability's simple name (also the local deps key).
426    pub name: Ident,
427    pub span: Span,
428}
429
430impl CapRef {
431    /// The local deps key / capability simple name (e.g. `Clock`).
432    pub fn key(&self) -> &str {
433        &self.name.name
434    }
435
436    /// True when this references a capability provided by a consumed context.
437    pub fn is_cross_context(&self) -> bool {
438        self.context.is_some()
439    }
440
441    /// The cross-context prefix (consumed-context qualified name or alias) as
442    /// a dotted string, if any.
443    pub fn prefix(&self) -> Option<String> {
444        self.context.as_ref().map(|q| q.joined())
445    }
446}
447
448/// A dotted name like `fitness.units`.
449#[derive(Debug, Clone)]
450pub struct QualifiedName {
451    pub parts: Vec<Ident>,
452    pub span: Span,
453}
454
455impl QualifiedName {
456    pub fn joined(&self) -> String {
457        self.parts
458            .iter()
459            .map(|p| p.name.as_str())
460            .collect::<Vec<_>>()
461            .join(".")
462    }
463}
464
465#[derive(Debug, Clone)]
466pub enum CommonsItem {
467    Type(TypeDecl),
468    Fn(FnDecl),
469    /// `capability Name { fn op(...) -> T ... }` (v0.5; contexts only).
470    Capability(CapabilityDecl),
471    /// `provides Cap = ProviderName { fn op(...) -> T { ... } ... }` (v0.5).
472    Provider(ProviderDecl),
473    /// `service Name { on call(...) -> T { ... } ... }` (v0.5).
474    Service(ServiceDecl),
475    /// `agent Name { key id: T; state { ... }; on call ... }` (v0.5).
476    Agent(AgentDecl),
477    /// `actor Name { auth = Scheme, identity = T }` (v0.45). A nominal boundary
478    /// contract consumed by a handler's `by` clause; not a runnable entity.
479    Actor(ActorDecl),
480    /// `messages <tag> @reference { "code" => "template" ... }` — a message
481    /// bundle for one locale. Commons-only (checker-enforced, not grammar);
482    /// legal syntactically wherever any `CommonsItem` is, per the existing
483    /// `Service`/`Agent`-in-`adapter` precedent.
484    Messages(MessagesDecl),
485}
486
487impl CommonsItem {
488    /// The declaring identifier, when the item is named by one. `Messages` is
489    /// the sole `None`: its locale tag is a `LocaleTag` string literal
490    /// (`"pt-BR"`), not an identifier, and synthesising an `Ident` from it
491    /// would be a lie any identifier-shaped consumer (rename, go-to-def) would
492    /// eventually surface.
493    pub fn name(&self) -> Option<&Ident> {
494        match self {
495            CommonsItem::Type(t) => Some(&t.name),
496            CommonsItem::Fn(f) => Some(f.name.ident()),
497            CommonsItem::Capability(c) => Some(&c.name),
498            CommonsItem::Provider(p) => Some(&p.provider_name),
499            CommonsItem::Service(s) => Some(&s.name),
500            CommonsItem::Agent(a) => Some(&a.name),
501            CommonsItem::Actor(a) => Some(&a.name),
502            CommonsItem::Messages(_) => None,
503        }
504    }
505}
506
507/// One locale's message bundle (v0.222+): `messages "<tag>" @reference { ... }`.
508/// `tag` is a `LocaleTag` string literal (like an entry's `code`/`template`);
509/// its refinement (`bynk.locale.types`) is checked by `check_messages_bundles`,
510/// which reports `bynk.messages.invalid_locale_tag` for a tag the pattern
511/// rejects.
512#[derive(Debug, Clone)]
513pub struct MessagesDecl {
514    pub tag: String,
515    pub tag_span: Span,
516    /// Every `@`-annotation attached to this block. The parser stays
517    /// permissive (zero or more, same as `store` field annotations); cardinality
518    /// (exactly one `@reference` per bundle, counted across every `Messages`
519    /// item in the commons) is a checker concern, not a parse error.
520    pub annotations: Vec<Annotation>,
521    pub entries: Vec<MessageEntry>,
522    pub documentation: Option<String>,
523    pub span: Span,
524    pub trivia: Trivia,
525}
526
527/// One `"code" => "template"` entry inside a `messages` block. Both sides are
528/// plain string literals — a template's `{name}` placeholders are resolved by
529/// a compile-time string scan during lowering, not parsed as expressions.
530#[derive(Debug, Clone)]
531pub struct MessageEntry {
532    pub code: String,
533    pub code_span: Span,
534    pub template: String,
535    pub template_span: Span,
536    pub span: Span,
537}
538
539/// A capability declaration (v0.5 §3.3). Capabilities are interface-like
540/// contracts for external dependencies, used inside contexts. They may only
541/// appear inside a `context` declaration.
542#[derive(Debug, Clone)]
543pub struct CapabilityDecl {
544    pub name: Ident,
545    pub ops: Vec<CapabilityOp>,
546    pub documentation: Option<String>,
547    pub span: Span,
548    pub trivia: Trivia,
549}
550
551/// One operation in a capability (signature only; no body).
552#[derive(Debug, Clone)]
553pub struct CapabilityOp {
554    pub name: Ident,
555    pub params: Vec<Param>,
556    pub return_type: TypeRef,
557    pub documentation: Option<String>,
558    pub span: Span,
559    pub trivia: Trivia,
560}
561
562/// A provider declaration (v0.5 §3.4). Supplies an implementation for a
563/// capability.
564#[derive(Debug, Clone)]
565pub struct ProviderDecl {
566    /// The capability being implemented.
567    pub capability: Ident,
568    /// The provider's identifier (used in tests/config to select impls).
569    pub provider_name: Ident,
570    /// v0.12: capabilities this provider depends on (`provides X = Impl given
571    /// Y, Z { … }`). The provider's operation bodies may use these. v0.15:
572    /// a dependency may be a cross-context capability (`given B.Cap`).
573    pub given: Vec<CapRef>,
574    pub ops: Vec<ProviderOp>,
575    /// v0.17: an *external* provider — `provides Cap = Name` with **no** brace
576    /// block — inside an adapter, supplied by the adapter's binding rather than
577    /// a Bynk body. When `true`, `ops` is empty and the emitter produces no
578    /// class. The absence of the brace block (not an empty one) is the signal.
579    pub external: bool,
580    pub documentation: Option<String>,
581    pub span: Span,
582    pub trivia: Trivia,
583}
584
585/// One operation in a provider (signature plus body).
586#[derive(Debug, Clone)]
587pub struct ProviderOp {
588    pub name: Ident,
589    pub params: Vec<Param>,
590    pub return_type: TypeRef,
591    pub body: Block,
592    pub span: Span,
593    pub trivia: Trivia,
594}
595
596/// A service declaration (v0.5 §3.5). Services are the boundary interface
597/// of a context.
598#[derive(Debug, Clone)]
599pub struct ServiceDecl {
600    pub name: Ident,
601    /// The protocol the service conforms to, from the `from <protocol>` header
602    /// clause (v0.44). `Call` when there is no clause.
603    pub protocol: ServiceProtocol,
604    /// The optional service-level `by` default (v0.155) — a `by <Actor>` clause on
605    /// the service header, `service Api from http by v: Visitor { … }`. Every
606    /// handler that omits its own `by` inherits this one (injected by the
607    /// normalization pass). `None` when absent — handlers then fall back to the
608    /// per-protocol default actor (HTTP/WebSocket have none, so `by` stays
609    /// mandatory there). The "public / bearer-authed" fact is usually a service
610    /// fact, so this removes the per-handler repetition.
611    pub default_by: Option<ByClause>,
612    /// The optional service-level `given` default (v0.155) — a `given C1, C2`
613    /// clause on the service header, following the `by` default. Every handler
614    /// that declares no `given` of its own inherits this list. Empty when absent.
615    pub default_given: Vec<CapRef>,
616    /// The optional cross-origin (CORS) policy (v0.131, ADR 0159) — a `cors { }`
617    /// section in the service body, only meaningful on a `from http` service.
618    /// `None` when absent (same-origin default, byte-for-byte unchanged output).
619    pub cors: Option<CorsPolicy>,
620    /// The optional security-headers policy (v0.141, ADR 0164) — a `security { }`
621    /// section in the service body, only meaningful on a `from http` service.
622    /// `None` when absent, but unlike `cors` the *absence* still stamps the safe
623    /// defaults (`nosniff` on) — the emitter synthesises a default policy for every
624    /// `from http` service, so `None` here means "defaults", not "no headers".
625    pub security: Option<SecurityPolicy>,
626    /// The optional request-body-size policy (v0.142, ADR 0165) — a `limits { }`
627    /// section in the service body, only meaningful on a `from http` service. It
628    /// declares a per-service `maxBody` ceiling (in bytes) for the service's
629    /// body-taking routes; a route may override it with `@limit(maxBody: …)`.
630    /// `None` when absent (no cap — byte-for-byte unchanged output, the opt-in
631    /// CORS posture, not the `security` default-on posture).
632    pub limits: Option<LimitsPolicy>,
633    pub handlers: Vec<Handler>,
634    pub documentation: Option<String>,
635    pub span: Span,
636    pub trivia: Trivia,
637}
638
639/// A cross-origin resource-sharing policy on a `from http` service (v0.131,
640/// ADR 0159): the `cors { }` section in the service body. Parsed leniently as a
641/// list of `name: value` fields (the grammar accepts any field name — an unknown
642/// one is a checker diagnostic, per the `@`-annotation precedent, ADR 0111), and
643/// interpreted through the typed accessors below.
644///
645/// `Access-Control-Allow-Methods` is deliberately **not** a field — it is derived
646/// from the service's routes at emit time (the routes already enumerate the
647/// methods; a restated list would drift). Likewise `Allow-Headers` defaults to
648/// `content-type` (+ `Authorization` when a Bearer route exists) and is only
649/// stored here when the author overrides it.
650#[derive(Debug, Clone)]
651pub struct CorsPolicy {
652    /// The `cors { }` fields as written, in source order. Field names are
653    /// validated against the closed set (`origins`/`headers`/`credentials`/
654    /// `maxAge`) by the checker, not the parser.
655    pub fields: Vec<CorsField>,
656    pub span: Span,
657    pub trivia: Trivia,
658}
659
660/// One `name: value` field inside a `cors { }` policy (v0.131).
661#[derive(Debug, Clone)]
662pub struct CorsField {
663    pub name: Ident,
664    pub value: Expr,
665    pub span: Span,
666}
667
668impl CorsPolicy {
669    /// The raw value expression for a field, by name (the last one wins if a
670    /// field is repeated — the checker flags the duplicate separately).
671    pub fn field(&self, name: &str) -> Option<&Expr> {
672        self.fields
673            .iter()
674            .rev()
675            .find(|f| f.name.name == name)
676            .map(|f| &f.value)
677    }
678
679    /// The allowed origins — the string literals of the `origins:` list. An
680    /// absent or malformed field yields an empty list (the checker has already
681    /// reported the shape error; the emitter fails closed on an empty list).
682    pub fn origins(&self) -> Vec<String> {
683        Self::str_list(self.field("origins")).unwrap_or_default()
684    }
685
686    /// `true` iff `origins` is exactly the wildcard `["*"]`.
687    pub fn is_wildcard(&self) -> bool {
688        let os = self.origins();
689        os.len() == 1 && os[0] == "*"
690    }
691
692    /// Whether credentialed requests are allowed (`credentials: true`); defaults
693    /// to `false` when the field is absent.
694    pub fn credentials(&self) -> bool {
695        matches!(
696            self.field("credentials").map(|e| &e.kind),
697            Some(ExprKind::BoolLit(true))
698        )
699    }
700
701    /// The explicit `Access-Control-Allow-Headers` override, if the author gave
702    /// a `headers:` list; `None` leaves the emitter to apply its smart default.
703    pub fn allow_headers(&self) -> Option<Vec<String>> {
704        self.field("headers").and_then(Self::str_list_of)
705    }
706
707    /// The `Access-Control-Max-Age` in whole seconds, if a `maxAge:` duration was
708    /// given; `None` leaves the header off (the browser default).
709    pub fn max_age_secs(&self) -> Option<i64> {
710        match self.field("maxAge").map(|e| &e.kind) {
711            Some(ExprKind::DurationLit { millis, .. }) => Some(millis / 1_000),
712            _ => None,
713        }
714    }
715
716    /// Interpret an expression as a list of string literals, if it is one.
717    fn str_list(expr: Option<&Expr>) -> Option<Vec<String>> {
718        expr.and_then(Self::str_list_of)
719    }
720
721    fn str_list_of(expr: &Expr) -> Option<Vec<String>> {
722        match &expr.kind {
723            ExprKind::ListLit(items) => items
724                .iter()
725                .map(|e| match &e.kind {
726                    ExprKind::StrLit(s) => Some(s.clone()),
727                    _ => None,
728                })
729                .collect(),
730            _ => None,
731        }
732    }
733}
734
735/// A security-headers policy on a `from http` service (v0.141, ADR 0164): the
736/// `security { }` section in the service body. Parsed leniently as a list of
737/// `name: value` fields (an unknown one is a checker diagnostic, per the CORS /
738/// `@`-annotation precedent) and interpreted through the typed accessors below.
739///
740/// The closed set is `nosniff` (a `Bool`, default `true` — stamps
741/// `X-Content-Type-Options: nosniff`) and `hsts` (a positive `Duration`, opt-in —
742/// stamps `Strict-Transport-Security: max-age=…`). Unlike `cors`, the *safe*
743/// header is on by default: a `from http` service with no `security { }` still
744/// stamps `nosniff`, because a security header you have to remember to switch on
745/// is the one you forget (ADR 0164 DECISION A).
746#[derive(Debug, Clone)]
747pub struct SecurityPolicy {
748    /// The `security { }` fields as written, in source order. Field names are
749    /// validated against the closed set (`hsts`/`nosniff`) by the checker, not
750    /// the parser.
751    pub fields: Vec<SecurityField>,
752    pub span: Span,
753    pub trivia: Trivia,
754}
755
756/// One `name: value` field inside a `security { }` policy (v0.141).
757#[derive(Debug, Clone)]
758pub struct SecurityField {
759    pub name: Ident,
760    pub value: Expr,
761    pub span: Span,
762}
763
764impl SecurityPolicy {
765    /// The raw value expression for a field, by name (the last one wins if a
766    /// field is repeated — the checker flags the duplicate separately).
767    pub fn field(&self, name: &str) -> Option<&Expr> {
768        self.fields
769            .iter()
770            .rev()
771            .find(|f| f.name.name == name)
772            .map(|f| &f.value)
773    }
774
775    /// Whether `X-Content-Type-Options: nosniff` is stamped. Defaults to `true`
776    /// (the safe default, ADR 0164 DECISION A); only an explicit `nosniff: false`
777    /// opts out. A malformed value has already been reported by the checker; it
778    /// falls back to the safe default here.
779    pub fn nosniff(&self) -> bool {
780        !matches!(
781            self.field("nosniff").map(|e| &e.kind),
782            Some(ExprKind::BoolLit(false))
783        )
784    }
785
786    /// The `Strict-Transport-Security` `max-age` in whole seconds, if the author
787    /// opted in with an `hsts:` duration; `None` leaves HSTS off (the default —
788    /// HSTS pins the browser to HTTPS and is a deliberate opt-in, DECISION A).
789    pub fn hsts_max_age_secs(&self) -> Option<i64> {
790        match self.field("hsts").map(|e| &e.kind) {
791            Some(ExprKind::DurationLit { millis, .. }) => Some(millis / 1_000),
792            _ => None,
793        }
794    }
795}
796
797/// A request-body-size policy on a `from http` service (v0.142, ADR 0165): the
798/// `limits { }` section in the service body. Parsed leniently as a list of
799/// `name: value` fields (an unknown one is a checker diagnostic, per the CORS /
800/// `security` / `@`-annotation precedent) and interpreted through the typed
801/// accessor below.
802///
803/// The closed set is `maxBody` — a positive `Int` byte count (there is no byte
804/// `Size` literal yet; a `1.mb`-style literal is a named follow-on, the
805/// `Duration` playbook). Unlike `security`, this is opt-in: a service with no
806/// `limits { }` (and no route `@limit`) has no cap and emits byte-for-byte
807/// unchanged output (ADR 0165 DECISION E — the CORS posture).
808#[derive(Debug, Clone)]
809pub struct LimitsPolicy {
810    /// The `limits { }` fields as written, in source order. Field names are
811    /// validated against the closed set (`maxBody`) by the checker, not the
812    /// parser.
813    pub fields: Vec<LimitsField>,
814    pub span: Span,
815    pub trivia: Trivia,
816}
817
818/// One `name: value` field inside a `limits { }` policy (v0.142).
819#[derive(Debug, Clone)]
820pub struct LimitsField {
821    pub name: Ident,
822    pub value: Expr,
823    pub span: Span,
824}
825
826impl LimitsPolicy {
827    /// The raw value expression for a field, by name (the last one wins if a
828    /// field is repeated — the checker flags the duplicate separately).
829    pub fn field(&self, name: &str) -> Option<&Expr> {
830        self.fields
831            .iter()
832            .rev()
833            .find(|f| f.name.name == name)
834            .map(|f| &f.value)
835    }
836
837    /// The service-wide maximum request-body size in bytes, if the author gave a
838    /// positive `maxBody:` `Int` literal; `None` leaves the service without a
839    /// default cap. A malformed or non-positive value has already been reported
840    /// by the checker; it falls back to `None` here (no cap).
841    pub fn max_body(&self) -> Option<i64> {
842        match self.field("maxBody").map(|e| &e.kind) {
843            Some(ExprKind::IntLit { value, .. }) if *value > 0 => Some(*value),
844            _ => None,
845        }
846    }
847}
848
849/// The protocol a service conforms to — declared on the header via
850/// `from <protocol>` (v0.44). `Call` is the default (no `from` clause): a
851/// contract-mediated internal-RPC surface, not a wire protocol. Multi-endpoint
852/// protocols (`Http`, `Cron`) carry no binding — the endpoint lives on each
853/// handler; single-binding `Queue` carries its queue name.
854#[derive(Debug, Clone)]
855pub enum ServiceProtocol {
856    /// No `from` clause: the service holds `on call` handlers only.
857    Call,
858    /// `from http` — many routes; each handler is `on <Method>("route")`.
859    Http,
860    /// `from cron` — many schedules; each handler is `on schedule("expr")`.
861    Cron,
862    /// `from queue("name")` — one bound queue; handlers are `on message(...)`.
863    Queue { name: String },
864    /// `from websocket(in: ClientFrame, out: ServerFrame)` — a held WebSocket
865    /// connection (v0.103, real-time track slice 3). `in_type` is the inbound
866    /// frame type (client→server, decoded and routed as typed agent messages);
867    /// `out_type` is the server→client frame type the held `Connection[out_type]`
868    /// carries. The service holds exactly one `on open` handler (edge auth via
869    /// `by`, then transfer of the connection to an agent).
870    WebSocket { in_type: TypeRef, out_type: TypeRef },
871}
872
873/// An agent declaration (v0.5 §3.6). Agents are state-bearing entities
874/// with their own handlers.
875#[derive(Debug, Clone)]
876pub struct AgentDecl {
877    pub name: Ident,
878    /// `key id: Type` — the identifier-typed value identifying instances.
879    pub key_name: Ident,
880    pub key_type: TypeRef,
881    /// `store` fields (v0.81, storage track) — each an access-pattern slot of a
882    /// declared storage kind (`Cell`/`Map`/…). The successor to the removed
883    /// `state { }` record (ADR 0108); every agent declares its state this way.
884    pub store_fields: Vec<StoreField>,
885    /// Invariants (v0.80 §14) — universally-quantified predicates over the
886    /// agent's `store` fields. The phase sits between the fields and the
887    /// handlers; each is checked against the state staged by a handler's writes
888    /// before it commits.
889    pub invariants: Vec<Invariant>,
890    /// Step invariants (v0.116 §, testing track slice 4) — named predicates over
891    /// the pre-/post-commit state *pair* (`old`/`new`), checked at the commit
892    /// boundary beside [`invariants`], from the second commit onward. Widen the
893    /// invariant subject from a snapshot to a step (ADR 0144 — one predicate
894    /// surface).
895    ///
896    /// [`invariants`]: AgentDecl::invariants
897    pub transitions: Vec<Transition>,
898    pub handlers: Vec<Handler>,
899    pub documentation: Option<String>,
900    pub span: Span,
901    pub trivia: Trivia,
902}
903
904/// A `store` field (v0.81, storage track). Each is an access-pattern slot of a
905/// declared storage kind: `store <name>: <Kind>[…] [@annotations] [= <init>]`.
906/// The kind and its element type are carried as an ordinary [`TypeRef`]
907/// (`Cell[Int]`, `Map[K, V]`); the checker restricts which heads are storage
908/// kinds. Access-pattern annotations (`@indexed`, …) parse into [`annotations`]
909/// (v0.85, ADR 0111); the checker validates them against the closed registry.
910///
911/// [`annotations`]: StoreField::annotations
912#[derive(Debug, Clone)]
913pub struct StoreField {
914    pub name: Ident,
915    /// The storage kind and its element type(s): `Cell[Int]`, `Map[K, V]`. A
916    /// dedicated [`StoreKind`] rather than a [`TypeRef`] — storage kinds are not
917    /// value types, and the checker dispatches kind-aware operations on the head.
918    pub kind: StoreKind,
919    /// Storage annotations on the field (v0.85, ADR 0111): `@ttl(5.minutes)`,
920    /// `@indexed(by: orderId)`. Parsed in declaration order (after the kind,
921    /// before the initialiser); the checker validates names against the closed
922    /// registry and gates each to the slice that implements it.
923    pub annotations: Vec<Annotation>,
924    /// The fresh-key initial value (`= expr`), if given — same disposition as a
925    /// `state` field's initialiser (ADRs 0003/0004 carry forward).
926    pub init: Option<Expr>,
927    pub documentation: Option<String>,
928    pub span: Span,
929    pub trivia: Trivia,
930}
931
932/// A storage annotation on a `store` field (v0.85, storage track; ADR 0111):
933/// `@<name>(<args>)`. The `name` is matched against the closed registry
934/// (`@indexed`/`@ttl`/`@retain`/`@bounded`) by the checker; the grammar accepts
935/// any identifier so an unknown name is a checker diagnostic, not a parse error.
936/// Arguments are compile-time metadata, restricted to literals (and the `by:`
937/// field-name labels of `@indexed`) by the checker per ADR 0111 D4.
938#[derive(Debug, Clone)]
939pub struct Annotation {
940    pub name: Ident,
941    pub args: Vec<AnnotationArg>,
942    pub span: Span,
943}
944
945/// A single annotation argument (v0.85; ADR 0111): an optional `label:` followed
946/// by a value expression — `by: orderId` (labelled) or `5.minutes` (positional).
947/// The value is parsed as an ordinary [`Expr`] so the duration-literal form
948/// (`5.minutes`, landing with the `Duration` slice) needs no special grammar;
949/// the checker restricts it to a literal where the annotation is functional.
950#[derive(Debug, Clone)]
951pub struct AnnotationArg {
952    pub label: Option<Ident>,
953    pub value: Expr,
954    pub span: Span,
955}
956
957/// A storage kind applied to its element type(s) (v0.81): `Cell[Int]`,
958/// `Map[ReservationId, Reservation]`. The `head` is the kind name (`Cell`,
959/// `Map`, `Set`, `Log`, `Queue`, `Cache`); the checker validates it against the
960/// closed catalogue. Element types are ordinary [`TypeRef`]s. Refined element
961/// types (`Cell[Int where NonNegative]`) ride a later slice (parse_type_ref does
962/// not yet accept an inline refinement in type-argument position).
963#[derive(Debug, Clone)]
964pub struct StoreKind {
965    pub head: Ident,
966    pub args: Vec<TypeRef>,
967    pub span: Span,
968}
969
970/// An agent invariant (v0.80 §14). A named predicate over the agent's state
971/// fields that must hold of every committed state; a commit that would violate
972/// it faults (`InvariantViolation`) before the state is persisted. The
973/// predicate references state fields by bare name, mirroring the design-notes
974/// worked examples (`status == Paid implies paymentRef.isSome()`).
975#[derive(Debug, Clone)]
976pub struct Invariant {
977    pub name: Ident,
978    /// The predicate expression — an ordinary `Bool`-typed expression over the
979    /// state fields, plus `implies` and `is`. The parsed-predicate-on-a-
980    /// declaration shape mirrors [`ActorRefinement::predicate`].
981    pub predicate: Expr,
982    pub documentation: Option<String>,
983    pub span: Span,
984    pub trivia: Trivia,
985}
986
987/// An agent step invariant (v0.116 §, testing track slice 4). A named predicate
988/// over the *pair* of committed states — the pre-commit `old` and the proposed
989/// `new`, each the agent's state record — that must hold of every state move; a
990/// commit that would violate it faults (`InvariantViolation`) before the state is
991/// persisted, exactly as a snapshot [`Invariant`] does. Widens the invariant
992/// subject from a snapshot to a step (ADR 0144 — one predicate surface); the
993/// predicate reuses the invariant surface (`implies`/`is`/pure methods) with
994/// `old`/`new` bound contextually (`old.status is Paid implies new.status is
995/// Paid`).
996#[derive(Debug, Clone)]
997pub struct Transition {
998    pub name: Ident,
999    /// The predicate expression — an ordinary `Bool`-typed expression over the
1000    /// `old` and `new` state records, with `implies`/`is` and pure methods,
1001    /// mirroring [`Invariant`].
1002    pub predicate: Expr,
1003    pub documentation: Option<String>,
1004    pub span: Span,
1005    pub trivia: Trivia,
1006}
1007
1008/// A function contract clause (v0.115 §, testing track slice 3). A named
1009/// predicate on a `fn` signature — a `requires` (precondition) or `ensures`
1010/// (postcondition). A contract is the invariant predicate attached to a
1011/// function (ADR 0144 — one predicate surface): the predicate is a pure `Bool`
1012/// expression over the parameters (`requires`) or the parameters plus `result`
1013/// (`ensures`), with `implies`/`is` and pure methods, mirroring [`Invariant`].
1014/// The name rides the failure report and the redundant-test dedup.
1015#[derive(Debug, Clone)]
1016pub struct Contract {
1017    pub name: Ident,
1018    /// The predicate expression — an ordinary `Bool`-typed expression over the
1019    /// parameters (and, for an `ensures`, the contextual `result` binding).
1020    pub predicate: Expr,
1021    pub span: Span,
1022}
1023
1024/// An actor declaration (v0.45 §3.7). An actor is a nominal *contract type*
1025/// describing an external party at a boundary — not a runnable entity. A
1026/// handler consumes an actor on its `by` clause; the boundary verifies the
1027/// declared `auth` scheme and mints a sealed identity (`name.identity`).
1028#[derive(Debug, Clone)]
1029pub struct ActorDecl {
1030    pub name: Ident,
1031    /// The authentication scheme from `auth = <Scheme>`, stored as the raw
1032    /// identifier. The checker classifies it: `None`/`Internal`/`Bearer` are
1033    /// admitted; `Signature` is reserved-and-rejected
1034    /// (`bynk.actor.scheme_unsupported`); anything else is
1035    /// `bynk.actor.unknown_scheme`. `None` for the refinement form.
1036    pub auth: Option<Ident>,
1037    /// The scheme's keyed config from `auth = Scheme(key = value, …)` (v0.47
1038    /// `Bearer(secret = "…")`; v0.51 generalised for `Signature(secret, header,
1039    /// timestamp?, tolerance?)`). Empty for schemes/forms with no config. The
1040    /// checker validates which keys each scheme requires/allows.
1041    pub auth_config: Vec<SchemeArg>,
1042    /// The optional identity type from `, identity = <T>`. Absent ⇒ the
1043    /// scheme default (`()` for `None`; a sealed `CallerId` for the `Internal`
1044    /// `on call` channel, `()` for other `Internal` channels).
1045    pub identity: Option<TypeRef>,
1046    /// The refinement form `actor Admin = Base where <predicate>` — narrows a
1047    /// base actor by an authorisation claim (ADR 0091). The predicate is parsed
1048    /// as a full expression; a static-semantics rule restricts it to the closed
1049    /// actor-claim catalogue (`hasClaim`/`claimEquals` over a `Bearer` base;
1050    /// `bynk.actor.refinement_predicate_unsupported` / `…_base_unsupported`).
1051    pub refinement: Option<ActorRefinement>,
1052    pub documentation: Option<String>,
1053    pub span: Span,
1054    pub trivia: Trivia,
1055}
1056
1057impl ActorDecl {
1058    /// The value of a scheme config arg by key, if present (e.g. `secret`,
1059    /// `header`).
1060    pub fn scheme_arg(&self, key: &str) -> Option<&SchemeArg> {
1061        self.auth_config.iter().find(|a| a.key.name == key)
1062    }
1063}
1064
1065/// One `key = value` argument in a scheme config (`Scheme(key = value, …)`).
1066#[derive(Debug, Clone)]
1067pub struct SchemeArg {
1068    pub key: Ident,
1069    pub value: SchemeArgValue,
1070    /// Span of the value, for diagnostics.
1071    pub span: Span,
1072}
1073
1074/// A scheme config arg value — a string literal or an integer.
1075#[derive(Debug, Clone)]
1076pub enum SchemeArgValue {
1077    Str(String),
1078    Int(i64),
1079}
1080
1081impl SchemeArgValue {
1082    pub fn as_str(&self) -> Option<&str> {
1083        match self {
1084            SchemeArgValue::Str(s) => Some(s),
1085            SchemeArgValue::Int(_) => None,
1086        }
1087    }
1088    pub fn as_int(&self) -> Option<i64> {
1089        match self {
1090            SchemeArgValue::Int(n) => Some(*n),
1091            SchemeArgValue::Str(_) => None,
1092        }
1093    }
1094}
1095
1096/// The reserved refinement form `actor Admin = User where <predicate>` (Q3).
1097/// Parsed in Foundations so the grammar is fixed; admission is a later slice.
1098#[derive(Debug, Clone)]
1099pub struct ActorRefinement {
1100    /// The base actor being refined.
1101    pub base: Ident,
1102    /// The `where` predicate. Parsed but not yet checked.
1103    pub predicate: Expr,
1104    pub span: Span,
1105}
1106
1107/// The `by (<binder>:)? <Actor>` clause on a handler (v0.45; binder optional in
1108/// v0.50). Names the actor contract the handler consumes; when a `binder` is
1109/// given, the verified identity binds to it and is read as `binder.identity`.
1110/// Omitting the binder (`by <Actor>`) declares-and-verifies the contract without
1111/// capturing the identity — for anonymous or verify-and-discard handlers. Sits
1112/// after the protocol config and before the parameters.
1113#[derive(Debug, Clone)]
1114pub struct ByClause {
1115    /// The identity binder, if the handler consumes the identity. `None` for the
1116    /// binder-less `by <Actor>` form. Required when `actors` names more than one
1117    /// (a sum is resolved by matching on the bound actor).
1118    pub binder: Option<Ident>,
1119    /// The actor contract(s) referenced — each a local actor decl or a prelude
1120    /// actor. A single name is the ordinary single-actor handler; more than one
1121    /// (`by who: A | B`, v0.52) is an **ordered sum of peer actors** resolved
1122    /// first-wins, the body matching on the resolved actor. Always non-empty.
1123    pub actors: Vec<Ident>,
1124    pub span: Span,
1125}
1126
1127impl ByClause {
1128    /// The first (and, for a single-actor handler, only) actor contract named.
1129    pub fn primary(&self) -> &Ident {
1130        &self.actors[0]
1131    }
1132    /// Whether this `by` clause names an ordered sum of peer actors (`A | B`).
1133    pub fn is_sum(&self) -> bool {
1134        self.actors.len() > 1
1135    }
1136}
1137
1138/// v0.182 (testing-the-boundary Slice A, #664): a call-site actor clause on a
1139/// test-body `let x <- <service address> by <Actor>(<identity>)`. Distinct from
1140/// [`ByClause`] (the handler/header form): the *declaration* names which actor
1141/// may call and binds the verified identity, whereas the *call site* names the
1142/// actor the case is acting as and supplies the identity value. A unit-identity
1143/// actor (`Visitor`, and cron/queue's internal actors) carries no `identity`.
1144#[derive(Debug, Clone)]
1145pub struct CallSiteActor {
1146    /// The actor the case acts as — a local actor decl or a prelude actor.
1147    pub actor: Ident,
1148    /// The supplied identity value (`"bob"` in `by User("bob")`), or `None` for a
1149    /// unit-identity actor written `by Visitor` with no argument.
1150    pub identity: Option<Box<Expr>>,
1151    pub span: Span,
1152}
1153
1154/// A handler block — `on call(args) -> T given C1, C2 { body }`.
1155/// Used by both services and agents.
1156#[derive(Debug, Clone)]
1157pub struct Handler {
1158    pub kind: HandlerKind,
1159    /// Handler-position annotations (v0.140, ADR 0163): `@cache(maxAge: 5.minutes)`
1160    /// written immediately before `on <METHOD>(…)`. Reuses the [`Annotation`] AST
1161    /// shared with `store` fields (ADR 0111); the grammar accepts any `@name(args)`
1162    /// so an unknown name is a project-validation diagnostic, not a parse error. The
1163    /// first handler-position annotation surface — empty for every handler that
1164    /// carries none.
1165    pub annotations: Vec<Annotation>,
1166    /// For agent handlers, the method-style handler name (e.g.
1167    /// `on call addItem(...)`). For service handlers, this is None (just
1168    /// `on call(...)`).
1169    pub method_name: Option<Ident>,
1170    /// The `by <binder>: <Actor>` clause (v0.45), if present. Service handlers
1171    /// only; an absent clause inherits the protocol's default actor.
1172    pub by_clause: Option<ByClause>,
1173    pub params: Vec<Param>,
1174    pub return_type: TypeRef,
1175    pub given: Vec<CapRef>,
1176    pub body: Block,
1177    pub documentation: Option<String>,
1178    pub span: Span,
1179    pub trivia: Trivia,
1180}
1181
1182#[derive(Debug, Clone, PartialEq, Eq)]
1183pub enum HandlerKind {
1184    /// `on call(...)` — typed RPC (the only kind in v0.5).
1185    Call,
1186    /// `on http METHOD "path"` — external-facing HTTP route (v0.9).
1187    Http { method: HttpMethod, path: String },
1188    /// `on cron "expr"` — scheduled task; `expr` is a 5-field cron
1189    /// expression (v0.10a).
1190    Cron { expr: String },
1191    /// `on message(m: T)` — a message off the service's bound queue. The queue
1192    /// binding lives on the service's `ServiceProtocol::Queue` (v0.44).
1193    Message,
1194    /// `on open ...` — the WebSocket upgrade handler (v0.103, real-time track
1195    /// slice 3). Exactly one per `from websocket` service; carries a mandatory
1196    /// `by` clause (edge auth) and receives a fresh owned `Connection[out]`.
1197    Open,
1198    /// `on close ...` — the WebSocket close handler (v0.106, real-time track slice
1199    /// 3b-iii). Optional, ≤1 per `from websocket` service; runs when the socket
1200    /// closes. Like `on open`, edge-authenticated (`by`), with the identity/params
1201    /// recovered from the socket attachment (set at `on open`). (A `from websocket`
1202    /// `on message` reuses [`HandlerKind::Message`], disambiguated by the protocol.)
1203    Close,
1204}
1205
1206/// HTTP methods supported by `on http` handlers (v0.9).
1207#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1208pub enum HttpMethod {
1209    Get,
1210    Post,
1211    Put,
1212    Patch,
1213    Delete,
1214}
1215
1216impl HttpMethod {
1217    pub fn as_str(self) -> &'static str {
1218        match self {
1219            HttpMethod::Get => "GET",
1220            HttpMethod::Post => "POST",
1221            HttpMethod::Put => "PUT",
1222            HttpMethod::Patch => "PATCH",
1223            HttpMethod::Delete => "DELETE",
1224        }
1225    }
1226
1227    pub fn from_ident(s: &str) -> Option<HttpMethod> {
1228        match s {
1229            "GET" => Some(HttpMethod::Get),
1230            "POST" => Some(HttpMethod::Post),
1231            "PUT" => Some(HttpMethod::Put),
1232            "PATCH" => Some(HttpMethod::Patch),
1233            "DELETE" => Some(HttpMethod::Delete),
1234            _ => None,
1235        }
1236    }
1237
1238    /// True if this method conventionally has no request body.
1239    pub fn forbids_body(self) -> bool {
1240        matches!(self, HttpMethod::Get | HttpMethod::Delete)
1241    }
1242}
1243
1244/// Payload shape of an `HttpResult[T]` variant (v0.9 §3.3).
1245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1246pub enum HttpVariantPayload {
1247    /// No payload (e.g. `NoContent`, `Unauthorized`).
1248    None,
1249    /// Carries a value of the `HttpResult` type parameter `T`.
1250    Value,
1251    /// Carries a `String` message (e.g. `BadRequest`, `Conflict`).
1252    Message,
1253    /// Carries a `String` target URL, emitted as a `Location` header — the
1254    /// redirect variants (`Found`, `SeeOther`, `PermanentRedirect`, …).
1255    Location,
1256    /// Carries a `Stream[String]`, emitted as an SSE (`text/event-stream`)
1257    /// streaming body — the `Streaming` (200) variant (v0.101, real-time track
1258    /// slice 1).
1259    Streamed,
1260    /// Carries `(body: Bytes, contentType: String)` — the author-owned raw body
1261    /// written straight into the response with the declared `content-type` and
1262    /// **no codec** (the typed-wire guarantee is deliberately off). The `Raw`
1263    /// (200) variant (v0.111); the first two-argument payload shape.
1264    Raw,
1265}
1266
1267/// One variant of the built-in `HttpResult[T]` sum (v0.9 §3.3).
1268#[derive(Debug, Clone, Copy)]
1269pub struct HttpVariant {
1270    pub name: &'static str,
1271    pub payload: HttpVariantPayload,
1272    pub status: u16,
1273}
1274
1275/// All `HttpResult[T]` variants, in declaration order (ascending status). The
1276/// vocabulary tracks the common, modern HTTP status codes (RFC 9110): success
1277/// and created/accepted (`Value`), redirects carrying a `Location` URL, and
1278/// the client/server failures that handlers routinely return (`Message` when
1279/// an explanation helps the caller, `None` for self-describing statuses).
1280pub const HTTP_VARIANTS: &[HttpVariant] = &[
1281    // ── 2xx success ──────────────────────────────────────────────────────
1282    HttpVariant {
1283        name: "Ok",
1284        payload: HttpVariantPayload::Value,
1285        status: 200,
1286    },
1287    // v0.101 (real-time track slice 1): a 200 whose body is a streamed
1288    // `Stream[String]`, SSE-framed. Status precedes the body, so streaming is
1289    // 200-only — pre-stream failures are ordinary variants returned instead.
1290    HttpVariant {
1291        name: "Streaming",
1292        payload: HttpVariantPayload::Streamed,
1293        status: 200,
1294    },
1295    // v0.111: a 200 whose body is an author-owned `Bytes` written straight into
1296    // the response with the declared `content-type` — no codec runs. 200-only,
1297    // like `Streaming`: it serves service-tier raw bodies (`robots.txt`,
1298    // `sitemap.xml`, feeds, a QR PNG), not custom-status error pages.
1299    HttpVariant {
1300        name: "Raw",
1301        payload: HttpVariantPayload::Raw,
1302        status: 200,
1303    },
1304    HttpVariant {
1305        name: "Created",
1306        payload: HttpVariantPayload::Value,
1307        status: 201,
1308    },
1309    HttpVariant {
1310        name: "Accepted",
1311        payload: HttpVariantPayload::Value,
1312        status: 202,
1313    },
1314    HttpVariant {
1315        name: "NoContent",
1316        payload: HttpVariantPayload::None,
1317        status: 204,
1318    },
1319    // ── 3xx redirection (carry a `Location` URL) ─────────────────────────
1320    HttpVariant {
1321        name: "MovedPermanently",
1322        payload: HttpVariantPayload::Location,
1323        status: 301,
1324    },
1325    HttpVariant {
1326        name: "Found",
1327        payload: HttpVariantPayload::Location,
1328        status: 302,
1329    },
1330    HttpVariant {
1331        name: "SeeOther",
1332        payload: HttpVariantPayload::Location,
1333        status: 303,
1334    },
1335    HttpVariant {
1336        name: "TemporaryRedirect",
1337        payload: HttpVariantPayload::Location,
1338        status: 307,
1339    },
1340    HttpVariant {
1341        name: "PermanentRedirect",
1342        payload: HttpVariantPayload::Location,
1343        status: 308,
1344    },
1345    // ── 4xx client error ─────────────────────────────────────────────────
1346    HttpVariant {
1347        name: "BadRequest",
1348        payload: HttpVariantPayload::Message,
1349        status: 400,
1350    },
1351    HttpVariant {
1352        name: "Unauthorized",
1353        payload: HttpVariantPayload::None,
1354        status: 401,
1355    },
1356    HttpVariant {
1357        name: "Forbidden",
1358        payload: HttpVariantPayload::None,
1359        status: 403,
1360    },
1361    HttpVariant {
1362        name: "NotFound",
1363        payload: HttpVariantPayload::None,
1364        status: 404,
1365    },
1366    HttpVariant {
1367        name: "MethodNotAllowed",
1368        payload: HttpVariantPayload::None,
1369        status: 405,
1370    },
1371    HttpVariant {
1372        name: "NotAcceptable",
1373        payload: HttpVariantPayload::None,
1374        status: 406,
1375    },
1376    HttpVariant {
1377        name: "RequestTimeout",
1378        payload: HttpVariantPayload::None,
1379        status: 408,
1380    },
1381    HttpVariant {
1382        name: "Conflict",
1383        payload: HttpVariantPayload::Message,
1384        status: 409,
1385    },
1386    HttpVariant {
1387        name: "Gone",
1388        payload: HttpVariantPayload::None,
1389        status: 410,
1390    },
1391    HttpVariant {
1392        name: "LengthRequired",
1393        payload: HttpVariantPayload::None,
1394        status: 411,
1395    },
1396    HttpVariant {
1397        name: "PayloadTooLarge",
1398        payload: HttpVariantPayload::Message,
1399        status: 413,
1400    },
1401    HttpVariant {
1402        name: "UnsupportedMediaType",
1403        payload: HttpVariantPayload::Message,
1404        status: 415,
1405    },
1406    HttpVariant {
1407        name: "UnprocessableEntity",
1408        payload: HttpVariantPayload::Message,
1409        status: 422,
1410    },
1411    HttpVariant {
1412        name: "TooManyRequests",
1413        payload: HttpVariantPayload::Message,
1414        status: 429,
1415    },
1416    HttpVariant {
1417        name: "UnavailableForLegalReasons",
1418        payload: HttpVariantPayload::Message,
1419        status: 451,
1420    },
1421    // ── 5xx server error ─────────────────────────────────────────────────
1422    HttpVariant {
1423        name: "ServerError",
1424        payload: HttpVariantPayload::Message,
1425        status: 500,
1426    },
1427    HttpVariant {
1428        name: "NotImplemented",
1429        payload: HttpVariantPayload::Message,
1430        status: 501,
1431    },
1432    HttpVariant {
1433        name: "BadGateway",
1434        payload: HttpVariantPayload::Message,
1435        status: 502,
1436    },
1437    HttpVariant {
1438        name: "ServiceUnavailable",
1439        payload: HttpVariantPayload::Message,
1440        status: 503,
1441    },
1442    HttpVariant {
1443        name: "GatewayTimeout",
1444        payload: HttpVariantPayload::Message,
1445        status: 504,
1446    },
1447];
1448
1449/// Find an `HttpResult[T]` variant by name. Returns the variant info or
1450/// `None` if the name doesn't match.
1451pub fn http_variant(name: &str) -> Option<HttpVariant> {
1452    HTTP_VARIANTS.iter().copied().find(|v| v.name == name)
1453}
1454
1455/// Payload shape of a `QueueResult` variant (v0.44). Non-generic — a verdict
1456/// carries no value; `Retry` carries a `String` reason for the log path.
1457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1458pub enum QueueVariantPayload {
1459    /// No payload (`Ack`).
1460    None,
1461    /// Carries a `String` reason (`Retry`).
1462    Message,
1463}
1464
1465/// One variant of the built-in `QueueResult` sum (v0.44).
1466#[derive(Debug, Clone, Copy)]
1467pub struct QueueVariant {
1468    pub name: &'static str,
1469    pub payload: QueueVariantPayload,
1470}
1471
1472/// All `QueueResult` variants, in declaration order. `Ack` confirms the
1473/// message; `Retry` redelivers it, carrying a reason for observability.
1474pub const QUEUE_VARIANTS: &[QueueVariant] = &[
1475    QueueVariant {
1476        name: "Ack",
1477        payload: QueueVariantPayload::None,
1478    },
1479    QueueVariant {
1480        name: "Retry",
1481        payload: QueueVariantPayload::Message,
1482    },
1483];
1484
1485/// Find a `QueueResult` variant by name.
1486pub fn queue_variant(name: &str) -> Option<QueueVariant> {
1487    QUEUE_VARIANTS.iter().copied().find(|v| v.name == name)
1488}
1489
1490#[derive(Debug, Clone)]
1491pub struct TypeDecl {
1492    pub name: Ident,
1493    /// `[T, U]` type parameters (v0.157, ADR 0183): empty for a non-generic
1494    /// type. A generic *record* type (`type Paginated[T] = { … }`) is the only
1495    /// generic body accepted; the checker rejects type parameters on refined /
1496    /// opaque / sum bodies. Mirrors [`FnDecl::type_params`].
1497    pub type_params: Vec<TypeParam>,
1498    pub body: TypeBody,
1499    /// Documentation block attached to this declaration (v0.3).
1500    pub documentation: Option<String>,
1501    pub span: Span,
1502    pub trivia: Trivia,
1503}
1504
1505/// The right-hand side of a `type` declaration. In v0/v0.1 only the
1506/// `Refined` variant existed; v0.2 adds records and sums; v0.3 adds opaque.
1507#[derive(Debug, Clone)]
1508pub enum TypeBody {
1509    /// Refined base type: `BaseType where refinement`.
1510    Refined {
1511        base: BaseType,
1512        base_span: Span,
1513        refinement: Option<Refinement>,
1514    },
1515    /// Record type: `{ field: T where ..., ... }`.
1516    Record(RecordBody),
1517    /// Sum type: pipe-form variants or `enum { ... }` shorthand.
1518    Sum(SumBody),
1519    /// Opaque base type: `opaque BaseType (where refinement)?` (v0.3 §3.4).
1520    /// Identity is nominal; the base type is hidden outside the defining commons.
1521    Opaque {
1522        base: BaseType,
1523        base_span: Span,
1524        refinement: Option<Refinement>,
1525    },
1526}
1527
1528/// Body of a record-type declaration (v0.2 §3.1).
1529#[derive(Debug, Clone)]
1530pub struct RecordBody {
1531    pub fields: Vec<RecordField>,
1532    pub span: Span,
1533}
1534
1535/// One field of a record type declaration. Each field may carry inline
1536/// refinement, which is enforced at construction time on the field's value.
1537#[derive(Debug, Clone)]
1538pub struct RecordField {
1539    pub name: Ident,
1540    pub type_ref: TypeRef,
1541    pub refinement: Option<Refinement>,
1542    /// v0.11: an optional initial-value expression. Only meaningful on agent
1543    /// `state` fields (the field's fresh-key value); ignored / rejected on
1544    /// record-type fields by the checker.
1545    pub init: Option<Expr>,
1546    pub span: Span,
1547}
1548
1549/// Body of a sum-type declaration (v0.2 §3.2).
1550#[derive(Debug, Clone)]
1551pub struct SumBody {
1552    pub variants: Vec<Variant>,
1553    /// v0.154 (ADR 0178): declared error embeddings — `embeds E as V, …` after
1554    /// the variants. Each says "an `E` value auto-wraps into variant `V`", which
1555    /// the `?` operator uses to convert a cross-context error without a manual
1556    /// `.mapErr`. Empty for a sum with no embeddings.
1557    pub embeds: Vec<EmbedsClause>,
1558    pub span: Span,
1559}
1560
1561/// One `embeds <source_type> as <variant>` mapping in a sum body (v0.154, ADR
1562/// 0178). Declares that a value of `source_type` can be auto-wrapped into the
1563/// named single-payload `variant` of the enclosing sum.
1564#[derive(Debug, Clone)]
1565pub struct EmbedsClause {
1566    pub source_type: TypeRef,
1567    pub variant: Ident,
1568    pub span: Span,
1569}
1570
1571/// One variant of a sum type. Variants may have payload fields; a
1572/// payload-less variant is a simple tag.
1573#[derive(Debug, Clone)]
1574pub struct Variant {
1575    pub name: Ident,
1576    pub payload: Vec<VariantField>,
1577    pub span: Span,
1578}
1579
1580/// One payload field of a sum variant. Variant payload fields use named
1581/// declarations like record fields, but do not carry refinement in v0.2.
1582#[derive(Debug, Clone)]
1583pub struct VariantField {
1584    pub name: Ident,
1585    pub type_ref: TypeRef,
1586    pub span: Span,
1587}
1588
1589#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1590pub enum BaseType {
1591    Int,
1592    String,
1593    Bool,
1594    Float,
1595    /// `Duration` (v0.86, ADR 0112) — a span of time, a distinct base type
1596    /// erased to TS `number` carrying milliseconds (the `Clock` unit). Modelled
1597    /// on `Float`: Bynk-side-only, no implicit `Int` coercion (save the one
1598    /// sanctioned clock-math mix).
1599    Duration,
1600    /// `Instant` (v0.90, ADR 0114) — an absolute point in time, a distinct base
1601    /// type erased to TS `number` carrying Unix epoch milliseconds (the
1602    /// `Clock` unit). No literal (minted by `Clock.now()`); arithmetic composes
1603    /// with `Duration` (`Instant ± Duration -> Instant`, `Instant − Instant ->
1604    /// Duration`). Supersedes ADR 0112 D4's `Int`↔`Duration` clock-math mix.
1605    Instant,
1606    /// `Bytes` (v0.110, ADR 0142) — an immutable finite octet sequence, the
1607    /// seventh base type. Unlike its neighbours it does **not** erase to TS
1608    /// `number`: a `Bytes` lowers to a `Uint8Array`. No source literal
1609    /// (constructed via `Bytes.fromUtf8`/`fromBase64`/`empty`); `==` compares
1610    /// by content (real emitter codegen, not host `===`); wires as a base64
1611    /// JSON string; not `Map`-keyable and not orderable.
1612    Bytes,
1613}
1614
1615impl BaseType {
1616    pub fn name(self) -> &'static str {
1617        match self {
1618            BaseType::Int => "Int",
1619            BaseType::String => "String",
1620            BaseType::Bool => "Bool",
1621            BaseType::Float => "Float",
1622            BaseType::Duration => "Duration",
1623            BaseType::Instant => "Instant",
1624            BaseType::Bytes => "Bytes",
1625        }
1626    }
1627}
1628
1629/// A `Duration` literal unit (v0.86, ADR 0112) — the closed set of suffixes in a
1630/// `<int>.<unit>` literal. Each maps to a fixed millisecond factor (`Duration`
1631/// erases to `Int` milliseconds).
1632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1633pub enum DurationUnit {
1634    Milliseconds,
1635    Seconds,
1636    Minutes,
1637    Hours,
1638    Days,
1639}
1640
1641impl DurationUnit {
1642    /// Resolve a unit name (`minutes`) to its variant, or `None` if it is not one
1643    /// of the closed set. Used by the parser to recognise an `<int>.<unit>`
1644    /// literal; an unrecognised name leaves the expression a field access.
1645    pub fn from_name(name: &str) -> Option<Self> {
1646        Some(match name {
1647            "milliseconds" => DurationUnit::Milliseconds,
1648            "seconds" => DurationUnit::Seconds,
1649            "minutes" => DurationUnit::Minutes,
1650            "hours" => DurationUnit::Hours,
1651            "days" => DurationUnit::Days,
1652            _ => return None,
1653        })
1654    }
1655
1656    /// The unit name as written.
1657    pub fn name(self) -> &'static str {
1658        match self {
1659            DurationUnit::Milliseconds => "milliseconds",
1660            DurationUnit::Seconds => "seconds",
1661            DurationUnit::Minutes => "minutes",
1662            DurationUnit::Hours => "hours",
1663            DurationUnit::Days => "days",
1664        }
1665    }
1666
1667    /// The unit's value in milliseconds.
1668    pub fn millis(self) -> i64 {
1669        match self {
1670            DurationUnit::Milliseconds => 1,
1671            DurationUnit::Seconds => 1_000,
1672            DurationUnit::Minutes => 60_000,
1673            DurationUnit::Hours => 3_600_000,
1674            DurationUnit::Days => 86_400_000,
1675        }
1676    }
1677}
1678
1679/// An integer refinement bound (v0.40, ADR 0073): the parsed value plus the
1680/// bound's source span (covering a leading `-`). Value-only beyond the span —
1681/// ints have one canonical printed form, so the formatter stays idempotent
1682/// without a stored lexeme. The span backs the `InRange`-swap quick-fix.
1683#[derive(Debug, Clone)]
1684pub struct IntBound {
1685    pub value: i64,
1686    pub span: Span,
1687}
1688
1689/// A float refinement bound (v0.21): the parsed value plus the signed source
1690/// lexeme (for byte-stable emission). v0.40 (ADR 0073): also the source span,
1691/// for the `InRange`-swap quick-fix.
1692#[derive(Debug, Clone)]
1693pub struct FloatBound {
1694    pub value: f64,
1695    pub lexeme: String,
1696    pub span: Span,
1697}
1698
1699#[derive(Debug, Clone)]
1700pub struct Refinement {
1701    pub predicates: Vec<RefinementPred>,
1702    pub span: Span,
1703}
1704
1705#[derive(Debug, Clone)]
1706pub struct RefinementPred {
1707    pub kind: PredKind,
1708    pub span: Span,
1709}
1710
1711#[derive(Debug, Clone)]
1712pub enum PredKind {
1713    Matches(String),
1714    InRange(IntBound, IntBound),
1715    /// `InRange` with float bounds (v0.21) — a separate variant so every
1716    /// `Int` refinement path stays untouched. Bounds keep their source
1717    /// lexemes (including any sign) so emitted runtime checks are
1718    /// byte-stable.
1719    InRangeF(FloatBound, FloatBound),
1720    MinLength(i64),
1721    MaxLength(i64),
1722    Length(i64),
1723    NonNegative,
1724    Positive,
1725    NonEmpty,
1726}
1727
1728impl PredKind {
1729    pub fn name(&self) -> &'static str {
1730        match self {
1731            PredKind::Matches(_) => "Matches",
1732            PredKind::InRange(..) | PredKind::InRangeF(..) => "InRange",
1733            PredKind::MinLength(_) => "MinLength",
1734            PredKind::MaxLength(_) => "MaxLength",
1735            PredKind::Length(_) => "Length",
1736            PredKind::NonNegative => "NonNegative",
1737            PredKind::Positive => "Positive",
1738            PredKind::NonEmpty => "NonEmpty",
1739        }
1740    }
1741}
1742
1743/// A function type parameter (v0.20a, `fn name[A, B](…)`). A struct rather
1744/// than a bare Ident so the ADR-0028 "bound-capable" promise is a later field
1745/// addition, not a representation change.
1746#[derive(Debug, Clone)]
1747pub struct TypeParam {
1748    pub name: Ident,
1749    pub span: Span,
1750}
1751
1752/// A lambda expression (v0.20a): `(params) => expr` or `(params) => { … }`.
1753/// `=>` is the value arrow (shared with `match`); param annotations are
1754/// optional where an expected function type supplies them.
1755#[derive(Debug, Clone)]
1756pub struct LambdaExpr {
1757    pub params: Vec<LambdaParam>,
1758    pub body: Box<Expr>,
1759    pub span: Span,
1760}
1761
1762/// A lambda parameter. A separate type from [`Param`] because its annotation
1763/// is optional — `Param.type_ref` stays mandatory at every signature site.
1764#[derive(Debug, Clone)]
1765pub struct LambdaParam {
1766    pub name: Ident,
1767    pub type_ref: Option<TypeRef>,
1768    pub span: Span,
1769}
1770
1771#[derive(Debug, Clone)]
1772pub struct FnDecl {
1773    /// v0.20a: `[A, B]` type parameters; empty for non-generic functions.
1774    pub type_params: Vec<TypeParam>,
1775    /// Free function or method (`TypeName.methodName`). See [`FnName`].
1776    pub name: FnName,
1777    pub params: Vec<Param>,
1778    pub return_type: TypeRef,
1779    /// v0.115: preconditions (`requires <name>: <pred>`), parsed between the
1780    /// return type and the body. A contract clause is the invariant predicate
1781    /// attached to a function (ADR 0144 — one predicate surface); `requires`
1782    /// scopes over the parameters only.
1783    pub requires: Vec<Contract>,
1784    /// v0.115: postconditions (`ensures <name>: <pred>`). Scopes over the
1785    /// parameters *and* `result`, the contextual binding for the return value.
1786    pub ensures: Vec<Contract>,
1787    pub body: Block,
1788    /// True when the first parameter is the special `self` parameter. Only
1789    /// valid for method declarations.
1790    pub has_self: bool,
1791    /// Documentation block attached to this declaration (v0.3).
1792    pub documentation: Option<String>,
1793    pub span: Span,
1794    pub trivia: Trivia,
1795}
1796
1797/// A function-declaration name: either a free function `f` or a method
1798/// `T.method` (v0.2 §3.6).
1799#[derive(Debug, Clone)]
1800pub enum FnName {
1801    /// `fn name(...)` — a free function.
1802    Free(Ident),
1803    /// `fn TypeName.methodName(...)` — a method attached to a type.
1804    Method {
1805        type_name: Ident,
1806        method_name: Ident,
1807    },
1808}
1809
1810impl FnName {
1811    /// The function's short name for diagnostics. For methods returns the
1812    /// method portion only; the type prefix is recovered via `type_name`.
1813    pub fn ident(&self) -> &Ident {
1814        match self {
1815            FnName::Free(id) => id,
1816            FnName::Method { method_name, .. } => method_name,
1817        }
1818    }
1819
1820    /// For methods, the attached type's identifier; `None` for free fns.
1821    pub fn type_name(&self) -> Option<&Ident> {
1822        match self {
1823            FnName::Free(_) => None,
1824            FnName::Method { type_name, .. } => Some(type_name),
1825        }
1826    }
1827
1828    /// The displayed full name (e.g., `Money.add` or `parseSku`).
1829    pub fn display(&self) -> String {
1830        match self {
1831            FnName::Free(id) => id.name.clone(),
1832            FnName::Method {
1833                type_name,
1834                method_name,
1835            } => format!("{}.{}", type_name.name, method_name.name),
1836        }
1837    }
1838}
1839
1840/// A brace-delimited block of statements ending in a tail expression
1841/// whose value is the block's value (spec v0.1 §3.1).
1842#[derive(Debug, Clone)]
1843pub struct Block {
1844    pub statements: Vec<Statement>,
1845    pub tail: Box<Expr>,
1846    pub span: Span,
1847    /// Line comments that appear between the last statement (or the
1848    /// opening brace) and the tail expression. Preserved here because
1849    /// expressions do not carry trivia in v1.1.
1850    pub tail_leading_comments: Vec<String>,
1851    /// `true` when the block was written with no explicit tail expression and
1852    /// the parser synthesised a `()` (unit) tail (v0.146, ADR 0170). The tail
1853    /// is a real `ExprKind::UnitLit` either way; this flag records that it was
1854    /// *implicit* so the formatter can omit it (Bynk has no statement
1855    /// terminator, so a printed `()` would re-attach to the last statement on
1856    /// re-parse — `x` `()` → `x()`). The parser re-derives the implicit unit
1857    /// tail, so omitting it is loss-free.
1858    pub implicit_tail: bool,
1859}
1860
1861impl Block {
1862    /// Whether this block is a synthesised empty unit block — no statements and
1863    /// an *implicit* `()` tail (v0.146, ADR 0170). This is exactly the shape the
1864    /// parser inserts for an `if` with no `else` branch, so both the checker
1865    /// (gating the else-less form to unit) and the formatter (omitting the
1866    /// synthetic `else { () }`) recognise it here.
1867    pub fn is_synth_unit(&self) -> bool {
1868        self.statements.is_empty()
1869            && self.implicit_tail
1870            && matches!(self.tail.kind, ExprKind::UnitLit)
1871    }
1872}
1873
1874/// Block-level statement.
1875#[derive(Debug, Clone)]
1876pub enum Statement {
1877    /// `let name (: T)? = expr` — pure binding (v0.1).
1878    Let(LetStmt),
1879    /// `let name (: T)? <- expr` — effectful binding (v0.5).
1880    EffectLet(LetStmt),
1881    /// `expect expr` — verify a Bool predicate at test runtime (v0.7; renamed
1882    /// from `assert` in v0.112). Only valid inside test case bodies.
1883    Expect(ExpectStmt),
1884    /// `~> expr` — an asynchronous fire-and-forget send (v0.79). The caller does
1885    /// not await the reply; legal only when the reply is `Effect[()]`. No binder.
1886    Send(SendStmt),
1887    /// `do expr` — an effect-performing expression statement (v0.146, ADR 0170).
1888    /// Runs an `Effect[()]` and discards its (unit) result — the binder-free
1889    /// sugar for `let _ <- expr` when the awaited value is unit. Legal only in
1890    /// an effectful body; the operand MUST be `Effect[()]` (a valued reply keeps
1891    /// the explicit `let _ <- e`, so throwing away a real value stays visible).
1892    Do(DoStmt),
1893    /// `name := expr` — a `Cell` store write (v0.81, storage track). The
1894    /// unconditional write form; `.update(fn)` (a method call) is the
1895    /// read-modify-write form. ADR 0108.
1896    Assign(AssignStmt),
1897}
1898
1899impl Statement {
1900    pub fn span(&self) -> Span {
1901        match self {
1902            Statement::Let(l) | Statement::EffectLet(l) => l.span,
1903            Statement::Expect(a) => a.span,
1904            Statement::Send(s) => s.span,
1905            Statement::Do(d) => d.span,
1906            Statement::Assign(a) => a.span,
1907        }
1908    }
1909}
1910
1911#[derive(Debug, Clone)]
1912pub struct ExpectStmt {
1913    pub value: Expr,
1914    pub span: Span,
1915    pub trivia: Trivia,
1916}
1917
1918/// `name := expr` — a `Cell` store write (v0.81, storage track). `target` is the
1919/// `Cell` field being written (a bare name for now; the checker resolves it to a
1920/// `store` field). `value` is the new value.
1921#[derive(Debug, Clone)]
1922pub struct AssignStmt {
1923    pub target: Ident,
1924    pub value: Expr,
1925    pub span: Span,
1926    pub trivia: Trivia,
1927}
1928
1929#[derive(Debug, Clone)]
1930pub struct LetStmt {
1931    pub name: Ident,
1932    pub type_annot: Option<TypeRef>,
1933    pub value: Expr,
1934    /// v0.182 (#664): the call-site `by <Actor>(<identity>)` clause on an
1935    /// `EffectLet` whose value addresses a test service handler. `None` on a pure
1936    /// `Let` (the `by` is parsed only in the `<-` arm) and on an effect-let with
1937    /// no principal.
1938    pub principal: Option<CallSiteActor>,
1939    pub span: Span,
1940    pub trivia: Trivia,
1941}
1942
1943#[derive(Debug, Clone)]
1944pub struct SendStmt {
1945    /// The send target — a recipient call, e.g. `Logger.info(msg)`.
1946    pub value: Expr,
1947    pub span: Span,
1948    pub trivia: Trivia,
1949}
1950
1951/// `do expr` — an effect-performing expression statement (v0.146, ADR 0170).
1952/// `value` is the awaited effect, which MUST be `Effect[()]`.
1953#[derive(Debug, Clone)]
1954pub struct DoStmt {
1955    pub value: Expr,
1956    pub span: Span,
1957    pub trivia: Trivia,
1958}
1959
1960#[derive(Debug, Clone)]
1961pub struct Param {
1962    pub name: Ident,
1963    pub type_ref: TypeRef,
1964    pub span: Span,
1965}
1966
1967#[derive(Debug, Clone)]
1968pub enum TypeRef {
1969    Base(BaseType, Span),
1970    Named(Ident),
1971    /// `Result[T, E]` — the built-in generic Result type (v0.1).
1972    Result(Box<TypeRef>, Box<TypeRef>, Span),
1973    /// `Option[T]` — the built-in generic Option type (v0.2).
1974    Option(Box<TypeRef>, Span),
1975    /// `Effect[T]` — the built-in generic Effect type (v0.5).
1976    Effect(Box<TypeRef>, Span),
1977    /// `HttpResult[T]` — the built-in HTTP-result sum (v0.9).
1978    HttpResult(Box<TypeRef>, Span),
1979    /// `QueueResult` — the built-in queue verdict sum (`Ack | Retry`),
1980    /// non-generic; the required return of a queue handler (v0.44).
1981    QueueResult(Span),
1982    /// `List[T]` — the built-in generic immutable list type (v0.20b).
1983    List(Box<TypeRef>, Span),
1984    /// `Map[K, V]` — the built-in generic immutable map type (v0.20b).
1985    /// Keys are confined to value-keyable types
1986    /// (`bynk.types.unkeyable_map_key`).
1987    Map(Box<TypeRef>, Box<TypeRef>, Span),
1988    /// `Query[T]` — the built-in lazy storage-read description (v0.91, ADR 0115).
1989    /// Nameable in a pure helper's return type; non-storable and non-boundary
1990    /// (like `Effect`/`Fn`).
1991    Query(Box<TypeRef>, Span),
1992    /// `Stream[T]` — the value-over-time primitive (v0.100, real-time track
1993    /// slice 0). A lazy, pull-shaped sequence produced over time; non-storable
1994    /// and non-boundary (like `Query`/`Effect`/`Fn`).
1995    Stream(Box<TypeRef>, Span),
1996    /// `Connection[F]` — a held WebSocket connection (v0.102, real-time track
1997    /// slice 2). `F` is the server→client frame type. A `Held` resource:
1998    /// non-serialisable, non-boundary, and governed by the linearity discipline
1999    /// (§2.9); storable only in `Cell[Option[Connection]]` / `Map[K, Connection]`.
2000    Connection(Box<TypeRef>, Span),
2001    /// `History[Agent]` — a generated, driven call-history of an agent (v0.119,
2002    /// testing track slice 7, ADR 0155). A test-only generator, legal only in
2003    /// `for all` binding position inside a `property`; it is not a value type,
2004    /// so it never resolves in a field/param/return position. The bound subject
2005    /// behaves as an ordinary `List[Step]`.
2006    History(Box<TypeRef>, Span),
2007    /// `ValidationError` — the built-in error type used by refined-type
2008    /// constructors (v0.1).
2009    ValidationError(Span),
2010    /// `JsonError` — the built-in JSON-decode error type (v0.22b). A
2011    /// uniform record (`kind`/`path`/`message`, all `String`) the codec
2012    /// maps `BoundaryError` variants and parse failures into.
2013    JsonError(Span),
2014    /// `()` — the unit type (v0.5).
2015    Unit(Span),
2016    /// `A -> B` / `(A, B) -> C` / `() -> B` — a function type (v0.20a).
2017    /// Right-associative; effectful iff the return type is `Effect[_]`
2018    /// (the structural rule). Confined to non-boundary positions
2019    /// (`bynk.types.function_at_boundary`).
2020    Fn(Vec<TypeRef>, Box<TypeRef>, Span),
2021    /// `Name[Arg, …]` — an application of a user-declared generic type
2022    /// (v0.157, ADR 0183). `name` is a user type name (never a built-in
2023    /// generic, which each have a dedicated variant above). Arity and the
2024    /// existence of the referenced type are checked in the resolver.
2025    App {
2026        name: Ident,
2027        args: Vec<TypeRef>,
2028        span: Span,
2029    },
2030}
2031
2032impl TypeRef {
2033    pub fn span(&self) -> Span {
2034        match self {
2035            TypeRef::Base(_, s) => *s,
2036            TypeRef::Named(id) => id.span,
2037            TypeRef::Result(_, _, s) => *s,
2038            TypeRef::Option(_, s) => *s,
2039            TypeRef::Effect(_, s) => *s,
2040            TypeRef::HttpResult(_, s) => *s,
2041            TypeRef::QueueResult(s) => *s,
2042            TypeRef::List(_, s) => *s,
2043            TypeRef::Map(_, _, s) => *s,
2044            TypeRef::Query(_, s) => *s,
2045            TypeRef::Stream(_, s) => *s,
2046            TypeRef::Connection(_, s) => *s,
2047            TypeRef::History(_, s) => *s,
2048            TypeRef::ValidationError(s) => *s,
2049            TypeRef::JsonError(s) => *s,
2050            TypeRef::Unit(s) => *s,
2051            TypeRef::Fn(_, _, s) => *s,
2052            TypeRef::App { span, .. } => *span,
2053        }
2054    }
2055}
2056
2057/// v0.174 (#592): does the generic record type `name` transitively contain a
2058/// reference to itself — through any field-type path, including collection and
2059/// `Option` wrappers, sum-variant payloads, and generic type arguments? Such a
2060/// type has no finite set of monomorphised boundary codecs: uniform recursion
2061/// (`Node[T] = { next: Option[Node[T]] }`) would need a self-referential codec
2062/// chain the per-instantiation model does not yet generate, and polymorphic
2063/// recursion (`Weird[T] = { next: Option[Weird[List[T]]] }`) an unbounded set of
2064/// instantiations. Both are rejected at a boundary
2065/// (`bynk.generics.recursive_generic_at_boundary`).
2066///
2067/// Detection is reachability over the type-containment graph: `name` is
2068/// recursive iff it is reachable from its own body, following every named /
2069/// applied head and descending into every wrapper, map/result pair, function
2070/// position, and generic argument. Terminates via the `visited` set.
2071pub fn generic_record_is_recursive(
2072    name: &str,
2073    types: &std::collections::HashMap<String, TypeDecl>,
2074) -> bool {
2075    fn heads(t: &TypeRef, out: &mut Vec<String>) {
2076        match t {
2077            TypeRef::Named(id) => out.push(id.name.clone()),
2078            TypeRef::App {
2079                name: app_name,
2080                args,
2081                ..
2082            } => {
2083                out.push(app_name.name.clone());
2084                for a in args {
2085                    heads(a, out);
2086                }
2087            }
2088            TypeRef::Option(a, _)
2089            | TypeRef::List(a, _)
2090            | TypeRef::Effect(a, _)
2091            | TypeRef::HttpResult(a, _)
2092            | TypeRef::Query(a, _)
2093            | TypeRef::Stream(a, _)
2094            | TypeRef::Connection(a, _)
2095            | TypeRef::History(a, _) => heads(a, out),
2096            TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
2097                heads(a, out);
2098                heads(b, out);
2099            }
2100            TypeRef::Fn(ps, r, _) => {
2101                for p in ps {
2102                    heads(p, out);
2103                }
2104                heads(r, out);
2105            }
2106            TypeRef::Base(..)
2107            | TypeRef::QueueResult(_)
2108            | TypeRef::ValidationError(_)
2109            | TypeRef::JsonError(_)
2110            | TypeRef::Unit(_) => {}
2111        }
2112    }
2113    fn body_heads(decl: &TypeDecl, out: &mut Vec<String>) {
2114        match &decl.body {
2115            TypeBody::Record(r) => {
2116                for f in &r.fields {
2117                    heads(&f.type_ref, out);
2118                }
2119            }
2120            TypeBody::Sum(s) => {
2121                for v in &s.variants {
2122                    for p in &v.payload {
2123                        heads(&p.type_ref, out);
2124                    }
2125                }
2126            }
2127            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
2128        }
2129    }
2130    let Some(root) = types.get(name) else {
2131        return false;
2132    };
2133    let mut visited: std::collections::HashSet<String> = std::collections::HashSet::new();
2134    let mut stack: Vec<String> = Vec::new();
2135    body_heads(root, &mut stack);
2136    while let Some(n) = stack.pop() {
2137        if n == name {
2138            return true;
2139        }
2140        if !visited.insert(n.clone()) {
2141            continue;
2142        }
2143        if let Some(decl) = types.get(&n) {
2144            body_heads(decl, &mut stack);
2145        }
2146    }
2147    false
2148}
2149
2150#[derive(Debug, Clone)]
2151pub struct Expr {
2152    pub kind: ExprKind,
2153    pub span: Span,
2154}
2155
2156impl ExprKind {
2157    /// Construct an `IntLit` for a *synthesized* integer — one the compiler
2158    /// invents rather than reading from source (a default `1`, a computed bound).
2159    /// The lexeme is the canonical decimal form (no separators). Source-parsed
2160    /// literals keep their as-written lexeme instead (v0.142, ADR 0166).
2161    pub fn int_lit(value: i64) -> ExprKind {
2162        ExprKind::IntLit {
2163            value,
2164            lexeme: value.to_string(),
2165        }
2166    }
2167}
2168
2169#[derive(Debug, Clone)]
2170pub enum ExprKind {
2171    /// An integer literal (typed `Int`). The lexeme is kept alongside the parsed
2172    /// value (v0.142, ADR 0166) so formatting is byte-stable: an author's `_`
2173    /// digit separators (`1_048_576`) survive a round-trip, mirroring the
2174    /// `FloatLit` treatment. The value is separator-free; emission lowers the
2175    /// value, so emitted output is unaffected.
2176    IntLit {
2177        value: i64,
2178        lexeme: String,
2179    },
2180    /// A float literal (v0.21). The lexeme is kept alongside the parsed
2181    /// value so emission and formatting are byte-stable (`1e10` must not
2182    /// normalise to `10000000000`).
2183    FloatLit {
2184        value: f64,
2185        lexeme: String,
2186    },
2187    /// A duration literal `<int>.<unit>` (v0.86, ADR 0112): `5.minutes`,
2188    /// `30.days`. The parser recognises the `IntLit . <unit>` shape and records
2189    /// the magnitude, the unit, and the resolved milliseconds (the value the
2190    /// emitter lowers to). Typed `Duration`.
2191    DurationLit {
2192        /// The integer magnitude as written (`5` in `5.minutes`).
2193        value: i64,
2194        /// The unit name (`minutes`), one of the closed set.
2195        unit: DurationUnit,
2196        /// The value in milliseconds — `value * unit factor`.
2197        millis: i64,
2198    },
2199    StrLit(String),
2200    /// An interpolated string `"… \(expr) …"` (v0.43, ADR 0075). Chunks and
2201    /// holes alternate. A plain `"…"` with no holes stays [`ExprKind::StrLit`],
2202    /// so existing code and the emitter/formatter fast-path are untouched.
2203    InterpStr(Vec<InterpPart>),
2204    BoolLit(bool),
2205    Ident(Ident),
2206    Call {
2207        name: Ident,
2208        /// v0.20a: explicit type arguments (`name[T](…)`); empty when absent.
2209        type_args: Vec<TypeRef>,
2210        args: Vec<Expr>,
2211    },
2212    /// A lambda (v0.20a). See [`LambdaExpr`].
2213    Lambda(LambdaExpr),
2214    BinOp(BinOp, Box<Expr>, Box<Expr>),
2215    UnaryOp(UnaryOp, Box<Expr>),
2216    Paren(Box<Expr>),
2217    /// `{ stmts; expr }` — block expression (v0.1).
2218    Block(Block),
2219    /// `if cond { then } else { else }` (v0.1).
2220    If {
2221        cond: Box<Expr>,
2222        then_block: Box<Block>,
2223        else_block: Box<Block>,
2224    },
2225    /// `Ok(value)` — Result success constructor (v0.1).
2226    Ok(Box<Expr>),
2227    /// `Err(error)` — Result failure constructor (v0.1).
2228    Err(Box<Expr>),
2229    /// `expr?` — propagation operator (v0.1).
2230    Question(Box<Expr>),
2231    /// `TypeName.method(args)` — qualified static call on a type
2232    /// (v0.1: only refined-type `of`; v0.2: any static method or variant
2233    /// constructor for sum types). The resolver decides which.
2234    ConstructorCall {
2235        type_name: Ident,
2236        method: Ident,
2237        args: Vec<Expr>,
2238    },
2239    /// `TypeName { field: value, ... }` — record construction (v0.2).
2240    RecordConstruction {
2241        type_name: Ident,
2242        fields: Vec<FieldInit>,
2243    },
2244    /// `receiver.field` — field access on a record value (v0.2). v0.3 adds
2245    /// `.raw` on opaque types within the defining commons.
2246    FieldAccess {
2247        receiver: Box<Expr>,
2248        field: Ident,
2249    },
2250    /// `receiver.method(args)` — instance method call (v0.2). The
2251    /// resolver determines the receiver's type and looks up the method.
2252    MethodCall {
2253        receiver: Box<Expr>,
2254        method: Ident,
2255        /// v0.22b: explicit type arguments on a qualified static
2256        /// (`Json.decode[T](…)`); empty when absent. The same-line-`[`
2257        /// rule applies as for `Call` type application (0039).
2258        type_args: Vec<TypeRef>,
2259        args: Vec<Expr>,
2260    },
2261    /// `match disc { arm+ }` — pattern matching (v0.2).
2262    Match {
2263        discriminant: Box<Expr>,
2264        arms: Vec<MatchArm>,
2265    },
2266    /// `expr is pattern` — pattern test, returns Bool (v0.2).
2267    Is {
2268        value: Box<Expr>,
2269        pattern: Pattern,
2270    },
2271    /// `Some(value)` — Option Some constructor (v0.2).
2272    Some(Box<Expr>),
2273    /// `None` — Option None constructor (v0.2).
2274    None,
2275    /// `()` — unit literal (v0.5).
2276    UnitLit,
2277    /// `TypeName { ...base, field: value, ... }` or `{ ...base, ... }` —
2278    /// record spread expression (v0.5).
2279    RecordSpread {
2280        /// Optional type prefix (`TypeName { ...base }`). Absent for the
2281        /// bare form used inside `commit`.
2282        type_name: Option<Ident>,
2283        /// The base record being spread.
2284        base: Box<Expr>,
2285        /// Field overrides (always full `name: value` form — never shorthand).
2286        overrides: Vec<FieldInit>,
2287    },
2288    /// `Effect.pure(value)` — wrap a synchronous value into `Effect[T]`
2289    /// (v0.5). Recognised in the parser as a special-form.
2290    EffectPure(Box<Expr>),
2291    /// `expect expr` — expectation as an expression of type `()` (v0.9.1;
2292    /// renamed from `assert` in v0.112). Valid only inside test bodies. Evaluates
2293    /// `expr` (must be Bool); if false, the surrounding test case fails.
2294    Expect(Box<Expr>),
2295    /// `Val[T]`, `Val[T](args)` — test-context value construction (v0.9.4).
2296    /// `args` is empty for the bare form and holds the pin arguments for
2297    /// `Val[T](...)`. The record-override form `Val[T] { ... }` is not yet
2298    /// parsed. Valid only inside test bodies; has type `T`.
2299    Val {
2300        type_ref: TypeRef,
2301        args: Vec<Expr>,
2302    },
2303    /// `Wire(<String>)` — a raw, pre-validation argument to a `system`-tier
2304    /// service address (testing-the-boundary Slice C). The inner expression is a
2305    /// `String` carrying the wire form the boundary will receive *unvalidated* —
2306    /// a body's JSON text or a path segment — so a case can drive the router with
2307    /// input the type system forbids and observe the rejection. Legal only at
2308    /// `system` (there is no wire at `unit`); the router validates it, so no
2309    /// refined value is ever minted from a `Wire` (ADR 0182 untouched).
2310    Wire(Box<Expr>),
2311    /// `[a, b, c]` — list literal (v0.20b). An empty `[]` requires an
2312    /// expected type (`bynk.types.uninferable_element_type`).
2313    ListLit(Vec<Expr>),
2314    /// An observation over a consumed capability's recorded calls (v0.117,
2315    /// testing track slice 5). The direct subject of an `expect` in a `case`
2316    /// body — `expect Cap.op called once with <pred>`, `expect Cap.op never
2317    /// called`, `expect A.op before B.op`. Types as `Bool` (the claim about the
2318    /// recorded trace), lowered to a boolean over the recorded log.
2319    Observation(ObservationExpr),
2320    /// `trace(Cap.op)` — the bound-trace escape hatch (v0.117, testing track
2321    /// slice 5). Yields the recorded calls of `Cap.op` as a `List[<CallRecord>]`
2322    /// (a synthetic record of the operation's parameters), asserted over with the
2323    /// ordinary value surface. Test-body-only, like [`ExprKind::Val`].
2324    Trace {
2325        cap: Ident,
2326        op: Ident,
2327    },
2328}
2329
2330/// Every directly-nested sub-expression of `e` — the **total** child
2331/// iterator. The match is exhaustive (no `_` arm), so adding an [`ExprKind`]
2332/// variant is a compile error here rather than a silently incomplete walk —
2333/// the trap the checker's three hand-rolled partial walkers each fell into
2334/// (block statements and match-arm bodies were skipped, so e.g. the `:=`
2335/// self-reference rule was bypassable through a match arm).
2336///
2337/// Descends one level: block *statements* and the tail, match-arm bodies,
2338/// lambda bodies, interpolation holes, record-field values, and observation
2339/// predicates are all children. Callers recurse for a deep walk.
2340pub fn expr_children(e: &Expr) -> Vec<&Expr> {
2341    fn block_children<'a>(b: &'a Block, out: &mut Vec<&'a Expr>) {
2342        for s in &b.statements {
2343            statement_exprs(s, out);
2344        }
2345        out.push(&b.tail);
2346    }
2347    let mut out = Vec::new();
2348    match &e.kind {
2349        ExprKind::IntLit { .. }
2350        | ExprKind::FloatLit { .. }
2351        | ExprKind::DurationLit { .. }
2352        | ExprKind::StrLit(_)
2353        | ExprKind::BoolLit(_)
2354        | ExprKind::Ident(_)
2355        | ExprKind::None
2356        | ExprKind::UnitLit
2357        | ExprKind::Trace { .. } => {}
2358        ExprKind::InterpStr(parts) => {
2359            for p in parts {
2360                if let InterpPart::Hole(h) = p {
2361                    out.push(h.as_ref());
2362                }
2363            }
2364        }
2365        ExprKind::Call { args, .. }
2366        | ExprKind::ConstructorCall { args, .. }
2367        | ExprKind::Val { args, .. }
2368        | ExprKind::ListLit(args) => out.extend(args.iter()),
2369        ExprKind::Wire(inner) => out.push(inner.as_ref()),
2370        ExprKind::Lambda(l) => out.push(l.body.as_ref()),
2371        ExprKind::BinOp(_, l, r) => {
2372            out.push(l.as_ref());
2373            out.push(r.as_ref());
2374        }
2375        ExprKind::UnaryOp(_, inner)
2376        | ExprKind::Paren(inner)
2377        | ExprKind::Ok(inner)
2378        | ExprKind::Err(inner)
2379        | ExprKind::Question(inner)
2380        | ExprKind::Some(inner)
2381        | ExprKind::EffectPure(inner)
2382        | ExprKind::Expect(inner) => out.push(inner.as_ref()),
2383        ExprKind::Block(b) => block_children(b, &mut out),
2384        ExprKind::If {
2385            cond,
2386            then_block,
2387            else_block,
2388        } => {
2389            out.push(cond.as_ref());
2390            block_children(then_block, &mut out);
2391            block_children(else_block, &mut out);
2392        }
2393        ExprKind::RecordConstruction { fields, .. } => {
2394            out.extend(fields.iter().filter_map(|f| f.value.as_ref()));
2395        }
2396        ExprKind::FieldAccess { receiver, .. } => out.push(receiver.as_ref()),
2397        ExprKind::MethodCall { receiver, args, .. } => {
2398            out.push(receiver.as_ref());
2399            out.extend(args.iter());
2400        }
2401        ExprKind::Match { discriminant, arms } => {
2402            out.push(discriminant.as_ref());
2403            for arm in arms {
2404                match &arm.body {
2405                    MatchBody::Expr(e) => out.push(e),
2406                    MatchBody::Block(b) => block_children(b, &mut out),
2407                }
2408            }
2409        }
2410        ExprKind::Is { value, .. } => out.push(value.as_ref()),
2411        ExprKind::RecordSpread {
2412            base, overrides, ..
2413        } => {
2414            out.push(base.as_ref());
2415            out.extend(overrides.iter().filter_map(|f| f.value.as_ref()));
2416        }
2417        ExprKind::Observation(obs) => match &obs.matcher {
2418            ObservationMatcher::Called { count, with_pred } => {
2419                if let Some(c) = count {
2420                    out.push(c.as_ref());
2421                }
2422                if let Some(p) = with_pred {
2423                    out.push(p.as_ref());
2424                }
2425            }
2426            ObservationMatcher::NeverCalled | ObservationMatcher::Before { .. } => {}
2427        },
2428    }
2429    out
2430}
2431
2432/// The expressions directly contained in a statement — the statement half of
2433/// [`expr_children`]'s total walk. Exhaustive over [`Statement`] for the same
2434/// reason.
2435pub fn statement_exprs<'a>(s: &'a Statement, out: &mut Vec<&'a Expr>) {
2436    match s {
2437        Statement::Let(l) | Statement::EffectLet(l) => out.push(&l.value),
2438        Statement::Expect(a) => out.push(&a.value),
2439        Statement::Send(snd) => out.push(&snd.value),
2440        Statement::Do(d) => out.push(&d.value),
2441        Statement::Assign(a) => out.push(&a.value),
2442    }
2443}
2444
2445/// An observation of a capability operation's recorded calls (v0.117, testing
2446/// track slice 5). `cap`/`op` name the seam (`Logger.log`); `matcher` is the
2447/// claim about the recorded calls.
2448#[derive(Debug, Clone)]
2449pub struct ObservationExpr {
2450    pub cap: Ident,
2451    pub op: Ident,
2452    pub matcher: ObservationMatcher,
2453}
2454
2455/// The claim an [`ObservationExpr`] makes about a seam's recorded calls (v0.117).
2456#[derive(Debug, Clone)]
2457pub enum ObservationMatcher {
2458    /// `called` [`once` | `<n> times`]? [`with` `<pred>`]?. `count` is `None`
2459    /// for a bare `called` (at least one); `Some(expr)` is the exact-count claim
2460    /// (a literal; `once` desugars to `1`). `with_pred` matches a call whose
2461    /// arguments (in scope by the operation's parameter names) satisfy it.
2462    Called {
2463        count: Option<Box<Expr>>,
2464        with_pred: Option<Box<Expr>>,
2465    },
2466    /// `never called` — zero calls.
2467    NeverCalled,
2468    /// `before Cap.op` — the first call of the subject precedes the first call
2469    /// of the named operation (both must have occurred).
2470    Before { cap: Ident, op: Ident },
2471}
2472
2473/// One part of an interpolated string (v0.43, ADR 0075). An
2474/// [`ExprKind::InterpStr`] holds an alternating run of these.
2475#[derive(Debug, Clone)]
2476pub enum InterpPart {
2477    /// Literal text between holes, with escapes already resolved.
2478    Chunk(String),
2479    /// An interpolated expression `\(expr)`. Type-checked by the hole rule
2480    /// (base scalars only; see the checker) and lowered into a template-
2481    /// literal `${…}` slot.
2482    Hole(Box<Expr>),
2483}
2484
2485/// One field-initialiser inside a record construction expression:
2486/// either `name: expr` or the shorthand `name` (which requires a binding
2487/// of the same name in scope and uses its value).
2488#[derive(Debug, Clone)]
2489pub struct FieldInit {
2490    pub name: Ident,
2491    /// `None` means shorthand — the field's value is the same-named binding.
2492    pub value: Option<Expr>,
2493    pub span: Span,
2494}
2495
2496/// One arm of a `match` expression: `pattern => body` or, with a guard,
2497/// `pattern if guard => body` (guard added in the nested-patterns increment,
2498/// ADR 0169). A guarded arm matches only when the pattern matches **and** the
2499/// `Bool` guard evaluates true; it never contributes to exhaustiveness.
2500#[derive(Debug, Clone)]
2501pub struct MatchArm {
2502    pub pattern: Pattern,
2503    /// Optional `if <Bool-expr>` guard between the pattern and `=>`.
2504    pub guard: Option<Expr>,
2505    pub body: MatchBody,
2506    pub span: Span,
2507}
2508
2509/// The right-hand side of a match arm — either a single expression or
2510/// a block.
2511#[derive(Debug, Clone)]
2512pub enum MatchBody {
2513    Expr(Expr),
2514    Block(Block),
2515}
2516
2517impl MatchBody {
2518    pub fn span(&self) -> Span {
2519        match self {
2520            MatchBody::Expr(e) => e.span,
2521            MatchBody::Block(b) => b.span,
2522        }
2523    }
2524}
2525
2526/// A pattern (v0.2 §3.8). Patterns appear in `match` arms and as the
2527/// right-hand side of the `is` operator.
2528#[derive(Debug, Clone)]
2529pub enum Pattern {
2530    /// `_` — matches any value, no bindings.
2531    Wildcard(Span),
2532    /// A lowercase identifier — binds the whole value to `name` and matches
2533    /// anything (ADR 0169). At the top of a `match` arm it binds the scrutinee
2534    /// (`n if n > 0 => …`); inside a payload position it binds the field
2535    /// (`Some(user)`). The uppercase-led counterpart is a nullary [`Pattern::Variant`].
2536    Binding(Ident),
2537    /// A literal pattern — `31`, `"english"`, `true` (v0.130 §2.3.4). Matches a
2538    /// primitive scrutinee (`Int`/`String`/`Bool`) by value equality. The
2539    /// admitted set mirrors ADR 0001's closed literal set (integers — including
2540    /// a leading unary minus — strings, and booleans); `Float`/`()` are not
2541    /// admitted as patterns.
2542    Literal { value: LiteralValue, span: Span },
2543    /// `Variant` or `Variant(bindings)` or `TypeName.Variant(bindings)`. Each
2544    /// payload binding is itself a [`Pattern`] (ADR 0169), so payloads nest:
2545    /// `Some(Ok(x))`, `Err(PollClosed)`.
2546    Variant {
2547        /// Optional qualifier: `TypeName.Variant`.
2548        type_name: Option<Ident>,
2549        /// The variant name.
2550        variant: Ident,
2551        /// Payload bindings (empty for nullary variants).
2552        bindings: Vec<PatternBinding>,
2553        span: Span,
2554    },
2555    /// `p 'where' refinement-predicate` — a refinement guard on a pattern
2556    /// (#472). Matches when `inner` matches *and* the scrutinee satisfies
2557    /// `predicate` at runtime. v1 admits only `Wildcard` as `inner` (no
2558    /// binding form yet); refutable — never counts toward exhaustiveness or
2559    /// as a catch-all arm, the same treatment as an `if` guard (§2.3.4).
2560    Refined {
2561        inner: Box<Pattern>,
2562        predicate: Refinement,
2563        span: Span,
2564    },
2565    /// `p₁ | p₂ | … | pₙ` — an or-pattern (#474 §2.3.4): matches if any
2566    /// alternative matches. Left-associative `|`, flattened by the parser's
2567    /// chain fold into one `Vec` — an alternative is always a leaf
2568    /// (`Wildcard`/`Binding`/`Literal`/`Variant`), never itself an `Or`
2569    /// (there is no parenthesized-pattern syntax to nest one inside another).
2570    /// Well-typedness (checked, not parsed): every alternative binds the same
2571    /// set of names, a name shared across alternatives has the same type
2572    /// (including refinement) in each, and every alternative matches the same
2573    /// value type.
2574    Or(Vec<Pattern>, Span),
2575}
2576
2577/// The value carried by a [`Pattern::Literal`]. A closed set (ADR 0001):
2578/// integer, string, and boolean. Kept distinct from [`ExprKind`] so patterns
2579/// carry only what they can actually match, and so it is `Eq`/`Hash` for the
2580/// duplicate-arm check.
2581#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2582pub enum LiteralValue {
2583    Int(i64),
2584    Str(String),
2585    Bool(bool),
2586}
2587
2588impl LiteralValue {
2589    /// A human-readable rendering for diagnostics (`31`, `"english"`, `true`).
2590    pub fn describe(&self) -> String {
2591        match self {
2592            LiteralValue::Int(n) => n.to_string(),
2593            LiteralValue::Str(s) => format!("{s:?}"),
2594            LiteralValue::Bool(b) => b.to_string(),
2595        }
2596    }
2597}
2598
2599impl Pattern {
2600    pub fn span(&self) -> Span {
2601        match self {
2602            Pattern::Wildcard(s) => *s,
2603            Pattern::Binding(id) => id.span,
2604            Pattern::Literal { span, .. } => *span,
2605            Pattern::Variant { span, .. } => *span,
2606            Pattern::Refined { span, .. } => *span,
2607            Pattern::Or(_, span) => *span,
2608        }
2609    }
2610
2611    /// Every identifier this pattern binds into scope, recursively (`_` and
2612    /// nullary variants bind nothing). Used by the resolver and the checker to
2613    /// populate an arm's scope, and by the guard to see the arm's bindings.
2614    ///
2615    /// For [`Pattern::Or`] this returns the *first* alternative's names — the
2616    /// checker separately verifies (#474 Rule 1) that every alternative binds
2617    /// the same set, so this is a defensive default when that rule is
2618    /// violated, not a semantic choice among alternatives.
2619    pub fn bound_names(&self) -> Vec<&Ident> {
2620        match self {
2621            Pattern::Wildcard(_) | Pattern::Literal { .. } => Vec::new(),
2622            Pattern::Binding(id) => vec![id],
2623            Pattern::Variant { bindings, .. } => bindings
2624                .iter()
2625                .flat_map(|b| b.pattern().bound_names())
2626                .collect(),
2627            Pattern::Refined { inner, .. } => inner.bound_names(),
2628            Pattern::Or(alts, _) => alts.first().map(Pattern::bound_names).unwrap_or_default(),
2629        }
2630    }
2631
2632    /// True when this pattern matches every value and binds nothing — a bare
2633    /// `_`. A [`Pattern::Binding`] also matches everything but *does* bind, so it
2634    /// is not a pure wildcard.
2635    pub fn is_wildcard(&self) -> bool {
2636        matches!(self, Pattern::Wildcard(_))
2637    }
2638
2639    /// True when this pattern matches every value (a `_` or a name binding),
2640    /// i.e. it is irrefutable and covers the position for exhaustiveness. An
2641    /// [`Pattern::Or`] is irrefutable when any alternative is — `_` in any
2642    /// position already makes the whole pattern match everything.
2643    pub fn is_irrefutable(&self) -> bool {
2644        match self {
2645            Pattern::Wildcard(_) | Pattern::Binding(_) => true,
2646            Pattern::Or(alts, _) => alts.iter().any(Pattern::is_irrefutable),
2647            _ => false,
2648        }
2649    }
2650}
2651
2652/// A single binding inside a variant pattern. Two surface forms:
2653/// `pattern` (positional — match the i-th payload field) and
2654/// `fieldName: pattern` (named — match the named payload field). The matched
2655/// sub-`pattern` is a full [`Pattern`] (ADR 0169), so a plain `name` is a
2656/// [`Pattern::Binding`], `_` a [`Pattern::Wildcard`], and `Ok(x)` a nested
2657/// [`Pattern::Variant`].
2658#[derive(Debug, Clone)]
2659pub struct PatternBinding {
2660    /// Source form: positional or named.
2661    pub kind: PatternBindingKind,
2662    pub span: Span,
2663}
2664
2665#[derive(Debug, Clone)]
2666pub enum PatternBindingKind {
2667    /// `pattern` (e.g. `x`, `_`, `Ok(v)`): match the payload field at this position.
2668    Positional { pattern: Pattern },
2669    /// `field: pattern`: match the named payload field against `pattern`.
2670    Named { field: Ident, pattern: Pattern },
2671}
2672
2673impl PatternBinding {
2674    /// The sub-pattern this binding matches its payload field against.
2675    pub fn pattern(&self) -> &Pattern {
2676        match &self.kind {
2677            PatternBindingKind::Positional { pattern } => pattern,
2678            PatternBindingKind::Named { pattern, .. } => pattern,
2679        }
2680    }
2681
2682    /// True when this binding discards its field (`_` or `field: _`) — a pure
2683    /// wildcard sub-pattern that binds nothing.
2684    pub fn is_wildcard(&self) -> bool {
2685        self.pattern().is_wildcard()
2686    }
2687}
2688
2689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2690pub enum BinOp {
2691    /// `P implies Q` — logical implication (v0.80). Desugars to `!P || Q`; sits
2692    /// at the lowest precedence (below `||`). Reads directionally (P → Q).
2693    Implies,
2694    Or,
2695    And,
2696    Eq,
2697    NotEq,
2698    Lt,
2699    LtEq,
2700    Gt,
2701    GtEq,
2702    Add,
2703    Sub,
2704    Mul,
2705    Div,
2706}
2707
2708impl BinOp {
2709    pub fn name(self) -> &'static str {
2710        match self {
2711            BinOp::Implies => "implies",
2712            BinOp::Or => "||",
2713            BinOp::And => "&&",
2714            BinOp::Eq => "==",
2715            BinOp::NotEq => "!=",
2716            BinOp::Lt => "<",
2717            BinOp::LtEq => "<=",
2718            BinOp::Gt => ">",
2719            BinOp::GtEq => ">=",
2720            BinOp::Add => "+",
2721            BinOp::Sub => "-",
2722            BinOp::Mul => "*",
2723            BinOp::Div => "/",
2724        }
2725    }
2726}
2727
2728#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2729pub enum UnaryOp {
2730    Neg,
2731    Not,
2732}
2733
2734impl UnaryOp {
2735    pub fn name(self) -> &'static str {
2736        match self {
2737            UnaryOp::Neg => "-",
2738            UnaryOp::Not => "!",
2739        }
2740    }
2741}