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/// 3) both extend a record body, so nothing here forecloses them. Legal only
1547/// inside a `context` — checker-enforced (`bynk.event.outside_context`), not
1548/// grammar, mirroring how `capability`/`provides` are commons-rejected at
1549/// the parser while `event` instead follows `messages`' precedent
1550/// (ADR 0272) of parsing uniformly and letting the checker place it, since
1551/// unlike `capability`/`provides` an `event` has no meaning to reject early
1552/// inside an `adapter` either.
1553#[derive(Debug, Clone)]
1554pub struct EventDecl {
1555    pub name: Ident,
1556    pub body: RecordBody,
1557    /// Documentation block attached to this declaration.
1558    pub documentation: Option<String>,
1559    pub span: Span,
1560    pub trivia: Trivia,
1561}
1562
1563impl EventDecl {
1564    /// A synthetic `TypeDecl` with this event's name and record body, so an
1565    /// event registers into the ordinary `types` symbol table and reuses
1566    /// every existing type-reference/exports/consumes/construction check —
1567    /// no non-generic type parameters, no separate resolution path. Callers
1568    /// that need to know a name is specifically an *event* (owner-only
1569    /// emission, `from Events(E)`/`Events.emit[E]`'s "must be an event, not
1570    /// just any type" gate) track that separately, alongside this.
1571    pub fn as_type_decl(&self) -> TypeDecl {
1572        TypeDecl {
1573            name: self.name.clone(),
1574            type_params: Vec::new(),
1575            body: TypeBody::Record(self.body.clone()),
1576            documentation: self.documentation.clone(),
1577            span: self.span,
1578            trivia: self.trivia.clone(),
1579        }
1580    }
1581}
1582
1583/// The structural filter on a `from Events(E { field: value, .. })`
1584/// subscription header (Events track, slice 1, spine #936) — deliver-and-filter:
1585/// every emission still reaches the fan-out mechanism, and the subscriber's
1586/// own generated handler evaluates this as a boolean guard before running the
1587/// body. Deliberately **not** a [`Pattern`] — an event is a plain record, not
1588/// a sum, so it has no tag for [`Pattern::Variant`] to test; extending the
1589/// shared `Pattern` enum to fit would touch parser/checker/emitter/fmt/
1590/// tree-sitter/LSP sites and drag in match-exhaustiveness semantics a
1591/// delivery filter does not need. This amends
1592/// [ADR 0286](../decisions/0286-events-pattern-dispatch-deliver-and-filter.md)'s
1593/// "no bespoke matching engine is introduced for Events" claim; its
1594/// deliver-and-filter decision is unchanged. No static narrowing: a matching
1595/// handler body still sees its parameter at its own declared type, never
1596/// narrowed to a listed field's specific value (deferred — narrowing needs a
1597/// singleton-variant type the checker does not have, and waits on the
1598/// refinement-propagation design question `design/bynk-type-system.md`
1599/// §2.5.4 names as still open).
1600#[derive(Debug, Clone)]
1601pub struct EventPattern {
1602    /// The listed fields, in source order. Never empty — a pattern with no
1603    /// fields has no shape (`from Events(E)`, no braces, is the pattern-less
1604    /// form; `from Events(E { })` is a parse error pointing at it).
1605    pub fields: Vec<EventPatternField>,
1606    /// The span of the required trailing `..` — every listed field leaves
1607    /// the rest of the record's fields unconstrained, and that must be
1608    /// written explicitly rather than implied.
1609    pub rest_span: Span,
1610    pub span: Span,
1611}
1612
1613/// One `name: value` entry in an [`EventPattern`].
1614#[derive(Debug, Clone)]
1615pub struct EventPatternField {
1616    pub name: Ident,
1617    pub value: EventPatternValue,
1618    pub span: Span,
1619}
1620
1621/// The value a pattern field is matched against. A closed set, mirroring
1622/// [`Pattern::Literal`]'s closed literal kinds plus a nullary sum-variant
1623/// reference — no nested record sub-patterns in v1 (slice 1 filters on
1624/// top-level fields only).
1625#[derive(Debug, Clone)]
1626pub enum EventPatternValue {
1627    /// An `Int`/`String`/`Bool` literal — matches the field by value equality.
1628    Literal { value: LiteralValue, span: Span },
1629    /// A nullary sum-type variant, optionally qualified: `Region.Domestic` or
1630    /// bare `Domestic` — both resolve against the field's declared sum type.
1631    /// A variant that carries a payload is rejected (`bynk.event.
1632    /// pattern_variant_payload`): testing only the tag while ignoring a
1633    /// payload would silently over-broaden the filter.
1634    Variant {
1635        /// `Some(Region)` for the qualified form, `None` for bare.
1636        type_name: Option<Ident>,
1637        variant: Ident,
1638        span: Span,
1639    },
1640}
1641
1642impl EventPattern {
1643    pub fn span(&self) -> Span {
1644        self.span
1645    }
1646}
1647
1648impl EventPatternValue {
1649    pub fn span(&self) -> Span {
1650        match self {
1651            EventPatternValue::Literal { span, .. } => *span,
1652            EventPatternValue::Variant { span, .. } => *span,
1653        }
1654    }
1655}
1656
1657/// The right-hand side of a `type` declaration. In v0/v0.1 only the
1658/// `Refined` variant existed; v0.2 adds records and sums; v0.3 adds opaque.
1659#[derive(Debug, Clone)]
1660pub enum TypeBody {
1661    /// Refined base type: `BaseType where refinement`.
1662    Refined {
1663        base: BaseType,
1664        base_span: Span,
1665        refinement: Option<Refinement>,
1666    },
1667    /// Record type: `{ field: T where ..., ... }`.
1668    Record(RecordBody),
1669    /// Sum type: pipe-form variants or `enum { ... }` shorthand.
1670    Sum(SumBody),
1671    /// Opaque base type: `opaque BaseType (where refinement)?` (v0.3 §3.4).
1672    /// Identity is nominal; the base type is hidden outside the defining commons.
1673    Opaque {
1674        base: BaseType,
1675        base_span: Span,
1676        refinement: Option<Refinement>,
1677    },
1678}
1679
1680/// Body of a record-type declaration (v0.2 §3.1).
1681#[derive(Debug, Clone)]
1682pub struct RecordBody {
1683    pub fields: Vec<RecordField>,
1684    pub span: Span,
1685}
1686
1687/// One field of a record type declaration. Each field may carry inline
1688/// refinement, which is enforced at construction time on the field's value.
1689#[derive(Debug, Clone)]
1690pub struct RecordField {
1691    pub name: Ident,
1692    pub type_ref: TypeRef,
1693    pub refinement: Option<Refinement>,
1694    /// v0.11: an optional initial-value expression. Only meaningful on agent
1695    /// `state` fields (the field's fresh-key value); ignored / rejected on
1696    /// record-type fields by the checker.
1697    pub init: Option<Expr>,
1698    pub span: Span,
1699}
1700
1701/// Body of a sum-type declaration (v0.2 §3.2).
1702#[derive(Debug, Clone)]
1703pub struct SumBody {
1704    pub variants: Vec<Variant>,
1705    /// v0.154 (ADR 0178): declared error embeddings — `embeds E as V, …` after
1706    /// the variants. Each says "an `E` value auto-wraps into variant `V`", which
1707    /// the `?` operator uses to convert a cross-context error without a manual
1708    /// `.mapErr`. Empty for a sum with no embeddings.
1709    pub embeds: Vec<EmbedsClause>,
1710    pub span: Span,
1711}
1712
1713/// One `embeds <source_type> as <variant>` mapping in a sum body (v0.154, ADR
1714/// 0178). Declares that a value of `source_type` can be auto-wrapped into the
1715/// named single-payload `variant` of the enclosing sum.
1716#[derive(Debug, Clone)]
1717pub struct EmbedsClause {
1718    pub source_type: TypeRef,
1719    pub variant: Ident,
1720    pub span: Span,
1721}
1722
1723/// One variant of a sum type. Variants may have payload fields; a
1724/// payload-less variant is a simple tag.
1725#[derive(Debug, Clone)]
1726pub struct Variant {
1727    pub name: Ident,
1728    pub payload: Vec<VariantField>,
1729    pub span: Span,
1730}
1731
1732/// One payload field of a sum variant. Variant payload fields use named
1733/// declarations like record fields, but do not carry refinement in v0.2.
1734#[derive(Debug, Clone)]
1735pub struct VariantField {
1736    pub name: Ident,
1737    pub type_ref: TypeRef,
1738    pub span: Span,
1739}
1740
1741#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1742pub enum BaseType {
1743    Int,
1744    String,
1745    Bool,
1746    Float,
1747    /// `Duration` (v0.86, ADR 0112) — a span of time, a distinct base type
1748    /// erased to TS `number` carrying milliseconds (the `Clock` unit). Modelled
1749    /// on `Float`: Bynk-side-only, no implicit `Int` coercion (save the one
1750    /// sanctioned clock-math mix).
1751    Duration,
1752    /// `Instant` (v0.90, ADR 0114) — an absolute point in time, a distinct base
1753    /// type erased to TS `number` carrying Unix epoch milliseconds (the
1754    /// `Clock` unit). No literal (minted by `Clock.now()`); arithmetic composes
1755    /// with `Duration` (`Instant ± Duration -> Instant`, `Instant − Instant ->
1756    /// Duration`). Supersedes ADR 0112 D4's `Int`↔`Duration` clock-math mix.
1757    Instant,
1758    /// `Bytes` (v0.110, ADR 0142) — an immutable finite octet sequence, the
1759    /// seventh base type. Unlike its neighbours it does **not** erase to TS
1760    /// `number`: a `Bytes` lowers to a `Uint8Array`. No source literal
1761    /// (constructed via `Bytes.fromUtf8`/`fromBase64`/`empty`); `==` compares
1762    /// by content (real emitter codegen, not host `===`); wires as a base64
1763    /// JSON string; not `Map`-keyable and not orderable.
1764    Bytes,
1765}
1766
1767impl BaseType {
1768    pub fn name(self) -> &'static str {
1769        match self {
1770            BaseType::Int => "Int",
1771            BaseType::String => "String",
1772            BaseType::Bool => "Bool",
1773            BaseType::Float => "Float",
1774            BaseType::Duration => "Duration",
1775            BaseType::Instant => "Instant",
1776            BaseType::Bytes => "Bytes",
1777        }
1778    }
1779}
1780
1781/// A `Duration` literal unit (v0.86, ADR 0112) — the closed set of suffixes in a
1782/// `<int>.<unit>` literal. Each maps to a fixed millisecond factor (`Duration`
1783/// erases to `Int` milliseconds).
1784#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1785pub enum DurationUnit {
1786    Milliseconds,
1787    Seconds,
1788    Minutes,
1789    Hours,
1790    Days,
1791}
1792
1793impl DurationUnit {
1794    /// Resolve a unit name (`minutes`) to its variant, or `None` if it is not one
1795    /// of the closed set. Used by the parser to recognise an `<int>.<unit>`
1796    /// literal; an unrecognised name leaves the expression a field access.
1797    pub fn from_name(name: &str) -> Option<Self> {
1798        Some(match name {
1799            "milliseconds" => DurationUnit::Milliseconds,
1800            "seconds" => DurationUnit::Seconds,
1801            "minutes" => DurationUnit::Minutes,
1802            "hours" => DurationUnit::Hours,
1803            "days" => DurationUnit::Days,
1804            _ => return None,
1805        })
1806    }
1807
1808    /// The unit name as written.
1809    pub fn name(self) -> &'static str {
1810        match self {
1811            DurationUnit::Milliseconds => "milliseconds",
1812            DurationUnit::Seconds => "seconds",
1813            DurationUnit::Minutes => "minutes",
1814            DurationUnit::Hours => "hours",
1815            DurationUnit::Days => "days",
1816        }
1817    }
1818
1819    /// The unit's value in milliseconds.
1820    pub fn millis(self) -> i64 {
1821        match self {
1822            DurationUnit::Milliseconds => 1,
1823            DurationUnit::Seconds => 1_000,
1824            DurationUnit::Minutes => 60_000,
1825            DurationUnit::Hours => 3_600_000,
1826            DurationUnit::Days => 86_400_000,
1827        }
1828    }
1829}
1830
1831/// An integer refinement bound (v0.40, ADR 0073): the parsed value plus the
1832/// bound's source span (covering a leading `-`). Value-only beyond the span —
1833/// ints have one canonical printed form, so the formatter stays idempotent
1834/// without a stored lexeme. The span backs the `InRange`-swap quick-fix.
1835#[derive(Debug, Clone)]
1836pub struct IntBound {
1837    pub value: i64,
1838    pub span: Span,
1839}
1840
1841/// A float refinement bound (v0.21): the parsed value plus the signed source
1842/// lexeme (for byte-stable emission). v0.40 (ADR 0073): also the source span,
1843/// for the `InRange`-swap quick-fix.
1844#[derive(Debug, Clone)]
1845pub struct FloatBound {
1846    pub value: f64,
1847    pub lexeme: String,
1848    pub span: Span,
1849}
1850
1851#[derive(Debug, Clone)]
1852pub struct Refinement {
1853    pub predicates: Vec<RefinementPred>,
1854    pub span: Span,
1855}
1856
1857#[derive(Debug, Clone)]
1858pub struct RefinementPred {
1859    pub kind: PredKind,
1860    pub span: Span,
1861}
1862
1863#[derive(Debug, Clone)]
1864pub enum PredKind {
1865    Matches(String),
1866    InRange(IntBound, IntBound),
1867    /// `InRange` with float bounds (v0.21) — a separate variant so every
1868    /// `Int` refinement path stays untouched. Bounds keep their source
1869    /// lexemes (including any sign) so emitted runtime checks are
1870    /// byte-stable.
1871    InRangeF(FloatBound, FloatBound),
1872    MinLength(i64),
1873    MaxLength(i64),
1874    Length(i64),
1875    NonNegative,
1876    Positive,
1877    NonEmpty,
1878}
1879
1880impl PredKind {
1881    pub fn name(&self) -> &'static str {
1882        match self {
1883            PredKind::Matches(_) => "Matches",
1884            PredKind::InRange(..) | PredKind::InRangeF(..) => "InRange",
1885            PredKind::MinLength(_) => "MinLength",
1886            PredKind::MaxLength(_) => "MaxLength",
1887            PredKind::Length(_) => "Length",
1888            PredKind::NonNegative => "NonNegative",
1889            PredKind::Positive => "Positive",
1890            PredKind::NonEmpty => "NonEmpty",
1891        }
1892    }
1893}
1894
1895/// A function type parameter (v0.20a, `fn name[A, B](…)`). A struct rather
1896/// than a bare Ident so the ADR-0028 "bound-capable" promise is a later field
1897/// addition, not a representation change.
1898#[derive(Debug, Clone)]
1899pub struct TypeParam {
1900    pub name: Ident,
1901    pub span: Span,
1902}
1903
1904/// A lambda expression (v0.20a): `(params) => expr` or `(params) => { … }`.
1905/// `=>` is the value arrow (shared with `match`); param annotations are
1906/// optional where an expected function type supplies them.
1907#[derive(Debug, Clone)]
1908pub struct LambdaExpr {
1909    pub params: Vec<LambdaParam>,
1910    pub body: Box<Expr>,
1911    pub span: Span,
1912}
1913
1914/// A lambda parameter. A separate type from [`Param`] because its annotation
1915/// is optional — `Param.type_ref` stays mandatory at every signature site.
1916#[derive(Debug, Clone)]
1917pub struct LambdaParam {
1918    pub name: Ident,
1919    pub type_ref: Option<TypeRef>,
1920    pub span: Span,
1921}
1922
1923#[derive(Debug, Clone)]
1924pub struct FnDecl {
1925    /// v0.20a: `[A, B]` type parameters; empty for non-generic functions.
1926    pub type_params: Vec<TypeParam>,
1927    /// Free function or method (`TypeName.methodName`). See [`FnName`].
1928    pub name: FnName,
1929    pub params: Vec<Param>,
1930    pub return_type: TypeRef,
1931    /// v0.115: preconditions (`requires <name>: <pred>`), parsed between the
1932    /// return type and the body. A contract clause is the invariant predicate
1933    /// attached to a function (ADR 0144 — one predicate surface); `requires`
1934    /// scopes over the parameters only.
1935    pub requires: Vec<Contract>,
1936    /// v0.115: postconditions (`ensures <name>: <pred>`). Scopes over the
1937    /// parameters *and* `result`, the contextual binding for the return value.
1938    pub ensures: Vec<Contract>,
1939    pub body: Block,
1940    /// True when the first parameter is the special `self` parameter. Only
1941    /// valid for method declarations.
1942    pub has_self: bool,
1943    /// Documentation block attached to this declaration (v0.3).
1944    pub documentation: Option<String>,
1945    pub span: Span,
1946    pub trivia: Trivia,
1947}
1948
1949/// A function-declaration name: either a free function `f` or a method
1950/// `T.method` (v0.2 §3.6).
1951#[derive(Debug, Clone)]
1952pub enum FnName {
1953    /// `fn name(...)` — a free function.
1954    Free(Ident),
1955    /// `fn TypeName.methodName(...)` — a method attached to a type.
1956    Method {
1957        type_name: Ident,
1958        method_name: Ident,
1959    },
1960}
1961
1962impl FnName {
1963    /// The function's short name for diagnostics. For methods returns the
1964    /// method portion only; the type prefix is recovered via `type_name`.
1965    pub fn ident(&self) -> &Ident {
1966        match self {
1967            FnName::Free(id) => id,
1968            FnName::Method { method_name, .. } => method_name,
1969        }
1970    }
1971
1972    /// For methods, the attached type's identifier; `None` for free fns.
1973    pub fn type_name(&self) -> Option<&Ident> {
1974        match self {
1975            FnName::Free(_) => None,
1976            FnName::Method { type_name, .. } => Some(type_name),
1977        }
1978    }
1979
1980    /// The displayed full name (e.g., `Money.add` or `parseSku`).
1981    pub fn display(&self) -> String {
1982        match self {
1983            FnName::Free(id) => id.name.clone(),
1984            FnName::Method {
1985                type_name,
1986                method_name,
1987            } => format!("{}.{}", type_name.name, method_name.name),
1988        }
1989    }
1990}
1991
1992/// A brace-delimited block of statements ending in a tail expression
1993/// whose value is the block's value (spec v0.1 §3.1).
1994#[derive(Debug, Clone)]
1995pub struct Block {
1996    pub statements: Vec<Statement>,
1997    pub tail: Box<Expr>,
1998    pub span: Span,
1999    /// Line comments that appear between the last statement (or the
2000    /// opening brace) and the tail expression. Preserved here because
2001    /// expressions do not carry trivia in v1.1.
2002    pub tail_leading_comments: Vec<String>,
2003    /// `true` when the block was written with no explicit tail expression and
2004    /// the parser synthesised a `()` (unit) tail (v0.146, ADR 0170). The tail
2005    /// is a real `ExprKind::UnitLit` either way; this flag records that it was
2006    /// *implicit* so the formatter can omit it (Bynk has no statement
2007    /// terminator, so a printed `()` would re-attach to the last statement on
2008    /// re-parse — `x` `()` → `x()`). The parser re-derives the implicit unit
2009    /// tail, so omitting it is loss-free.
2010    pub implicit_tail: bool,
2011}
2012
2013impl Block {
2014    /// Whether this block is a synthesised empty unit block — no statements and
2015    /// an *implicit* `()` tail (v0.146, ADR 0170). This is exactly the shape the
2016    /// parser inserts for an `if` with no `else` branch, so both the checker
2017    /// (gating the else-less form to unit) and the formatter (omitting the
2018    /// synthetic `else { () }`) recognise it here.
2019    pub fn is_synth_unit(&self) -> bool {
2020        self.statements.is_empty()
2021            && self.implicit_tail
2022            && matches!(self.tail.kind, ExprKind::UnitLit)
2023    }
2024}
2025
2026/// Block-level statement.
2027#[derive(Debug, Clone)]
2028pub enum Statement {
2029    /// `let name (: T)? = expr` — pure binding (v0.1).
2030    Let(LetStmt),
2031    /// `let name (: T)? <- expr` — effectful binding (v0.5).
2032    EffectLet(LetStmt),
2033    /// `expect expr` — verify a Bool predicate at test runtime (v0.7; renamed
2034    /// from `assert` in v0.112). Only valid inside test case bodies.
2035    Expect(ExpectStmt),
2036    /// `~> expr` — an asynchronous fire-and-forget send (v0.79). The caller does
2037    /// not await the reply; legal only when the reply is `Effect[()]`. No binder.
2038    Send(SendStmt),
2039    /// `do expr` — an effect-performing expression statement (v0.146, ADR 0170).
2040    /// Runs an `Effect[()]` and discards its (unit) result — the binder-free
2041    /// sugar for `let _ <- expr` when the awaited value is unit. Legal only in
2042    /// an effectful body; the operand MUST be `Effect[()]` (a valued reply keeps
2043    /// the explicit `let _ <- e`, so throwing away a real value stays visible).
2044    Do(DoStmt),
2045    /// `name := expr` — a `Cell` store write (v0.81, storage track). The
2046    /// unconditional write form; `.update(fn)` (a method call) is the
2047    /// read-modify-write form. ADR 0108.
2048    Assign(AssignStmt),
2049}
2050
2051impl Statement {
2052    pub fn span(&self) -> Span {
2053        match self {
2054            Statement::Let(l) | Statement::EffectLet(l) => l.span,
2055            Statement::Expect(a) => a.span,
2056            Statement::Send(s) => s.span,
2057            Statement::Do(d) => d.span,
2058            Statement::Assign(a) => a.span,
2059        }
2060    }
2061}
2062
2063#[derive(Debug, Clone)]
2064pub struct ExpectStmt {
2065    pub value: Expr,
2066    pub span: Span,
2067    pub trivia: Trivia,
2068}
2069
2070/// `name := expr` — a `Cell` store write (v0.81, storage track). `target` is the
2071/// `Cell` field being written (a bare name for now; the checker resolves it to a
2072/// `store` field). `value` is the new value.
2073#[derive(Debug, Clone)]
2074pub struct AssignStmt {
2075    pub target: Ident,
2076    pub value: Expr,
2077    pub span: Span,
2078    pub trivia: Trivia,
2079}
2080
2081#[derive(Debug, Clone)]
2082pub struct LetStmt {
2083    pub name: Ident,
2084    pub type_annot: Option<TypeRef>,
2085    pub value: Expr,
2086    /// v0.182 (#664): the call-site `by <Actor>(<identity>)` clause on an
2087    /// `EffectLet` whose value addresses a test service handler. `None` on a pure
2088    /// `Let` (the `by` is parsed only in the `<-` arm) and on an effect-let with
2089    /// no principal.
2090    pub principal: Option<CallSiteActor>,
2091    pub span: Span,
2092    pub trivia: Trivia,
2093}
2094
2095#[derive(Debug, Clone)]
2096pub struct SendStmt {
2097    /// The send target — a recipient call, e.g. `Logger.info(msg)`.
2098    pub value: Expr,
2099    pub span: Span,
2100    pub trivia: Trivia,
2101}
2102
2103/// `do expr` — an effect-performing expression statement (v0.146, ADR 0170).
2104/// `value` is the awaited effect, which MUST be `Effect[()]`.
2105#[derive(Debug, Clone)]
2106pub struct DoStmt {
2107    pub value: Expr,
2108    pub span: Span,
2109    pub trivia: Trivia,
2110}
2111
2112#[derive(Debug, Clone)]
2113pub struct Param {
2114    pub name: Ident,
2115    pub type_ref: TypeRef,
2116    pub span: Span,
2117}
2118
2119#[derive(Debug, Clone)]
2120pub enum TypeRef {
2121    Base(BaseType, Span),
2122    Named(Ident),
2123    /// `Result[T, E]` — the built-in generic Result type (v0.1).
2124    Result(Box<TypeRef>, Box<TypeRef>, Span),
2125    /// `Option[T]` — the built-in generic Option type (v0.2).
2126    Option(Box<TypeRef>, Span),
2127    /// `Effect[T]` — the built-in generic Effect type (v0.5).
2128    Effect(Box<TypeRef>, Span),
2129    /// `HttpResult[T]` — the built-in HTTP-result sum (v0.9).
2130    HttpResult(Box<TypeRef>, Span),
2131    /// `QueueResult` — the built-in queue verdict sum (`Ack | Retry`),
2132    /// non-generic; the required return of a queue handler (v0.44).
2133    QueueResult(Span),
2134    /// `List[T]` — the built-in generic immutable list type (v0.20b).
2135    List(Box<TypeRef>, Span),
2136    /// `Map[K, V]` — the built-in generic immutable map type (v0.20b).
2137    /// Keys are confined to value-keyable types
2138    /// (`bynk.types.unkeyable_map_key`).
2139    Map(Box<TypeRef>, Box<TypeRef>, Span),
2140    /// `Query[T]` — the built-in lazy storage-read description (v0.91, ADR 0115).
2141    /// Nameable in a pure helper's return type; non-storable and non-boundary
2142    /// (like `Effect`/`Fn`).
2143    Query(Box<TypeRef>, Span),
2144    /// `Stream[T]` — the value-over-time primitive (v0.100, real-time track
2145    /// slice 0). A lazy, pull-shaped sequence produced over time; non-storable
2146    /// and non-boundary (like `Query`/`Effect`/`Fn`).
2147    Stream(Box<TypeRef>, Span),
2148    /// `Connection[F]` — a held WebSocket connection (v0.102, real-time track
2149    /// slice 2). `F` is the server→client frame type. A `Held` resource:
2150    /// non-serialisable, non-boundary, and governed by the linearity discipline
2151    /// (§2.9); storable only in `Cell[Option[Connection]]` / `Map[K, Connection]`.
2152    Connection(Box<TypeRef>, Span),
2153    /// `History[Agent]` — a generated, driven call-history of an agent (v0.119,
2154    /// testing track slice 7, ADR 0155). A test-only generator, legal only in
2155    /// `for all` binding position inside a `property`; it is not a value type,
2156    /// so it never resolves in a field/param/return position. The bound subject
2157    /// behaves as an ordinary `List[Step]`.
2158    History(Box<TypeRef>, Span),
2159    /// `ValidationError` — the built-in error type used by refined-type
2160    /// constructors (v0.1).
2161    ValidationError(Span),
2162    /// `JsonError` — the built-in JSON-decode error type (v0.22b). A
2163    /// uniform record (`kind`/`path`/`message`, all `String`) the codec
2164    /// maps `BoundaryError` variants and parse failures into.
2165    JsonError(Span),
2166    /// `()` — the unit type (v0.5).
2167    Unit(Span),
2168    /// `A -> B` / `(A, B) -> C` / `() -> B` — a function type (v0.20a).
2169    /// Right-associative; effectful iff the return type is `Effect[_]`
2170    /// (the structural rule). Confined to non-boundary positions
2171    /// (`bynk.types.function_at_boundary`).
2172    Fn(Vec<TypeRef>, Box<TypeRef>, Span),
2173    /// `Name[Arg, …]` — an application of a user-declared generic type
2174    /// (v0.157, ADR 0183). `name` is a user type name (never a built-in
2175    /// generic, which each have a dedicated variant above). Arity and the
2176    /// existence of the referenced type are checked in the resolver.
2177    App {
2178        name: Ident,
2179        args: Vec<TypeRef>,
2180        span: Span,
2181    },
2182}
2183
2184impl TypeRef {
2185    pub fn span(&self) -> Span {
2186        match self {
2187            TypeRef::Base(_, s) => *s,
2188            TypeRef::Named(id) => id.span,
2189            TypeRef::Result(_, _, s) => *s,
2190            TypeRef::Option(_, s) => *s,
2191            TypeRef::Effect(_, s) => *s,
2192            TypeRef::HttpResult(_, s) => *s,
2193            TypeRef::QueueResult(s) => *s,
2194            TypeRef::List(_, s) => *s,
2195            TypeRef::Map(_, _, s) => *s,
2196            TypeRef::Query(_, s) => *s,
2197            TypeRef::Stream(_, s) => *s,
2198            TypeRef::Connection(_, s) => *s,
2199            TypeRef::History(_, s) => *s,
2200            TypeRef::ValidationError(s) => *s,
2201            TypeRef::JsonError(s) => *s,
2202            TypeRef::Unit(s) => *s,
2203            TypeRef::Fn(_, _, s) => *s,
2204            TypeRef::App { span, .. } => *span,
2205        }
2206    }
2207}
2208
2209/// v0.174 (#592): does the generic record type `name` transitively contain a
2210/// reference to itself — through any field-type path, including collection and
2211/// `Option` wrappers, sum-variant payloads, and generic type arguments? Such a
2212/// type has no finite set of monomorphised boundary codecs: uniform recursion
2213/// (`Node[T] = { next: Option[Node[T]] }`) would need a self-referential codec
2214/// chain the per-instantiation model does not yet generate, and polymorphic
2215/// recursion (`Weird[T] = { next: Option[Weird[List[T]]] }`) an unbounded set of
2216/// instantiations. Both are rejected at a boundary
2217/// (`bynk.generics.recursive_generic_at_boundary`).
2218///
2219/// Detection is reachability over the type-containment graph: `name` is
2220/// recursive iff it is reachable from its own body, following every named /
2221/// applied head and descending into every wrapper, map/result pair, function
2222/// position, and generic argument. Terminates via the `visited` set.
2223pub fn generic_record_is_recursive(
2224    name: &str,
2225    types: &std::collections::HashMap<String, std::sync::Arc<TypeDecl>>,
2226) -> bool {
2227    fn heads(t: &TypeRef, out: &mut Vec<String>) {
2228        match t {
2229            TypeRef::Named(id) => out.push(id.name.clone()),
2230            TypeRef::App {
2231                name: app_name,
2232                args,
2233                ..
2234            } => {
2235                out.push(app_name.name.clone());
2236                for a in args {
2237                    heads(a, out);
2238                }
2239            }
2240            TypeRef::Option(a, _)
2241            | TypeRef::List(a, _)
2242            | TypeRef::Effect(a, _)
2243            | TypeRef::HttpResult(a, _)
2244            | TypeRef::Query(a, _)
2245            | TypeRef::Stream(a, _)
2246            | TypeRef::Connection(a, _)
2247            | TypeRef::History(a, _) => heads(a, out),
2248            TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
2249                heads(a, out);
2250                heads(b, out);
2251            }
2252            TypeRef::Fn(ps, r, _) => {
2253                for p in ps {
2254                    heads(p, out);
2255                }
2256                heads(r, out);
2257            }
2258            TypeRef::Base(..)
2259            | TypeRef::QueueResult(_)
2260            | TypeRef::ValidationError(_)
2261            | TypeRef::JsonError(_)
2262            | TypeRef::Unit(_) => {}
2263        }
2264    }
2265    fn body_heads(decl: &TypeDecl, out: &mut Vec<String>) {
2266        match &decl.body {
2267            TypeBody::Record(r) => {
2268                for f in &r.fields {
2269                    heads(&f.type_ref, out);
2270                }
2271            }
2272            TypeBody::Sum(s) => {
2273                for v in &s.variants {
2274                    for p in &v.payload {
2275                        heads(&p.type_ref, out);
2276                    }
2277                }
2278            }
2279            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
2280        }
2281    }
2282    let Some(root) = types.get(name) else {
2283        return false;
2284    };
2285    let mut visited: std::collections::HashSet<String> = std::collections::HashSet::new();
2286    let mut stack: Vec<String> = Vec::new();
2287    body_heads(root, &mut stack);
2288    while let Some(n) = stack.pop() {
2289        if n == name {
2290            return true;
2291        }
2292        if !visited.insert(n.clone()) {
2293            continue;
2294        }
2295        if let Some(decl) = types.get(&n) {
2296            body_heads(decl, &mut stack);
2297        }
2298    }
2299    false
2300}
2301
2302#[derive(Debug, Clone)]
2303pub struct Expr {
2304    pub kind: ExprKind,
2305    pub span: Span,
2306}
2307
2308/// Finding #31: `Expr` sets the size of every expression node in the
2309/// program — `ExprKind::Observation`'s payload and `ExprKind::Is`'s pattern
2310/// field are boxed specifically to keep it small (176 bytes unboxed, 128
2311/// boxed, measured on this target). Pinned so the next large variant added
2312/// to `ExprKind` is a compile error here rather than a silent regression.
2313const _: () = assert!(std::mem::size_of::<Expr>() <= 128);
2314
2315impl ExprKind {
2316    /// Construct an `IntLit` for a *synthesized* integer — one the compiler
2317    /// invents rather than reading from source (a default `1`, a computed bound).
2318    /// The lexeme is the canonical decimal form (no separators). Source-parsed
2319    /// literals keep their as-written lexeme instead (v0.142, ADR 0166).
2320    pub fn int_lit(value: i64) -> ExprKind {
2321        ExprKind::IntLit {
2322            value,
2323            lexeme: value.to_string(),
2324        }
2325    }
2326}
2327
2328#[derive(Debug, Clone)]
2329pub enum ExprKind {
2330    /// An integer literal (typed `Int`). The lexeme is kept alongside the parsed
2331    /// value (v0.142, ADR 0166) so formatting is byte-stable: an author's `_`
2332    /// digit separators (`1_048_576`) survive a round-trip, mirroring the
2333    /// `FloatLit` treatment. The value is separator-free; emission lowers the
2334    /// value, so emitted output is unaffected.
2335    IntLit {
2336        value: i64,
2337        lexeme: String,
2338    },
2339    /// A float literal (v0.21). The lexeme is kept alongside the parsed
2340    /// value so emission and formatting are byte-stable (`1e10` must not
2341    /// normalise to `10000000000`).
2342    FloatLit {
2343        value: f64,
2344        lexeme: String,
2345    },
2346    /// A duration literal `<int>.<unit>` (v0.86, ADR 0112): `5.minutes`,
2347    /// `30.days`. The parser recognises the `IntLit . <unit>` shape and records
2348    /// the magnitude, the unit, and the resolved milliseconds (the value the
2349    /// emitter lowers to). Typed `Duration`.
2350    DurationLit {
2351        /// The integer magnitude as written (`5` in `5.minutes`).
2352        value: i64,
2353        /// The unit name (`minutes`), one of the closed set.
2354        unit: DurationUnit,
2355        /// The value in milliseconds — `value * unit factor`.
2356        millis: i64,
2357    },
2358    StrLit(String),
2359    /// An interpolated string `"… \(expr) …"` (v0.43, ADR 0075). Chunks and
2360    /// holes alternate. A plain `"…"` with no holes stays [`ExprKind::StrLit`],
2361    /// so existing code and the emitter/formatter fast-path are untouched.
2362    InterpStr(Vec<InterpPart>),
2363    BoolLit(bool),
2364    Ident(Ident),
2365    Call {
2366        name: Ident,
2367        /// v0.20a: explicit type arguments (`name[T](…)`); empty when absent.
2368        type_args: Vec<TypeRef>,
2369        args: Vec<Expr>,
2370    },
2371    /// A lambda (v0.20a). See [`LambdaExpr`].
2372    Lambda(LambdaExpr),
2373    BinOp(BinOp, Box<Expr>, Box<Expr>),
2374    UnaryOp(UnaryOp, Box<Expr>),
2375    Paren(Box<Expr>),
2376    /// `{ stmts; expr }` — block expression (v0.1).
2377    Block(Block),
2378    /// `if cond { then } else { else }` (v0.1).
2379    If {
2380        cond: Box<Expr>,
2381        then_block: Box<Block>,
2382        else_block: Box<Block>,
2383    },
2384    /// `Ok(value)` — Result success constructor (v0.1).
2385    Ok(Box<Expr>),
2386    /// `Err(error)` — Result failure constructor (v0.1).
2387    Err(Box<Expr>),
2388    /// `expr?` — propagation operator (v0.1).
2389    Question(Box<Expr>),
2390    /// `TypeName.method(args)` — qualified static call on a type
2391    /// (v0.1: only refined-type `of`; v0.2: any static method or variant
2392    /// constructor for sum types). The resolver decides which.
2393    ConstructorCall {
2394        type_name: Ident,
2395        method: Ident,
2396        args: Vec<Expr>,
2397    },
2398    /// `TypeName { field: value, ... }` — record construction (v0.2).
2399    RecordConstruction {
2400        type_name: Ident,
2401        fields: Vec<FieldInit>,
2402    },
2403    /// `receiver.field` — field access on a record value (v0.2). v0.3 adds
2404    /// `.raw` on opaque types within the defining commons.
2405    FieldAccess {
2406        receiver: Box<Expr>,
2407        field: Ident,
2408    },
2409    /// `receiver.method(args)` — instance method call (v0.2). The
2410    /// resolver determines the receiver's type and looks up the method.
2411    MethodCall {
2412        receiver: Box<Expr>,
2413        method: Ident,
2414        /// v0.22b: explicit type arguments on a qualified static
2415        /// (`Json.decode[T](…)`); empty when absent. The same-line-`[`
2416        /// rule applies as for `Call` type application (0039).
2417        type_args: Vec<TypeRef>,
2418        args: Vec<Expr>,
2419    },
2420    /// `match disc { arm+ }` — pattern matching (v0.2).
2421    Match {
2422        discriminant: Box<Expr>,
2423        arms: Vec<MatchArm>,
2424    },
2425    /// `expr is pattern` — pattern test, returns Bool (v0.2).
2426    ///
2427    /// `pattern` is boxed (finding #31): `Pattern`'s `Variant` case carries two
2428    /// `Ident`s plus a `Vec`, inlining it into every `ExprKind` sets the size
2429    /// of every expression node in the program for the one variant that
2430    /// tests a pattern.
2431    Is {
2432        value: Box<Expr>,
2433        pattern: Box<Pattern>,
2434    },
2435    /// `Some(value)` — Option Some constructor (v0.2).
2436    Some(Box<Expr>),
2437    /// `None` — Option None constructor (v0.2).
2438    None,
2439    /// `()` — unit literal (v0.5).
2440    UnitLit,
2441    /// `TypeName { ...base, field: value, ... }` or `{ ...base, ... }` —
2442    /// record spread expression (v0.5).
2443    RecordSpread {
2444        /// Optional type prefix (`TypeName { ...base }`). Absent for the
2445        /// bare form used inside `commit`.
2446        type_name: Option<Ident>,
2447        /// The base record being spread.
2448        base: Box<Expr>,
2449        /// Field overrides (always full `name: value` form — never shorthand).
2450        overrides: Vec<FieldInit>,
2451    },
2452    /// `Effect.pure(value)` — wrap a synchronous value into `Effect[T]`
2453    /// (v0.5). Recognised in the parser as a special-form.
2454    EffectPure(Box<Expr>),
2455    /// `expect expr` — expectation as an expression of type `()` (v0.9.1;
2456    /// renamed from `assert` in v0.112). Valid only inside test bodies. Evaluates
2457    /// `expr` (must be Bool); if false, the surrounding test case fails.
2458    Expect(Box<Expr>),
2459    /// `Val[T]`, `Val[T](args)` — test-context value construction (v0.9.4).
2460    /// `args` is empty for the bare form and holds the pin arguments for
2461    /// `Val[T](...)`. The record-override form `Val[T] { ... }` is not yet
2462    /// parsed. Valid only inside test bodies; has type `T`.
2463    Val {
2464        type_ref: TypeRef,
2465        args: Vec<Expr>,
2466    },
2467    /// `Wire(<String>)` — a raw, pre-validation argument to a `system`-tier
2468    /// service address (testing-the-boundary Slice C). The inner expression is a
2469    /// `String` carrying the wire form the boundary will receive *unvalidated* —
2470    /// a body's JSON text or a path segment — so a case can drive the router with
2471    /// input the type system forbids and observe the rejection. Legal only at
2472    /// `system` (there is no wire at `unit`); the router validates it, so no
2473    /// refined value is ever minted from a `Wire` (ADR 0182 untouched).
2474    Wire(Box<Expr>),
2475    /// `[a, b, c]` — list literal (v0.20b). An empty `[]` requires an
2476    /// expected type (`bynk.types.uninferable_element_type`).
2477    ListLit(Vec<Expr>),
2478    /// An observation over a consumed capability's recorded calls (v0.117,
2479    /// testing track slice 5). The direct subject of an `expect` in a `case`
2480    /// body — `expect Cap.op called once with <pred>`, `expect Cap.op never
2481    /// called`, `expect A.op before B.op`. Types as `Bool` (the claim about the
2482    /// recorded trace), lowered to a boolean over the recorded log.
2483    /// Boxed (finding #31): at ~160 bytes, `ObservationExpr` inlined here set
2484    /// the size of every `ExprKind` for the one variant that records a
2485    /// capability-call observation.
2486    Observation(Box<ObservationExpr>),
2487    /// `trace(Cap.op)` — the bound-trace escape hatch (v0.117, testing track
2488    /// slice 5). Yields the recorded calls of `Cap.op` as a `List[<CallRecord>]`
2489    /// (a synthetic record of the operation's parameters), asserted over with the
2490    /// ordinary value surface. Test-body-only, like [`ExprKind::Val`].
2491    Trace {
2492        cap: Ident,
2493        op: Ident,
2494    },
2495}
2496
2497/// Every directly-nested sub-expression of `e` — the **total** child
2498/// iterator. The match is exhaustive (no `_` arm), so adding an [`ExprKind`]
2499/// variant is a compile error here rather than a silently incomplete walk —
2500/// the trap the checker's three hand-rolled partial walkers each fell into
2501/// (block statements and match-arm bodies were skipped, so e.g. the `:=`
2502/// self-reference rule was bypassable through a match arm).
2503///
2504/// Descends one level: block *statements* and the tail, match-arm bodies,
2505/// lambda bodies, interpolation holes, record-field values, and observation
2506/// predicates are all children. Callers recurse for a deep walk.
2507pub fn expr_children(e: &Expr) -> Vec<&Expr> {
2508    fn block_children<'a>(b: &'a Block, out: &mut Vec<&'a Expr>) {
2509        for s in &b.statements {
2510            statement_exprs(s, out);
2511        }
2512        out.push(&b.tail);
2513    }
2514    let mut out = Vec::new();
2515    match &e.kind {
2516        ExprKind::IntLit { .. }
2517        | ExprKind::FloatLit { .. }
2518        | ExprKind::DurationLit { .. }
2519        | ExprKind::StrLit(_)
2520        | ExprKind::BoolLit(_)
2521        | ExprKind::Ident(_)
2522        | ExprKind::None
2523        | ExprKind::UnitLit
2524        | ExprKind::Trace { .. } => {}
2525        ExprKind::InterpStr(parts) => {
2526            for p in parts {
2527                if let InterpPart::Hole(h) = p {
2528                    out.push(h.as_ref());
2529                }
2530            }
2531        }
2532        ExprKind::Call { args, .. }
2533        | ExprKind::ConstructorCall { args, .. }
2534        | ExprKind::Val { args, .. }
2535        | ExprKind::ListLit(args) => out.extend(args.iter()),
2536        ExprKind::Wire(inner) => out.push(inner.as_ref()),
2537        ExprKind::Lambda(l) => out.push(l.body.as_ref()),
2538        ExprKind::BinOp(_, l, r) => {
2539            out.push(l.as_ref());
2540            out.push(r.as_ref());
2541        }
2542        ExprKind::UnaryOp(_, inner)
2543        | ExprKind::Paren(inner)
2544        | ExprKind::Ok(inner)
2545        | ExprKind::Err(inner)
2546        | ExprKind::Question(inner)
2547        | ExprKind::Some(inner)
2548        | ExprKind::EffectPure(inner)
2549        | ExprKind::Expect(inner) => out.push(inner.as_ref()),
2550        ExprKind::Block(b) => block_children(b, &mut out),
2551        ExprKind::If {
2552            cond,
2553            then_block,
2554            else_block,
2555        } => {
2556            out.push(cond.as_ref());
2557            block_children(then_block, &mut out);
2558            block_children(else_block, &mut out);
2559        }
2560        ExprKind::RecordConstruction { fields, .. } => {
2561            out.extend(fields.iter().filter_map(|f| f.value.as_ref()));
2562        }
2563        ExprKind::FieldAccess { receiver, .. } => out.push(receiver.as_ref()),
2564        ExprKind::MethodCall { receiver, args, .. } => {
2565            out.push(receiver.as_ref());
2566            out.extend(args.iter());
2567        }
2568        ExprKind::Match { discriminant, arms } => {
2569            out.push(discriminant.as_ref());
2570            for arm in arms {
2571                match &arm.body {
2572                    MatchBody::Expr(e) => out.push(e),
2573                    MatchBody::Block(b) => block_children(b, &mut out),
2574                }
2575            }
2576        }
2577        ExprKind::Is { value, .. } => out.push(value.as_ref()),
2578        ExprKind::RecordSpread {
2579            base, overrides, ..
2580        } => {
2581            out.push(base.as_ref());
2582            out.extend(overrides.iter().filter_map(|f| f.value.as_ref()));
2583        }
2584        ExprKind::Observation(obs) => match &obs.matcher {
2585            ObservationMatcher::Called { count, with_pred } => {
2586                if let Some(c) = count {
2587                    out.push(c.as_ref());
2588                }
2589                if let Some(p) = with_pred {
2590                    out.push(p.as_ref());
2591                }
2592            }
2593            ObservationMatcher::NeverCalled | ObservationMatcher::Before { .. } => {}
2594        },
2595    }
2596    out
2597}
2598
2599/// The expressions directly contained in a statement — the statement half of
2600/// [`expr_children`]'s total walk. Exhaustive over [`Statement`] for the same
2601/// reason.
2602pub fn statement_exprs<'a>(s: &'a Statement, out: &mut Vec<&'a Expr>) {
2603    match s {
2604        Statement::Let(l) | Statement::EffectLet(l) => out.push(&l.value),
2605        Statement::Expect(a) => out.push(&a.value),
2606        Statement::Send(snd) => out.push(&snd.value),
2607        Statement::Do(d) => out.push(&d.value),
2608        Statement::Assign(a) => out.push(&a.value),
2609    }
2610}
2611
2612/// An observation of a capability operation's recorded calls (v0.117, testing
2613/// track slice 5). `cap`/`op` name the seam (`Logger.log`); `matcher` is the
2614/// claim about the recorded calls.
2615#[derive(Debug, Clone)]
2616pub struct ObservationExpr {
2617    pub cap: Ident,
2618    pub op: Ident,
2619    pub matcher: ObservationMatcher,
2620}
2621
2622/// The claim an [`ObservationExpr`] makes about a seam's recorded calls (v0.117).
2623#[derive(Debug, Clone)]
2624pub enum ObservationMatcher {
2625    /// `called` [`once` | `<n> times`]? [`with` `<pred>`]?. `count` is `None`
2626    /// for a bare `called` (at least one); `Some(expr)` is the exact-count claim
2627    /// (a literal; `once` desugars to `1`). `with_pred` matches a call whose
2628    /// arguments (in scope by the operation's parameter names) satisfy it.
2629    Called {
2630        count: Option<Box<Expr>>,
2631        with_pred: Option<Box<Expr>>,
2632    },
2633    /// `never called` — zero calls.
2634    NeverCalled,
2635    /// `before Cap.op` — the first call of the subject precedes the first call
2636    /// of the named operation (both must have occurred).
2637    Before { cap: Ident, op: Ident },
2638}
2639
2640/// One part of an interpolated string (v0.43, ADR 0075). An
2641/// [`ExprKind::InterpStr`] holds an alternating run of these.
2642#[derive(Debug, Clone)]
2643pub enum InterpPart {
2644    /// Literal text between holes, with escapes already resolved.
2645    Chunk(String),
2646    /// An interpolated expression `\(expr)`. Type-checked by the hole rule
2647    /// (base scalars only; see the checker) and lowered into a template-
2648    /// literal `${…}` slot.
2649    Hole(Box<Expr>),
2650}
2651
2652/// One field-initialiser inside a record construction expression:
2653/// either `name: expr` or the shorthand `name` (which requires a binding
2654/// of the same name in scope and uses its value).
2655#[derive(Debug, Clone)]
2656pub struct FieldInit {
2657    pub name: Ident,
2658    /// `None` means shorthand — the field's value is the same-named binding.
2659    pub value: Option<Expr>,
2660    pub span: Span,
2661}
2662
2663/// One arm of a `match` expression: `pattern => body` or, with a guard,
2664/// `pattern if guard => body` (guard added in the nested-patterns increment,
2665/// ADR 0169). A guarded arm matches only when the pattern matches **and** the
2666/// `Bool` guard evaluates true; it never contributes to exhaustiveness.
2667#[derive(Debug, Clone)]
2668pub struct MatchArm {
2669    pub pattern: Pattern,
2670    /// Optional `if <Bool-expr>` guard between the pattern and `=>`.
2671    pub guard: Option<Expr>,
2672    pub body: MatchBody,
2673    pub span: Span,
2674}
2675
2676/// The right-hand side of a match arm — either a single expression or
2677/// a block.
2678#[derive(Debug, Clone)]
2679pub enum MatchBody {
2680    Expr(Expr),
2681    Block(Block),
2682}
2683
2684impl MatchBody {
2685    pub fn span(&self) -> Span {
2686        match self {
2687            MatchBody::Expr(e) => e.span,
2688            MatchBody::Block(b) => b.span,
2689        }
2690    }
2691}
2692
2693/// A pattern (v0.2 §3.8). Patterns appear in `match` arms and as the
2694/// right-hand side of the `is` operator.
2695#[derive(Debug, Clone)]
2696pub enum Pattern {
2697    /// `_` — matches any value, no bindings.
2698    Wildcard(Span),
2699    /// A lowercase identifier — binds the whole value to `name` and matches
2700    /// anything (ADR 0169). At the top of a `match` arm it binds the scrutinee
2701    /// (`n if n > 0 => …`); inside a payload position it binds the field
2702    /// (`Some(user)`). The uppercase-led counterpart is a nullary [`Pattern::Variant`].
2703    Binding(Ident),
2704    /// A literal pattern — `31`, `"english"`, `true` (v0.130 §2.3.4). Matches a
2705    /// primitive scrutinee (`Int`/`String`/`Bool`) by value equality. The
2706    /// admitted set mirrors ADR 0001's closed literal set (integers — including
2707    /// a leading unary minus — strings, and booleans); `Float`/`()` are not
2708    /// admitted as patterns.
2709    Literal { value: LiteralValue, span: Span },
2710    /// `Variant` or `Variant(bindings)` or `TypeName.Variant(bindings)`. Each
2711    /// payload binding is itself a [`Pattern`] (ADR 0169), so payloads nest:
2712    /// `Some(Ok(x))`, `Err(PollClosed)`.
2713    Variant {
2714        /// Optional qualifier: `TypeName.Variant`.
2715        type_name: Option<Ident>,
2716        /// The variant name.
2717        variant: Ident,
2718        /// Payload bindings (empty for nullary variants).
2719        bindings: Vec<PatternBinding>,
2720        span: Span,
2721    },
2722    /// `p 'where' refinement-predicate` — a refinement guard on a pattern
2723    /// (#472). Matches when `inner` matches *and* the scrutinee satisfies
2724    /// `predicate` at runtime. v1 admits only `Wildcard` as `inner` (no
2725    /// binding form yet); refutable — never counts toward exhaustiveness or
2726    /// as a catch-all arm, the same treatment as an `if` guard (§2.3.4).
2727    Refined {
2728        inner: Box<Pattern>,
2729        predicate: Refinement,
2730        span: Span,
2731    },
2732    /// `p₁ | p₂ | … | pₙ` — an or-pattern (#474 §2.3.4): matches if any
2733    /// alternative matches. Left-associative `|`, flattened by the parser's
2734    /// chain fold into one `Vec` — an alternative is always a leaf
2735    /// (`Wildcard`/`Binding`/`Literal`/`Variant`), never itself an `Or`
2736    /// (there is no parenthesized-pattern syntax to nest one inside another).
2737    /// Well-typedness (checked, not parsed): every alternative binds the same
2738    /// set of names, a name shared across alternatives has the same type
2739    /// (including refinement) in each, and every alternative matches the same
2740    /// value type.
2741    Or(Vec<Pattern>, Span),
2742}
2743
2744/// The value carried by a [`Pattern::Literal`]. A closed set (ADR 0001):
2745/// integer, string, and boolean. Kept distinct from [`ExprKind`] so patterns
2746/// carry only what they can actually match, and so it is `Eq`/`Hash` for the
2747/// duplicate-arm check.
2748#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2749pub enum LiteralValue {
2750    Int(i64),
2751    Str(String),
2752    Bool(bool),
2753}
2754
2755impl LiteralValue {
2756    /// A human-readable rendering for diagnostics (`31`, `"english"`, `true`).
2757    pub fn describe(&self) -> String {
2758        match self {
2759            LiteralValue::Int(n) => n.to_string(),
2760            LiteralValue::Str(s) => format!("{s:?}"),
2761            LiteralValue::Bool(b) => b.to_string(),
2762        }
2763    }
2764}
2765
2766impl Pattern {
2767    pub fn span(&self) -> Span {
2768        match self {
2769            Pattern::Wildcard(s) => *s,
2770            Pattern::Binding(id) => id.span,
2771            Pattern::Literal { span, .. } => *span,
2772            Pattern::Variant { span, .. } => *span,
2773            Pattern::Refined { span, .. } => *span,
2774            Pattern::Or(_, span) => *span,
2775        }
2776    }
2777
2778    /// Every identifier this pattern binds into scope, recursively (`_` and
2779    /// nullary variants bind nothing). Used by the resolver and the checker to
2780    /// populate an arm's scope, and by the guard to see the arm's bindings.
2781    ///
2782    /// For [`Pattern::Or`] this returns the *first* alternative's names — the
2783    /// checker separately verifies (#474 Rule 1) that every alternative binds
2784    /// the same set, so this is a defensive default when that rule is
2785    /// violated, not a semantic choice among alternatives.
2786    pub fn bound_names(&self) -> Vec<&Ident> {
2787        match self {
2788            Pattern::Wildcard(_) | Pattern::Literal { .. } => Vec::new(),
2789            Pattern::Binding(id) => vec![id],
2790            Pattern::Variant { bindings, .. } => bindings
2791                .iter()
2792                .flat_map(|b| b.pattern().bound_names())
2793                .collect(),
2794            Pattern::Refined { inner, .. } => inner.bound_names(),
2795            Pattern::Or(alts, _) => alts.first().map(Pattern::bound_names).unwrap_or_default(),
2796        }
2797    }
2798
2799    /// True when this pattern matches every value and binds nothing — a bare
2800    /// `_`. A [`Pattern::Binding`] also matches everything but *does* bind, so it
2801    /// is not a pure wildcard.
2802    pub fn is_wildcard(&self) -> bool {
2803        matches!(self, Pattern::Wildcard(_))
2804    }
2805
2806    /// True when this pattern matches every value (a `_` or a name binding),
2807    /// i.e. it is irrefutable and covers the position for exhaustiveness. An
2808    /// [`Pattern::Or`] is irrefutable when any alternative is — `_` in any
2809    /// position already makes the whole pattern match everything.
2810    pub fn is_irrefutable(&self) -> bool {
2811        match self {
2812            Pattern::Wildcard(_) | Pattern::Binding(_) => true,
2813            Pattern::Or(alts, _) => alts.iter().any(Pattern::is_irrefutable),
2814            _ => false,
2815        }
2816    }
2817}
2818
2819/// A single binding inside a variant pattern. Two surface forms:
2820/// `pattern` (positional — match the i-th payload field) and
2821/// `fieldName: pattern` (named — match the named payload field). The matched
2822/// sub-`pattern` is a full [`Pattern`] (ADR 0169), so a plain `name` is a
2823/// [`Pattern::Binding`], `_` a [`Pattern::Wildcard`], and `Ok(x)` a nested
2824/// [`Pattern::Variant`].
2825#[derive(Debug, Clone)]
2826pub struct PatternBinding {
2827    /// Source form: positional or named.
2828    pub kind: PatternBindingKind,
2829    pub span: Span,
2830}
2831
2832#[derive(Debug, Clone)]
2833pub enum PatternBindingKind {
2834    /// `pattern` (e.g. `x`, `_`, `Ok(v)`): match the payload field at this position.
2835    Positional { pattern: Pattern },
2836    /// `field: pattern`: match the named payload field against `pattern`.
2837    Named { field: Ident, pattern: Pattern },
2838}
2839
2840impl PatternBinding {
2841    /// The sub-pattern this binding matches its payload field against.
2842    pub fn pattern(&self) -> &Pattern {
2843        match &self.kind {
2844            PatternBindingKind::Positional { pattern } => pattern,
2845            PatternBindingKind::Named { pattern, .. } => pattern,
2846        }
2847    }
2848
2849    /// True when this binding discards its field (`_` or `field: _`) — a pure
2850    /// wildcard sub-pattern that binds nothing.
2851    pub fn is_wildcard(&self) -> bool {
2852        self.pattern().is_wildcard()
2853    }
2854}
2855
2856#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2857pub enum BinOp {
2858    /// `P implies Q` — logical implication (v0.80). Desugars to `!P || Q`; sits
2859    /// at the lowest precedence (below `||`). Reads directionally (P → Q).
2860    Implies,
2861    Or,
2862    And,
2863    Eq,
2864    NotEq,
2865    Lt,
2866    LtEq,
2867    Gt,
2868    GtEq,
2869    Add,
2870    Sub,
2871    Mul,
2872    Div,
2873}
2874
2875impl BinOp {
2876    pub fn name(self) -> &'static str {
2877        match self {
2878            BinOp::Implies => "implies",
2879            BinOp::Or => "||",
2880            BinOp::And => "&&",
2881            BinOp::Eq => "==",
2882            BinOp::NotEq => "!=",
2883            BinOp::Lt => "<",
2884            BinOp::LtEq => "<=",
2885            BinOp::Gt => ">",
2886            BinOp::GtEq => ">=",
2887            BinOp::Add => "+",
2888            BinOp::Sub => "-",
2889            BinOp::Mul => "*",
2890            BinOp::Div => "/",
2891        }
2892    }
2893}
2894
2895#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2896pub enum UnaryOp {
2897    Neg,
2898    Not,
2899}
2900
2901impl UnaryOp {
2902    pub fn name(self) -> &'static str {
2903        match self {
2904            UnaryOp::Neg => "-",
2905            UnaryOp::Not => "!",
2906        }
2907    }
2908}
2909
2910#[cfg(test)]
2911mod size_tests {
2912    use super::*;
2913
2914    /// Finding #31: boxing `ExprKind::Observation`'s payload and
2915    /// `ExprKind::Is`'s pattern field took `Expr` from 176 to 128 bytes on
2916    /// this target (the module-level `const _` assertion is the real pin;
2917    /// this test just makes the before/after concrete and fails loudly if a
2918    /// future change silently regresses the win rather than tripping the
2919    /// `<= 128` ceiling by enough to notice).
2920    #[test]
2921    fn expr_is_smaller_than_before_the_boxing() {
2922        assert!(
2923            std::mem::size_of::<Expr>() < 176,
2924            "Expr should be smaller than its pre-#31 size of 176 bytes"
2925        );
2926    }
2927}