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