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    Test(TestDecl),
208    /// v0.16: a `test integration "name" { wires … }` multi-Worker integration
209    /// test. Its `name()` is synthesised from the suite name.
210    Integration(IntegrationDecl),
211    /// v0.17: an `adapter` unit — the host boundary (capability contract +
212    /// external binding).
213    Adapter(AdapterDecl),
214}
215
216impl SourceUnit {
217    pub fn name(&self) -> &QualifiedName {
218        match self {
219            SourceUnit::Commons(c) => &c.name,
220            SourceUnit::Context(c) => &c.name,
221            SourceUnit::Test(t) => &t.target,
222            SourceUnit::Integration(i) => &i.name,
223            SourceUnit::Adapter(a) => &a.name,
224        }
225    }
226
227    pub fn span(&self) -> Span {
228        match self {
229            SourceUnit::Commons(c) => c.span,
230            SourceUnit::Context(c) => c.span,
231            SourceUnit::Test(t) => t.span,
232            SourceUnit::Integration(i) => i.span,
233            SourceUnit::Adapter(a) => a.span,
234        }
235    }
236
237    pub fn kind_name(&self) -> &'static str {
238        match self {
239            SourceUnit::Commons(_) => "commons",
240            SourceUnit::Context(_) => "context",
241            SourceUnit::Test(_) => "test",
242            SourceUnit::Integration(_) => "integration test",
243            SourceUnit::Adapter(_) => "adapter",
244        }
245    }
246}
247
248/// A `test <qualified-name> { ... }` declaration (v0.7 §3.1).
249///
250/// A test targets a commons or context by qualified name and bundles a set of
251/// test cases plus optional mock declarations. As with commons and contexts, a
252/// test may be split across multiple files (fragment form).
253#[derive(Debug, Clone)]
254pub struct TestDecl {
255    /// The targeted commons or context.
256    pub target: QualifiedName,
257    /// `uses` clauses brought in by this test fragment.
258    pub uses: Vec<UsesDecl>,
259    /// Provider or consumed-context mocks declared for the test.
260    pub mocks: Vec<MockDecl>,
261    /// The individual test cases.
262    pub cases: Vec<TestCase>,
263    /// Surface form: brace-delimited body or headerless fragment.
264    pub form: CommonsForm,
265    /// Optional documentation block attached to the test declaration.
266    pub documentation: Option<String>,
267    pub span: Span,
268    pub trivia: Trivia,
269    pub trailing_comments: Vec<String>,
270}
271
272/// A `mocks Name = Impl { ops }` declaration inside a test body (v0.7 §3.2).
273#[derive(Debug, Clone)]
274pub struct MockDecl {
275    /// The capability or consumed-context alias being mocked.
276    pub target_name: Ident,
277    /// The implementation identifier (used as the TypeScript class name).
278    pub impl_name: Ident,
279    /// One operation per mock body entry.
280    pub ops: Vec<MockOp>,
281    pub documentation: Option<String>,
282    pub span: Span,
283    pub trivia: Trivia,
284}
285
286/// One operation inside a mock declaration: `fn name(params) -> T { body }`.
287#[derive(Debug, Clone)]
288pub struct MockOp {
289    pub name: Ident,
290    pub params: Vec<Param>,
291    pub return_type: TypeRef,
292    pub body: Block,
293    pub span: Span,
294    pub trivia: Trivia,
295}
296
297/// A `test "name" { body }` block inside a test declaration (v0.7 §3.3).
298#[derive(Debug, Clone)]
299pub struct TestCase {
300    /// The test name, taken from the string literal.
301    pub name: String,
302    /// The span of the string literal — used for diagnostics and runtime
303    /// failure reports.
304    pub name_span: Span,
305    pub body: Block,
306    pub documentation: Option<String>,
307    pub span: Span,
308    pub trivia: Trivia,
309}
310
311/// A `test integration "name" { wires C1, C2, … ; cases }` declaration
312/// (v0.16 §3.1). Unlike a unit test, an integration test names a *set* of
313/// participating contexts (`wires`), stands each up as its own Worker, and
314/// exercises a flow across the real Worker boundary. It carries no `mocks`.
315#[derive(Debug, Clone)]
316pub struct IntegrationDecl {
317    /// The suite name, taken from the string literal after `integration`.
318    pub suite: String,
319    /// The span of the suite-name literal — used in diagnostics and reports.
320    pub suite_span: Span,
321    /// A synthesised qualified name (`integration <suite>`), so the unit shares
322    /// the `SourceUnit::name()` shape. Not user-written.
323    pub name: QualifiedName,
324    /// The participating contexts, in declaration order (≥ 2, validated later).
325    pub participants: Vec<QualifiedName>,
326    /// `uses` clauses bringing commons into the case bodies.
327    pub uses: Vec<UsesDecl>,
328    /// The individual test cases.
329    pub cases: Vec<TestCase>,
330    /// Surface form: brace-delimited body or headerless fragment.
331    pub form: CommonsForm,
332    pub documentation: Option<String>,
333    pub span: Span,
334    pub trivia: Trivia,
335    pub trailing_comments: Vec<String>,
336}
337
338/// A capability reference in a `given` clause (v0.15 §3.2). A bare name is a
339/// local capability (`given Cap`); a dotted name refers to a capability a
340/// consumed context provides (`given B.Cap` / `given Alias.Cap`).
341#[derive(Debug, Clone)]
342pub struct CapRef {
343    /// `None` for a local capability; `Some(prefix)` for a cross-context
344    /// reference where `prefix` is a consumed-context qualified name or alias.
345    pub context: Option<QualifiedName>,
346    /// The capability's simple name (also the local deps key).
347    pub name: Ident,
348    pub span: Span,
349}
350
351impl CapRef {
352    /// The local deps key / capability simple name (e.g. `Clock`).
353    pub fn key(&self) -> &str {
354        &self.name.name
355    }
356
357    /// True when this references a capability provided by a consumed context.
358    pub fn is_cross_context(&self) -> bool {
359        self.context.is_some()
360    }
361
362    /// The cross-context prefix (consumed-context qualified name or alias) as
363    /// a dotted string, if any.
364    pub fn prefix(&self) -> Option<String> {
365        self.context.as_ref().map(|q| q.joined())
366    }
367}
368
369/// A dotted name like `fitness.units`.
370#[derive(Debug, Clone)]
371pub struct QualifiedName {
372    pub parts: Vec<Ident>,
373    pub span: Span,
374}
375
376impl QualifiedName {
377    pub fn joined(&self) -> String {
378        self.parts
379            .iter()
380            .map(|p| p.name.as_str())
381            .collect::<Vec<_>>()
382            .join(".")
383    }
384}
385
386#[derive(Debug, Clone)]
387pub enum CommonsItem {
388    Type(TypeDecl),
389    Fn(FnDecl),
390    /// `capability Name { fn op(...) -> T ... }` (v0.5; contexts only).
391    Capability(CapabilityDecl),
392    /// `provides Cap = ProviderName { fn op(...) -> T { ... } ... }` (v0.5).
393    Provider(ProviderDecl),
394    /// `service Name { on call(...) -> T { ... } ... }` (v0.5).
395    Service(ServiceDecl),
396    /// `agent Name { key id: T; state { ... }; on call ... }` (v0.5).
397    Agent(AgentDecl),
398    /// `actor Name { auth = Scheme, identity = T }` (v0.45). A nominal boundary
399    /// contract consumed by a handler's `by` clause; not a runnable entity.
400    Actor(ActorDecl),
401}
402
403impl CommonsItem {
404    pub fn name(&self) -> &Ident {
405        match self {
406            CommonsItem::Type(t) => &t.name,
407            CommonsItem::Fn(f) => f.name.ident(),
408            CommonsItem::Capability(c) => &c.name,
409            CommonsItem::Provider(p) => &p.provider_name,
410            CommonsItem::Service(s) => &s.name,
411            CommonsItem::Agent(a) => &a.name,
412            CommonsItem::Actor(a) => &a.name,
413        }
414    }
415}
416
417/// A capability declaration (v0.5 §3.3). Capabilities are interface-like
418/// contracts for external dependencies, used inside contexts. They may only
419/// appear inside a `context` declaration.
420#[derive(Debug, Clone)]
421pub struct CapabilityDecl {
422    pub name: Ident,
423    pub ops: Vec<CapabilityOp>,
424    pub documentation: Option<String>,
425    pub span: Span,
426    pub trivia: Trivia,
427}
428
429/// One operation in a capability (signature only; no body).
430#[derive(Debug, Clone)]
431pub struct CapabilityOp {
432    pub name: Ident,
433    pub params: Vec<Param>,
434    pub return_type: TypeRef,
435    pub documentation: Option<String>,
436    pub span: Span,
437    pub trivia: Trivia,
438}
439
440/// A provider declaration (v0.5 §3.4). Supplies an implementation for a
441/// capability.
442#[derive(Debug, Clone)]
443pub struct ProviderDecl {
444    /// The capability being implemented.
445    pub capability: Ident,
446    /// The provider's identifier (used in tests/config to select impls).
447    pub provider_name: Ident,
448    /// v0.12: capabilities this provider depends on (`provides X = Impl given
449    /// Y, Z { … }`). The provider's operation bodies may use these. v0.15:
450    /// a dependency may be a cross-context capability (`given B.Cap`).
451    pub given: Vec<CapRef>,
452    pub ops: Vec<ProviderOp>,
453    /// v0.17: an *external* provider — `provides Cap = Name` with **no** brace
454    /// block — inside an adapter, supplied by the adapter's binding rather than
455    /// a Bynk body. When `true`, `ops` is empty and the emitter produces no
456    /// class. The absence of the brace block (not an empty one) is the signal.
457    pub external: bool,
458    pub documentation: Option<String>,
459    pub span: Span,
460    pub trivia: Trivia,
461}
462
463/// One operation in a provider (signature plus body).
464#[derive(Debug, Clone)]
465pub struct ProviderOp {
466    pub name: Ident,
467    pub params: Vec<Param>,
468    pub return_type: TypeRef,
469    pub body: Block,
470    pub span: Span,
471    pub trivia: Trivia,
472}
473
474/// A service declaration (v0.5 §3.5). Services are the boundary interface
475/// of a context.
476#[derive(Debug, Clone)]
477pub struct ServiceDecl {
478    pub name: Ident,
479    /// The protocol the service conforms to, from the `from <protocol>` header
480    /// clause (v0.44). `Call` when there is no clause.
481    pub protocol: ServiceProtocol,
482    pub handlers: Vec<Handler>,
483    pub documentation: Option<String>,
484    pub span: Span,
485    pub trivia: Trivia,
486}
487
488/// The protocol a service conforms to — declared on the header via
489/// `from <protocol>` (v0.44). `Call` is the default (no `from` clause): a
490/// contract-mediated internal-RPC surface, not a wire protocol. Multi-endpoint
491/// protocols (`Http`, `Cron`) carry no binding — the endpoint lives on each
492/// handler; single-binding `Queue` carries its queue name.
493#[derive(Debug, Clone, PartialEq, Eq)]
494pub enum ServiceProtocol {
495    /// No `from` clause: the service holds `on call` handlers only.
496    Call,
497    /// `from http` — many routes; each handler is `on <Method>("route")`.
498    Http,
499    /// `from cron` — many schedules; each handler is `on schedule("expr")`.
500    Cron,
501    /// `from queue("name")` — one bound queue; handlers are `on message(...)`.
502    Queue { name: String },
503}
504
505/// An agent declaration (v0.5 §3.6). Agents are state-bearing entities
506/// with their own handlers.
507#[derive(Debug, Clone)]
508pub struct AgentDecl {
509    pub name: Ident,
510    /// `key id: Type` — the identifier-typed value identifying instances.
511    pub key_name: Ident,
512    pub key_type: TypeRef,
513    /// State fields — a record-shaped declaration of persistent state.
514    pub state_fields: Vec<RecordField>,
515    pub state_span: Span,
516    /// Invariants (v0.80 §14) — universally-quantified predicates over the
517    /// agent's state record. The phase sits between the `state { }` block and
518    /// the handlers; each is checked against every value passed to `commit`.
519    pub invariants: Vec<Invariant>,
520    pub handlers: Vec<Handler>,
521    pub documentation: Option<String>,
522    pub span: Span,
523    pub trivia: Trivia,
524}
525
526/// An agent invariant (v0.80 §14). A named predicate over the agent's state
527/// fields that must hold of every committed state; a commit that would violate
528/// it faults (`InvariantViolation`) before the state is persisted. The
529/// predicate references state fields by bare name, mirroring the design-notes
530/// worked examples (`status == Paid implies paymentRef.isSome()`).
531#[derive(Debug, Clone)]
532pub struct Invariant {
533    pub name: Ident,
534    /// The predicate expression — an ordinary `Bool`-typed expression over the
535    /// state fields, plus `implies` and `is`. The parsed-predicate-on-a-
536    /// declaration shape mirrors [`ActorRefinement::predicate`].
537    pub predicate: Expr,
538    pub documentation: Option<String>,
539    pub span: Span,
540    pub trivia: Trivia,
541}
542
543/// An actor declaration (v0.45 §3.7). An actor is a nominal *contract type*
544/// describing an external party at a boundary — not a runnable entity. A
545/// handler consumes an actor on its `by` clause; the boundary verifies the
546/// declared `auth` scheme and mints a sealed identity (`name.identity`).
547#[derive(Debug, Clone)]
548pub struct ActorDecl {
549    pub name: Ident,
550    /// The authentication scheme from `auth = <Scheme>`, stored as the raw
551    /// identifier. The checker classifies it: `None`/`Internal`/`Bearer` are
552    /// admitted; `Signature` is reserved-and-rejected
553    /// (`bynk.actor.scheme_unsupported`); anything else is
554    /// `bynk.actor.unknown_scheme`. `None` for the refinement form.
555    pub auth: Option<Ident>,
556    /// The scheme's keyed config from `auth = Scheme(key = value, …)` (v0.47
557    /// `Bearer(secret = "…")`; v0.51 generalised for `Signature(secret, header,
558    /// timestamp?, tolerance?)`). Empty for schemes/forms with no config. The
559    /// checker validates which keys each scheme requires/allows.
560    pub auth_config: Vec<SchemeArg>,
561    /// The optional identity type from `, identity = <T>`. Absent ⇒ the
562    /// scheme default (`()` for `None`; a sealed `CallerId` for the `Internal`
563    /// `on call` channel, `()` for other `Internal` channels).
564    pub identity: Option<TypeRef>,
565    /// The reserved-and-rejected refinement form `actor Admin = Base where p`
566    /// (Q3). Parsed so the grammar is fixed now; the checker emits
567    /// `bynk.actor.refinement_unsupported`.
568    pub refinement: Option<ActorRefinement>,
569    pub documentation: Option<String>,
570    pub span: Span,
571    pub trivia: Trivia,
572}
573
574impl ActorDecl {
575    /// The value of a scheme config arg by key, if present (e.g. `secret`,
576    /// `header`).
577    pub fn scheme_arg(&self, key: &str) -> Option<&SchemeArg> {
578        self.auth_config.iter().find(|a| a.key.name == key)
579    }
580}
581
582/// One `key = value` argument in a scheme config (`Scheme(key = value, …)`).
583#[derive(Debug, Clone)]
584pub struct SchemeArg {
585    pub key: Ident,
586    pub value: SchemeArgValue,
587    /// Span of the value, for diagnostics.
588    pub span: Span,
589}
590
591/// A scheme config arg value — a string literal or an integer.
592#[derive(Debug, Clone)]
593pub enum SchemeArgValue {
594    Str(String),
595    Int(i64),
596}
597
598impl SchemeArgValue {
599    pub fn as_str(&self) -> Option<&str> {
600        match self {
601            SchemeArgValue::Str(s) => Some(s),
602            SchemeArgValue::Int(_) => None,
603        }
604    }
605    pub fn as_int(&self) -> Option<i64> {
606        match self {
607            SchemeArgValue::Int(n) => Some(*n),
608            SchemeArgValue::Str(_) => None,
609        }
610    }
611}
612
613/// The reserved refinement form `actor Admin = User where <predicate>` (Q3).
614/// Parsed in Foundations so the grammar is fixed; admission is a later slice.
615#[derive(Debug, Clone)]
616pub struct ActorRefinement {
617    /// The base actor being refined.
618    pub base: Ident,
619    /// The `where` predicate. Parsed but not yet checked.
620    pub predicate: Expr,
621    pub span: Span,
622}
623
624/// The `by (<binder>:)? <Actor>` clause on a handler (v0.45; binder optional in
625/// v0.50). Names the actor contract the handler consumes; when a `binder` is
626/// given, the verified identity binds to it and is read as `binder.identity`.
627/// Omitting the binder (`by <Actor>`) declares-and-verifies the contract without
628/// capturing the identity — for anonymous or verify-and-discard handlers. Sits
629/// after the protocol config and before the parameters.
630#[derive(Debug, Clone)]
631pub struct ByClause {
632    /// The identity binder, if the handler consumes the identity. `None` for the
633    /// binder-less `by <Actor>` form. Required when `actors` names more than one
634    /// (a sum is resolved by matching on the bound actor).
635    pub binder: Option<Ident>,
636    /// The actor contract(s) referenced — each a local actor decl or a prelude
637    /// actor. A single name is the ordinary single-actor handler; more than one
638    /// (`by who: A | B`, v0.52) is an **ordered sum of peer actors** resolved
639    /// first-wins, the body matching on the resolved actor. Always non-empty.
640    pub actors: Vec<Ident>,
641    pub span: Span,
642}
643
644impl ByClause {
645    /// The first (and, for a single-actor handler, only) actor contract named.
646    pub fn primary(&self) -> &Ident {
647        &self.actors[0]
648    }
649    /// Whether this `by` clause names an ordered sum of peer actors (`A | B`).
650    pub fn is_sum(&self) -> bool {
651        self.actors.len() > 1
652    }
653}
654
655/// A handler block — `on call(args) -> T given C1, C2 { body }`.
656/// Used by both services and agents.
657#[derive(Debug, Clone)]
658pub struct Handler {
659    pub kind: HandlerKind,
660    /// For agent handlers, the method-style handler name (e.g.
661    /// `on call addItem(...)`). For service handlers, this is None (just
662    /// `on call(...)`).
663    pub method_name: Option<Ident>,
664    /// The `by <binder>: <Actor>` clause (v0.45), if present. Service handlers
665    /// only; an absent clause inherits the protocol's default actor.
666    pub by_clause: Option<ByClause>,
667    pub params: Vec<Param>,
668    pub return_type: TypeRef,
669    pub given: Vec<CapRef>,
670    pub body: Block,
671    pub documentation: Option<String>,
672    pub span: Span,
673    pub trivia: Trivia,
674}
675
676#[derive(Debug, Clone, PartialEq, Eq)]
677pub enum HandlerKind {
678    /// `on call(...)` — typed RPC (the only kind in v0.5).
679    Call,
680    /// `on http METHOD "path"` — external-facing HTTP route (v0.9).
681    Http { method: HttpMethod, path: String },
682    /// `on cron "expr"` — scheduled task; `expr` is a 5-field cron
683    /// expression (v0.10a).
684    Cron { expr: String },
685    /// `on message(m: T)` — a message off the service's bound queue. The queue
686    /// binding lives on the service's `ServiceProtocol::Queue` (v0.44).
687    Message,
688}
689
690/// HTTP methods supported by `on http` handlers (v0.9).
691#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
692pub enum HttpMethod {
693    Get,
694    Post,
695    Put,
696    Patch,
697    Delete,
698}
699
700impl HttpMethod {
701    pub fn as_str(self) -> &'static str {
702        match self {
703            HttpMethod::Get => "GET",
704            HttpMethod::Post => "POST",
705            HttpMethod::Put => "PUT",
706            HttpMethod::Patch => "PATCH",
707            HttpMethod::Delete => "DELETE",
708        }
709    }
710
711    pub fn from_ident(s: &str) -> Option<HttpMethod> {
712        match s {
713            "GET" => Some(HttpMethod::Get),
714            "POST" => Some(HttpMethod::Post),
715            "PUT" => Some(HttpMethod::Put),
716            "PATCH" => Some(HttpMethod::Patch),
717            "DELETE" => Some(HttpMethod::Delete),
718            _ => None,
719        }
720    }
721
722    /// True if this method conventionally has no request body.
723    pub fn forbids_body(self) -> bool {
724        matches!(self, HttpMethod::Get | HttpMethod::Delete)
725    }
726}
727
728/// Payload shape of an `HttpResult[T]` variant (v0.9 §3.3).
729#[derive(Debug, Clone, Copy, PartialEq, Eq)]
730pub enum HttpVariantPayload {
731    /// No payload (e.g. `NoContent`, `Unauthorized`).
732    None,
733    /// Carries a value of the `HttpResult` type parameter `T`.
734    Value,
735    /// Carries a `String` message (e.g. `BadRequest`, `Conflict`).
736    Message,
737}
738
739/// One variant of the built-in `HttpResult[T]` sum (v0.9 §3.3).
740#[derive(Debug, Clone, Copy)]
741pub struct HttpVariant {
742    pub name: &'static str,
743    pub payload: HttpVariantPayload,
744    pub status: u16,
745}
746
747/// All `HttpResult[T]` variants, in declaration order.
748pub const HTTP_VARIANTS: &[HttpVariant] = &[
749    HttpVariant {
750        name: "Ok",
751        payload: HttpVariantPayload::Value,
752        status: 200,
753    },
754    HttpVariant {
755        name: "Created",
756        payload: HttpVariantPayload::Value,
757        status: 201,
758    },
759    HttpVariant {
760        name: "NoContent",
761        payload: HttpVariantPayload::None,
762        status: 204,
763    },
764    HttpVariant {
765        name: "BadRequest",
766        payload: HttpVariantPayload::Message,
767        status: 400,
768    },
769    HttpVariant {
770        name: "Unauthorized",
771        payload: HttpVariantPayload::None,
772        status: 401,
773    },
774    HttpVariant {
775        name: "Forbidden",
776        payload: HttpVariantPayload::None,
777        status: 403,
778    },
779    HttpVariant {
780        name: "NotFound",
781        payload: HttpVariantPayload::None,
782        status: 404,
783    },
784    HttpVariant {
785        name: "Conflict",
786        payload: HttpVariantPayload::Message,
787        status: 409,
788    },
789    HttpVariant {
790        name: "UnprocessableEntity",
791        payload: HttpVariantPayload::Message,
792        status: 422,
793    },
794    HttpVariant {
795        name: "ServerError",
796        payload: HttpVariantPayload::Message,
797        status: 500,
798    },
799];
800
801/// Find an `HttpResult[T]` variant by name. Returns the variant info or
802/// `None` if the name doesn't match.
803pub fn http_variant(name: &str) -> Option<HttpVariant> {
804    HTTP_VARIANTS.iter().copied().find(|v| v.name == name)
805}
806
807/// Payload shape of a `QueueResult` variant (v0.44). Non-generic — a verdict
808/// carries no value; `Retry` carries a `String` reason for the log path.
809#[derive(Debug, Clone, Copy, PartialEq, Eq)]
810pub enum QueueVariantPayload {
811    /// No payload (`Ack`).
812    None,
813    /// Carries a `String` reason (`Retry`).
814    Message,
815}
816
817/// One variant of the built-in `QueueResult` sum (v0.44).
818#[derive(Debug, Clone, Copy)]
819pub struct QueueVariant {
820    pub name: &'static str,
821    pub payload: QueueVariantPayload,
822}
823
824/// All `QueueResult` variants, in declaration order. `Ack` confirms the
825/// message; `Retry` redelivers it, carrying a reason for observability.
826pub const QUEUE_VARIANTS: &[QueueVariant] = &[
827    QueueVariant {
828        name: "Ack",
829        payload: QueueVariantPayload::None,
830    },
831    QueueVariant {
832        name: "Retry",
833        payload: QueueVariantPayload::Message,
834    },
835];
836
837/// Find a `QueueResult` variant by name.
838pub fn queue_variant(name: &str) -> Option<QueueVariant> {
839    QUEUE_VARIANTS.iter().copied().find(|v| v.name == name)
840}
841
842#[derive(Debug, Clone)]
843pub struct TypeDecl {
844    pub name: Ident,
845    pub body: TypeBody,
846    /// Documentation block attached to this declaration (v0.3).
847    pub documentation: Option<String>,
848    pub span: Span,
849    pub trivia: Trivia,
850}
851
852/// The right-hand side of a `type` declaration. In v0/v0.1 only the
853/// `Refined` variant existed; v0.2 adds records and sums; v0.3 adds opaque.
854#[derive(Debug, Clone)]
855pub enum TypeBody {
856    /// Refined base type: `BaseType where refinement`.
857    Refined {
858        base: BaseType,
859        base_span: Span,
860        refinement: Option<Refinement>,
861    },
862    /// Record type: `{ field: T where ..., ... }`.
863    Record(RecordBody),
864    /// Sum type: pipe-form variants or `enum { ... }` shorthand.
865    Sum(SumBody),
866    /// Opaque base type: `opaque BaseType (where refinement)?` (v0.3 §3.4).
867    /// Identity is nominal; the base type is hidden outside the defining commons.
868    Opaque {
869        base: BaseType,
870        base_span: Span,
871        refinement: Option<Refinement>,
872    },
873}
874
875/// Body of a record-type declaration (v0.2 §3.1).
876#[derive(Debug, Clone)]
877pub struct RecordBody {
878    pub fields: Vec<RecordField>,
879    pub span: Span,
880}
881
882/// One field of a record type declaration. Each field may carry inline
883/// refinement, which is enforced at construction time on the field's value.
884#[derive(Debug, Clone)]
885pub struct RecordField {
886    pub name: Ident,
887    pub type_ref: TypeRef,
888    pub refinement: Option<Refinement>,
889    /// v0.11: an optional initial-value expression. Only meaningful on agent
890    /// `state` fields (the field's fresh-key value); ignored / rejected on
891    /// record-type fields by the checker.
892    pub init: Option<Expr>,
893    pub span: Span,
894}
895
896/// Body of a sum-type declaration (v0.2 §3.2).
897#[derive(Debug, Clone)]
898pub struct SumBody {
899    pub variants: Vec<Variant>,
900    pub span: Span,
901}
902
903/// One variant of a sum type. Variants may have payload fields; a
904/// payload-less variant is a simple tag.
905#[derive(Debug, Clone)]
906pub struct Variant {
907    pub name: Ident,
908    pub payload: Vec<VariantField>,
909    pub span: Span,
910}
911
912/// One payload field of a sum variant. Variant payload fields use named
913/// declarations like record fields, but do not carry refinement in v0.2.
914#[derive(Debug, Clone)]
915pub struct VariantField {
916    pub name: Ident,
917    pub type_ref: TypeRef,
918    pub span: Span,
919}
920
921#[derive(Debug, Clone, Copy, PartialEq, Eq)]
922pub enum BaseType {
923    Int,
924    String,
925    Bool,
926    Float,
927}
928
929impl BaseType {
930    pub fn name(self) -> &'static str {
931        match self {
932            BaseType::Int => "Int",
933            BaseType::String => "String",
934            BaseType::Bool => "Bool",
935            BaseType::Float => "Float",
936        }
937    }
938}
939
940/// An integer refinement bound (v0.40, ADR 0073): the parsed value plus the
941/// bound's source span (covering a leading `-`). Value-only beyond the span —
942/// ints have one canonical printed form, so the formatter stays idempotent
943/// without a stored lexeme. The span backs the `InRange`-swap quick-fix.
944#[derive(Debug, Clone)]
945pub struct IntBound {
946    pub value: i64,
947    pub span: Span,
948}
949
950/// A float refinement bound (v0.21): the parsed value plus the signed source
951/// lexeme (for byte-stable emission). v0.40 (ADR 0073): also the source span,
952/// for the `InRange`-swap quick-fix.
953#[derive(Debug, Clone)]
954pub struct FloatBound {
955    pub value: f64,
956    pub lexeme: String,
957    pub span: Span,
958}
959
960#[derive(Debug, Clone)]
961pub struct Refinement {
962    pub predicates: Vec<RefinementPred>,
963    pub span: Span,
964}
965
966#[derive(Debug, Clone)]
967pub struct RefinementPred {
968    pub kind: PredKind,
969    pub span: Span,
970}
971
972#[derive(Debug, Clone)]
973pub enum PredKind {
974    Matches(String),
975    InRange(IntBound, IntBound),
976    /// `InRange` with float bounds (v0.21) — a separate variant so every
977    /// `Int` refinement path stays untouched. Bounds keep their source
978    /// lexemes (including any sign) so emitted runtime checks are
979    /// byte-stable.
980    InRangeF(FloatBound, FloatBound),
981    MinLength(i64),
982    MaxLength(i64),
983    Length(i64),
984    NonNegative,
985    Positive,
986    NonEmpty,
987}
988
989impl PredKind {
990    pub fn name(&self) -> &'static str {
991        match self {
992            PredKind::Matches(_) => "Matches",
993            PredKind::InRange(..) | PredKind::InRangeF(..) => "InRange",
994            PredKind::MinLength(_) => "MinLength",
995            PredKind::MaxLength(_) => "MaxLength",
996            PredKind::Length(_) => "Length",
997            PredKind::NonNegative => "NonNegative",
998            PredKind::Positive => "Positive",
999            PredKind::NonEmpty => "NonEmpty",
1000        }
1001    }
1002}
1003
1004/// A function type parameter (v0.20a, `fn name[A, B](…)`). A struct rather
1005/// than a bare Ident so the ADR-0028 "bound-capable" promise is a later field
1006/// addition, not a representation change.
1007#[derive(Debug, Clone)]
1008pub struct TypeParam {
1009    pub name: Ident,
1010    pub span: Span,
1011}
1012
1013/// A lambda expression (v0.20a): `(params) => expr` or `(params) => { … }`.
1014/// `=>` is the value arrow (shared with `match`); param annotations are
1015/// optional where an expected function type supplies them.
1016#[derive(Debug, Clone)]
1017pub struct LambdaExpr {
1018    pub params: Vec<LambdaParam>,
1019    pub body: Box<Expr>,
1020    pub span: Span,
1021}
1022
1023/// A lambda parameter. A separate type from [`Param`] because its annotation
1024/// is optional — `Param.type_ref` stays mandatory at every signature site.
1025#[derive(Debug, Clone)]
1026pub struct LambdaParam {
1027    pub name: Ident,
1028    pub type_ref: Option<TypeRef>,
1029    pub span: Span,
1030}
1031
1032#[derive(Debug, Clone)]
1033pub struct FnDecl {
1034    /// v0.20a: `[A, B]` type parameters; empty for non-generic functions.
1035    pub type_params: Vec<TypeParam>,
1036    /// Free function or method (`TypeName.methodName`). See [`FnName`].
1037    pub name: FnName,
1038    pub params: Vec<Param>,
1039    pub return_type: TypeRef,
1040    pub body: Block,
1041    /// True when the first parameter is the special `self` parameter. Only
1042    /// valid for method declarations.
1043    pub has_self: bool,
1044    /// Documentation block attached to this declaration (v0.3).
1045    pub documentation: Option<String>,
1046    pub span: Span,
1047    pub trivia: Trivia,
1048}
1049
1050/// A function-declaration name: either a free function `f` or a method
1051/// `T.method` (v0.2 §3.6).
1052#[derive(Debug, Clone)]
1053pub enum FnName {
1054    /// `fn name(...)` — a free function.
1055    Free(Ident),
1056    /// `fn TypeName.methodName(...)` — a method attached to a type.
1057    Method {
1058        type_name: Ident,
1059        method_name: Ident,
1060    },
1061}
1062
1063impl FnName {
1064    /// The function's short name for diagnostics. For methods returns the
1065    /// method portion only; the type prefix is recovered via `type_name`.
1066    pub fn ident(&self) -> &Ident {
1067        match self {
1068            FnName::Free(id) => id,
1069            FnName::Method { method_name, .. } => method_name,
1070        }
1071    }
1072
1073    /// For methods, the attached type's identifier; `None` for free fns.
1074    pub fn type_name(&self) -> Option<&Ident> {
1075        match self {
1076            FnName::Free(_) => None,
1077            FnName::Method { type_name, .. } => Some(type_name),
1078        }
1079    }
1080
1081    /// The displayed full name (e.g., `Money.add` or `parseSku`).
1082    pub fn display(&self) -> String {
1083        match self {
1084            FnName::Free(id) => id.name.clone(),
1085            FnName::Method {
1086                type_name,
1087                method_name,
1088            } => format!("{}.{}", type_name.name, method_name.name),
1089        }
1090    }
1091}
1092
1093/// A brace-delimited block of statements ending in a tail expression
1094/// whose value is the block's value (spec v0.1 §3.1).
1095#[derive(Debug, Clone)]
1096pub struct Block {
1097    pub statements: Vec<Statement>,
1098    pub tail: Box<Expr>,
1099    pub span: Span,
1100    /// Line comments that appear between the last statement (or the
1101    /// opening brace) and the tail expression. Preserved here because
1102    /// expressions do not carry trivia in v1.1.
1103    pub tail_leading_comments: Vec<String>,
1104}
1105
1106/// Block-level statement.
1107#[derive(Debug, Clone)]
1108pub enum Statement {
1109    /// `let name (: T)? = expr` — pure binding (v0.1).
1110    Let(LetStmt),
1111    /// `let name (: T)? <- expr` — effectful binding (v0.5).
1112    EffectLet(LetStmt),
1113    /// `commit expr` — within an agent handler, declares the new persistent
1114    /// state (v0.5).
1115    Commit(CommitStmt),
1116    /// `assert expr` — verify a Bool expression at test runtime (v0.7).
1117    /// Only valid inside test case bodies.
1118    Assert(AssertStmt),
1119    /// `~> expr` — an asynchronous fire-and-forget send (v0.79). The caller does
1120    /// not await the reply; legal only when the reply is `Effect[()]`. No binder.
1121    Send(SendStmt),
1122}
1123
1124impl Statement {
1125    pub fn span(&self) -> Span {
1126        match self {
1127            Statement::Let(l) | Statement::EffectLet(l) => l.span,
1128            Statement::Commit(c) => c.span,
1129            Statement::Assert(a) => a.span,
1130            Statement::Send(s) => s.span,
1131        }
1132    }
1133}
1134
1135#[derive(Debug, Clone)]
1136pub struct AssertStmt {
1137    pub value: Expr,
1138    pub span: Span,
1139    pub trivia: Trivia,
1140}
1141
1142#[derive(Debug, Clone)]
1143pub struct LetStmt {
1144    pub name: Ident,
1145    pub type_annot: Option<TypeRef>,
1146    pub value: Expr,
1147    pub span: Span,
1148    pub trivia: Trivia,
1149}
1150
1151#[derive(Debug, Clone)]
1152pub struct CommitStmt {
1153    pub value: Expr,
1154    pub span: Span,
1155    pub trivia: Trivia,
1156}
1157
1158#[derive(Debug, Clone)]
1159pub struct SendStmt {
1160    /// The send target — a recipient call, e.g. `Logger.info(msg)`.
1161    pub value: Expr,
1162    pub span: Span,
1163    pub trivia: Trivia,
1164}
1165
1166#[derive(Debug, Clone)]
1167pub struct Param {
1168    pub name: Ident,
1169    pub type_ref: TypeRef,
1170    pub span: Span,
1171}
1172
1173#[derive(Debug, Clone)]
1174pub enum TypeRef {
1175    Base(BaseType, Span),
1176    Named(Ident),
1177    /// `Result[T, E]` — the built-in generic Result type (v0.1).
1178    Result(Box<TypeRef>, Box<TypeRef>, Span),
1179    /// `Option[T]` — the built-in generic Option type (v0.2).
1180    Option(Box<TypeRef>, Span),
1181    /// `Effect[T]` — the built-in generic Effect type (v0.5).
1182    Effect(Box<TypeRef>, Span),
1183    /// `HttpResult[T]` — the built-in HTTP-result sum (v0.9).
1184    HttpResult(Box<TypeRef>, Span),
1185    /// `QueueResult` — the built-in queue verdict sum (`Ack | Retry`),
1186    /// non-generic; the required return of a queue handler (v0.44).
1187    QueueResult(Span),
1188    /// `List[T]` — the built-in generic immutable list type (v0.20b).
1189    List(Box<TypeRef>, Span),
1190    /// `Map[K, V]` — the built-in generic immutable map type (v0.20b).
1191    /// Keys are confined to value-keyable types
1192    /// (`bynk.types.unkeyable_map_key`).
1193    Map(Box<TypeRef>, Box<TypeRef>, Span),
1194    /// `ValidationError` — the built-in error type used by refined-type
1195    /// constructors (v0.1).
1196    ValidationError(Span),
1197    /// `JsonError` — the built-in JSON-decode error type (v0.22b). A
1198    /// uniform record (`kind`/`path`/`message`, all `String`) the codec
1199    /// maps `BoundaryError` variants and parse failures into.
1200    JsonError(Span),
1201    /// `()` — the unit type (v0.5).
1202    Unit(Span),
1203    /// `A -> B` / `(A, B) -> C` / `() -> B` — a function type (v0.20a).
1204    /// Right-associative; effectful iff the return type is `Effect[_]`
1205    /// (the structural rule). Confined to non-boundary positions
1206    /// (`bynk.types.function_at_boundary`).
1207    Fn(Vec<TypeRef>, Box<TypeRef>, Span),
1208}
1209
1210impl TypeRef {
1211    pub fn span(&self) -> Span {
1212        match self {
1213            TypeRef::Base(_, s) => *s,
1214            TypeRef::Named(id) => id.span,
1215            TypeRef::Result(_, _, s) => *s,
1216            TypeRef::Option(_, s) => *s,
1217            TypeRef::Effect(_, s) => *s,
1218            TypeRef::HttpResult(_, s) => *s,
1219            TypeRef::QueueResult(s) => *s,
1220            TypeRef::List(_, s) => *s,
1221            TypeRef::Map(_, _, s) => *s,
1222            TypeRef::ValidationError(s) => *s,
1223            TypeRef::JsonError(s) => *s,
1224            TypeRef::Unit(s) => *s,
1225            TypeRef::Fn(_, _, s) => *s,
1226        }
1227    }
1228}
1229
1230#[derive(Debug, Clone)]
1231pub struct Expr {
1232    pub kind: ExprKind,
1233    pub span: Span,
1234}
1235
1236#[derive(Debug, Clone)]
1237pub enum ExprKind {
1238    IntLit(i64),
1239    /// A float literal (v0.21). The lexeme is kept alongside the parsed
1240    /// value so emission and formatting are byte-stable (`1e10` must not
1241    /// normalise to `10000000000`).
1242    FloatLit {
1243        value: f64,
1244        lexeme: String,
1245    },
1246    StrLit(String),
1247    /// An interpolated string `"… \(expr) …"` (v0.43, ADR 0075). Chunks and
1248    /// holes alternate. A plain `"…"` with no holes stays [`ExprKind::StrLit`],
1249    /// so existing code and the emitter/formatter fast-path are untouched.
1250    InterpStr(Vec<InterpPart>),
1251    BoolLit(bool),
1252    Ident(Ident),
1253    Call {
1254        name: Ident,
1255        /// v0.20a: explicit type arguments (`name[T](…)`); empty when absent.
1256        type_args: Vec<TypeRef>,
1257        args: Vec<Expr>,
1258    },
1259    /// A lambda (v0.20a). See [`LambdaExpr`].
1260    Lambda(LambdaExpr),
1261    BinOp(BinOp, Box<Expr>, Box<Expr>),
1262    UnaryOp(UnaryOp, Box<Expr>),
1263    Paren(Box<Expr>),
1264    /// `{ stmts; expr }` — block expression (v0.1).
1265    Block(Block),
1266    /// `if cond { then } else { else }` (v0.1).
1267    If {
1268        cond: Box<Expr>,
1269        then_block: Box<Block>,
1270        else_block: Box<Block>,
1271    },
1272    /// `Ok(value)` — Result success constructor (v0.1).
1273    Ok(Box<Expr>),
1274    /// `Err(error)` — Result failure constructor (v0.1).
1275    Err(Box<Expr>),
1276    /// `expr?` — propagation operator (v0.1).
1277    Question(Box<Expr>),
1278    /// `TypeName.method(args)` — qualified static call on a type
1279    /// (v0.1: only refined-type `of`; v0.2: any static method or variant
1280    /// constructor for sum types). The resolver decides which.
1281    ConstructorCall {
1282        type_name: Ident,
1283        method: Ident,
1284        args: Vec<Expr>,
1285    },
1286    /// `TypeName { field: value, ... }` — record construction (v0.2).
1287    RecordConstruction {
1288        type_name: Ident,
1289        fields: Vec<FieldInit>,
1290    },
1291    /// `receiver.field` — field access on a record value (v0.2). v0.3 adds
1292    /// `.raw` on opaque types within the defining commons.
1293    FieldAccess {
1294        receiver: Box<Expr>,
1295        field: Ident,
1296    },
1297    /// `receiver.method(args)` — instance method call (v0.2). The
1298    /// resolver determines the receiver's type and looks up the method.
1299    MethodCall {
1300        receiver: Box<Expr>,
1301        method: Ident,
1302        /// v0.22b: explicit type arguments on a qualified static
1303        /// (`Json.decode[T](…)`); empty when absent. The same-line-`[`
1304        /// rule applies as for `Call` type application (0039).
1305        type_args: Vec<TypeRef>,
1306        args: Vec<Expr>,
1307    },
1308    /// `match disc { arm+ }` — pattern matching (v0.2).
1309    Match {
1310        discriminant: Box<Expr>,
1311        arms: Vec<MatchArm>,
1312    },
1313    /// `expr is pattern` — pattern test, returns Bool (v0.2).
1314    Is {
1315        value: Box<Expr>,
1316        pattern: Pattern,
1317    },
1318    /// `Some(value)` — Option Some constructor (v0.2).
1319    Some(Box<Expr>),
1320    /// `None` — Option None constructor (v0.2).
1321    None,
1322    /// `()` — unit literal (v0.5).
1323    UnitLit,
1324    /// `TypeName { ...base, field: value, ... }` or `{ ...base, ... }` —
1325    /// record spread expression (v0.5).
1326    RecordSpread {
1327        /// Optional type prefix (`TypeName { ...base }`). Absent for the
1328        /// bare form used inside `commit`.
1329        type_name: Option<Ident>,
1330        /// The base record being spread.
1331        base: Box<Expr>,
1332        /// Field overrides (always full `name: value` form — never shorthand).
1333        overrides: Vec<FieldInit>,
1334    },
1335    /// `Effect.pure(value)` — wrap a synchronous value into `Effect[T]`
1336    /// (v0.5). Recognised in the parser as a special-form.
1337    EffectPure(Box<Expr>),
1338    /// `assert expr` — assertion as an expression of type `()` (v0.9.1).
1339    /// Valid only inside test bodies. Evaluates `expr` (must be Bool); if
1340    /// false, the surrounding test case fails.
1341    Assert(Box<Expr>),
1342    /// `Mock[T]`, `Mock[T](args)` — test-context value construction (v0.9.4).
1343    /// `args` is empty for the bare form and holds the pin arguments for
1344    /// `Mock[T](...)`. The record-override form `Mock[T] { ... }` is not yet
1345    /// parsed. Valid only inside test bodies; has type `T`.
1346    Mock {
1347        type_ref: TypeRef,
1348        args: Vec<Expr>,
1349    },
1350    /// `[a, b, c]` — list literal (v0.20b). An empty `[]` requires an
1351    /// expected type (`bynk.types.uninferable_element_type`).
1352    ListLit(Vec<Expr>),
1353}
1354
1355/// One part of an interpolated string (v0.43, ADR 0075). An
1356/// [`ExprKind::InterpStr`] holds an alternating run of these.
1357#[derive(Debug, Clone)]
1358pub enum InterpPart {
1359    /// Literal text between holes, with escapes already resolved.
1360    Chunk(String),
1361    /// An interpolated expression `\(expr)`. Type-checked by the hole rule
1362    /// (base scalars only; see the checker) and lowered into a template-
1363    /// literal `${…}` slot.
1364    Hole(Box<Expr>),
1365}
1366
1367/// One field-initialiser inside a record construction expression:
1368/// either `name: expr` or the shorthand `name` (which requires a binding
1369/// of the same name in scope and uses its value).
1370#[derive(Debug, Clone)]
1371pub struct FieldInit {
1372    pub name: Ident,
1373    /// `None` means shorthand — the field's value is the same-named binding.
1374    pub value: Option<Expr>,
1375    pub span: Span,
1376}
1377
1378/// One arm of a `match` expression: `pattern => body`.
1379#[derive(Debug, Clone)]
1380pub struct MatchArm {
1381    pub pattern: Pattern,
1382    pub body: MatchBody,
1383    pub span: Span,
1384}
1385
1386/// The right-hand side of a match arm — either a single expression or
1387/// a block.
1388#[derive(Debug, Clone)]
1389pub enum MatchBody {
1390    Expr(Expr),
1391    Block(Block),
1392}
1393
1394impl MatchBody {
1395    pub fn span(&self) -> Span {
1396        match self {
1397            MatchBody::Expr(e) => e.span,
1398            MatchBody::Block(b) => b.span,
1399        }
1400    }
1401}
1402
1403/// A pattern (v0.2 §3.8). Patterns appear in `match` arms and as the
1404/// right-hand side of the `is` operator.
1405#[derive(Debug, Clone)]
1406pub enum Pattern {
1407    /// `_` — matches any value, no bindings.
1408    Wildcard(Span),
1409    /// `Variant` or `Variant(bindings)` or `TypeName.Variant(bindings)`.
1410    Variant {
1411        /// Optional qualifier: `TypeName.Variant`.
1412        type_name: Option<Ident>,
1413        /// The variant name.
1414        variant: Ident,
1415        /// Payload bindings (empty for nullary variants).
1416        bindings: Vec<PatternBinding>,
1417        span: Span,
1418    },
1419}
1420
1421impl Pattern {
1422    pub fn span(&self) -> Span {
1423        match self {
1424            Pattern::Wildcard(s) => *s,
1425            Pattern::Variant { span, .. } => *span,
1426        }
1427    }
1428}
1429
1430/// A single binding inside a variant pattern. Two surface forms:
1431/// `name` (positional — bind the i-th payload field) and
1432/// `fieldName: bindName` (named — bind the named payload field).
1433/// Both forms also accept `_` as the bind name to discard.
1434#[derive(Debug, Clone)]
1435pub struct PatternBinding {
1436    /// Source form: positional or named.
1437    pub kind: PatternBindingKind,
1438    pub span: Span,
1439}
1440
1441#[derive(Debug, Clone)]
1442pub enum PatternBindingKind {
1443    /// `name` (or `_`): bind the payload field at this position to `name`.
1444    Positional { name: Ident },
1445    /// `field: name` (or `field: _`): bind the named payload field to `name`.
1446    Named { field: Ident, name: Ident },
1447}
1448
1449impl PatternBinding {
1450    /// The local name introduced by this binding (used for scope).
1451    /// `_` is a sentinel for "no binding"; callers should compare against it.
1452    pub fn local_name(&self) -> &Ident {
1453        match &self.kind {
1454            PatternBindingKind::Positional { name } => name,
1455            PatternBindingKind::Named { name, .. } => name,
1456        }
1457    }
1458
1459    pub fn is_wildcard(&self) -> bool {
1460        self.local_name().name == "_"
1461    }
1462}
1463
1464#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1465pub enum BinOp {
1466    /// `P implies Q` — logical implication (v0.80). Desugars to `!P || Q`; sits
1467    /// at the lowest precedence (below `||`). Reads directionally (P → Q).
1468    Implies,
1469    Or,
1470    And,
1471    Eq,
1472    NotEq,
1473    Lt,
1474    LtEq,
1475    Gt,
1476    GtEq,
1477    Add,
1478    Sub,
1479    Mul,
1480    Div,
1481}
1482
1483impl BinOp {
1484    pub fn name(self) -> &'static str {
1485        match self {
1486            BinOp::Implies => "implies",
1487            BinOp::Or => "||",
1488            BinOp::And => "&&",
1489            BinOp::Eq => "==",
1490            BinOp::NotEq => "!=",
1491            BinOp::Lt => "<",
1492            BinOp::LtEq => "<=",
1493            BinOp::Gt => ">",
1494            BinOp::GtEq => ">=",
1495            BinOp::Add => "+",
1496            BinOp::Sub => "-",
1497            BinOp::Mul => "*",
1498            BinOp::Div => "/",
1499        }
1500    }
1501}
1502
1503#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1504pub enum UnaryOp {
1505    Neg,
1506    Not,
1507}
1508
1509impl UnaryOp {
1510    pub fn name(self) -> &'static str {
1511        match self {
1512            UnaryOp::Neg => "-",
1513            UnaryOp::Not => "!",
1514        }
1515    }
1516}