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