Skip to main content

bynk_syntax/
keywords.rs

1//! Registry of reserved keywords.
2//!
3//! Single source of truth for the keyword list in
4//! `site/src/content/docs/reference/keywords.md`, generated by
5//! [`render_markdown`]. The test
6//! `tests/keywords_reference.rs` asserts this table matches exactly the
7//! alphabetic `#[token("…")]` keywords declared in `lexer.rs`, so the two
8//! cannot drift.
9
10/// One reserved keyword and a one-line description of its role.
11pub struct KeywordInfo {
12    pub word: &'static str,
13    pub meaning: &'static str,
14}
15
16/// Every reserved keyword, sorted.
17pub const KEYWORDS: &[KeywordInfo] = &[
18    k("Bool", "The boolean base type."),
19    k(
20        "Bytes",
21        "The binary base type — an immutable octet sequence, erased to `Uint8Array` (`Bytes.fromUtf8(s)`).",
22    ),
23    k(
24        "Decimal",
25        "The exact decimal base type — an arbitrary-precision coefficient with a scale (`1.20d`).",
26    ),
27    k(
28        "DecodeError",
29        "The decode error type, `Result[T, DecodeError]` from `Json.decode`. Its fields are `kind` (`Malformed`, `StructuralMismatch` or `RefinementViolation`), `path` (e.g. `$.qty`) and `message`, all `String`: write `\"\\(e.kind) at \\(e.path): \\(e.message)\"`.",
30    ),
31    k(
32        "Duration",
33        "The time-span base type, in milliseconds (`5.minutes`).",
34    ),
35    k("Effect", "The effectful-computation type, `Effect[T]`."),
36    k("Err", "The error variant of `Result`."),
37    k("Float", "The floating-point base type."),
38    k(
39        "Instant",
40        "The absolute-time base type, in epoch milliseconds (`Clock.now()`).",
41    ),
42    k("Int", "The integer base type."),
43    k(
44        "JsonError",
45        "Deprecated spelling of `DecodeError`; it still compiles, with a warning and an auto-fix.",
46    ),
47    k("None", "The empty variant of `Option`."),
48    k("Ok", "The success variant of `Result`."),
49    k("Option", "The optional-value type, `Option[T]`."),
50    k("Result", "The success-or-error type, `Result[T, E]`."),
51    k("Some", "The present variant of `Option`."),
52    k("String", "The string base type."),
53    k(
54        "ValidationError",
55        "The error type returned by a refined type's `.of`. Its fields are `field` and `message`, both `String`: write `\"\\(e.field): \\(e.message)\"`.",
56    ),
57    k(
58        "actor",
59        "Declare an actor — a boundary contract a handler consumes via `by`.",
60    ),
61    k(
62        "adapter",
63        "Declare an adapter — the host boundary (capability contract + binding).",
64    ),
65    k("agent", "Declare a stateful, keyed agent inside a context."),
66    k(
67        "as",
68        "Alias a consumed context (`consumes X as Y`) or a consumed type (`consumes U { T as Y }`).",
69    ),
70    k(
71        "asset",
72        "Declare a static file the platform serves, public by construction (`asset name = \"path\"`).",
73    ),
74    k(
75        "binding",
76        "Name an adapter's TypeScript binding module (`binding \"<module>\"`).",
77    ),
78    k(
79        "capability",
80        "Declare a capability (a dependency interface) in a context, or a distinct instance of a platform resource (`capability Sessions = Kv`).",
81    ),
82    k(
83        "case",
84        "Declare a test case inside a `suite` (`case \"…\" { … }`).",
85    ),
86    k(
87        "commons",
88        "Declare a pure, stateless module of types and functions.",
89    ),
90    k(
91        "const",
92        "Declare a named constant — a static value of a declared type, in a context or commons (`const MaxRetries: Int = 3`).",
93    ),
94    k(
95        "consumes",
96        "Declare a dependency on another context's services.",
97    ),
98    k(
99        "context",
100        "Declare a deployable context (services, agents, capabilities).",
101    ),
102    k(
103        "cron",
104        "The cron protocol on a service header (`from cron`).",
105    ),
106    k(
107        "do",
108        "Perform a unit effect as a statement (`do e` — the binder-free `let _ <- e`).",
109    ),
110    k(
111        "else",
112        "The alternative branch of an `if`, or what a block produces when a `let` pattern does not match (`let Ok(x) = r else { … }`).",
113    ),
114    k(
115        "embed",
116        "Declare a project file whose text is a `String` constant, compiled into the code and never served (`embed name = \"path\"`).",
117    ),
118    k(
119        "ensures",
120        "Declare a function postcondition — a pure `Bool` clause over the parameters and `result` (`ensures <name>: <pred>`).",
121    ),
122    k("enum", "Declare a payloadless sum type (`enum { A, B }`)."),
123    k(
124        "event",
125        "Declare a typed fact a context may emit (`event Name = { fields }`), inside a context.",
126    ),
127    k(
128        "expect",
129        "Assert a predicate inside a test case (`expect <bool-predicate>`).",
130    ),
131    k("exports", "Declare which types a context exposes, and how."),
132    k("false", "The boolean literal `false`."),
133    k("fn", "Declare a function."),
134    k(
135        "from",
136        "Name the protocol a service conforms to (`service X from http`).",
137    ),
138    k("given", "Declare the capabilities a handler requires."),
139    k(
140        "http",
141        "The HTTP protocol on a service header (`from http`).",
142    ),
143    k("if", "A conditional expression."),
144    k(
145        "implies",
146        "Logical implication (`P implies Q` ≡ `!P || Q`), used in invariant predicates.",
147    ),
148    k(
149        "invariant",
150        "Declare an agent invariant — a predicate that must hold of every committed state.",
151    ),
152    k(
153        "is",
154        "Test a value against a variant pattern, yielding a `Bool`.",
155    ),
156    k(
157        "let",
158        "Bind a local value (`let x = …`, or `let x <- …` for an effect), or match a pattern with a fallback (`let Ok(x) = r else { … }`).",
159    ),
160    k(
161        "match",
162        "Pattern-match over a sum type, `Result`, or `Option`.",
163    ),
164    k(
165        "messages",
166        "Declare a message bundle for one locale (`messages \"<tag>\" { \"code\" => \"template\" }`), inside a commons.",
167    ),
168    k(
169        "on",
170        "Begin a handler declaration (`on call`, `on GET(…)`, `on message`, `on open`/`on close`).",
171    ),
172    k(
173        "opaque",
174        "Declare an opaque type, or export a type opaquely.",
175    ),
176    k(
177        "property",
178        "Declare a generative test inside a `suite` (`property \"…\" { for all … }`).",
179    ),
180    k(
181        "protocol",
182        "Reserved keyword (protocols are a closed, compiler-known set).",
183    ),
184    k("provides", "Provide an implementation of a capability."),
185    k(
186        "queue",
187        "The queue protocol on a service header (`from queue(\"name\")`).",
188    ),
189    k(
190        "record",
191        "Reserved keyword (records are written `type X = { … }`).",
192    ),
193    k(
194        "requires",
195        "Declare a function precondition — a pure `Bool` clause over the parameters (`requires <name>: <pred>`).",
196    ),
197    k("self", "The current agent instance, inside a handler."),
198    k(
199        "service",
200        "Declare a service (a group of handlers) in a context.",
201    ),
202    k(
203        "stub",
204        "Stub a consumed capability operation at a test seam (`stub Cap.op(…) returns <v>` / `returns <v> after <d>` / `fails` / `never`).",
205    ),
206    k(
207        "suite",
208        "Declare a test suite targeting a unit (`suite <target> { case … }`).",
209    ),
210    k(
211        "transition",
212        "Declare an agent step invariant over the `old`/`new` state pair (`transition <name>: …`).",
213    ),
214    k(
215        "transparent",
216        "Export a type with its structure visible (`exports transparent { … }`).",
217    ),
218    k("true", "The boolean literal `true`."),
219    k(
220        "type",
221        "Declare a type: alias, record, sum, opaque, or refined.",
222    ),
223    k("uses", "Bring a commons into scope."),
224    k("where", "Attach refinement predicates to a base type."),
225];
226
227/// Contextual keywords — words that read as keywords in one position but stay
228/// usable as ordinary identifiers elsewhere, so they are lexed as `Ident` and
229/// are deliberately *absent* from [`KEYWORDS`] (which is drift-guarded to equal
230/// the lexer's reserved `#[token]`s). Editor surfaces still owe them a hover and
231/// a doc — the mechanical floor over this table lives in
232/// `bynk-lsp/tests/editor_coverage.rs`, mirroring the reserved-keyword tooth
233/// (ADR 0156 / ADR 0161).
234pub const CONTEXTUAL_KEYWORDS: &[KeywordInfo] = &[
235    k(
236        "advance",
237        "Move the test harness's clock forward in a `case` (`advance Clock by 15.minutes`).",
238    ),
239    k(
240        "by",
241        "A clause word only in its positions — naming the actor a handler consumes after the return type or on a service header (`… -> T by <name>: <Actor>`), the actor of a call (`let r <- f() by User(\"bob\")`), and the amount of `advance Clock by <Duration>`; an ordinary name (a parameter, a binding, a field) everywhere else.",
242    ),
243    k(
244        "derives",
245        "After a type declaration's body, opts the type into a constraint (`type Priority = enum { Low, High } derives Ord`): the type is then ordered by declaration order.",
246    ),
247    k(
248        "drop",
249        "Inside a `migrate` step, discard a stored field's value on purpose (`drop owner`).",
250    ),
251    k(
252        "fixture",
253        "In a suite, declares a project file's text as a `String` constant for its cases (`fixture issue = \"fixtures/issue.json\"`): test-only, read from the `fixtures/` folder and never deployed.",
254    ),
255    k(
256        "key",
257        "The agent's identity field — one per agent; keys the store.",
258    ),
259    k(
260        "migrate",
261        "An agent's migration step: carries a stored record from an older schema version to the current shape (`migrate from 1 (old: CartV1) { … }`).",
262    ),
263    k(
264        "par",
265        "Opens a concurrent binding block (`par { let a <- e1  let b <- e2 }`): every effect is issued before any is awaited, and the block completes when all have settled.",
266    ),
267    k(
268        "private",
269        "Before a `fn`, `type`, `messages`, `asset`, `embed` or `const` declaration in a commons or context: visible only within its own unit (and that unit's suites), never through `uses` (`private fn helper(…)`).",
270    ),
271    k(
272        "removed",
273        "Declares an agent class gone (`removed agent Old`): its stored data is deleted at the next deploy, after a named confirmation.",
274    ),
275    k(
276        "replaces",
277        "Renames an agent class (`agent New replaces Old`): the old class's stored data and schema history move to the new one.",
278    ),
279    k("store", "A persisted agent-state field."),
280];
281
282/// The reserved lexer tokens the parser deliberately re-admits as identifiers
283/// outside their one keyword position (`expect_ident`, ADR-tracked at
284/// `parser.rs`). Unlike [`CONTEXTUAL_KEYWORDS`] these words *are* real
285/// `#[token]`s and *are* members of [`KEYWORDS`] (so the lexer↔registry drift
286/// guard sees them) — they simply are not rejected in identifier position. The
287/// keyword reference renders them as a distinct tier so the page no longer
288/// claims, falsely, that every listed word is unusable as an identifier.
289///
290/// Single source of truth: the `expect_ident` exemption arm (via
291/// [`is_reserved_contextual`]) and the
292/// `is_reserved_keyword_covers_every_lexer_keyword` drift guard both defer to
293/// this list, so adding a word here is enough to make the parser admit it.
294pub const RESERVED_CONTEXTUAL: &[&str] = &[
295    "asset", "case", "const", "embed", "event", "messages", "on", "suite",
296];
297
298/// True when `word` is a [reserved contextual keyword](RESERVED_CONTEXTUAL) —
299/// a reserved token `expect_ident` re-admits as an identifier. Because each of
300/// these words lexes only to its own dedicated token, matching on the source
301/// text is equivalent to matching the token kind, but keeps the exemption
302/// single-sourced against [`RESERVED_CONTEXTUAL`].
303pub fn is_reserved_contextual(word: &str) -> bool {
304    RESERVED_CONTEXTUAL.contains(&word)
305}
306
307/// Built-in type names — compiler-known type constructors the parser dispatches
308/// on by identifier text in `parser/types.rs`, *outside* the keyword/token
309/// system entirely (they are lexed as ordinary `Ident`s, so they are absent
310/// from both the lexer's `#[token]`s and [`KEYWORDS`]). They are nonetheless
311/// reserved in type position: a `type` declaration may not reuse one of these
312/// names (`bynk.resolve.reserved_builtin_type`), because the parser would
313/// otherwise intercept every later reference and the user's alias would be
314/// silently shadowed or fail incoherently.
315///
316/// Single source of truth: [`is_builtin_type_name`] gates the resolver's
317/// redeclaration diagnostic, and a drift guard
318/// (`xtask/tests/docs_consistency/keywords_reference.rs`) asserts this list equals the set of
319/// names the type parser dispatches on. Keep it sorted.
320pub const BUILTIN_TYPE_NAMES: &[KeywordInfo] = &[
321    k(
322        "Asset",
323        "A static file declared by `asset name = \"path\"`; its `.url` is the content-hashed URL the platform serves it at.",
324    ),
325    k(
326        "BoundaryRejection",
327        "Why the router refused a request before any handler ran; the parameter of `on rejected`.",
328    ),
329    k(
330        "Connection",
331        "A held WebSocket connection, `Connection[F]`.",
332    ),
333    k(
334        "History",
335        "A generated call-history generator, `History[Agent]` (test-only).",
336    ),
337    k(
338        "HttpResult",
339        "The HTTP handler result type, `HttpResult[T]`.",
340    ),
341    k("List", "The immutable list type, `List[T]`."),
342    k("Map", "The immutable map type, `Map[K, V]`."),
343    k("Query", "The lazy storage-read type, `Query[T]`."),
344    k(
345        "QueueResult",
346        "The queue handler result type (non-generic).",
347    ),
348    k(
349        "RequestCookies",
350        "An HTTP handler's read-only view of the request's cookies (`cookies: RequestCookies`).",
351    ),
352    k(
353        "RequestHeaders",
354        "An HTTP handler's read-only view of the request's headers (`headers: RequestHeaders`).",
355    ),
356    k(
357        "RequestQuery",
358        "An HTTP handler's read-only view of the request's query string (`query: RequestQuery`).",
359    ),
360    k("Set", "The immutable set type, `Set[T]`."),
361    k("Stream", "The value-over-time primitive, `Stream[T]`."),
362    k(
363        "TokenClaims",
364        "An `Oidc` actor's verified token claims, read through its binder (`who.claims`).",
365    ),
366];
367
368/// #2620: ambient built-in functions — bare calls the compiler knows without a
369/// declaration. Not keywords: a `fn` (or any binding) of the same name shadows
370/// them, as `Json` is shadowed. Both have the bottom type, so a call fits any
371/// position, and both fault when evaluated. Keep it sorted.
372pub const BUILTIN_FUNCTIONS: &[KeywordInfo] = &[
373    k(
374        "todo",
375        "Placeholder for unfinished code, `todo(message: String)`: type-checks anywhere, faults when run, and raises the `bynk.fault.todo` warning so `check --deny-warnings` can refuse it.",
376    ),
377    k(
378        "unreachable",
379        "Mark a case that cannot happen, `unreachable(message: String)`: type-checks anywhere and faults when evaluated, so a broken assumption is loud instead of masked by a made-up default.",
380    ),
381];
382
383/// True when `name` is a compiler-known [built-in type name](BUILTIN_TYPE_NAMES).
384/// Used by the resolver to reject `type <name> = …` redeclarations.
385pub fn is_builtin_type_name(name: &str) -> bool {
386    BUILTIN_TYPE_NAMES.iter().any(|b| b.word == name)
387}
388
389const fn k(word: &'static str, meaning: &'static str) -> KeywordInfo {
390    KeywordInfo { word, meaning }
391}
392
393/// Render the keyword reference page — four tiers, each with prose that is
394/// true of *that* tier (the page used to make one blanket claim that was false
395/// of two of them).
396pub fn render_markdown() -> String {
397    let mut out = String::new();
398    out.push_str("# Keywords\n\n");
399    out.push_str(
400        "<!-- GENERATED FILE — do not edit by hand.\n     \
401         Source: bynk-syntax/src/keywords.rs (`render_markdown`).\n     \
402         Regenerate with: BYNK_BLESS=1 cargo test -p xtask --test docs_consistency keywords_reference:: -->\n\n",
403    );
404    out.push_str(
405        "Bynk reserves names in four tiers. The first two are lexer keywords; the \
406         third are words the lexer treats as plain identifiers; the fourth are \
407         compiler-known type names. Only the **hard keywords** can never be used \
408         as an identifier. A last section lists the ambient built-in functions, \
409         which reserve nothing.\n\n",
410    );
411    out.push_str(
412        "A hard keyword is still allowed where a name is a *label* rather than a \
413         binding, so a field can carry the key a third-party payload uses \
414         (`type`, `from`, `self`):\n\n\
415         - a record field, a construction initialiser, a record or named pattern \
416         field and a variant payload field, when the keyword is followed by `:` \
417         (`{ type: String }`, `Account { type: \"Org\" }`, `Account { type: t, .. }`, \
418         `Push(from: String)`). `kind` stays reserved as a variant payload field.\n\
419         - a member after `.`, a field access or a method call, and a method \
420         declaration, when the keyword is on the same line as the `.` \
421         (`a.type`, `fn Sorted.from(…)`, `Sorted.from(xs)`).\n\n\
422         A keyword is never a parameter, a `let` or lambda binding or a bare \
423         reference, so field shorthand is refused: `Account { type, .. }` and \
424         `Account { type }` are `bynk.parse.keyword_field_shorthand`. Write \
425         `type: type_` in a pattern and `type: <value>` in a construction.\n\n",
426    );
427
428    // Tier 1 — hard keywords: every reserved token except the contextual ones.
429    let hard: Vec<&KeywordInfo> = KEYWORDS
430        .iter()
431        .filter(|k| !RESERVED_CONTEXTUAL.contains(&k.word))
432        .collect();
433    out.push_str("## Hard keywords\n\n");
434    out.push_str(&format!(
435        "Reserved everywhere — these **{}** words can never be used as an \
436         identifier.\n\n",
437        hard.len()
438    ));
439    out.push_str("| Keyword | Meaning |\n|---|---|\n");
440    for info in hard {
441        out.push_str(&format!("| `{}` | {} |\n", info.word, info.meaning));
442    }
443
444    // Tier 2 — contextual keywords: reserved tokens the parser re-admits as
445    // identifiers outside their one keyword position.
446    let contextual: Vec<&KeywordInfo> = RESERVED_CONTEXTUAL
447        .iter()
448        .filter_map(|w| KEYWORDS.iter().find(|k| &k.word == w))
449        .collect();
450    out.push_str("\n## Contextual keywords\n\n");
451    out.push_str(
452        "Reserved only in the one position named below; elsewhere (a field, \
453         parameter, or other identifier) they are ordinary names.\n\n",
454    );
455    out.push_str("| Keyword | Meaning |\n|---|---|\n");
456    for info in contextual {
457        out.push_str(&format!("| `{}` | {} |\n", info.word, info.meaning));
458    }
459
460    // Tier 3 — contextual words: not lexer keywords at all; ordinary identifiers
461    // that carry meaning in one position.
462    out.push_str("\n## Contextual words\n\n");
463    out.push_str(
464        "Not lexer keywords: the lexer treats these as ordinary identifiers, and \
465         they carry meaning only in the position each entry describes (inside an \
466         agent body or a `migrate` step, for instance). You can still use them as a \
467         field, parameter, or other name elsewhere.\n\n",
468    );
469    out.push_str("| Word | Meaning |\n|---|---|\n");
470    for info in CONTEXTUAL_KEYWORDS {
471        out.push_str(&format!("| `{}` | {} |\n", info.word, info.meaning));
472    }
473
474    // Tier 4 — built-in type names: not lexer keywords at all, but reserved in
475    // type position (a `type` declaration may not reuse one).
476    out.push_str("\n## Built-in type names\n\n");
477    out.push_str(
478        "Compiler-known type constructors. They are not lexer keywords — you may \
479         use them as an identifier in value position — but they are reserved in \
480         type position: a `type` declaration may not reuse one of these names \
481         (`bynk.resolve.reserved_builtin_type`).\n\n",
482    );
483    out.push_str("| Name | Meaning |\n|---|---|\n");
484    for info in BUILTIN_TYPE_NAMES {
485        out.push_str(&format!("| `{}` | {} |\n", info.word, info.meaning));
486    }
487
488    // Ambient built-in functions: not reserved at all — a declaration of the
489    // same name shadows them.
490    out.push_str("\n## Built-in functions\n\n");
491    out.push_str(
492        "Functions the compiler provides without a declaration. They reserve \
493         nothing: a `fn`, parameter or local of the same name shadows the built-in.\n\n",
494    );
495    out.push_str("| Name | Meaning |\n|---|---|\n");
496    for info in BUILTIN_FUNCTIONS {
497        out.push_str(&format!("| `{}` | {} |\n", info.word, info.meaning));
498    }
499    out
500}