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/book/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        "Duration",
25        "The time-span base type, in milliseconds (`5.minutes`).",
26    ),
27    k("Effect", "The effectful-computation type, `Effect[T]`."),
28    k("Err", "The error variant of `Result`."),
29    k("Float", "The floating-point base type."),
30    k(
31        "Instant",
32        "The absolute-time base type, in epoch milliseconds (`Clock.now()`).",
33    ),
34    k("Int", "The integer base type."),
35    k(
36        "JsonError",
37        "The JSON-decode error type, `Result[T, JsonError]` from `Json.decode`.",
38    ),
39    k("None", "The empty variant of `Option`."),
40    k("Ok", "The success variant of `Result`."),
41    k("Option", "The optional-value type, `Option[T]`."),
42    k("Result", "The success-or-error type, `Result[T, E]`."),
43    k("Some", "The present variant of `Option`."),
44    k("String", "The string base type."),
45    k(
46        "ValidationError",
47        "The error type returned by a refined type's `.of`.",
48    ),
49    k(
50        "actor",
51        "Declare an actor — a boundary contract a handler consumes via `by`.",
52    ),
53    k(
54        "adapter",
55        "Declare an adapter — the host boundary (capability contract + binding).",
56    ),
57    k("agent", "Declare a stateful, keyed agent inside a context."),
58    k("as", "Alias a consumed context (`consumes X as Y`)."),
59    k(
60        "asset",
61        "Declare a static file the platform serves, public by construction (`asset name = \"path\"`).",
62    ),
63    k(
64        "binding",
65        "Name an adapter's TypeScript binding module (`binding \"<module>\"`).",
66    ),
67    k(
68        "by",
69        "Name the actor a handler consumes, after the return type — or a service-level default on the header (`… -> T by <name>: <Actor>`).",
70    ),
71    k(
72        "capability",
73        "Declare a capability (a dependency interface) in a context.",
74    ),
75    k(
76        "case",
77        "Declare a test case inside a `suite` (`case \"…\" { … }`).",
78    ),
79    k(
80        "commons",
81        "Declare a pure, stateless module of types and functions.",
82    ),
83    k(
84        "consumes",
85        "Declare a dependency on another context's services.",
86    ),
87    k(
88        "context",
89        "Declare a deployable context (services, agents, capabilities).",
90    ),
91    k(
92        "cron",
93        "The cron protocol on a service header (`from cron`).",
94    ),
95    k(
96        "do",
97        "Perform a unit effect as a statement (`do e` — the binder-free `let _ <- e`).",
98    ),
99    k("else", "The alternative branch of an `if` expression."),
100    k(
101        "ensures",
102        "Declare a function postcondition — a pure `Bool` clause over the parameters and `result` (`ensures <name>: <pred>`).",
103    ),
104    k("enum", "Declare a payloadless sum type (`enum { A, B }`)."),
105    k(
106        "event",
107        "Declare a typed fact a context may emit (`event Name = { fields }`), inside a context.",
108    ),
109    k(
110        "expect",
111        "Assert a predicate inside a test case (`expect <bool-predicate>`).",
112    ),
113    k("exports", "Declare which types a context exposes, and how."),
114    k("false", "The boolean literal `false`."),
115    k("fn", "Declare a function."),
116    k(
117        "from",
118        "Name the protocol a service conforms to (`service X from http`).",
119    ),
120    k("given", "Declare the capabilities a handler requires."),
121    k(
122        "http",
123        "The HTTP protocol on a service header (`from http`).",
124    ),
125    k("if", "A conditional expression."),
126    k(
127        "implies",
128        "Logical implication (`P implies Q` ≡ `!P || Q`), used in invariant predicates.",
129    ),
130    k(
131        "invariant",
132        "Declare an agent invariant — a predicate that must hold of every committed state.",
133    ),
134    k(
135        "is",
136        "Test a value against a variant pattern, yielding a `Bool`.",
137    ),
138    k(
139        "let",
140        "Bind a local value (`let x = …`, or `let x <- …` for an effect).",
141    ),
142    k(
143        "match",
144        "Pattern-match over a sum type, `Result`, or `Option`.",
145    ),
146    k(
147        "messages",
148        "Declare a message bundle for one locale (`messages \"<tag>\" { \"code\" => \"template\" }`), inside a commons.",
149    ),
150    k(
151        "on",
152        "Begin a handler declaration (`on call`, `on GET(…)`, `on message`, `on open`/`on close`).",
153    ),
154    k(
155        "opaque",
156        "Declare an opaque type, or export a type opaquely.",
157    ),
158    k(
159        "property",
160        "Declare a generative test inside a `suite` (`property \"…\" { for all … }`).",
161    ),
162    k(
163        "protocol",
164        "Reserved keyword (protocols are a closed, compiler-known set).",
165    ),
166    k("provides", "Provide an implementation of a capability."),
167    k(
168        "queue",
169        "The queue protocol on a service header (`from queue(\"name\")`).",
170    ),
171    k(
172        "record",
173        "Reserved keyword (records are written `type X = { … }`).",
174    ),
175    k(
176        "requires",
177        "Declare a function precondition — a pure `Bool` clause over the parameters (`requires <name>: <pred>`).",
178    ),
179    k("self", "The current agent instance, inside a handler."),
180    k(
181        "service",
182        "Declare a service (a group of handlers) in a context.",
183    ),
184    k(
185        "stub",
186        "Stub a consumed capability operation at a test seam (`stub Cap.op(…) returns <v>` / `fails`).",
187    ),
188    k(
189        "suite",
190        "Declare a test suite targeting a unit (`suite <target> { case … }`).",
191    ),
192    k(
193        "transition",
194        "Declare an agent step invariant over the `old`/`new` state pair (`transition <name>: …`).",
195    ),
196    k(
197        "transparent",
198        "Export a type with its structure visible (`exports transparent { … }`).",
199    ),
200    k("true", "The boolean literal `true`."),
201    k(
202        "type",
203        "Declare a type: alias, record, sum, opaque, or refined.",
204    ),
205    k("uses", "Bring a commons into scope."),
206    k("where", "Attach refinement predicates to a base type."),
207];
208
209/// Contextual keywords — words that read as keywords in one position but stay
210/// usable as ordinary identifiers elsewhere, so they are lexed as `Ident` and
211/// are deliberately *absent* from [`KEYWORDS`] (which is drift-guarded to equal
212/// the lexer's reserved `#[token]`s). Editor surfaces still owe them a hover and
213/// a doc — the mechanical floor over this table lives in
214/// `bynk-lsp/tests/editor_coverage.rs`, mirroring the reserved-keyword tooth
215/// (ADR 0156 / ADR 0161).
216pub const CONTEXTUAL_KEYWORDS: &[KeywordInfo] = &[
217    k(
218        "key",
219        "The agent's identity field — one per agent; keys the store.",
220    ),
221    k("store", "A persisted agent-state field."),
222];
223
224/// The reserved lexer tokens the parser deliberately re-admits as identifiers
225/// outside their one keyword position (`expect_ident`, ADR-tracked at
226/// `parser.rs`). Unlike [`CONTEXTUAL_KEYWORDS`] these words *are* real
227/// `#[token]`s and *are* members of [`KEYWORDS`] (so the lexer↔registry drift
228/// guard sees them) — they simply are not rejected in identifier position. The
229/// keyword reference renders them as a distinct tier so the page no longer
230/// claims, falsely, that every listed word is unusable as an identifier.
231///
232/// Single source of truth: the `expect_ident` exemption arm (via
233/// [`is_reserved_contextual`]) and the
234/// `is_reserved_keyword_covers_every_lexer_keyword` drift guard both defer to
235/// this list, so adding a word here is enough to make the parser admit it.
236pub const RESERVED_CONTEXTUAL: &[&str] = &["asset", "case", "event", "messages", "on", "suite"];
237
238/// True when `word` is a [reserved contextual keyword](RESERVED_CONTEXTUAL) —
239/// a reserved token `expect_ident` re-admits as an identifier. Because each of
240/// these words lexes only to its own dedicated token, matching on the source
241/// text is equivalent to matching the token kind, but keeps the exemption
242/// single-sourced against [`RESERVED_CONTEXTUAL`].
243pub fn is_reserved_contextual(word: &str) -> bool {
244    RESERVED_CONTEXTUAL.contains(&word)
245}
246
247/// Built-in type names — compiler-known type constructors the parser dispatches
248/// on by identifier text in `parser/types.rs`, *outside* the keyword/token
249/// system entirely (they are lexed as ordinary `Ident`s, so they are absent
250/// from both the lexer's `#[token]`s and [`KEYWORDS`]). They are nonetheless
251/// reserved in type position: a `type` declaration may not reuse one of these
252/// names (`bynk.resolve.reserved_builtin_type`), because the parser would
253/// otherwise intercept every later reference and the user's alias would be
254/// silently shadowed or fail incoherently.
255///
256/// Single source of truth: [`is_builtin_type_name`] gates the resolver's
257/// redeclaration diagnostic, and a drift guard
258/// (`bynkc/tests/keywords_reference.rs`) asserts this list equals the set of
259/// names the type parser dispatches on. Keep it sorted.
260pub const BUILTIN_TYPE_NAMES: &[KeywordInfo] = &[
261    k(
262        "Asset",
263        "A static file declared by `asset name = \"path\"`; its `.url` is the content-hashed URL the platform serves it at.",
264    ),
265    k(
266        "Connection",
267        "A held WebSocket connection, `Connection[F]`.",
268    ),
269    k(
270        "History",
271        "A generated call-history generator, `History[Agent]` (test-only).",
272    ),
273    k(
274        "HttpResult",
275        "The HTTP handler result type, `HttpResult[T]`.",
276    ),
277    k("List", "The immutable list type, `List[T]`."),
278    k("Map", "The immutable map type, `Map[K, V]`."),
279    k("Query", "The lazy storage-read type, `Query[T]`."),
280    k(
281        "QueueResult",
282        "The queue handler result type (non-generic).",
283    ),
284    k("Stream", "The value-over-time primitive, `Stream[T]`."),
285];
286
287/// True when `name` is a compiler-known [built-in type name](BUILTIN_TYPE_NAMES).
288/// Used by the resolver to reject `type <name> = …` redeclarations.
289pub fn is_builtin_type_name(name: &str) -> bool {
290    BUILTIN_TYPE_NAMES.iter().any(|b| b.word == name)
291}
292
293const fn k(word: &'static str, meaning: &'static str) -> KeywordInfo {
294    KeywordInfo { word, meaning }
295}
296
297/// Render the keyword reference page — three tiers, each with prose that is
298/// true of *that* tier (the page used to make one blanket claim that was false
299/// of two of them).
300pub fn render_markdown() -> String {
301    let mut out = String::new();
302    out.push_str("# Keywords\n\n");
303    out.push_str(
304        "<!-- GENERATED FILE — do not edit by hand.\n     \
305         Source: bynk-syntax/src/keywords.rs (`render_markdown`).\n     \
306         Regenerate with: BYNK_BLESS=1 cargo test -p bynkc --test keywords_reference -->\n\n",
307    );
308    out.push_str(
309        "Bynk reserves names in three tiers. The first two are lexer keywords; the \
310         third are compiler-known type names. Only the **hard keywords** can never \
311         be used as an identifier.\n\n",
312    );
313
314    // Tier 1 — hard keywords: every reserved token except the contextual ones.
315    let hard: Vec<&KeywordInfo> = KEYWORDS
316        .iter()
317        .filter(|k| !RESERVED_CONTEXTUAL.contains(&k.word))
318        .collect();
319    out.push_str("## Hard keywords\n\n");
320    out.push_str(&format!(
321        "Reserved everywhere — these **{}** words can never be used as an \
322         identifier.\n\n",
323        hard.len()
324    ));
325    out.push_str("| Keyword | Meaning |\n|---|---|\n");
326    for info in hard {
327        out.push_str(&format!("| `{}` | {} |\n", info.word, info.meaning));
328    }
329
330    // Tier 2 — contextual keywords: reserved tokens the parser re-admits as
331    // identifiers outside their one keyword position.
332    let contextual: Vec<&KeywordInfo> = RESERVED_CONTEXTUAL
333        .iter()
334        .filter_map(|w| KEYWORDS.iter().find(|k| &k.word == w))
335        .collect();
336    out.push_str("\n## Contextual keywords\n\n");
337    out.push_str(
338        "Reserved only in the one position named below; elsewhere (a field, \
339         parameter, or other identifier) they are ordinary names.\n\n",
340    );
341    out.push_str("| Keyword | Meaning |\n|---|---|\n");
342    for info in contextual {
343        out.push_str(&format!("| `{}` | {} |\n", info.word, info.meaning));
344    }
345
346    // Tier 3 — built-in type names: not lexer keywords at all, but reserved in
347    // type position (a `type` declaration may not reuse one).
348    out.push_str("\n## Built-in type names\n\n");
349    out.push_str(
350        "Compiler-known type constructors. They are not lexer keywords — you may \
351         use them as an identifier in value position — but they are reserved in \
352         type position: a `type` declaration may not reuse one of these names \
353         (`bynk.resolve.reserved_builtin_type`).\n\n",
354    );
355    out.push_str("| Name | Meaning |\n|---|---|\n");
356    for info in BUILTIN_TYPE_NAMES {
357        out.push_str(&format!("| `{}` | {} |\n", info.word, info.meaning));
358    }
359    out
360}