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