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