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