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    /// `store` fields (v0.81, storage track) — each an access-pattern slot of a
514    /// declared storage kind (`Cell`/`Map`/…). The successor to the removed
515    /// `state { }` record (ADR 0108); every agent declares its state this way.
516    pub store_fields: Vec<StoreField>,
517    /// Invariants (v0.80 §14) — universally-quantified predicates over the
518    /// agent's `store` fields. The phase sits between the fields and the
519    /// handlers; each is checked against the state staged by a handler's writes
520    /// before it commits.
521    pub invariants: Vec<Invariant>,
522    pub handlers: Vec<Handler>,
523    pub documentation: Option<String>,
524    pub span: Span,
525    pub trivia: Trivia,
526}
527
528/// A `store` field (v0.81, storage track). Each is an access-pattern slot of a
529/// declared storage kind: `store <name>: <Kind>[…] [@annotations] [= <init>]`.
530/// The kind and its element type are carried as an ordinary [`TypeRef`]
531/// (`Cell[Int]`, `Map[K, V]`); the checker restricts which heads are storage
532/// kinds. Access-pattern annotations (`@indexed`, …) parse into [`annotations`]
533/// (v0.85, ADR 0111); the checker validates them against the closed registry.
534///
535/// [`annotations`]: StoreField::annotations
536#[derive(Debug, Clone)]
537pub struct StoreField {
538    pub name: Ident,
539    /// The storage kind and its element type(s): `Cell[Int]`, `Map[K, V]`. A
540    /// dedicated [`StoreKind`] rather than a [`TypeRef`] — storage kinds are not
541    /// value types, and the checker dispatches kind-aware operations on the head.
542    pub kind: StoreKind,
543    /// Storage annotations on the field (v0.85, ADR 0111): `@ttl(5.minutes)`,
544    /// `@indexed(by: orderId)`. Parsed in declaration order (after the kind,
545    /// before the initialiser); the checker validates names against the closed
546    /// registry and gates each to the slice that implements it.
547    pub annotations: Vec<Annotation>,
548    /// The fresh-key initial value (`= expr`), if given — same disposition as a
549    /// `state` field's initialiser (ADRs 0003/0004 carry forward).
550    pub init: Option<Expr>,
551    pub documentation: Option<String>,
552    pub span: Span,
553    pub trivia: Trivia,
554}
555
556/// A storage annotation on a `store` field (v0.85, storage track; ADR 0111):
557/// `@<name>(<args>)`. The `name` is matched against the closed registry
558/// (`@indexed`/`@ttl`/`@retain`/`@bounded`) by the checker; the grammar accepts
559/// any identifier so an unknown name is a checker diagnostic, not a parse error.
560/// Arguments are compile-time metadata, restricted to literals (and the `by:`
561/// field-name labels of `@indexed`) by the checker per ADR 0111 D4.
562#[derive(Debug, Clone)]
563pub struct Annotation {
564    pub name: Ident,
565    pub args: Vec<AnnotationArg>,
566    pub span: Span,
567}
568
569/// A single annotation argument (v0.85; ADR 0111): an optional `label:` followed
570/// by a value expression — `by: orderId` (labelled) or `5.minutes` (positional).
571/// The value is parsed as an ordinary [`Expr`] so the duration-literal form
572/// (`5.minutes`, landing with the `Duration` slice) needs no special grammar;
573/// the checker restricts it to a literal where the annotation is functional.
574#[derive(Debug, Clone)]
575pub struct AnnotationArg {
576    pub label: Option<Ident>,
577    pub value: Expr,
578    pub span: Span,
579}
580
581/// A storage kind applied to its element type(s) (v0.81): `Cell[Int]`,
582/// `Map[ReservationId, Reservation]`. The `head` is the kind name (`Cell`,
583/// `Map`, `Set`, `Log`, `Queue`, `Cache`); the checker validates it against the
584/// closed catalogue. Element types are ordinary [`TypeRef`]s. Refined element
585/// types (`Cell[Int where NonNegative]`) ride a later slice (parse_type_ref does
586/// not yet accept an inline refinement in type-argument position).
587#[derive(Debug, Clone)]
588pub struct StoreKind {
589    pub head: Ident,
590    pub args: Vec<TypeRef>,
591    pub span: Span,
592}
593
594/// An agent invariant (v0.80 §14). A named predicate over the agent's state
595/// fields that must hold of every committed state; a commit that would violate
596/// it faults (`InvariantViolation`) before the state is persisted. The
597/// predicate references state fields by bare name, mirroring the design-notes
598/// worked examples (`status == Paid implies paymentRef.isSome()`).
599#[derive(Debug, Clone)]
600pub struct Invariant {
601    pub name: Ident,
602    /// The predicate expression — an ordinary `Bool`-typed expression over the
603    /// state fields, plus `implies` and `is`. The parsed-predicate-on-a-
604    /// declaration shape mirrors [`ActorRefinement::predicate`].
605    pub predicate: Expr,
606    pub documentation: Option<String>,
607    pub span: Span,
608    pub trivia: Trivia,
609}
610
611/// An actor declaration (v0.45 §3.7). An actor is a nominal *contract type*
612/// describing an external party at a boundary — not a runnable entity. A
613/// handler consumes an actor on its `by` clause; the boundary verifies the
614/// declared `auth` scheme and mints a sealed identity (`name.identity`).
615#[derive(Debug, Clone)]
616pub struct ActorDecl {
617    pub name: Ident,
618    /// The authentication scheme from `auth = <Scheme>`, stored as the raw
619    /// identifier. The checker classifies it: `None`/`Internal`/`Bearer` are
620    /// admitted; `Signature` is reserved-and-rejected
621    /// (`bynk.actor.scheme_unsupported`); anything else is
622    /// `bynk.actor.unknown_scheme`. `None` for the refinement form.
623    pub auth: Option<Ident>,
624    /// The scheme's keyed config from `auth = Scheme(key = value, …)` (v0.47
625    /// `Bearer(secret = "…")`; v0.51 generalised for `Signature(secret, header,
626    /// timestamp?, tolerance?)`). Empty for schemes/forms with no config. The
627    /// checker validates which keys each scheme requires/allows.
628    pub auth_config: Vec<SchemeArg>,
629    /// The optional identity type from `, identity = <T>`. Absent ⇒ the
630    /// scheme default (`()` for `None`; a sealed `CallerId` for the `Internal`
631    /// `on call` channel, `()` for other `Internal` channels).
632    pub identity: Option<TypeRef>,
633    /// The reserved-and-rejected refinement form `actor Admin = Base where p`
634    /// (Q3). Parsed so the grammar is fixed now; the checker emits
635    /// `bynk.actor.refinement_unsupported`.
636    pub refinement: Option<ActorRefinement>,
637    pub documentation: Option<String>,
638    pub span: Span,
639    pub trivia: Trivia,
640}
641
642impl ActorDecl {
643    /// The value of a scheme config arg by key, if present (e.g. `secret`,
644    /// `header`).
645    pub fn scheme_arg(&self, key: &str) -> Option<&SchemeArg> {
646        self.auth_config.iter().find(|a| a.key.name == key)
647    }
648}
649
650/// One `key = value` argument in a scheme config (`Scheme(key = value, …)`).
651#[derive(Debug, Clone)]
652pub struct SchemeArg {
653    pub key: Ident,
654    pub value: SchemeArgValue,
655    /// Span of the value, for diagnostics.
656    pub span: Span,
657}
658
659/// A scheme config arg value — a string literal or an integer.
660#[derive(Debug, Clone)]
661pub enum SchemeArgValue {
662    Str(String),
663    Int(i64),
664}
665
666impl SchemeArgValue {
667    pub fn as_str(&self) -> Option<&str> {
668        match self {
669            SchemeArgValue::Str(s) => Some(s),
670            SchemeArgValue::Int(_) => None,
671        }
672    }
673    pub fn as_int(&self) -> Option<i64> {
674        match self {
675            SchemeArgValue::Int(n) => Some(*n),
676            SchemeArgValue::Str(_) => None,
677        }
678    }
679}
680
681/// The reserved refinement form `actor Admin = User where <predicate>` (Q3).
682/// Parsed in Foundations so the grammar is fixed; admission is a later slice.
683#[derive(Debug, Clone)]
684pub struct ActorRefinement {
685    /// The base actor being refined.
686    pub base: Ident,
687    /// The `where` predicate. Parsed but not yet checked.
688    pub predicate: Expr,
689    pub span: Span,
690}
691
692/// The `by (<binder>:)? <Actor>` clause on a handler (v0.45; binder optional in
693/// v0.50). Names the actor contract the handler consumes; when a `binder` is
694/// given, the verified identity binds to it and is read as `binder.identity`.
695/// Omitting the binder (`by <Actor>`) declares-and-verifies the contract without
696/// capturing the identity — for anonymous or verify-and-discard handlers. Sits
697/// after the protocol config and before the parameters.
698#[derive(Debug, Clone)]
699pub struct ByClause {
700    /// The identity binder, if the handler consumes the identity. `None` for the
701    /// binder-less `by <Actor>` form. Required when `actors` names more than one
702    /// (a sum is resolved by matching on the bound actor).
703    pub binder: Option<Ident>,
704    /// The actor contract(s) referenced — each a local actor decl or a prelude
705    /// actor. A single name is the ordinary single-actor handler; more than one
706    /// (`by who: A | B`, v0.52) is an **ordered sum of peer actors** resolved
707    /// first-wins, the body matching on the resolved actor. Always non-empty.
708    pub actors: Vec<Ident>,
709    pub span: Span,
710}
711
712impl ByClause {
713    /// The first (and, for a single-actor handler, only) actor contract named.
714    pub fn primary(&self) -> &Ident {
715        &self.actors[0]
716    }
717    /// Whether this `by` clause names an ordered sum of peer actors (`A | B`).
718    pub fn is_sum(&self) -> bool {
719        self.actors.len() > 1
720    }
721}
722
723/// A handler block — `on call(args) -> T given C1, C2 { body }`.
724/// Used by both services and agents.
725#[derive(Debug, Clone)]
726pub struct Handler {
727    pub kind: HandlerKind,
728    /// For agent handlers, the method-style handler name (e.g.
729    /// `on call addItem(...)`). For service handlers, this is None (just
730    /// `on call(...)`).
731    pub method_name: Option<Ident>,
732    /// The `by <binder>: <Actor>` clause (v0.45), if present. Service handlers
733    /// only; an absent clause inherits the protocol's default actor.
734    pub by_clause: Option<ByClause>,
735    pub params: Vec<Param>,
736    pub return_type: TypeRef,
737    pub given: Vec<CapRef>,
738    pub body: Block,
739    pub documentation: Option<String>,
740    pub span: Span,
741    pub trivia: Trivia,
742}
743
744#[derive(Debug, Clone, PartialEq, Eq)]
745pub enum HandlerKind {
746    /// `on call(...)` — typed RPC (the only kind in v0.5).
747    Call,
748    /// `on http METHOD "path"` — external-facing HTTP route (v0.9).
749    Http { method: HttpMethod, path: String },
750    /// `on cron "expr"` — scheduled task; `expr` is a 5-field cron
751    /// expression (v0.10a).
752    Cron { expr: String },
753    /// `on message(m: T)` — a message off the service's bound queue. The queue
754    /// binding lives on the service's `ServiceProtocol::Queue` (v0.44).
755    Message,
756}
757
758/// HTTP methods supported by `on http` handlers (v0.9).
759#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
760pub enum HttpMethod {
761    Get,
762    Post,
763    Put,
764    Patch,
765    Delete,
766}
767
768impl HttpMethod {
769    pub fn as_str(self) -> &'static str {
770        match self {
771            HttpMethod::Get => "GET",
772            HttpMethod::Post => "POST",
773            HttpMethod::Put => "PUT",
774            HttpMethod::Patch => "PATCH",
775            HttpMethod::Delete => "DELETE",
776        }
777    }
778
779    pub fn from_ident(s: &str) -> Option<HttpMethod> {
780        match s {
781            "GET" => Some(HttpMethod::Get),
782            "POST" => Some(HttpMethod::Post),
783            "PUT" => Some(HttpMethod::Put),
784            "PATCH" => Some(HttpMethod::Patch),
785            "DELETE" => Some(HttpMethod::Delete),
786            _ => None,
787        }
788    }
789
790    /// True if this method conventionally has no request body.
791    pub fn forbids_body(self) -> bool {
792        matches!(self, HttpMethod::Get | HttpMethod::Delete)
793    }
794}
795
796/// Payload shape of an `HttpResult[T]` variant (v0.9 §3.3).
797#[derive(Debug, Clone, Copy, PartialEq, Eq)]
798pub enum HttpVariantPayload {
799    /// No payload (e.g. `NoContent`, `Unauthorized`).
800    None,
801    /// Carries a value of the `HttpResult` type parameter `T`.
802    Value,
803    /// Carries a `String` message (e.g. `BadRequest`, `Conflict`).
804    Message,
805}
806
807/// One variant of the built-in `HttpResult[T]` sum (v0.9 §3.3).
808#[derive(Debug, Clone, Copy)]
809pub struct HttpVariant {
810    pub name: &'static str,
811    pub payload: HttpVariantPayload,
812    pub status: u16,
813}
814
815/// All `HttpResult[T]` variants, in declaration order.
816pub const HTTP_VARIANTS: &[HttpVariant] = &[
817    HttpVariant {
818        name: "Ok",
819        payload: HttpVariantPayload::Value,
820        status: 200,
821    },
822    HttpVariant {
823        name: "Created",
824        payload: HttpVariantPayload::Value,
825        status: 201,
826    },
827    HttpVariant {
828        name: "NoContent",
829        payload: HttpVariantPayload::None,
830        status: 204,
831    },
832    HttpVariant {
833        name: "BadRequest",
834        payload: HttpVariantPayload::Message,
835        status: 400,
836    },
837    HttpVariant {
838        name: "Unauthorized",
839        payload: HttpVariantPayload::None,
840        status: 401,
841    },
842    HttpVariant {
843        name: "Forbidden",
844        payload: HttpVariantPayload::None,
845        status: 403,
846    },
847    HttpVariant {
848        name: "NotFound",
849        payload: HttpVariantPayload::None,
850        status: 404,
851    },
852    HttpVariant {
853        name: "Conflict",
854        payload: HttpVariantPayload::Message,
855        status: 409,
856    },
857    HttpVariant {
858        name: "UnprocessableEntity",
859        payload: HttpVariantPayload::Message,
860        status: 422,
861    },
862    HttpVariant {
863        name: "ServerError",
864        payload: HttpVariantPayload::Message,
865        status: 500,
866    },
867];
868
869/// Find an `HttpResult[T]` variant by name. Returns the variant info or
870/// `None` if the name doesn't match.
871pub fn http_variant(name: &str) -> Option<HttpVariant> {
872    HTTP_VARIANTS.iter().copied().find(|v| v.name == name)
873}
874
875/// Payload shape of a `QueueResult` variant (v0.44). Non-generic — a verdict
876/// carries no value; `Retry` carries a `String` reason for the log path.
877#[derive(Debug, Clone, Copy, PartialEq, Eq)]
878pub enum QueueVariantPayload {
879    /// No payload (`Ack`).
880    None,
881    /// Carries a `String` reason (`Retry`).
882    Message,
883}
884
885/// One variant of the built-in `QueueResult` sum (v0.44).
886#[derive(Debug, Clone, Copy)]
887pub struct QueueVariant {
888    pub name: &'static str,
889    pub payload: QueueVariantPayload,
890}
891
892/// All `QueueResult` variants, in declaration order. `Ack` confirms the
893/// message; `Retry` redelivers it, carrying a reason for observability.
894pub const QUEUE_VARIANTS: &[QueueVariant] = &[
895    QueueVariant {
896        name: "Ack",
897        payload: QueueVariantPayload::None,
898    },
899    QueueVariant {
900        name: "Retry",
901        payload: QueueVariantPayload::Message,
902    },
903];
904
905/// Find a `QueueResult` variant by name.
906pub fn queue_variant(name: &str) -> Option<QueueVariant> {
907    QUEUE_VARIANTS.iter().copied().find(|v| v.name == name)
908}
909
910#[derive(Debug, Clone)]
911pub struct TypeDecl {
912    pub name: Ident,
913    pub body: TypeBody,
914    /// Documentation block attached to this declaration (v0.3).
915    pub documentation: Option<String>,
916    pub span: Span,
917    pub trivia: Trivia,
918}
919
920/// The right-hand side of a `type` declaration. In v0/v0.1 only the
921/// `Refined` variant existed; v0.2 adds records and sums; v0.3 adds opaque.
922#[derive(Debug, Clone)]
923pub enum TypeBody {
924    /// Refined base type: `BaseType where refinement`.
925    Refined {
926        base: BaseType,
927        base_span: Span,
928        refinement: Option<Refinement>,
929    },
930    /// Record type: `{ field: T where ..., ... }`.
931    Record(RecordBody),
932    /// Sum type: pipe-form variants or `enum { ... }` shorthand.
933    Sum(SumBody),
934    /// Opaque base type: `opaque BaseType (where refinement)?` (v0.3 §3.4).
935    /// Identity is nominal; the base type is hidden outside the defining commons.
936    Opaque {
937        base: BaseType,
938        base_span: Span,
939        refinement: Option<Refinement>,
940    },
941}
942
943/// Body of a record-type declaration (v0.2 §3.1).
944#[derive(Debug, Clone)]
945pub struct RecordBody {
946    pub fields: Vec<RecordField>,
947    pub span: Span,
948}
949
950/// One field of a record type declaration. Each field may carry inline
951/// refinement, which is enforced at construction time on the field's value.
952#[derive(Debug, Clone)]
953pub struct RecordField {
954    pub name: Ident,
955    pub type_ref: TypeRef,
956    pub refinement: Option<Refinement>,
957    /// v0.11: an optional initial-value expression. Only meaningful on agent
958    /// `state` fields (the field's fresh-key value); ignored / rejected on
959    /// record-type fields by the checker.
960    pub init: Option<Expr>,
961    pub span: Span,
962}
963
964/// Body of a sum-type declaration (v0.2 §3.2).
965#[derive(Debug, Clone)]
966pub struct SumBody {
967    pub variants: Vec<Variant>,
968    pub span: Span,
969}
970
971/// One variant of a sum type. Variants may have payload fields; a
972/// payload-less variant is a simple tag.
973#[derive(Debug, Clone)]
974pub struct Variant {
975    pub name: Ident,
976    pub payload: Vec<VariantField>,
977    pub span: Span,
978}
979
980/// One payload field of a sum variant. Variant payload fields use named
981/// declarations like record fields, but do not carry refinement in v0.2.
982#[derive(Debug, Clone)]
983pub struct VariantField {
984    pub name: Ident,
985    pub type_ref: TypeRef,
986    pub span: Span,
987}
988
989#[derive(Debug, Clone, Copy, PartialEq, Eq)]
990pub enum BaseType {
991    Int,
992    String,
993    Bool,
994    Float,
995    /// `Duration` (v0.86, ADR 0112) — a span of time, a distinct base type
996    /// erased to TS `number` carrying milliseconds (the `Clock` unit). Modelled
997    /// on `Float`: Bynk-side-only, no implicit `Int` coercion (save the one
998    /// sanctioned clock-math mix).
999    Duration,
1000    /// `Instant` (v0.90, ADR 0114) — an absolute point in time, a distinct base
1001    /// type erased to TS `number` carrying Unix epoch milliseconds (the
1002    /// `Clock` unit). No literal (minted by `Clock.now()`); arithmetic composes
1003    /// with `Duration` (`Instant ± Duration -> Instant`, `Instant − Instant ->
1004    /// Duration`). Supersedes ADR 0112 D4's `Int`↔`Duration` clock-math mix.
1005    Instant,
1006}
1007
1008impl BaseType {
1009    pub fn name(self) -> &'static str {
1010        match self {
1011            BaseType::Int => "Int",
1012            BaseType::String => "String",
1013            BaseType::Bool => "Bool",
1014            BaseType::Float => "Float",
1015            BaseType::Duration => "Duration",
1016            BaseType::Instant => "Instant",
1017        }
1018    }
1019}
1020
1021/// A `Duration` literal unit (v0.86, ADR 0112) — the closed set of suffixes in a
1022/// `<int>.<unit>` literal. Each maps to a fixed millisecond factor (`Duration`
1023/// erases to `Int` milliseconds).
1024#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1025pub enum DurationUnit {
1026    Milliseconds,
1027    Seconds,
1028    Minutes,
1029    Hours,
1030    Days,
1031}
1032
1033impl DurationUnit {
1034    /// Resolve a unit name (`minutes`) to its variant, or `None` if it is not one
1035    /// of the closed set. Used by the parser to recognise an `<int>.<unit>`
1036    /// literal; an unrecognised name leaves the expression a field access.
1037    pub fn from_name(name: &str) -> Option<Self> {
1038        Some(match name {
1039            "milliseconds" => DurationUnit::Milliseconds,
1040            "seconds" => DurationUnit::Seconds,
1041            "minutes" => DurationUnit::Minutes,
1042            "hours" => DurationUnit::Hours,
1043            "days" => DurationUnit::Days,
1044            _ => return None,
1045        })
1046    }
1047
1048    /// The unit name as written.
1049    pub fn name(self) -> &'static str {
1050        match self {
1051            DurationUnit::Milliseconds => "milliseconds",
1052            DurationUnit::Seconds => "seconds",
1053            DurationUnit::Minutes => "minutes",
1054            DurationUnit::Hours => "hours",
1055            DurationUnit::Days => "days",
1056        }
1057    }
1058
1059    /// The unit's value in milliseconds.
1060    pub fn millis(self) -> i64 {
1061        match self {
1062            DurationUnit::Milliseconds => 1,
1063            DurationUnit::Seconds => 1_000,
1064            DurationUnit::Minutes => 60_000,
1065            DurationUnit::Hours => 3_600_000,
1066            DurationUnit::Days => 86_400_000,
1067        }
1068    }
1069}
1070
1071/// An integer refinement bound (v0.40, ADR 0073): the parsed value plus the
1072/// bound's source span (covering a leading `-`). Value-only beyond the span —
1073/// ints have one canonical printed form, so the formatter stays idempotent
1074/// without a stored lexeme. The span backs the `InRange`-swap quick-fix.
1075#[derive(Debug, Clone)]
1076pub struct IntBound {
1077    pub value: i64,
1078    pub span: Span,
1079}
1080
1081/// A float refinement bound (v0.21): the parsed value plus the signed source
1082/// lexeme (for byte-stable emission). v0.40 (ADR 0073): also the source span,
1083/// for the `InRange`-swap quick-fix.
1084#[derive(Debug, Clone)]
1085pub struct FloatBound {
1086    pub value: f64,
1087    pub lexeme: String,
1088    pub span: Span,
1089}
1090
1091#[derive(Debug, Clone)]
1092pub struct Refinement {
1093    pub predicates: Vec<RefinementPred>,
1094    pub span: Span,
1095}
1096
1097#[derive(Debug, Clone)]
1098pub struct RefinementPred {
1099    pub kind: PredKind,
1100    pub span: Span,
1101}
1102
1103#[derive(Debug, Clone)]
1104pub enum PredKind {
1105    Matches(String),
1106    InRange(IntBound, IntBound),
1107    /// `InRange` with float bounds (v0.21) — a separate variant so every
1108    /// `Int` refinement path stays untouched. Bounds keep their source
1109    /// lexemes (including any sign) so emitted runtime checks are
1110    /// byte-stable.
1111    InRangeF(FloatBound, FloatBound),
1112    MinLength(i64),
1113    MaxLength(i64),
1114    Length(i64),
1115    NonNegative,
1116    Positive,
1117    NonEmpty,
1118}
1119
1120impl PredKind {
1121    pub fn name(&self) -> &'static str {
1122        match self {
1123            PredKind::Matches(_) => "Matches",
1124            PredKind::InRange(..) | PredKind::InRangeF(..) => "InRange",
1125            PredKind::MinLength(_) => "MinLength",
1126            PredKind::MaxLength(_) => "MaxLength",
1127            PredKind::Length(_) => "Length",
1128            PredKind::NonNegative => "NonNegative",
1129            PredKind::Positive => "Positive",
1130            PredKind::NonEmpty => "NonEmpty",
1131        }
1132    }
1133}
1134
1135/// A function type parameter (v0.20a, `fn name[A, B](…)`). A struct rather
1136/// than a bare Ident so the ADR-0028 "bound-capable" promise is a later field
1137/// addition, not a representation change.
1138#[derive(Debug, Clone)]
1139pub struct TypeParam {
1140    pub name: Ident,
1141    pub span: Span,
1142}
1143
1144/// A lambda expression (v0.20a): `(params) => expr` or `(params) => { … }`.
1145/// `=>` is the value arrow (shared with `match`); param annotations are
1146/// optional where an expected function type supplies them.
1147#[derive(Debug, Clone)]
1148pub struct LambdaExpr {
1149    pub params: Vec<LambdaParam>,
1150    pub body: Box<Expr>,
1151    pub span: Span,
1152}
1153
1154/// A lambda parameter. A separate type from [`Param`] because its annotation
1155/// is optional — `Param.type_ref` stays mandatory at every signature site.
1156#[derive(Debug, Clone)]
1157pub struct LambdaParam {
1158    pub name: Ident,
1159    pub type_ref: Option<TypeRef>,
1160    pub span: Span,
1161}
1162
1163#[derive(Debug, Clone)]
1164pub struct FnDecl {
1165    /// v0.20a: `[A, B]` type parameters; empty for non-generic functions.
1166    pub type_params: Vec<TypeParam>,
1167    /// Free function or method (`TypeName.methodName`). See [`FnName`].
1168    pub name: FnName,
1169    pub params: Vec<Param>,
1170    pub return_type: TypeRef,
1171    pub body: Block,
1172    /// True when the first parameter is the special `self` parameter. Only
1173    /// valid for method declarations.
1174    pub has_self: bool,
1175    /// Documentation block attached to this declaration (v0.3).
1176    pub documentation: Option<String>,
1177    pub span: Span,
1178    pub trivia: Trivia,
1179}
1180
1181/// A function-declaration name: either a free function `f` or a method
1182/// `T.method` (v0.2 §3.6).
1183#[derive(Debug, Clone)]
1184pub enum FnName {
1185    /// `fn name(...)` — a free function.
1186    Free(Ident),
1187    /// `fn TypeName.methodName(...)` — a method attached to a type.
1188    Method {
1189        type_name: Ident,
1190        method_name: Ident,
1191    },
1192}
1193
1194impl FnName {
1195    /// The function's short name for diagnostics. For methods returns the
1196    /// method portion only; the type prefix is recovered via `type_name`.
1197    pub fn ident(&self) -> &Ident {
1198        match self {
1199            FnName::Free(id) => id,
1200            FnName::Method { method_name, .. } => method_name,
1201        }
1202    }
1203
1204    /// For methods, the attached type's identifier; `None` for free fns.
1205    pub fn type_name(&self) -> Option<&Ident> {
1206        match self {
1207            FnName::Free(_) => None,
1208            FnName::Method { type_name, .. } => Some(type_name),
1209        }
1210    }
1211
1212    /// The displayed full name (e.g., `Money.add` or `parseSku`).
1213    pub fn display(&self) -> String {
1214        match self {
1215            FnName::Free(id) => id.name.clone(),
1216            FnName::Method {
1217                type_name,
1218                method_name,
1219            } => format!("{}.{}", type_name.name, method_name.name),
1220        }
1221    }
1222}
1223
1224/// A brace-delimited block of statements ending in a tail expression
1225/// whose value is the block's value (spec v0.1 §3.1).
1226#[derive(Debug, Clone)]
1227pub struct Block {
1228    pub statements: Vec<Statement>,
1229    pub tail: Box<Expr>,
1230    pub span: Span,
1231    /// Line comments that appear between the last statement (or the
1232    /// opening brace) and the tail expression. Preserved here because
1233    /// expressions do not carry trivia in v1.1.
1234    pub tail_leading_comments: Vec<String>,
1235}
1236
1237/// Block-level statement.
1238#[derive(Debug, Clone)]
1239pub enum Statement {
1240    /// `let name (: T)? = expr` — pure binding (v0.1).
1241    Let(LetStmt),
1242    /// `let name (: T)? <- expr` — effectful binding (v0.5).
1243    EffectLet(LetStmt),
1244    /// `assert expr` — verify a Bool expression at test runtime (v0.7).
1245    /// Only valid inside test case bodies.
1246    Assert(AssertStmt),
1247    /// `~> expr` — an asynchronous fire-and-forget send (v0.79). The caller does
1248    /// not await the reply; legal only when the reply is `Effect[()]`. No binder.
1249    Send(SendStmt),
1250    /// `name := expr` — a `Cell` store write (v0.81, storage track). The
1251    /// unconditional write form; `.update(fn)` (a method call) is the
1252    /// read-modify-write form. ADR 0108.
1253    Assign(AssignStmt),
1254}
1255
1256impl Statement {
1257    pub fn span(&self) -> Span {
1258        match self {
1259            Statement::Let(l) | Statement::EffectLet(l) => l.span,
1260            Statement::Assert(a) => a.span,
1261            Statement::Send(s) => s.span,
1262            Statement::Assign(a) => a.span,
1263        }
1264    }
1265}
1266
1267#[derive(Debug, Clone)]
1268pub struct AssertStmt {
1269    pub value: Expr,
1270    pub span: Span,
1271    pub trivia: Trivia,
1272}
1273
1274/// `name := expr` — a `Cell` store write (v0.81, storage track). `target` is the
1275/// `Cell` field being written (a bare name for now; the checker resolves it to a
1276/// `store` field). `value` is the new value.
1277#[derive(Debug, Clone)]
1278pub struct AssignStmt {
1279    pub target: Ident,
1280    pub value: Expr,
1281    pub span: Span,
1282    pub trivia: Trivia,
1283}
1284
1285#[derive(Debug, Clone)]
1286pub struct LetStmt {
1287    pub name: Ident,
1288    pub type_annot: Option<TypeRef>,
1289    pub value: Expr,
1290    pub span: Span,
1291    pub trivia: Trivia,
1292}
1293
1294#[derive(Debug, Clone)]
1295pub struct SendStmt {
1296    /// The send target — a recipient call, e.g. `Logger.info(msg)`.
1297    pub value: Expr,
1298    pub span: Span,
1299    pub trivia: Trivia,
1300}
1301
1302#[derive(Debug, Clone)]
1303pub struct Param {
1304    pub name: Ident,
1305    pub type_ref: TypeRef,
1306    pub span: Span,
1307}
1308
1309#[derive(Debug, Clone)]
1310pub enum TypeRef {
1311    Base(BaseType, Span),
1312    Named(Ident),
1313    /// `Result[T, E]` — the built-in generic Result type (v0.1).
1314    Result(Box<TypeRef>, Box<TypeRef>, Span),
1315    /// `Option[T]` — the built-in generic Option type (v0.2).
1316    Option(Box<TypeRef>, Span),
1317    /// `Effect[T]` — the built-in generic Effect type (v0.5).
1318    Effect(Box<TypeRef>, Span),
1319    /// `HttpResult[T]` — the built-in HTTP-result sum (v0.9).
1320    HttpResult(Box<TypeRef>, Span),
1321    /// `QueueResult` — the built-in queue verdict sum (`Ack | Retry`),
1322    /// non-generic; the required return of a queue handler (v0.44).
1323    QueueResult(Span),
1324    /// `List[T]` — the built-in generic immutable list type (v0.20b).
1325    List(Box<TypeRef>, Span),
1326    /// `Map[K, V]` — the built-in generic immutable map type (v0.20b).
1327    /// Keys are confined to value-keyable types
1328    /// (`bynk.types.unkeyable_map_key`).
1329    Map(Box<TypeRef>, Box<TypeRef>, Span),
1330    /// `Query[T]` — the built-in lazy storage-read description (v0.91, ADR 0115).
1331    /// Nameable in a pure helper's return type; non-storable and non-boundary
1332    /// (like `Effect`/`Fn`).
1333    Query(Box<TypeRef>, Span),
1334    /// `ValidationError` — the built-in error type used by refined-type
1335    /// constructors (v0.1).
1336    ValidationError(Span),
1337    /// `JsonError` — the built-in JSON-decode error type (v0.22b). A
1338    /// uniform record (`kind`/`path`/`message`, all `String`) the codec
1339    /// maps `BoundaryError` variants and parse failures into.
1340    JsonError(Span),
1341    /// `()` — the unit type (v0.5).
1342    Unit(Span),
1343    /// `A -> B` / `(A, B) -> C` / `() -> B` — a function type (v0.20a).
1344    /// Right-associative; effectful iff the return type is `Effect[_]`
1345    /// (the structural rule). Confined to non-boundary positions
1346    /// (`bynk.types.function_at_boundary`).
1347    Fn(Vec<TypeRef>, Box<TypeRef>, Span),
1348}
1349
1350impl TypeRef {
1351    pub fn span(&self) -> Span {
1352        match self {
1353            TypeRef::Base(_, s) => *s,
1354            TypeRef::Named(id) => id.span,
1355            TypeRef::Result(_, _, s) => *s,
1356            TypeRef::Option(_, s) => *s,
1357            TypeRef::Effect(_, s) => *s,
1358            TypeRef::HttpResult(_, s) => *s,
1359            TypeRef::QueueResult(s) => *s,
1360            TypeRef::List(_, s) => *s,
1361            TypeRef::Map(_, _, s) => *s,
1362            TypeRef::Query(_, s) => *s,
1363            TypeRef::ValidationError(s) => *s,
1364            TypeRef::JsonError(s) => *s,
1365            TypeRef::Unit(s) => *s,
1366            TypeRef::Fn(_, _, s) => *s,
1367        }
1368    }
1369}
1370
1371#[derive(Debug, Clone)]
1372pub struct Expr {
1373    pub kind: ExprKind,
1374    pub span: Span,
1375}
1376
1377#[derive(Debug, Clone)]
1378pub enum ExprKind {
1379    IntLit(i64),
1380    /// A float literal (v0.21). The lexeme is kept alongside the parsed
1381    /// value so emission and formatting are byte-stable (`1e10` must not
1382    /// normalise to `10000000000`).
1383    FloatLit {
1384        value: f64,
1385        lexeme: String,
1386    },
1387    /// A duration literal `<int>.<unit>` (v0.86, ADR 0112): `5.minutes`,
1388    /// `30.days`. The parser recognises the `IntLit . <unit>` shape and records
1389    /// the magnitude, the unit, and the resolved milliseconds (the value the
1390    /// emitter lowers to). Typed `Duration`.
1391    DurationLit {
1392        /// The integer magnitude as written (`5` in `5.minutes`).
1393        value: i64,
1394        /// The unit name (`minutes`), one of the closed set.
1395        unit: DurationUnit,
1396        /// The value in milliseconds — `value * unit factor`.
1397        millis: i64,
1398    },
1399    StrLit(String),
1400    /// An interpolated string `"… \(expr) …"` (v0.43, ADR 0075). Chunks and
1401    /// holes alternate. A plain `"…"` with no holes stays [`ExprKind::StrLit`],
1402    /// so existing code and the emitter/formatter fast-path are untouched.
1403    InterpStr(Vec<InterpPart>),
1404    BoolLit(bool),
1405    Ident(Ident),
1406    Call {
1407        name: Ident,
1408        /// v0.20a: explicit type arguments (`name[T](…)`); empty when absent.
1409        type_args: Vec<TypeRef>,
1410        args: Vec<Expr>,
1411    },
1412    /// A lambda (v0.20a). See [`LambdaExpr`].
1413    Lambda(LambdaExpr),
1414    BinOp(BinOp, Box<Expr>, Box<Expr>),
1415    UnaryOp(UnaryOp, Box<Expr>),
1416    Paren(Box<Expr>),
1417    /// `{ stmts; expr }` — block expression (v0.1).
1418    Block(Block),
1419    /// `if cond { then } else { else }` (v0.1).
1420    If {
1421        cond: Box<Expr>,
1422        then_block: Box<Block>,
1423        else_block: Box<Block>,
1424    },
1425    /// `Ok(value)` — Result success constructor (v0.1).
1426    Ok(Box<Expr>),
1427    /// `Err(error)` — Result failure constructor (v0.1).
1428    Err(Box<Expr>),
1429    /// `expr?` — propagation operator (v0.1).
1430    Question(Box<Expr>),
1431    /// `TypeName.method(args)` — qualified static call on a type
1432    /// (v0.1: only refined-type `of`; v0.2: any static method or variant
1433    /// constructor for sum types). The resolver decides which.
1434    ConstructorCall {
1435        type_name: Ident,
1436        method: Ident,
1437        args: Vec<Expr>,
1438    },
1439    /// `TypeName { field: value, ... }` — record construction (v0.2).
1440    RecordConstruction {
1441        type_name: Ident,
1442        fields: Vec<FieldInit>,
1443    },
1444    /// `receiver.field` — field access on a record value (v0.2). v0.3 adds
1445    /// `.raw` on opaque types within the defining commons.
1446    FieldAccess {
1447        receiver: Box<Expr>,
1448        field: Ident,
1449    },
1450    /// `receiver.method(args)` — instance method call (v0.2). The
1451    /// resolver determines the receiver's type and looks up the method.
1452    MethodCall {
1453        receiver: Box<Expr>,
1454        method: Ident,
1455        /// v0.22b: explicit type arguments on a qualified static
1456        /// (`Json.decode[T](…)`); empty when absent. The same-line-`[`
1457        /// rule applies as for `Call` type application (0039).
1458        type_args: Vec<TypeRef>,
1459        args: Vec<Expr>,
1460    },
1461    /// `match disc { arm+ }` — pattern matching (v0.2).
1462    Match {
1463        discriminant: Box<Expr>,
1464        arms: Vec<MatchArm>,
1465    },
1466    /// `expr is pattern` — pattern test, returns Bool (v0.2).
1467    Is {
1468        value: Box<Expr>,
1469        pattern: Pattern,
1470    },
1471    /// `Some(value)` — Option Some constructor (v0.2).
1472    Some(Box<Expr>),
1473    /// `None` — Option None constructor (v0.2).
1474    None,
1475    /// `()` — unit literal (v0.5).
1476    UnitLit,
1477    /// `TypeName { ...base, field: value, ... }` or `{ ...base, ... }` —
1478    /// record spread expression (v0.5).
1479    RecordSpread {
1480        /// Optional type prefix (`TypeName { ...base }`). Absent for the
1481        /// bare form used inside `commit`.
1482        type_name: Option<Ident>,
1483        /// The base record being spread.
1484        base: Box<Expr>,
1485        /// Field overrides (always full `name: value` form — never shorthand).
1486        overrides: Vec<FieldInit>,
1487    },
1488    /// `Effect.pure(value)` — wrap a synchronous value into `Effect[T]`
1489    /// (v0.5). Recognised in the parser as a special-form.
1490    EffectPure(Box<Expr>),
1491    /// `assert expr` — assertion as an expression of type `()` (v0.9.1).
1492    /// Valid only inside test bodies. Evaluates `expr` (must be Bool); if
1493    /// false, the surrounding test case fails.
1494    Assert(Box<Expr>),
1495    /// `Mock[T]`, `Mock[T](args)` — test-context value construction (v0.9.4).
1496    /// `args` is empty for the bare form and holds the pin arguments for
1497    /// `Mock[T](...)`. The record-override form `Mock[T] { ... }` is not yet
1498    /// parsed. Valid only inside test bodies; has type `T`.
1499    Mock {
1500        type_ref: TypeRef,
1501        args: Vec<Expr>,
1502    },
1503    /// `[a, b, c]` — list literal (v0.20b). An empty `[]` requires an
1504    /// expected type (`bynk.types.uninferable_element_type`).
1505    ListLit(Vec<Expr>),
1506}
1507
1508/// One part of an interpolated string (v0.43, ADR 0075). An
1509/// [`ExprKind::InterpStr`] holds an alternating run of these.
1510#[derive(Debug, Clone)]
1511pub enum InterpPart {
1512    /// Literal text between holes, with escapes already resolved.
1513    Chunk(String),
1514    /// An interpolated expression `\(expr)`. Type-checked by the hole rule
1515    /// (base scalars only; see the checker) and lowered into a template-
1516    /// literal `${…}` slot.
1517    Hole(Box<Expr>),
1518}
1519
1520/// One field-initialiser inside a record construction expression:
1521/// either `name: expr` or the shorthand `name` (which requires a binding
1522/// of the same name in scope and uses its value).
1523#[derive(Debug, Clone)]
1524pub struct FieldInit {
1525    pub name: Ident,
1526    /// `None` means shorthand — the field's value is the same-named binding.
1527    pub value: Option<Expr>,
1528    pub span: Span,
1529}
1530
1531/// One arm of a `match` expression: `pattern => body`.
1532#[derive(Debug, Clone)]
1533pub struct MatchArm {
1534    pub pattern: Pattern,
1535    pub body: MatchBody,
1536    pub span: Span,
1537}
1538
1539/// The right-hand side of a match arm — either a single expression or
1540/// a block.
1541#[derive(Debug, Clone)]
1542pub enum MatchBody {
1543    Expr(Expr),
1544    Block(Block),
1545}
1546
1547impl MatchBody {
1548    pub fn span(&self) -> Span {
1549        match self {
1550            MatchBody::Expr(e) => e.span,
1551            MatchBody::Block(b) => b.span,
1552        }
1553    }
1554}
1555
1556/// A pattern (v0.2 §3.8). Patterns appear in `match` arms and as the
1557/// right-hand side of the `is` operator.
1558#[derive(Debug, Clone)]
1559pub enum Pattern {
1560    /// `_` — matches any value, no bindings.
1561    Wildcard(Span),
1562    /// `Variant` or `Variant(bindings)` or `TypeName.Variant(bindings)`.
1563    Variant {
1564        /// Optional qualifier: `TypeName.Variant`.
1565        type_name: Option<Ident>,
1566        /// The variant name.
1567        variant: Ident,
1568        /// Payload bindings (empty for nullary variants).
1569        bindings: Vec<PatternBinding>,
1570        span: Span,
1571    },
1572}
1573
1574impl Pattern {
1575    pub fn span(&self) -> Span {
1576        match self {
1577            Pattern::Wildcard(s) => *s,
1578            Pattern::Variant { span, .. } => *span,
1579        }
1580    }
1581}
1582
1583/// A single binding inside a variant pattern. Two surface forms:
1584/// `name` (positional — bind the i-th payload field) and
1585/// `fieldName: bindName` (named — bind the named payload field).
1586/// Both forms also accept `_` as the bind name to discard.
1587#[derive(Debug, Clone)]
1588pub struct PatternBinding {
1589    /// Source form: positional or named.
1590    pub kind: PatternBindingKind,
1591    pub span: Span,
1592}
1593
1594#[derive(Debug, Clone)]
1595pub enum PatternBindingKind {
1596    /// `name` (or `_`): bind the payload field at this position to `name`.
1597    Positional { name: Ident },
1598    /// `field: name` (or `field: _`): bind the named payload field to `name`.
1599    Named { field: Ident, name: Ident },
1600}
1601
1602impl PatternBinding {
1603    /// The local name introduced by this binding (used for scope).
1604    /// `_` is a sentinel for "no binding"; callers should compare against it.
1605    pub fn local_name(&self) -> &Ident {
1606        match &self.kind {
1607            PatternBindingKind::Positional { name } => name,
1608            PatternBindingKind::Named { name, .. } => name,
1609        }
1610    }
1611
1612    pub fn is_wildcard(&self) -> bool {
1613        self.local_name().name == "_"
1614    }
1615}
1616
1617#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1618pub enum BinOp {
1619    /// `P implies Q` — logical implication (v0.80). Desugars to `!P || Q`; sits
1620    /// at the lowest precedence (below `||`). Reads directionally (P → Q).
1621    Implies,
1622    Or,
1623    And,
1624    Eq,
1625    NotEq,
1626    Lt,
1627    LtEq,
1628    Gt,
1629    GtEq,
1630    Add,
1631    Sub,
1632    Mul,
1633    Div,
1634}
1635
1636impl BinOp {
1637    pub fn name(self) -> &'static str {
1638        match self {
1639            BinOp::Implies => "implies",
1640            BinOp::Or => "||",
1641            BinOp::And => "&&",
1642            BinOp::Eq => "==",
1643            BinOp::NotEq => "!=",
1644            BinOp::Lt => "<",
1645            BinOp::LtEq => "<=",
1646            BinOp::Gt => ">",
1647            BinOp::GtEq => ">=",
1648            BinOp::Add => "+",
1649            BinOp::Sub => "-",
1650            BinOp::Mul => "*",
1651            BinOp::Div => "/",
1652        }
1653    }
1654}
1655
1656#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1657pub enum UnaryOp {
1658    Neg,
1659    Not,
1660}
1661
1662impl UnaryOp {
1663    pub fn name(self) -> &'static str {
1664        match self {
1665            UnaryOp::Neg => "-",
1666            UnaryOp::Not => "!",
1667        }
1668    }
1669}