bynk_syntax/ast.rs
1//! Abstract syntax tree types for Bynk v0 (spec §9.2).
2
3use crate::span::Span;
4
5/// An identifier with its source span.
6#[derive(Debug, Clone)]
7pub struct Ident {
8 pub name: String,
9 pub span: Span,
10}
11
12/// Comment trivia attached to a declaration or statement (v1.1 LSP spec
13/// §3.5). The parser collects line comments from the token stream and
14/// attaches them to nearby AST nodes so the formatter can re-emit them.
15///
16/// - `leading` holds comments that appear immediately above the node,
17/// ordered top-to-bottom. Each entry is the body of one `--` line
18/// (the text after the marker, with its original inline whitespace
19/// preserved).
20/// - `trailing` holds a single comment that appears on the same source
21/// line as the node's final token (e.g. `expr -- note`).
22#[derive(Debug, Clone, Default)]
23pub struct Trivia {
24 pub leading: Vec<String>,
25 pub trailing: Option<String>,
26}
27
28impl Trivia {
29 pub fn is_empty(&self) -> bool {
30 self.leading.is_empty() && self.trailing.is_none()
31 }
32}
33
34/// A whole parsed commons source file.
35///
36/// In v0.3 a commons may be split across multiple files in a directory; the
37/// resolver merges them into one logical commons. Each parsed AST instance
38/// represents the contribution from a single source file.
39#[derive(Debug, Clone)]
40pub struct Commons {
41 pub name: QualifiedName,
42 pub items: Vec<CommonsItem>,
43 /// `uses` clauses declared in this file.
44 pub uses: Vec<UsesDecl>,
45 /// Optional documentation block attached to the commons declaration.
46 pub documentation: Option<String>,
47 /// Surface form of the file: brace-delimited body or headerless fragment.
48 pub form: CommonsForm,
49 pub span: Span,
50 /// Trivia attached to the commons declaration itself — leading comments
51 /// before the `commons` keyword and a trailing comment after the header
52 /// or closing brace.
53 pub trivia: Trivia,
54 /// Comments appearing after the last item but before the file ends
55 /// (or the closing brace, for brace form). One entry per `--` line.
56 pub trailing_comments: Vec<String>,
57}
58
59/// The two surface forms in which a commons body may be parsed (v0.3 §3.1).
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum CommonsForm {
62 /// `commons name { ... }`
63 Brace,
64 /// `commons name` followed by top-level declarations to EOF.
65 Fragment,
66}
67
68/// A `uses other.commons` declaration (v0.3 §3.3).
69#[derive(Debug, Clone)]
70pub struct UsesDecl {
71 pub target: QualifiedName,
72 pub span: Span,
73 pub trivia: Trivia,
74}
75
76/// A whole parsed context source file (v0.4 §3.1).
77///
78/// Contexts are the architectural-layer declaration kind. Like commons, a
79/// context may be split across multiple files in a directory.
80#[derive(Debug, Clone)]
81pub struct Context {
82 pub name: QualifiedName,
83 pub items: Vec<CommonsItem>,
84 /// `uses` clauses declared in this file.
85 pub uses: Vec<UsesDecl>,
86 /// `consumes` clauses declared in this file.
87 pub consumes: Vec<ConsumesDecl>,
88 /// `exports` clauses declared in this file.
89 pub exports: Vec<ExportsDecl>,
90 /// Optional documentation block attached to the context declaration.
91 pub documentation: Option<String>,
92 /// Surface form of the file: brace-delimited body or headerless fragment.
93 pub form: CommonsForm,
94 pub span: Span,
95 /// Trivia attached to the context declaration itself — leading comments
96 /// before the `context` keyword.
97 pub trivia: Trivia,
98 /// Comments appearing after the last item but before the file ends
99 /// (or the closing brace, for brace form). One entry per `--` line.
100 pub trailing_comments: Vec<String>,
101}
102
103/// A `consumes other.context` declaration (v0.4 §3.2). May optionally carry
104/// an alias introduced by `consumes other.context as Alias` (v0.6 §3.1).
105#[derive(Debug, Clone)]
106pub struct ConsumesDecl {
107 pub target: QualifiedName,
108 pub alias: Option<Ident>,
109 /// v0.17: `consumes U { Cap, … }` — selected capabilities flattened into
110 /// the consumer's local capability namespace under their bare names (§3.3).
111 /// `None` for the whole-unit forms; `Some` (possibly empty) for the braced
112 /// form. Mutually exclusive with `alias`.
113 pub selected: Option<Vec<Ident>>,
114 pub span: Span,
115 pub trivia: Trivia,
116}
117
118/// An `exports visibility { names }` clause (v0.4 §3.3) or, v0.15, an
119/// `exports capability { names }` clause.
120#[derive(Debug, Clone)]
121pub struct ExportsDecl {
122 pub kind: ExportKind,
123 pub names: Vec<Ident>,
124 pub span: Span,
125 pub trivia: Trivia,
126}
127
128/// What an `exports` clause exposes: types (with a visibility) or, v0.15,
129/// capabilities offered for cross-context consumption.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum ExportKind {
132 /// `exports opaque { ... }` / `exports transparent { ... }` — type exports.
133 Type(Visibility),
134 /// `exports capability { ... }` — capabilities offered to consumers (v0.15).
135 Capability,
136}
137
138/// Visibility level for an exports clause (v0.4 §3.3).
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum Visibility {
141 /// Token-only outside the context: hold, pass, compare; no inspect, no construct.
142 Opaque,
143 /// Readable shape outside the context: inspect fields, match variants; no construct.
144 Transparent,
145}
146
147/// An `adapter qualified.name { … }` declaration (v0.17 §3.1). An adapter
148/// co-locates a capability contract with a non-Bynk binding: it may declare
149/// capabilities, the boundary types they reference, inline pure helper
150/// `type`/`fn` (and `uses`), external (bodiless) providers, `exports
151/// capability`, and exactly one `binding` clause. It may *not* declare
152/// services, agents, or bodied providers. Like commons/contexts it may be
153/// split across files in a directory.
154#[derive(Debug, Clone)]
155pub struct AdapterDecl {
156 pub name: QualifiedName,
157 pub items: Vec<CommonsItem>,
158 /// `uses` clauses declared in this file (pure-vocabulary mixin; allowed
159 /// because helpers cannot pierce containment — spec [DECISION B]).
160 pub uses: Vec<UsesDecl>,
161 /// `exports capability { … }` clauses (adapters export capabilities and
162 /// boundary types, never services).
163 pub exports: Vec<ExportsDecl>,
164 /// v0.18: `consumes U { Cap, … }` clauses — adapter-to-adapter capability
165 /// dependencies (spec §4.5, \[N\]). Braced form only; adapter targets only
166 /// (both enforced semantically, not in the parser).
167 pub consumes: Vec<ConsumesDecl>,
168 /// The `binding "<module>" requires { … }` clause, if present. Required
169 /// when the adapter declares any external provider (`bynk.adapter.no_binding`).
170 pub binding: Option<BindingDecl>,
171 pub documentation: Option<String>,
172 pub form: CommonsForm,
173 pub span: Span,
174 pub trivia: Trivia,
175 pub trailing_comments: Vec<String>,
176}
177
178/// A `binding "<module>" requires { "pkg": "range", … }` clause inside an
179/// adapter (v0.17 §3.5). `module` is the TypeScript module supplying the
180/// adapter's external provider symbols, resolved relative to the adapter's
181/// source file. `requires` declares npm dependencies folded into the
182/// generated `package.json`.
183#[derive(Debug, Clone)]
184pub struct BindingDecl {
185 /// The module path as written (the string-literal contents, no quotes).
186 pub module: String,
187 pub module_span: Span,
188 pub requires: Vec<RequiresDep>,
189 pub span: Span,
190 pub trivia: Trivia,
191}
192
193/// One `"pkg": "range"` entry in a binding's `requires { … }` map.
194#[derive(Debug, Clone)]
195pub struct RequiresDep {
196 pub package: String,
197 pub range: String,
198 pub span: Span,
199}
200
201/// Either a commons or a context — the two declaration kinds at the file
202/// level (v0.4 §3.1). v0.7 adds the test declaration kind; v0.17 the adapter.
203#[derive(Debug, Clone)]
204pub enum SourceUnit {
205 Commons(Commons),
206 Context(Context),
207 Suite(SuiteDecl),
208 /// v0.17: an `adapter` unit — the host boundary (capability contract +
209 /// external binding).
210 Adapter(AdapterDecl),
211}
212
213impl SourceUnit {
214 pub fn name(&self) -> &QualifiedName {
215 match self {
216 SourceUnit::Commons(c) => &c.name,
217 SourceUnit::Context(c) => &c.name,
218 SourceUnit::Suite(t) => &t.target,
219 SourceUnit::Adapter(a) => &a.name,
220 }
221 }
222
223 pub fn span(&self) -> Span {
224 match self {
225 SourceUnit::Commons(c) => c.span,
226 SourceUnit::Context(c) => c.span,
227 SourceUnit::Suite(t) => t.span,
228 SourceUnit::Adapter(a) => a.span,
229 }
230 }
231
232 pub fn kind_name(&self) -> &'static str {
233 match self {
234 SourceUnit::Commons(_) => "commons",
235 SourceUnit::Context(_) => "context",
236 SourceUnit::Suite(_) => "suite",
237 SourceUnit::Adapter(_) => "adapter",
238 }
239 }
240}
241
242/// A `test <qualified-name> { ... }` declaration (v0.7 §3.1).
243///
244/// A test targets a commons or context by qualified name and bundles a set of
245/// test cases plus optional mock declarations. As with commons and contexts, a
246/// test may be split across multiple files (fragment form).
247#[derive(Debug, Clone)]
248pub struct SuiteDecl {
249 /// The targeted commons or context.
250 pub target: QualifiedName,
251 /// `uses` clauses brought in by this test fragment.
252 pub uses: Vec<UsesDecl>,
253 /// v0.118: suite-scoped `provides` clauses — per-seam provider overrides
254 /// applied to every case (a case-scoped `provides` takes precedence).
255 pub provides: Vec<ProvidesClause>,
256 /// The individual test cases.
257 pub cases: Vec<Case>,
258 /// v0.114: generative `property` blocks (testing track slice 2).
259 pub properties: Vec<PropertyDecl>,
260 /// v0.118: the suite-level tier default (`suite … as integration`). `None`
261 /// means the `unit` default; a `case`'s own tier overrides it. A `property`
262 /// ignores a suite tier (tiers are a `case`-only affordance).
263 pub tier: Option<TestTier>,
264 /// Surface form: brace-delimited body or headerless fragment.
265 pub form: CommonsForm,
266 /// Optional documentation block attached to the test declaration.
267 pub documentation: Option<String>,
268 pub span: Span,
269 pub trivia: Trivia,
270 pub trailing_comments: Vec<String>,
271}
272
273/// v0.118: the tier a `case` runs at (testing track slice 6, ADR 0153). One
274/// body promoted across the testing pyramid; `unit` is the default and elided.
275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
276pub enum TestTier {
277 /// Collaborators stubbed (the default).
278 Unit,
279 /// Real collaborators within one context, no serialisation wire.
280 Integration,
281 /// Contexts wired across the real serialise → JSON → deserialise boundary.
282 System,
283}
284
285impl TestTier {
286 pub fn as_str(self) -> &'static str {
287 match self {
288 TestTier::Unit => "unit",
289 TestTier::Integration => "integration",
290 TestTier::System => "system",
291 }
292 }
293}
294
295/// v0.118: a per-seam provider override `provides Cap.method(<args>) returns <v>
296/// | fails` (testing track slice 6, ADR 0154). Substitutes one capability
297/// method's provision under test; the right-hand side is a value or a fault,
298/// never a computed body.
299#[derive(Debug, Clone)]
300pub struct ProvidesClause {
301 /// The capability being overridden (a consumed seam of the unit).
302 pub capability: Ident,
303 /// The overridden method.
304 pub method: Ident,
305 /// One argument pattern per parameter (`_` or a value the arg must equal).
306 pub args: Vec<ArgPattern>,
307 /// The provision: a value, a fault, or a per-call sequence.
308 pub rhs: ProvidesRhs,
309 pub documentation: Option<String>,
310 pub span: Span,
311 pub trivia: Trivia,
312}
313
314/// v0.118: one argument pattern in a `provides` call pattern. Patterns for the
315/// same method are tried top-to-bottom, first match wins.
316#[derive(Debug, Clone)]
317pub enum ArgPattern {
318 /// `_` — matches any argument.
319 Any(Span),
320 /// A value the recorded argument must equal (a literal or pure value expr).
321 Value(Expr),
322}
323
324/// v0.118: the right-hand side of a `provides` clause.
325#[derive(Debug, Clone)]
326pub enum ProvidesRhs {
327 /// `returns <value>` — a single success value, repeated for every call.
328 Returns(Expr),
329 /// `fails` — inject a capability fault (Principle 3).
330 Fails(Span),
331 /// `returns each [<outcome>, …]` — one outcome per call, in order; the last
332 /// outcome repeats once the sequence is exhausted (DECISION V).
333 ReturnsEach(Vec<SeqOutcome>, Span),
334}
335
336impl ProvidesRhs {
337 pub fn span(&self) -> Span {
338 match self {
339 ProvidesRhs::Returns(e) => e.span,
340 ProvidesRhs::Fails(s) => *s,
341 ProvidesRhs::ReturnsEach(_, s) => *s,
342 }
343 }
344}
345
346/// v0.118: one outcome in a sequenced (`returns each`) `provides`.
347#[derive(Debug, Clone)]
348pub enum SeqOutcome {
349 /// A success value.
350 Value(Expr),
351 /// A fault.
352 Fails(Span),
353}
354
355/// A `case "name" [as <tier>] { [provides …] body }` block inside a suite
356/// (v0.7 §3.3; v0.118 adds the tier clause and case-scoped `provides`).
357#[derive(Debug, Clone)]
358pub struct Case {
359 /// The test name, taken from the string literal.
360 pub name: String,
361 /// The span of the string literal — used for diagnostics and runtime
362 /// failure reports.
363 pub name_span: Span,
364 /// v0.118: the case's own tier, if written (`as integration` / `as system`).
365 /// `None` means inherit the suite default (itself `unit` when unset).
366 pub tier: Option<TestTier>,
367 /// v0.118: case-scoped `provides` clauses (override the suite's, and the
368 /// tier default).
369 pub provides: Vec<ProvidesClause>,
370 pub body: Block,
371 pub documentation: Option<String>,
372 pub span: Span,
373 pub trivia: Trivia,
374}
375
376/// A `property "name" { for all <bindings> [where <pred>] { body } }` block
377/// inside a suite (v0.114, testing track slice 2, ADR 0149). The generative
378/// sibling of [`Case`]: the runner draws inhabitants of each binding's type from
379/// its refinement domain and evaluates the body's `expect`s over them.
380#[derive(Debug, Clone)]
381pub struct PropertyDecl {
382 /// The property name, taken from the string literal.
383 pub name: String,
384 /// The span of the string literal — used for diagnostics and reports.
385 pub name_span: Span,
386 /// The `for all` binder: the generated bindings, an optional `where` filter,
387 /// and the predicate body.
388 pub forall: ForAll,
389 pub documentation: Option<String>,
390 pub span: Span,
391 pub trivia: Trivia,
392}
393
394/// The `for all x: T, … [where <pred>] { … }` binder inside a [`PropertyDecl`].
395#[derive(Debug, Clone)]
396pub struct ForAll {
397 /// The generated bindings, `x: T` (one or more).
398 pub bindings: Vec<ForAllBinding>,
399 /// An optional `where <pred>` filter (a pure `Bool`) applied to generated
400 /// tuples before the body runs.
401 pub where_pred: Option<Expr>,
402 /// The body — one or more statements, typically `expect`s.
403 pub body: Block,
404 pub span: Span,
405}
406
407/// One `for all` binding: `name: T`, where the runner generates inhabitants of
408/// `T` from its refinements.
409#[derive(Debug, Clone)]
410pub struct ForAllBinding {
411 pub name: Ident,
412 pub type_ref: TypeRef,
413}
414
415/// A capability reference in a `given` clause (v0.15 §3.2). A bare name is a
416/// local capability (`given Cap`); a dotted name refers to a capability a
417/// consumed context provides (`given B.Cap` / `given Alias.Cap`).
418#[derive(Debug, Clone)]
419pub struct CapRef {
420 /// `None` for a local capability; `Some(prefix)` for a cross-context
421 /// reference where `prefix` is a consumed-context qualified name or alias.
422 pub context: Option<QualifiedName>,
423 /// The capability's simple name (also the local deps key).
424 pub name: Ident,
425 pub span: Span,
426}
427
428impl CapRef {
429 /// The local deps key / capability simple name (e.g. `Clock`).
430 pub fn key(&self) -> &str {
431 &self.name.name
432 }
433
434 /// True when this references a capability provided by a consumed context.
435 pub fn is_cross_context(&self) -> bool {
436 self.context.is_some()
437 }
438
439 /// The cross-context prefix (consumed-context qualified name or alias) as
440 /// a dotted string, if any.
441 pub fn prefix(&self) -> Option<String> {
442 self.context.as_ref().map(|q| q.joined())
443 }
444}
445
446/// A dotted name like `fitness.units`.
447#[derive(Debug, Clone)]
448pub struct QualifiedName {
449 pub parts: Vec<Ident>,
450 pub span: Span,
451}
452
453impl QualifiedName {
454 pub fn joined(&self) -> String {
455 self.parts
456 .iter()
457 .map(|p| p.name.as_str())
458 .collect::<Vec<_>>()
459 .join(".")
460 }
461}
462
463#[derive(Debug, Clone)]
464pub enum CommonsItem {
465 Type(TypeDecl),
466 Fn(FnDecl),
467 /// `capability Name { fn op(...) -> T ... }` (v0.5; contexts only).
468 Capability(CapabilityDecl),
469 /// `provides Cap = ProviderName { fn op(...) -> T { ... } ... }` (v0.5).
470 Provider(ProviderDecl),
471 /// `service Name { on call(...) -> T { ... } ... }` (v0.5).
472 Service(ServiceDecl),
473 /// `agent Name { key id: T; state { ... }; on call ... }` (v0.5).
474 Agent(AgentDecl),
475 /// `actor Name { auth = Scheme, identity = T }` (v0.45). A nominal boundary
476 /// contract consumed by a handler's `by` clause; not a runnable entity.
477 Actor(ActorDecl),
478}
479
480impl CommonsItem {
481 pub fn name(&self) -> &Ident {
482 match self {
483 CommonsItem::Type(t) => &t.name,
484 CommonsItem::Fn(f) => f.name.ident(),
485 CommonsItem::Capability(c) => &c.name,
486 CommonsItem::Provider(p) => &p.provider_name,
487 CommonsItem::Service(s) => &s.name,
488 CommonsItem::Agent(a) => &a.name,
489 CommonsItem::Actor(a) => &a.name,
490 }
491 }
492}
493
494/// A capability declaration (v0.5 §3.3). Capabilities are interface-like
495/// contracts for external dependencies, used inside contexts. They may only
496/// appear inside a `context` declaration.
497#[derive(Debug, Clone)]
498pub struct CapabilityDecl {
499 pub name: Ident,
500 pub ops: Vec<CapabilityOp>,
501 pub documentation: Option<String>,
502 pub span: Span,
503 pub trivia: Trivia,
504}
505
506/// One operation in a capability (signature only; no body).
507#[derive(Debug, Clone)]
508pub struct CapabilityOp {
509 pub name: Ident,
510 pub params: Vec<Param>,
511 pub return_type: TypeRef,
512 pub documentation: Option<String>,
513 pub span: Span,
514 pub trivia: Trivia,
515}
516
517/// A provider declaration (v0.5 §3.4). Supplies an implementation for a
518/// capability.
519#[derive(Debug, Clone)]
520pub struct ProviderDecl {
521 /// The capability being implemented.
522 pub capability: Ident,
523 /// The provider's identifier (used in tests/config to select impls).
524 pub provider_name: Ident,
525 /// v0.12: capabilities this provider depends on (`provides X = Impl given
526 /// Y, Z { … }`). The provider's operation bodies may use these. v0.15:
527 /// a dependency may be a cross-context capability (`given B.Cap`).
528 pub given: Vec<CapRef>,
529 pub ops: Vec<ProviderOp>,
530 /// v0.17: an *external* provider — `provides Cap = Name` with **no** brace
531 /// block — inside an adapter, supplied by the adapter's binding rather than
532 /// a Bynk body. When `true`, `ops` is empty and the emitter produces no
533 /// class. The absence of the brace block (not an empty one) is the signal.
534 pub external: bool,
535 pub documentation: Option<String>,
536 pub span: Span,
537 pub trivia: Trivia,
538}
539
540/// One operation in a provider (signature plus body).
541#[derive(Debug, Clone)]
542pub struct ProviderOp {
543 pub name: Ident,
544 pub params: Vec<Param>,
545 pub return_type: TypeRef,
546 pub body: Block,
547 pub span: Span,
548 pub trivia: Trivia,
549}
550
551/// A service declaration (v0.5 §3.5). Services are the boundary interface
552/// of a context.
553#[derive(Debug, Clone)]
554pub struct ServiceDecl {
555 pub name: Ident,
556 /// The protocol the service conforms to, from the `from <protocol>` header
557 /// clause (v0.44). `Call` when there is no clause.
558 pub protocol: ServiceProtocol,
559 /// The optional cross-origin (CORS) policy (v0.131, ADR 0159) — a `cors { }`
560 /// section in the service body, only meaningful on a `from http` service.
561 /// `None` when absent (same-origin default, byte-for-byte unchanged output).
562 pub cors: Option<CorsPolicy>,
563 pub handlers: Vec<Handler>,
564 pub documentation: Option<String>,
565 pub span: Span,
566 pub trivia: Trivia,
567}
568
569/// A cross-origin resource-sharing policy on a `from http` service (v0.131,
570/// ADR 0159): the `cors { }` section in the service body. Parsed leniently as a
571/// list of `name: value` fields (the grammar accepts any field name — an unknown
572/// one is a checker diagnostic, per the `@`-annotation precedent, ADR 0111), and
573/// interpreted through the typed accessors below.
574///
575/// `Access-Control-Allow-Methods` is deliberately **not** a field — it is derived
576/// from the service's routes at emit time (the routes already enumerate the
577/// methods; a restated list would drift). Likewise `Allow-Headers` defaults to
578/// `content-type` (+ `Authorization` when a Bearer route exists) and is only
579/// stored here when the author overrides it.
580#[derive(Debug, Clone)]
581pub struct CorsPolicy {
582 /// The `cors { }` fields as written, in source order. Field names are
583 /// validated against the closed set (`origins`/`headers`/`credentials`/
584 /// `maxAge`) by the checker, not the parser.
585 pub fields: Vec<CorsField>,
586 pub span: Span,
587 pub trivia: Trivia,
588}
589
590/// One `name: value` field inside a `cors { }` policy (v0.131).
591#[derive(Debug, Clone)]
592pub struct CorsField {
593 pub name: Ident,
594 pub value: Expr,
595 pub span: Span,
596}
597
598impl CorsPolicy {
599 /// The raw value expression for a field, by name (the last one wins if a
600 /// field is repeated — the checker flags the duplicate separately).
601 pub fn field(&self, name: &str) -> Option<&Expr> {
602 self.fields
603 .iter()
604 .rev()
605 .find(|f| f.name.name == name)
606 .map(|f| &f.value)
607 }
608
609 /// The allowed origins — the string literals of the `origins:` list. An
610 /// absent or malformed field yields an empty list (the checker has already
611 /// reported the shape error; the emitter fails closed on an empty list).
612 pub fn origins(&self) -> Vec<String> {
613 Self::str_list(self.field("origins")).unwrap_or_default()
614 }
615
616 /// `true` iff `origins` is exactly the wildcard `["*"]`.
617 pub fn is_wildcard(&self) -> bool {
618 let os = self.origins();
619 os.len() == 1 && os[0] == "*"
620 }
621
622 /// Whether credentialed requests are allowed (`credentials: true`); defaults
623 /// to `false` when the field is absent.
624 pub fn credentials(&self) -> bool {
625 matches!(
626 self.field("credentials").map(|e| &e.kind),
627 Some(ExprKind::BoolLit(true))
628 )
629 }
630
631 /// The explicit `Access-Control-Allow-Headers` override, if the author gave
632 /// a `headers:` list; `None` leaves the emitter to apply its smart default.
633 pub fn allow_headers(&self) -> Option<Vec<String>> {
634 self.field("headers").and_then(Self::str_list_of)
635 }
636
637 /// The `Access-Control-Max-Age` in whole seconds, if a `maxAge:` duration was
638 /// given; `None` leaves the header off (the browser default).
639 pub fn max_age_secs(&self) -> Option<i64> {
640 match self.field("maxAge").map(|e| &e.kind) {
641 Some(ExprKind::DurationLit { millis, .. }) => Some(millis / 1_000),
642 _ => None,
643 }
644 }
645
646 /// Interpret an expression as a list of string literals, if it is one.
647 fn str_list(expr: Option<&Expr>) -> Option<Vec<String>> {
648 expr.and_then(Self::str_list_of)
649 }
650
651 fn str_list_of(expr: &Expr) -> Option<Vec<String>> {
652 match &expr.kind {
653 ExprKind::ListLit(items) => items
654 .iter()
655 .map(|e| match &e.kind {
656 ExprKind::StrLit(s) => Some(s.clone()),
657 _ => None,
658 })
659 .collect(),
660 _ => None,
661 }
662 }
663}
664
665/// The protocol a service conforms to — declared on the header via
666/// `from <protocol>` (v0.44). `Call` is the default (no `from` clause): a
667/// contract-mediated internal-RPC surface, not a wire protocol. Multi-endpoint
668/// protocols (`Http`, `Cron`) carry no binding — the endpoint lives on each
669/// handler; single-binding `Queue` carries its queue name.
670#[derive(Debug, Clone)]
671pub enum ServiceProtocol {
672 /// No `from` clause: the service holds `on call` handlers only.
673 Call,
674 /// `from http` — many routes; each handler is `on <Method>("route")`.
675 Http,
676 /// `from cron` — many schedules; each handler is `on schedule("expr")`.
677 Cron,
678 /// `from queue("name")` — one bound queue; handlers are `on message(...)`.
679 Queue { name: String },
680 /// `from WebSocket(in: ClientFrame, out: ServerFrame)` — a held WebSocket
681 /// connection (v0.103, real-time track slice 3). `in_type` is the inbound
682 /// frame type (client→server, decoded and routed as typed agent messages);
683 /// `out_type` is the server→client frame type the held `Connection[out_type]`
684 /// carries. The service holds exactly one `on open` handler (edge auth via
685 /// `by`, then transfer of the connection to an agent).
686 WebSocket { in_type: TypeRef, out_type: TypeRef },
687}
688
689/// An agent declaration (v0.5 §3.6). Agents are state-bearing entities
690/// with their own handlers.
691#[derive(Debug, Clone)]
692pub struct AgentDecl {
693 pub name: Ident,
694 /// `key id: Type` — the identifier-typed value identifying instances.
695 pub key_name: Ident,
696 pub key_type: TypeRef,
697 /// `store` fields (v0.81, storage track) — each an access-pattern slot of a
698 /// declared storage kind (`Cell`/`Map`/…). The successor to the removed
699 /// `state { }` record (ADR 0108); every agent declares its state this way.
700 pub store_fields: Vec<StoreField>,
701 /// Invariants (v0.80 §14) — universally-quantified predicates over the
702 /// agent's `store` fields. The phase sits between the fields and the
703 /// handlers; each is checked against the state staged by a handler's writes
704 /// before it commits.
705 pub invariants: Vec<Invariant>,
706 /// Step invariants (v0.116 §, testing track slice 4) — named predicates over
707 /// the pre-/post-commit state *pair* (`old`/`new`), checked at the commit
708 /// boundary beside [`invariants`], from the second commit onward. Widen the
709 /// invariant subject from a snapshot to a step (ADR 0144 — one predicate
710 /// surface).
711 ///
712 /// [`invariants`]: AgentDecl::invariants
713 pub transitions: Vec<Transition>,
714 pub handlers: Vec<Handler>,
715 pub documentation: Option<String>,
716 pub span: Span,
717 pub trivia: Trivia,
718}
719
720/// A `store` field (v0.81, storage track). Each is an access-pattern slot of a
721/// declared storage kind: `store <name>: <Kind>[…] [@annotations] [= <init>]`.
722/// The kind and its element type are carried as an ordinary [`TypeRef`]
723/// (`Cell[Int]`, `Map[K, V]`); the checker restricts which heads are storage
724/// kinds. Access-pattern annotations (`@indexed`, …) parse into [`annotations`]
725/// (v0.85, ADR 0111); the checker validates them against the closed registry.
726///
727/// [`annotations`]: StoreField::annotations
728#[derive(Debug, Clone)]
729pub struct StoreField {
730 pub name: Ident,
731 /// The storage kind and its element type(s): `Cell[Int]`, `Map[K, V]`. A
732 /// dedicated [`StoreKind`] rather than a [`TypeRef`] — storage kinds are not
733 /// value types, and the checker dispatches kind-aware operations on the head.
734 pub kind: StoreKind,
735 /// Storage annotations on the field (v0.85, ADR 0111): `@ttl(5.minutes)`,
736 /// `@indexed(by: orderId)`. Parsed in declaration order (after the kind,
737 /// before the initialiser); the checker validates names against the closed
738 /// registry and gates each to the slice that implements it.
739 pub annotations: Vec<Annotation>,
740 /// The fresh-key initial value (`= expr`), if given — same disposition as a
741 /// `state` field's initialiser (ADRs 0003/0004 carry forward).
742 pub init: Option<Expr>,
743 pub documentation: Option<String>,
744 pub span: Span,
745 pub trivia: Trivia,
746}
747
748/// A storage annotation on a `store` field (v0.85, storage track; ADR 0111):
749/// `@<name>(<args>)`. The `name` is matched against the closed registry
750/// (`@indexed`/`@ttl`/`@retain`/`@bounded`) by the checker; the grammar accepts
751/// any identifier so an unknown name is a checker diagnostic, not a parse error.
752/// Arguments are compile-time metadata, restricted to literals (and the `by:`
753/// field-name labels of `@indexed`) by the checker per ADR 0111 D4.
754#[derive(Debug, Clone)]
755pub struct Annotation {
756 pub name: Ident,
757 pub args: Vec<AnnotationArg>,
758 pub span: Span,
759}
760
761/// A single annotation argument (v0.85; ADR 0111): an optional `label:` followed
762/// by a value expression — `by: orderId` (labelled) or `5.minutes` (positional).
763/// The value is parsed as an ordinary [`Expr`] so the duration-literal form
764/// (`5.minutes`, landing with the `Duration` slice) needs no special grammar;
765/// the checker restricts it to a literal where the annotation is functional.
766#[derive(Debug, Clone)]
767pub struct AnnotationArg {
768 pub label: Option<Ident>,
769 pub value: Expr,
770 pub span: Span,
771}
772
773/// A storage kind applied to its element type(s) (v0.81): `Cell[Int]`,
774/// `Map[ReservationId, Reservation]`. The `head` is the kind name (`Cell`,
775/// `Map`, `Set`, `Log`, `Queue`, `Cache`); the checker validates it against the
776/// closed catalogue. Element types are ordinary [`TypeRef`]s. Refined element
777/// types (`Cell[Int where NonNegative]`) ride a later slice (parse_type_ref does
778/// not yet accept an inline refinement in type-argument position).
779#[derive(Debug, Clone)]
780pub struct StoreKind {
781 pub head: Ident,
782 pub args: Vec<TypeRef>,
783 pub span: Span,
784}
785
786/// An agent invariant (v0.80 §14). A named predicate over the agent's state
787/// fields that must hold of every committed state; a commit that would violate
788/// it faults (`InvariantViolation`) before the state is persisted. The
789/// predicate references state fields by bare name, mirroring the design-notes
790/// worked examples (`status == Paid implies paymentRef.isSome()`).
791#[derive(Debug, Clone)]
792pub struct Invariant {
793 pub name: Ident,
794 /// The predicate expression — an ordinary `Bool`-typed expression over the
795 /// state fields, plus `implies` and `is`. The parsed-predicate-on-a-
796 /// declaration shape mirrors [`ActorRefinement::predicate`].
797 pub predicate: Expr,
798 pub documentation: Option<String>,
799 pub span: Span,
800 pub trivia: Trivia,
801}
802
803/// An agent step invariant (v0.116 §, testing track slice 4). A named predicate
804/// over the *pair* of committed states — the pre-commit `old` and the proposed
805/// `new`, each the agent's state record — that must hold of every state move; a
806/// commit that would violate it faults (`InvariantViolation`) before the state is
807/// persisted, exactly as a snapshot [`Invariant`] does. Widens the invariant
808/// subject from a snapshot to a step (ADR 0144 — one predicate surface); the
809/// predicate reuses the invariant surface (`implies`/`is`/pure methods) with
810/// `old`/`new` bound contextually (`old.status is Paid implies new.status is
811/// Paid`).
812#[derive(Debug, Clone)]
813pub struct Transition {
814 pub name: Ident,
815 /// The predicate expression — an ordinary `Bool`-typed expression over the
816 /// `old` and `new` state records, with `implies`/`is` and pure methods,
817 /// mirroring [`Invariant`].
818 pub predicate: Expr,
819 pub documentation: Option<String>,
820 pub span: Span,
821 pub trivia: Trivia,
822}
823
824/// A function contract clause (v0.115 §, testing track slice 3). A named
825/// predicate on a `fn` signature — a `requires` (precondition) or `ensures`
826/// (postcondition). A contract is the invariant predicate attached to a
827/// function (ADR 0144 — one predicate surface): the predicate is a pure `Bool`
828/// expression over the parameters (`requires`) or the parameters plus `result`
829/// (`ensures`), with `implies`/`is` and pure methods, mirroring [`Invariant`].
830/// The name rides the failure report and the redundant-test dedup.
831#[derive(Debug, Clone)]
832pub struct Contract {
833 pub name: Ident,
834 /// The predicate expression — an ordinary `Bool`-typed expression over the
835 /// parameters (and, for an `ensures`, the contextual `result` binding).
836 pub predicate: Expr,
837 pub span: Span,
838}
839
840/// An actor declaration (v0.45 §3.7). An actor is a nominal *contract type*
841/// describing an external party at a boundary — not a runnable entity. A
842/// handler consumes an actor on its `by` clause; the boundary verifies the
843/// declared `auth` scheme and mints a sealed identity (`name.identity`).
844#[derive(Debug, Clone)]
845pub struct ActorDecl {
846 pub name: Ident,
847 /// The authentication scheme from `auth = <Scheme>`, stored as the raw
848 /// identifier. The checker classifies it: `None`/`Internal`/`Bearer` are
849 /// admitted; `Signature` is reserved-and-rejected
850 /// (`bynk.actor.scheme_unsupported`); anything else is
851 /// `bynk.actor.unknown_scheme`. `None` for the refinement form.
852 pub auth: Option<Ident>,
853 /// The scheme's keyed config from `auth = Scheme(key = value, …)` (v0.47
854 /// `Bearer(secret = "…")`; v0.51 generalised for `Signature(secret, header,
855 /// timestamp?, tolerance?)`). Empty for schemes/forms with no config. The
856 /// checker validates which keys each scheme requires/allows.
857 pub auth_config: Vec<SchemeArg>,
858 /// The optional identity type from `, identity = <T>`. Absent ⇒ the
859 /// scheme default (`()` for `None`; a sealed `CallerId` for the `Internal`
860 /// `on call` channel, `()` for other `Internal` channels).
861 pub identity: Option<TypeRef>,
862 /// The reserved-and-rejected refinement form `actor Admin = Base where p`
863 /// (Q3). Parsed so the grammar is fixed now; the checker emits
864 /// `bynk.actor.refinement_unsupported`.
865 pub refinement: Option<ActorRefinement>,
866 pub documentation: Option<String>,
867 pub span: Span,
868 pub trivia: Trivia,
869}
870
871impl ActorDecl {
872 /// The value of a scheme config arg by key, if present (e.g. `secret`,
873 /// `header`).
874 pub fn scheme_arg(&self, key: &str) -> Option<&SchemeArg> {
875 self.auth_config.iter().find(|a| a.key.name == key)
876 }
877}
878
879/// One `key = value` argument in a scheme config (`Scheme(key = value, …)`).
880#[derive(Debug, Clone)]
881pub struct SchemeArg {
882 pub key: Ident,
883 pub value: SchemeArgValue,
884 /// Span of the value, for diagnostics.
885 pub span: Span,
886}
887
888/// A scheme config arg value — a string literal or an integer.
889#[derive(Debug, Clone)]
890pub enum SchemeArgValue {
891 Str(String),
892 Int(i64),
893}
894
895impl SchemeArgValue {
896 pub fn as_str(&self) -> Option<&str> {
897 match self {
898 SchemeArgValue::Str(s) => Some(s),
899 SchemeArgValue::Int(_) => None,
900 }
901 }
902 pub fn as_int(&self) -> Option<i64> {
903 match self {
904 SchemeArgValue::Int(n) => Some(*n),
905 SchemeArgValue::Str(_) => None,
906 }
907 }
908}
909
910/// The reserved refinement form `actor Admin = User where <predicate>` (Q3).
911/// Parsed in Foundations so the grammar is fixed; admission is a later slice.
912#[derive(Debug, Clone)]
913pub struct ActorRefinement {
914 /// The base actor being refined.
915 pub base: Ident,
916 /// The `where` predicate. Parsed but not yet checked.
917 pub predicate: Expr,
918 pub span: Span,
919}
920
921/// The `by (<binder>:)? <Actor>` clause on a handler (v0.45; binder optional in
922/// v0.50). Names the actor contract the handler consumes; when a `binder` is
923/// given, the verified identity binds to it and is read as `binder.identity`.
924/// Omitting the binder (`by <Actor>`) declares-and-verifies the contract without
925/// capturing the identity — for anonymous or verify-and-discard handlers. Sits
926/// after the protocol config and before the parameters.
927#[derive(Debug, Clone)]
928pub struct ByClause {
929 /// The identity binder, if the handler consumes the identity. `None` for the
930 /// binder-less `by <Actor>` form. Required when `actors` names more than one
931 /// (a sum is resolved by matching on the bound actor).
932 pub binder: Option<Ident>,
933 /// The actor contract(s) referenced — each a local actor decl or a prelude
934 /// actor. A single name is the ordinary single-actor handler; more than one
935 /// (`by who: A | B`, v0.52) is an **ordered sum of peer actors** resolved
936 /// first-wins, the body matching on the resolved actor. Always non-empty.
937 pub actors: Vec<Ident>,
938 pub span: Span,
939}
940
941impl ByClause {
942 /// The first (and, for a single-actor handler, only) actor contract named.
943 pub fn primary(&self) -> &Ident {
944 &self.actors[0]
945 }
946 /// Whether this `by` clause names an ordered sum of peer actors (`A | B`).
947 pub fn is_sum(&self) -> bool {
948 self.actors.len() > 1
949 }
950}
951
952/// A handler block — `on call(args) -> T given C1, C2 { body }`.
953/// Used by both services and agents.
954#[derive(Debug, Clone)]
955pub struct Handler {
956 pub kind: HandlerKind,
957 /// For agent handlers, the method-style handler name (e.g.
958 /// `on call addItem(...)`). For service handlers, this is None (just
959 /// `on call(...)`).
960 pub method_name: Option<Ident>,
961 /// The `by <binder>: <Actor>` clause (v0.45), if present. Service handlers
962 /// only; an absent clause inherits the protocol's default actor.
963 pub by_clause: Option<ByClause>,
964 pub params: Vec<Param>,
965 pub return_type: TypeRef,
966 pub given: Vec<CapRef>,
967 pub body: Block,
968 pub documentation: Option<String>,
969 pub span: Span,
970 pub trivia: Trivia,
971}
972
973#[derive(Debug, Clone, PartialEq, Eq)]
974pub enum HandlerKind {
975 /// `on call(...)` — typed RPC (the only kind in v0.5).
976 Call,
977 /// `on http METHOD "path"` — external-facing HTTP route (v0.9).
978 Http { method: HttpMethod, path: String },
979 /// `on cron "expr"` — scheduled task; `expr` is a 5-field cron
980 /// expression (v0.10a).
981 Cron { expr: String },
982 /// `on message(m: T)` — a message off the service's bound queue. The queue
983 /// binding lives on the service's `ServiceProtocol::Queue` (v0.44).
984 Message,
985 /// `on open ...` — the WebSocket upgrade handler (v0.103, real-time track
986 /// slice 3). Exactly one per `from WebSocket` service; carries a mandatory
987 /// `by` clause (edge auth) and receives a fresh owned `Connection[out]`.
988 Open,
989 /// `on close ...` — the WebSocket close handler (v0.106, real-time track slice
990 /// 3b-iii). Optional, ≤1 per `from WebSocket` service; runs when the socket
991 /// closes. Like `on open`, edge-authenticated (`by`), with the identity/params
992 /// recovered from the socket attachment (set at `on open`). (A `from WebSocket`
993 /// `on message` reuses [`HandlerKind::Message`], disambiguated by the protocol.)
994 Close,
995}
996
997/// HTTP methods supported by `on http` handlers (v0.9).
998#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
999pub enum HttpMethod {
1000 Get,
1001 Post,
1002 Put,
1003 Patch,
1004 Delete,
1005}
1006
1007impl HttpMethod {
1008 pub fn as_str(self) -> &'static str {
1009 match self {
1010 HttpMethod::Get => "GET",
1011 HttpMethod::Post => "POST",
1012 HttpMethod::Put => "PUT",
1013 HttpMethod::Patch => "PATCH",
1014 HttpMethod::Delete => "DELETE",
1015 }
1016 }
1017
1018 pub fn from_ident(s: &str) -> Option<HttpMethod> {
1019 match s {
1020 "GET" => Some(HttpMethod::Get),
1021 "POST" => Some(HttpMethod::Post),
1022 "PUT" => Some(HttpMethod::Put),
1023 "PATCH" => Some(HttpMethod::Patch),
1024 "DELETE" => Some(HttpMethod::Delete),
1025 _ => None,
1026 }
1027 }
1028
1029 /// True if this method conventionally has no request body.
1030 pub fn forbids_body(self) -> bool {
1031 matches!(self, HttpMethod::Get | HttpMethod::Delete)
1032 }
1033}
1034
1035/// Payload shape of an `HttpResult[T]` variant (v0.9 §3.3).
1036#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1037pub enum HttpVariantPayload {
1038 /// No payload (e.g. `NoContent`, `Unauthorized`).
1039 None,
1040 /// Carries a value of the `HttpResult` type parameter `T`.
1041 Value,
1042 /// Carries a `String` message (e.g. `BadRequest`, `Conflict`).
1043 Message,
1044 /// Carries a `String` target URL, emitted as a `Location` header — the
1045 /// redirect variants (`Found`, `SeeOther`, `PermanentRedirect`, …).
1046 Location,
1047 /// Carries a `Stream[String]`, emitted as an SSE (`text/event-stream`)
1048 /// streaming body — the `Streaming` (200) variant (v0.101, real-time track
1049 /// slice 1).
1050 Streamed,
1051 /// Carries `(body: Bytes, contentType: String)` — the author-owned raw body
1052 /// written straight into the response with the declared `content-type` and
1053 /// **no codec** (the typed-wire guarantee is deliberately off). The `Raw`
1054 /// (200) variant (v0.111); the first two-argument payload shape.
1055 Raw,
1056}
1057
1058/// One variant of the built-in `HttpResult[T]` sum (v0.9 §3.3).
1059#[derive(Debug, Clone, Copy)]
1060pub struct HttpVariant {
1061 pub name: &'static str,
1062 pub payload: HttpVariantPayload,
1063 pub status: u16,
1064}
1065
1066/// All `HttpResult[T]` variants, in declaration order (ascending status). The
1067/// vocabulary tracks the common, modern HTTP status codes (RFC 9110): success
1068/// and created/accepted (`Value`), redirects carrying a `Location` URL, and
1069/// the client/server failures that handlers routinely return (`Message` when
1070/// an explanation helps the caller, `None` for self-describing statuses).
1071pub const HTTP_VARIANTS: &[HttpVariant] = &[
1072 // ── 2xx success ──────────────────────────────────────────────────────
1073 HttpVariant {
1074 name: "Ok",
1075 payload: HttpVariantPayload::Value,
1076 status: 200,
1077 },
1078 // v0.101 (real-time track slice 1): a 200 whose body is a streamed
1079 // `Stream[String]`, SSE-framed. Status precedes the body, so streaming is
1080 // 200-only — pre-stream failures are ordinary variants returned instead.
1081 HttpVariant {
1082 name: "Streaming",
1083 payload: HttpVariantPayload::Streamed,
1084 status: 200,
1085 },
1086 // v0.111: a 200 whose body is an author-owned `Bytes` written straight into
1087 // the response with the declared `content-type` — no codec runs. 200-only,
1088 // like `Streaming`: it serves service-tier raw bodies (`robots.txt`,
1089 // `sitemap.xml`, feeds, a QR PNG), not custom-status error pages.
1090 HttpVariant {
1091 name: "Raw",
1092 payload: HttpVariantPayload::Raw,
1093 status: 200,
1094 },
1095 HttpVariant {
1096 name: "Created",
1097 payload: HttpVariantPayload::Value,
1098 status: 201,
1099 },
1100 HttpVariant {
1101 name: "Accepted",
1102 payload: HttpVariantPayload::Value,
1103 status: 202,
1104 },
1105 HttpVariant {
1106 name: "NoContent",
1107 payload: HttpVariantPayload::None,
1108 status: 204,
1109 },
1110 // ── 3xx redirection (carry a `Location` URL) ─────────────────────────
1111 HttpVariant {
1112 name: "MovedPermanently",
1113 payload: HttpVariantPayload::Location,
1114 status: 301,
1115 },
1116 HttpVariant {
1117 name: "Found",
1118 payload: HttpVariantPayload::Location,
1119 status: 302,
1120 },
1121 HttpVariant {
1122 name: "SeeOther",
1123 payload: HttpVariantPayload::Location,
1124 status: 303,
1125 },
1126 HttpVariant {
1127 name: "TemporaryRedirect",
1128 payload: HttpVariantPayload::Location,
1129 status: 307,
1130 },
1131 HttpVariant {
1132 name: "PermanentRedirect",
1133 payload: HttpVariantPayload::Location,
1134 status: 308,
1135 },
1136 // ── 4xx client error ─────────────────────────────────────────────────
1137 HttpVariant {
1138 name: "BadRequest",
1139 payload: HttpVariantPayload::Message,
1140 status: 400,
1141 },
1142 HttpVariant {
1143 name: "Unauthorized",
1144 payload: HttpVariantPayload::None,
1145 status: 401,
1146 },
1147 HttpVariant {
1148 name: "Forbidden",
1149 payload: HttpVariantPayload::None,
1150 status: 403,
1151 },
1152 HttpVariant {
1153 name: "NotFound",
1154 payload: HttpVariantPayload::None,
1155 status: 404,
1156 },
1157 HttpVariant {
1158 name: "MethodNotAllowed",
1159 payload: HttpVariantPayload::None,
1160 status: 405,
1161 },
1162 HttpVariant {
1163 name: "NotAcceptable",
1164 payload: HttpVariantPayload::None,
1165 status: 406,
1166 },
1167 HttpVariant {
1168 name: "RequestTimeout",
1169 payload: HttpVariantPayload::None,
1170 status: 408,
1171 },
1172 HttpVariant {
1173 name: "Conflict",
1174 payload: HttpVariantPayload::Message,
1175 status: 409,
1176 },
1177 HttpVariant {
1178 name: "Gone",
1179 payload: HttpVariantPayload::None,
1180 status: 410,
1181 },
1182 HttpVariant {
1183 name: "LengthRequired",
1184 payload: HttpVariantPayload::None,
1185 status: 411,
1186 },
1187 HttpVariant {
1188 name: "PayloadTooLarge",
1189 payload: HttpVariantPayload::Message,
1190 status: 413,
1191 },
1192 HttpVariant {
1193 name: "UnsupportedMediaType",
1194 payload: HttpVariantPayload::Message,
1195 status: 415,
1196 },
1197 HttpVariant {
1198 name: "UnprocessableEntity",
1199 payload: HttpVariantPayload::Message,
1200 status: 422,
1201 },
1202 HttpVariant {
1203 name: "TooManyRequests",
1204 payload: HttpVariantPayload::Message,
1205 status: 429,
1206 },
1207 HttpVariant {
1208 name: "UnavailableForLegalReasons",
1209 payload: HttpVariantPayload::Message,
1210 status: 451,
1211 },
1212 // ── 5xx server error ─────────────────────────────────────────────────
1213 HttpVariant {
1214 name: "ServerError",
1215 payload: HttpVariantPayload::Message,
1216 status: 500,
1217 },
1218 HttpVariant {
1219 name: "NotImplemented",
1220 payload: HttpVariantPayload::Message,
1221 status: 501,
1222 },
1223 HttpVariant {
1224 name: "BadGateway",
1225 payload: HttpVariantPayload::Message,
1226 status: 502,
1227 },
1228 HttpVariant {
1229 name: "ServiceUnavailable",
1230 payload: HttpVariantPayload::Message,
1231 status: 503,
1232 },
1233 HttpVariant {
1234 name: "GatewayTimeout",
1235 payload: HttpVariantPayload::Message,
1236 status: 504,
1237 },
1238];
1239
1240/// Find an `HttpResult[T]` variant by name. Returns the variant info or
1241/// `None` if the name doesn't match.
1242pub fn http_variant(name: &str) -> Option<HttpVariant> {
1243 HTTP_VARIANTS.iter().copied().find(|v| v.name == name)
1244}
1245
1246/// Payload shape of a `QueueResult` variant (v0.44). Non-generic — a verdict
1247/// carries no value; `Retry` carries a `String` reason for the log path.
1248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1249pub enum QueueVariantPayload {
1250 /// No payload (`Ack`).
1251 None,
1252 /// Carries a `String` reason (`Retry`).
1253 Message,
1254}
1255
1256/// One variant of the built-in `QueueResult` sum (v0.44).
1257#[derive(Debug, Clone, Copy)]
1258pub struct QueueVariant {
1259 pub name: &'static str,
1260 pub payload: QueueVariantPayload,
1261}
1262
1263/// All `QueueResult` variants, in declaration order. `Ack` confirms the
1264/// message; `Retry` redelivers it, carrying a reason for observability.
1265pub const QUEUE_VARIANTS: &[QueueVariant] = &[
1266 QueueVariant {
1267 name: "Ack",
1268 payload: QueueVariantPayload::None,
1269 },
1270 QueueVariant {
1271 name: "Retry",
1272 payload: QueueVariantPayload::Message,
1273 },
1274];
1275
1276/// Find a `QueueResult` variant by name.
1277pub fn queue_variant(name: &str) -> Option<QueueVariant> {
1278 QUEUE_VARIANTS.iter().copied().find(|v| v.name == name)
1279}
1280
1281#[derive(Debug, Clone)]
1282pub struct TypeDecl {
1283 pub name: Ident,
1284 pub body: TypeBody,
1285 /// Documentation block attached to this declaration (v0.3).
1286 pub documentation: Option<String>,
1287 pub span: Span,
1288 pub trivia: Trivia,
1289}
1290
1291/// The right-hand side of a `type` declaration. In v0/v0.1 only the
1292/// `Refined` variant existed; v0.2 adds records and sums; v0.3 adds opaque.
1293#[derive(Debug, Clone)]
1294pub enum TypeBody {
1295 /// Refined base type: `BaseType where refinement`.
1296 Refined {
1297 base: BaseType,
1298 base_span: Span,
1299 refinement: Option<Refinement>,
1300 },
1301 /// Record type: `{ field: T where ..., ... }`.
1302 Record(RecordBody),
1303 /// Sum type: pipe-form variants or `enum { ... }` shorthand.
1304 Sum(SumBody),
1305 /// Opaque base type: `opaque BaseType (where refinement)?` (v0.3 §3.4).
1306 /// Identity is nominal; the base type is hidden outside the defining commons.
1307 Opaque {
1308 base: BaseType,
1309 base_span: Span,
1310 refinement: Option<Refinement>,
1311 },
1312}
1313
1314/// Body of a record-type declaration (v0.2 §3.1).
1315#[derive(Debug, Clone)]
1316pub struct RecordBody {
1317 pub fields: Vec<RecordField>,
1318 pub span: Span,
1319}
1320
1321/// One field of a record type declaration. Each field may carry inline
1322/// refinement, which is enforced at construction time on the field's value.
1323#[derive(Debug, Clone)]
1324pub struct RecordField {
1325 pub name: Ident,
1326 pub type_ref: TypeRef,
1327 pub refinement: Option<Refinement>,
1328 /// v0.11: an optional initial-value expression. Only meaningful on agent
1329 /// `state` fields (the field's fresh-key value); ignored / rejected on
1330 /// record-type fields by the checker.
1331 pub init: Option<Expr>,
1332 pub span: Span,
1333}
1334
1335/// Body of a sum-type declaration (v0.2 §3.2).
1336#[derive(Debug, Clone)]
1337pub struct SumBody {
1338 pub variants: Vec<Variant>,
1339 pub span: Span,
1340}
1341
1342/// One variant of a sum type. Variants may have payload fields; a
1343/// payload-less variant is a simple tag.
1344#[derive(Debug, Clone)]
1345pub struct Variant {
1346 pub name: Ident,
1347 pub payload: Vec<VariantField>,
1348 pub span: Span,
1349}
1350
1351/// One payload field of a sum variant. Variant payload fields use named
1352/// declarations like record fields, but do not carry refinement in v0.2.
1353#[derive(Debug, Clone)]
1354pub struct VariantField {
1355 pub name: Ident,
1356 pub type_ref: TypeRef,
1357 pub span: Span,
1358}
1359
1360#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1361pub enum BaseType {
1362 Int,
1363 String,
1364 Bool,
1365 Float,
1366 /// `Duration` (v0.86, ADR 0112) — a span of time, a distinct base type
1367 /// erased to TS `number` carrying milliseconds (the `Clock` unit). Modelled
1368 /// on `Float`: Bynk-side-only, no implicit `Int` coercion (save the one
1369 /// sanctioned clock-math mix).
1370 Duration,
1371 /// `Instant` (v0.90, ADR 0114) — an absolute point in time, a distinct base
1372 /// type erased to TS `number` carrying Unix epoch milliseconds (the
1373 /// `Clock` unit). No literal (minted by `Clock.now()`); arithmetic composes
1374 /// with `Duration` (`Instant ± Duration -> Instant`, `Instant − Instant ->
1375 /// Duration`). Supersedes ADR 0112 D4's `Int`↔`Duration` clock-math mix.
1376 Instant,
1377 /// `Bytes` (v0.110, ADR 0142) — an immutable finite octet sequence, the
1378 /// seventh base type. Unlike its neighbours it does **not** erase to TS
1379 /// `number`: a `Bytes` lowers to a `Uint8Array`. No source literal
1380 /// (constructed via `Bytes.fromUtf8`/`fromBase64`/`empty`); `==` compares
1381 /// by content (real emitter codegen, not host `===`); wires as a base64
1382 /// JSON string; not `Map`-keyable and not orderable.
1383 Bytes,
1384}
1385
1386impl BaseType {
1387 pub fn name(self) -> &'static str {
1388 match self {
1389 BaseType::Int => "Int",
1390 BaseType::String => "String",
1391 BaseType::Bool => "Bool",
1392 BaseType::Float => "Float",
1393 BaseType::Duration => "Duration",
1394 BaseType::Instant => "Instant",
1395 BaseType::Bytes => "Bytes",
1396 }
1397 }
1398}
1399
1400/// A `Duration` literal unit (v0.86, ADR 0112) — the closed set of suffixes in a
1401/// `<int>.<unit>` literal. Each maps to a fixed millisecond factor (`Duration`
1402/// erases to `Int` milliseconds).
1403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1404pub enum DurationUnit {
1405 Milliseconds,
1406 Seconds,
1407 Minutes,
1408 Hours,
1409 Days,
1410}
1411
1412impl DurationUnit {
1413 /// Resolve a unit name (`minutes`) to its variant, or `None` if it is not one
1414 /// of the closed set. Used by the parser to recognise an `<int>.<unit>`
1415 /// literal; an unrecognised name leaves the expression a field access.
1416 pub fn from_name(name: &str) -> Option<Self> {
1417 Some(match name {
1418 "milliseconds" => DurationUnit::Milliseconds,
1419 "seconds" => DurationUnit::Seconds,
1420 "minutes" => DurationUnit::Minutes,
1421 "hours" => DurationUnit::Hours,
1422 "days" => DurationUnit::Days,
1423 _ => return None,
1424 })
1425 }
1426
1427 /// The unit name as written.
1428 pub fn name(self) -> &'static str {
1429 match self {
1430 DurationUnit::Milliseconds => "milliseconds",
1431 DurationUnit::Seconds => "seconds",
1432 DurationUnit::Minutes => "minutes",
1433 DurationUnit::Hours => "hours",
1434 DurationUnit::Days => "days",
1435 }
1436 }
1437
1438 /// The unit's value in milliseconds.
1439 pub fn millis(self) -> i64 {
1440 match self {
1441 DurationUnit::Milliseconds => 1,
1442 DurationUnit::Seconds => 1_000,
1443 DurationUnit::Minutes => 60_000,
1444 DurationUnit::Hours => 3_600_000,
1445 DurationUnit::Days => 86_400_000,
1446 }
1447 }
1448}
1449
1450/// An integer refinement bound (v0.40, ADR 0073): the parsed value plus the
1451/// bound's source span (covering a leading `-`). Value-only beyond the span —
1452/// ints have one canonical printed form, so the formatter stays idempotent
1453/// without a stored lexeme. The span backs the `InRange`-swap quick-fix.
1454#[derive(Debug, Clone)]
1455pub struct IntBound {
1456 pub value: i64,
1457 pub span: Span,
1458}
1459
1460/// A float refinement bound (v0.21): the parsed value plus the signed source
1461/// lexeme (for byte-stable emission). v0.40 (ADR 0073): also the source span,
1462/// for the `InRange`-swap quick-fix.
1463#[derive(Debug, Clone)]
1464pub struct FloatBound {
1465 pub value: f64,
1466 pub lexeme: String,
1467 pub span: Span,
1468}
1469
1470#[derive(Debug, Clone)]
1471pub struct Refinement {
1472 pub predicates: Vec<RefinementPred>,
1473 pub span: Span,
1474}
1475
1476#[derive(Debug, Clone)]
1477pub struct RefinementPred {
1478 pub kind: PredKind,
1479 pub span: Span,
1480}
1481
1482#[derive(Debug, Clone)]
1483pub enum PredKind {
1484 Matches(String),
1485 InRange(IntBound, IntBound),
1486 /// `InRange` with float bounds (v0.21) — a separate variant so every
1487 /// `Int` refinement path stays untouched. Bounds keep their source
1488 /// lexemes (including any sign) so emitted runtime checks are
1489 /// byte-stable.
1490 InRangeF(FloatBound, FloatBound),
1491 MinLength(i64),
1492 MaxLength(i64),
1493 Length(i64),
1494 NonNegative,
1495 Positive,
1496 NonEmpty,
1497}
1498
1499impl PredKind {
1500 pub fn name(&self) -> &'static str {
1501 match self {
1502 PredKind::Matches(_) => "Matches",
1503 PredKind::InRange(..) | PredKind::InRangeF(..) => "InRange",
1504 PredKind::MinLength(_) => "MinLength",
1505 PredKind::MaxLength(_) => "MaxLength",
1506 PredKind::Length(_) => "Length",
1507 PredKind::NonNegative => "NonNegative",
1508 PredKind::Positive => "Positive",
1509 PredKind::NonEmpty => "NonEmpty",
1510 }
1511 }
1512}
1513
1514/// A function type parameter (v0.20a, `fn name[A, B](…)`). A struct rather
1515/// than a bare Ident so the ADR-0028 "bound-capable" promise is a later field
1516/// addition, not a representation change.
1517#[derive(Debug, Clone)]
1518pub struct TypeParam {
1519 pub name: Ident,
1520 pub span: Span,
1521}
1522
1523/// A lambda expression (v0.20a): `(params) => expr` or `(params) => { … }`.
1524/// `=>` is the value arrow (shared with `match`); param annotations are
1525/// optional where an expected function type supplies them.
1526#[derive(Debug, Clone)]
1527pub struct LambdaExpr {
1528 pub params: Vec<LambdaParam>,
1529 pub body: Box<Expr>,
1530 pub span: Span,
1531}
1532
1533/// A lambda parameter. A separate type from [`Param`] because its annotation
1534/// is optional — `Param.type_ref` stays mandatory at every signature site.
1535#[derive(Debug, Clone)]
1536pub struct LambdaParam {
1537 pub name: Ident,
1538 pub type_ref: Option<TypeRef>,
1539 pub span: Span,
1540}
1541
1542#[derive(Debug, Clone)]
1543pub struct FnDecl {
1544 /// v0.20a: `[A, B]` type parameters; empty for non-generic functions.
1545 pub type_params: Vec<TypeParam>,
1546 /// Free function or method (`TypeName.methodName`). See [`FnName`].
1547 pub name: FnName,
1548 pub params: Vec<Param>,
1549 pub return_type: TypeRef,
1550 /// v0.115: preconditions (`requires <name>: <pred>`), parsed between the
1551 /// return type and the body. A contract clause is the invariant predicate
1552 /// attached to a function (ADR 0144 — one predicate surface); `requires`
1553 /// scopes over the parameters only.
1554 pub requires: Vec<Contract>,
1555 /// v0.115: postconditions (`ensures <name>: <pred>`). Scopes over the
1556 /// parameters *and* `result`, the contextual binding for the return value.
1557 pub ensures: Vec<Contract>,
1558 pub body: Block,
1559 /// True when the first parameter is the special `self` parameter. Only
1560 /// valid for method declarations.
1561 pub has_self: bool,
1562 /// Documentation block attached to this declaration (v0.3).
1563 pub documentation: Option<String>,
1564 pub span: Span,
1565 pub trivia: Trivia,
1566}
1567
1568/// A function-declaration name: either a free function `f` or a method
1569/// `T.method` (v0.2 §3.6).
1570#[derive(Debug, Clone)]
1571pub enum FnName {
1572 /// `fn name(...)` — a free function.
1573 Free(Ident),
1574 /// `fn TypeName.methodName(...)` — a method attached to a type.
1575 Method {
1576 type_name: Ident,
1577 method_name: Ident,
1578 },
1579}
1580
1581impl FnName {
1582 /// The function's short name for diagnostics. For methods returns the
1583 /// method portion only; the type prefix is recovered via `type_name`.
1584 pub fn ident(&self) -> &Ident {
1585 match self {
1586 FnName::Free(id) => id,
1587 FnName::Method { method_name, .. } => method_name,
1588 }
1589 }
1590
1591 /// For methods, the attached type's identifier; `None` for free fns.
1592 pub fn type_name(&self) -> Option<&Ident> {
1593 match self {
1594 FnName::Free(_) => None,
1595 FnName::Method { type_name, .. } => Some(type_name),
1596 }
1597 }
1598
1599 /// The displayed full name (e.g., `Money.add` or `parseSku`).
1600 pub fn display(&self) -> String {
1601 match self {
1602 FnName::Free(id) => id.name.clone(),
1603 FnName::Method {
1604 type_name,
1605 method_name,
1606 } => format!("{}.{}", type_name.name, method_name.name),
1607 }
1608 }
1609}
1610
1611/// A brace-delimited block of statements ending in a tail expression
1612/// whose value is the block's value (spec v0.1 §3.1).
1613#[derive(Debug, Clone)]
1614pub struct Block {
1615 pub statements: Vec<Statement>,
1616 pub tail: Box<Expr>,
1617 pub span: Span,
1618 /// Line comments that appear between the last statement (or the
1619 /// opening brace) and the tail expression. Preserved here because
1620 /// expressions do not carry trivia in v1.1.
1621 pub tail_leading_comments: Vec<String>,
1622}
1623
1624/// Block-level statement.
1625#[derive(Debug, Clone)]
1626pub enum Statement {
1627 /// `let name (: T)? = expr` — pure binding (v0.1).
1628 Let(LetStmt),
1629 /// `let name (: T)? <- expr` — effectful binding (v0.5).
1630 EffectLet(LetStmt),
1631 /// `expect expr` — verify a Bool predicate at test runtime (v0.7; renamed
1632 /// from `assert` in v0.112). Only valid inside test case bodies.
1633 Expect(ExpectStmt),
1634 /// `~> expr` — an asynchronous fire-and-forget send (v0.79). The caller does
1635 /// not await the reply; legal only when the reply is `Effect[()]`. No binder.
1636 Send(SendStmt),
1637 /// `name := expr` — a `Cell` store write (v0.81, storage track). The
1638 /// unconditional write form; `.update(fn)` (a method call) is the
1639 /// read-modify-write form. ADR 0108.
1640 Assign(AssignStmt),
1641}
1642
1643impl Statement {
1644 pub fn span(&self) -> Span {
1645 match self {
1646 Statement::Let(l) | Statement::EffectLet(l) => l.span,
1647 Statement::Expect(a) => a.span,
1648 Statement::Send(s) => s.span,
1649 Statement::Assign(a) => a.span,
1650 }
1651 }
1652}
1653
1654#[derive(Debug, Clone)]
1655pub struct ExpectStmt {
1656 pub value: Expr,
1657 pub span: Span,
1658 pub trivia: Trivia,
1659}
1660
1661/// `name := expr` — a `Cell` store write (v0.81, storage track). `target` is the
1662/// `Cell` field being written (a bare name for now; the checker resolves it to a
1663/// `store` field). `value` is the new value.
1664#[derive(Debug, Clone)]
1665pub struct AssignStmt {
1666 pub target: Ident,
1667 pub value: Expr,
1668 pub span: Span,
1669 pub trivia: Trivia,
1670}
1671
1672#[derive(Debug, Clone)]
1673pub struct LetStmt {
1674 pub name: Ident,
1675 pub type_annot: Option<TypeRef>,
1676 pub value: Expr,
1677 pub span: Span,
1678 pub trivia: Trivia,
1679}
1680
1681#[derive(Debug, Clone)]
1682pub struct SendStmt {
1683 /// The send target — a recipient call, e.g. `Logger.info(msg)`.
1684 pub value: Expr,
1685 pub span: Span,
1686 pub trivia: Trivia,
1687}
1688
1689#[derive(Debug, Clone)]
1690pub struct Param {
1691 pub name: Ident,
1692 pub type_ref: TypeRef,
1693 pub span: Span,
1694}
1695
1696#[derive(Debug, Clone)]
1697pub enum TypeRef {
1698 Base(BaseType, Span),
1699 Named(Ident),
1700 /// `Result[T, E]` — the built-in generic Result type (v0.1).
1701 Result(Box<TypeRef>, Box<TypeRef>, Span),
1702 /// `Option[T]` — the built-in generic Option type (v0.2).
1703 Option(Box<TypeRef>, Span),
1704 /// `Effect[T]` — the built-in generic Effect type (v0.5).
1705 Effect(Box<TypeRef>, Span),
1706 /// `HttpResult[T]` — the built-in HTTP-result sum (v0.9).
1707 HttpResult(Box<TypeRef>, Span),
1708 /// `QueueResult` — the built-in queue verdict sum (`Ack | Retry`),
1709 /// non-generic; the required return of a queue handler (v0.44).
1710 QueueResult(Span),
1711 /// `List[T]` — the built-in generic immutable list type (v0.20b).
1712 List(Box<TypeRef>, Span),
1713 /// `Map[K, V]` — the built-in generic immutable map type (v0.20b).
1714 /// Keys are confined to value-keyable types
1715 /// (`bynk.types.unkeyable_map_key`).
1716 Map(Box<TypeRef>, Box<TypeRef>, Span),
1717 /// `Query[T]` — the built-in lazy storage-read description (v0.91, ADR 0115).
1718 /// Nameable in a pure helper's return type; non-storable and non-boundary
1719 /// (like `Effect`/`Fn`).
1720 Query(Box<TypeRef>, Span),
1721 /// `Stream[T]` — the value-over-time primitive (v0.100, real-time track
1722 /// slice 0). A lazy, pull-shaped sequence produced over time; non-storable
1723 /// and non-boundary (like `Query`/`Effect`/`Fn`).
1724 Stream(Box<TypeRef>, Span),
1725 /// `Connection[F]` — a held WebSocket connection (v0.102, real-time track
1726 /// slice 2). `F` is the server→client frame type. A `Held` resource:
1727 /// non-serialisable, non-boundary, and governed by the linearity discipline
1728 /// (§2.9); storable only in `Cell[Option[Connection]]` / `Map[K, Connection]`.
1729 Connection(Box<TypeRef>, Span),
1730 /// `History[Agent]` — a generated, driven call-history of an agent (v0.119,
1731 /// testing track slice 7, ADR 0155). A test-only generator, legal only in
1732 /// `for all` binding position inside a `property`; it is not a value type,
1733 /// so it never resolves in a field/param/return position. The bound subject
1734 /// behaves as an ordinary `List[Step]`.
1735 History(Box<TypeRef>, Span),
1736 /// `ValidationError` — the built-in error type used by refined-type
1737 /// constructors (v0.1).
1738 ValidationError(Span),
1739 /// `JsonError` — the built-in JSON-decode error type (v0.22b). A
1740 /// uniform record (`kind`/`path`/`message`, all `String`) the codec
1741 /// maps `BoundaryError` variants and parse failures into.
1742 JsonError(Span),
1743 /// `()` — the unit type (v0.5).
1744 Unit(Span),
1745 /// `A -> B` / `(A, B) -> C` / `() -> B` — a function type (v0.20a).
1746 /// Right-associative; effectful iff the return type is `Effect[_]`
1747 /// (the structural rule). Confined to non-boundary positions
1748 /// (`bynk.types.function_at_boundary`).
1749 Fn(Vec<TypeRef>, Box<TypeRef>, Span),
1750}
1751
1752impl TypeRef {
1753 pub fn span(&self) -> Span {
1754 match self {
1755 TypeRef::Base(_, s) => *s,
1756 TypeRef::Named(id) => id.span,
1757 TypeRef::Result(_, _, s) => *s,
1758 TypeRef::Option(_, s) => *s,
1759 TypeRef::Effect(_, s) => *s,
1760 TypeRef::HttpResult(_, s) => *s,
1761 TypeRef::QueueResult(s) => *s,
1762 TypeRef::List(_, s) => *s,
1763 TypeRef::Map(_, _, s) => *s,
1764 TypeRef::Query(_, s) => *s,
1765 TypeRef::Stream(_, s) => *s,
1766 TypeRef::Connection(_, s) => *s,
1767 TypeRef::History(_, s) => *s,
1768 TypeRef::ValidationError(s) => *s,
1769 TypeRef::JsonError(s) => *s,
1770 TypeRef::Unit(s) => *s,
1771 TypeRef::Fn(_, _, s) => *s,
1772 }
1773 }
1774}
1775
1776#[derive(Debug, Clone)]
1777pub struct Expr {
1778 pub kind: ExprKind,
1779 pub span: Span,
1780}
1781
1782#[derive(Debug, Clone)]
1783pub enum ExprKind {
1784 IntLit(i64),
1785 /// A float literal (v0.21). The lexeme is kept alongside the parsed
1786 /// value so emission and formatting are byte-stable (`1e10` must not
1787 /// normalise to `10000000000`).
1788 FloatLit {
1789 value: f64,
1790 lexeme: String,
1791 },
1792 /// A duration literal `<int>.<unit>` (v0.86, ADR 0112): `5.minutes`,
1793 /// `30.days`. The parser recognises the `IntLit . <unit>` shape and records
1794 /// the magnitude, the unit, and the resolved milliseconds (the value the
1795 /// emitter lowers to). Typed `Duration`.
1796 DurationLit {
1797 /// The integer magnitude as written (`5` in `5.minutes`).
1798 value: i64,
1799 /// The unit name (`minutes`), one of the closed set.
1800 unit: DurationUnit,
1801 /// The value in milliseconds — `value * unit factor`.
1802 millis: i64,
1803 },
1804 StrLit(String),
1805 /// An interpolated string `"… \(expr) …"` (v0.43, ADR 0075). Chunks and
1806 /// holes alternate. A plain `"…"` with no holes stays [`ExprKind::StrLit`],
1807 /// so existing code and the emitter/formatter fast-path are untouched.
1808 InterpStr(Vec<InterpPart>),
1809 BoolLit(bool),
1810 Ident(Ident),
1811 Call {
1812 name: Ident,
1813 /// v0.20a: explicit type arguments (`name[T](…)`); empty when absent.
1814 type_args: Vec<TypeRef>,
1815 args: Vec<Expr>,
1816 },
1817 /// A lambda (v0.20a). See [`LambdaExpr`].
1818 Lambda(LambdaExpr),
1819 BinOp(BinOp, Box<Expr>, Box<Expr>),
1820 UnaryOp(UnaryOp, Box<Expr>),
1821 Paren(Box<Expr>),
1822 /// `{ stmts; expr }` — block expression (v0.1).
1823 Block(Block),
1824 /// `if cond { then } else { else }` (v0.1).
1825 If {
1826 cond: Box<Expr>,
1827 then_block: Box<Block>,
1828 else_block: Box<Block>,
1829 },
1830 /// `Ok(value)` — Result success constructor (v0.1).
1831 Ok(Box<Expr>),
1832 /// `Err(error)` — Result failure constructor (v0.1).
1833 Err(Box<Expr>),
1834 /// `expr?` — propagation operator (v0.1).
1835 Question(Box<Expr>),
1836 /// `TypeName.method(args)` — qualified static call on a type
1837 /// (v0.1: only refined-type `of`; v0.2: any static method or variant
1838 /// constructor for sum types). The resolver decides which.
1839 ConstructorCall {
1840 type_name: Ident,
1841 method: Ident,
1842 args: Vec<Expr>,
1843 },
1844 /// `TypeName { field: value, ... }` — record construction (v0.2).
1845 RecordConstruction {
1846 type_name: Ident,
1847 fields: Vec<FieldInit>,
1848 },
1849 /// `receiver.field` — field access on a record value (v0.2). v0.3 adds
1850 /// `.raw` on opaque types within the defining commons.
1851 FieldAccess {
1852 receiver: Box<Expr>,
1853 field: Ident,
1854 },
1855 /// `receiver.method(args)` — instance method call (v0.2). The
1856 /// resolver determines the receiver's type and looks up the method.
1857 MethodCall {
1858 receiver: Box<Expr>,
1859 method: Ident,
1860 /// v0.22b: explicit type arguments on a qualified static
1861 /// (`Json.decode[T](…)`); empty when absent. The same-line-`[`
1862 /// rule applies as for `Call` type application (0039).
1863 type_args: Vec<TypeRef>,
1864 args: Vec<Expr>,
1865 },
1866 /// `match disc { arm+ }` — pattern matching (v0.2).
1867 Match {
1868 discriminant: Box<Expr>,
1869 arms: Vec<MatchArm>,
1870 },
1871 /// `expr is pattern` — pattern test, returns Bool (v0.2).
1872 Is {
1873 value: Box<Expr>,
1874 pattern: Pattern,
1875 },
1876 /// `Some(value)` — Option Some constructor (v0.2).
1877 Some(Box<Expr>),
1878 /// `None` — Option None constructor (v0.2).
1879 None,
1880 /// `()` — unit literal (v0.5).
1881 UnitLit,
1882 /// `TypeName { ...base, field: value, ... }` or `{ ...base, ... }` —
1883 /// record spread expression (v0.5).
1884 RecordSpread {
1885 /// Optional type prefix (`TypeName { ...base }`). Absent for the
1886 /// bare form used inside `commit`.
1887 type_name: Option<Ident>,
1888 /// The base record being spread.
1889 base: Box<Expr>,
1890 /// Field overrides (always full `name: value` form — never shorthand).
1891 overrides: Vec<FieldInit>,
1892 },
1893 /// `Effect.pure(value)` — wrap a synchronous value into `Effect[T]`
1894 /// (v0.5). Recognised in the parser as a special-form.
1895 EffectPure(Box<Expr>),
1896 /// `expect expr` — expectation as an expression of type `()` (v0.9.1;
1897 /// renamed from `assert` in v0.112). Valid only inside test bodies. Evaluates
1898 /// `expr` (must be Bool); if false, the surrounding test case fails.
1899 Expect(Box<Expr>),
1900 /// `Val[T]`, `Val[T](args)` — test-context value construction (v0.9.4).
1901 /// `args` is empty for the bare form and holds the pin arguments for
1902 /// `Val[T](...)`. The record-override form `Val[T] { ... }` is not yet
1903 /// parsed. Valid only inside test bodies; has type `T`.
1904 Val {
1905 type_ref: TypeRef,
1906 args: Vec<Expr>,
1907 },
1908 /// `[a, b, c]` — list literal (v0.20b). An empty `[]` requires an
1909 /// expected type (`bynk.types.uninferable_element_type`).
1910 ListLit(Vec<Expr>),
1911 /// An observation over a consumed capability's recorded calls (v0.117,
1912 /// testing track slice 5). The direct subject of an `expect` in a `case`
1913 /// body — `expect Cap.op called once with <pred>`, `expect Cap.op never
1914 /// called`, `expect A.op before B.op`. Types as `Bool` (the claim about the
1915 /// recorded trace), lowered to a boolean over the recorded log.
1916 Observation(ObservationExpr),
1917 /// `trace(Cap.op)` — the bound-trace escape hatch (v0.117, testing track
1918 /// slice 5). Yields the recorded calls of `Cap.op` as a `List[<CallRecord>]`
1919 /// (a synthetic record of the operation's parameters), asserted over with the
1920 /// ordinary value surface. Test-body-only, like [`ExprKind::Val`].
1921 Trace {
1922 cap: Ident,
1923 op: Ident,
1924 },
1925}
1926
1927/// An observation of a capability operation's recorded calls (v0.117, testing
1928/// track slice 5). `cap`/`op` name the seam (`Logger.log`); `matcher` is the
1929/// claim about the recorded calls.
1930#[derive(Debug, Clone)]
1931pub struct ObservationExpr {
1932 pub cap: Ident,
1933 pub op: Ident,
1934 pub matcher: ObservationMatcher,
1935}
1936
1937/// The claim an [`ObservationExpr`] makes about a seam's recorded calls (v0.117).
1938#[derive(Debug, Clone)]
1939pub enum ObservationMatcher {
1940 /// `called` [`once` | `<n> times`]? [`with` `<pred>`]?. `count` is `None`
1941 /// for a bare `called` (at least one); `Some(expr)` is the exact-count claim
1942 /// (a literal; `once` desugars to `1`). `with_pred` matches a call whose
1943 /// arguments (in scope by the operation's parameter names) satisfy it.
1944 Called {
1945 count: Option<Box<Expr>>,
1946 with_pred: Option<Box<Expr>>,
1947 },
1948 /// `never called` — zero calls.
1949 NeverCalled,
1950 /// `before Cap.op` — the first call of the subject precedes the first call
1951 /// of the named operation (both must have occurred).
1952 Before { cap: Ident, op: Ident },
1953}
1954
1955/// One part of an interpolated string (v0.43, ADR 0075). An
1956/// [`ExprKind::InterpStr`] holds an alternating run of these.
1957#[derive(Debug, Clone)]
1958pub enum InterpPart {
1959 /// Literal text between holes, with escapes already resolved.
1960 Chunk(String),
1961 /// An interpolated expression `\(expr)`. Type-checked by the hole rule
1962 /// (base scalars only; see the checker) and lowered into a template-
1963 /// literal `${…}` slot.
1964 Hole(Box<Expr>),
1965}
1966
1967/// One field-initialiser inside a record construction expression:
1968/// either `name: expr` or the shorthand `name` (which requires a binding
1969/// of the same name in scope and uses its value).
1970#[derive(Debug, Clone)]
1971pub struct FieldInit {
1972 pub name: Ident,
1973 /// `None` means shorthand — the field's value is the same-named binding.
1974 pub value: Option<Expr>,
1975 pub span: Span,
1976}
1977
1978/// One arm of a `match` expression: `pattern => body`.
1979#[derive(Debug, Clone)]
1980pub struct MatchArm {
1981 pub pattern: Pattern,
1982 pub body: MatchBody,
1983 pub span: Span,
1984}
1985
1986/// The right-hand side of a match arm — either a single expression or
1987/// a block.
1988#[derive(Debug, Clone)]
1989pub enum MatchBody {
1990 Expr(Expr),
1991 Block(Block),
1992}
1993
1994impl MatchBody {
1995 pub fn span(&self) -> Span {
1996 match self {
1997 MatchBody::Expr(e) => e.span,
1998 MatchBody::Block(b) => b.span,
1999 }
2000 }
2001}
2002
2003/// A pattern (v0.2 §3.8). Patterns appear in `match` arms and as the
2004/// right-hand side of the `is` operator.
2005#[derive(Debug, Clone)]
2006pub enum Pattern {
2007 /// `_` — matches any value, no bindings.
2008 Wildcard(Span),
2009 /// A literal pattern — `31`, `"english"`, `true` (v0.130 §2.3.4). Matches a
2010 /// primitive scrutinee (`Int`/`String`/`Bool`) by value equality. The
2011 /// admitted set mirrors ADR 0001's closed literal set (integers — including
2012 /// a leading unary minus — strings, and booleans); `Float`/`()` are not
2013 /// admitted as patterns.
2014 Literal { value: LiteralValue, span: Span },
2015 /// `Variant` or `Variant(bindings)` or `TypeName.Variant(bindings)`.
2016 Variant {
2017 /// Optional qualifier: `TypeName.Variant`.
2018 type_name: Option<Ident>,
2019 /// The variant name.
2020 variant: Ident,
2021 /// Payload bindings (empty for nullary variants).
2022 bindings: Vec<PatternBinding>,
2023 span: Span,
2024 },
2025}
2026
2027/// The value carried by a [`Pattern::Literal`]. A closed set (ADR 0001):
2028/// integer, string, and boolean. Kept distinct from [`ExprKind`] so patterns
2029/// carry only what they can actually match, and so it is `Eq`/`Hash` for the
2030/// duplicate-arm check.
2031#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2032pub enum LiteralValue {
2033 Int(i64),
2034 Str(String),
2035 Bool(bool),
2036}
2037
2038impl LiteralValue {
2039 /// A human-readable rendering for diagnostics (`31`, `"english"`, `true`).
2040 pub fn describe(&self) -> String {
2041 match self {
2042 LiteralValue::Int(n) => n.to_string(),
2043 LiteralValue::Str(s) => format!("{s:?}"),
2044 LiteralValue::Bool(b) => b.to_string(),
2045 }
2046 }
2047}
2048
2049impl Pattern {
2050 pub fn span(&self) -> Span {
2051 match self {
2052 Pattern::Wildcard(s) => *s,
2053 Pattern::Literal { span, .. } => *span,
2054 Pattern::Variant { span, .. } => *span,
2055 }
2056 }
2057}
2058
2059/// A single binding inside a variant pattern. Two surface forms:
2060/// `name` (positional — bind the i-th payload field) and
2061/// `fieldName: bindName` (named — bind the named payload field).
2062/// Both forms also accept `_` as the bind name to discard.
2063#[derive(Debug, Clone)]
2064pub struct PatternBinding {
2065 /// Source form: positional or named.
2066 pub kind: PatternBindingKind,
2067 pub span: Span,
2068}
2069
2070#[derive(Debug, Clone)]
2071pub enum PatternBindingKind {
2072 /// `name` (or `_`): bind the payload field at this position to `name`.
2073 Positional { name: Ident },
2074 /// `field: name` (or `field: _`): bind the named payload field to `name`.
2075 Named { field: Ident, name: Ident },
2076}
2077
2078impl PatternBinding {
2079 /// The local name introduced by this binding (used for scope).
2080 /// `_` is a sentinel for "no binding"; callers should compare against it.
2081 pub fn local_name(&self) -> &Ident {
2082 match &self.kind {
2083 PatternBindingKind::Positional { name } => name,
2084 PatternBindingKind::Named { name, .. } => name,
2085 }
2086 }
2087
2088 pub fn is_wildcard(&self) -> bool {
2089 self.local_name().name == "_"
2090 }
2091}
2092
2093#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2094pub enum BinOp {
2095 /// `P implies Q` — logical implication (v0.80). Desugars to `!P || Q`; sits
2096 /// at the lowest precedence (below `||`). Reads directionally (P → Q).
2097 Implies,
2098 Or,
2099 And,
2100 Eq,
2101 NotEq,
2102 Lt,
2103 LtEq,
2104 Gt,
2105 GtEq,
2106 Add,
2107 Sub,
2108 Mul,
2109 Div,
2110}
2111
2112impl BinOp {
2113 pub fn name(self) -> &'static str {
2114 match self {
2115 BinOp::Implies => "implies",
2116 BinOp::Or => "||",
2117 BinOp::And => "&&",
2118 BinOp::Eq => "==",
2119 BinOp::NotEq => "!=",
2120 BinOp::Lt => "<",
2121 BinOp::LtEq => "<=",
2122 BinOp::Gt => ">",
2123 BinOp::GtEq => ">=",
2124 BinOp::Add => "+",
2125 BinOp::Sub => "-",
2126 BinOp::Mul => "*",
2127 BinOp::Div => "/",
2128 }
2129 }
2130}
2131
2132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2133pub enum UnaryOp {
2134 Neg,
2135 Not,
2136}
2137
2138impl UnaryOp {
2139 pub fn name(self) -> &'static str {
2140 match self {
2141 UnaryOp::Neg => "-",
2142 UnaryOp::Not => "!",
2143 }
2144 }
2145}