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