Skip to main content

xtask/
grammar.rs

1//! Render the `tree-sitter-bynk` grammar to EBNF.
2//!
3//! This crate is the single source of the grammar reference. It takes the
4//! compiled grammar JSON (`tree-sitter-bynk/src/grammar.json`) as input and is
5//! otherwise location-agnostic, so the same renderer feeds both the full
6//! appendix page ([`render_appendix`]) and the per-rule includes embedded in
7//! the curated reference page ([`render_production`] / [`render_rule`]). Because
8//! both come from one implementation, an embedded production cannot drift from
9//! the appendix.
10//!
11//! **Display names.** Grammar rule names are parser-internal (`_type_ref`,
12//! `_expression`, …). For the reference we render *readable* names via
13//! [`display_name`]: a trivial `_x ::= y` wrapper collapses to its target, an
14//! optional override applies, otherwise a single leading underscore is stripped.
15//! The transform is applied to both rule heads and the nonterminal references
16//! inside productions, so the whole reference reads as language, not internals.
17//!
18//! See `xtask/tests/docs_consistency/grammar_reference.rs` (the appendix generator) and
19//! `site/src/plugins/remark-bynk-directives.mjs` (the `{{#grammar <rule>}}`
20//! include directive the Book renders with).
21
22use std::error::Error;
23use std::fmt;
24
25use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
26use serde::{Deserialize, Serialize, Serializer};
27use serde_json::{Map, Value};
28
29/// An error rendering a grammar production.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum GrammarError {
32    /// The grammar JSON could not be parsed.
33    Parse(String),
34    /// `name` is not a top-level rule in the grammar.
35    UnknownRule(String),
36}
37
38impl fmt::Display for GrammarError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            GrammarError::Parse(e) => write!(f, "could not parse grammar JSON: {e}"),
42            GrammarError::UnknownRule(name) => {
43                write!(
44                    f,
45                    "unknown grammar rule `{name}` (not a top-level production)"
46                )
47            }
48        }
49    }
50}
51
52impl Error for GrammarError {}
53
54/// Display-name overrides for rules whose mechanical name reads badly. Each key
55/// must be a real top-level rule (checked in tests). Keep this tiny — most rules
56/// read fine after collapsing wrappers and stripping the leading underscore.
57const OVERRIDES: &[(&str, &str)] = &[];
58
59/// A parsed grammar document plus the source order of its top-level rules.
60///
61/// `serde_json`'s object map is key-sorted unless the workspace-unifying
62/// `preserve_order` feature is on, so the rule order the reference depends on
63/// is read here, from the text, and never from the map.
64struct Grammar {
65    doc: Value,
66    order: Vec<String>,
67}
68
69impl Grammar {
70    fn parse(grammar_json: &str) -> Result<Grammar, serde_json::Error> {
71        let doc: Value = serde_json::from_str(grammar_json)?;
72        // Tolerant: a root or `rules` that isn't an object has no order, and
73        // `rules()` is then `None`, as before the order was read separately.
74        let order = serde_json::from_str::<RuleOrder>(grammar_json)
75            .map(|o| o.0)
76            .unwrap_or_default();
77        Ok(Grammar { doc, order })
78    }
79
80    fn rules(&self) -> Option<Rules<'_>> {
81        let map = self.doc.get("rules").and_then(Value::as_object)?;
82        Some(Rules {
83            map,
84            order: &self.order,
85        })
86    }
87}
88
89/// The top-level rules of a [`Grammar`], iterated in source order.
90#[derive(Clone, Copy)]
91struct Rules<'a> {
92    map: &'a Map<String, Value>,
93    order: &'a [String],
94}
95
96impl<'a> Rules<'a> {
97    fn get(&self, name: &str) -> Option<&'a Value> {
98        self.map.get(name)
99    }
100
101    fn contains_key(&self, name: &str) -> bool {
102        self.map.contains_key(name)
103    }
104
105    fn keys(&self) -> impl Iterator<Item = &'a String> + use<'a> {
106        self.order.iter()
107    }
108
109    fn iter(&self) -> impl Iterator<Item = (&'a String, &'a Value)> + use<'a> {
110        let map = self.map;
111        self.order
112            .iter()
113            .filter_map(move |k| map.get(k).map(|v| (k, v)))
114    }
115}
116
117/// Deserialises only the key order of the top-level `rules` object.
118struct RuleOrder(Vec<String>);
119
120impl<'de> Deserialize<'de> for RuleOrder {
121    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
122        struct Doc(Vec<String>);
123        struct DocVisitor;
124        impl<'de> Visitor<'de> for DocVisitor {
125            type Value = Doc;
126            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127                f.write_str("a grammar object")
128            }
129            fn visit_map<A: MapAccess<'de>>(self, mut m: A) -> Result<Doc, A::Error> {
130                let mut order = Vec::new();
131                while let Some(key) = m.next_key::<String>()? {
132                    if key == "rules" {
133                        order = m.next_value::<KeysOnly>()?.0;
134                    } else {
135                        m.next_value::<IgnoredAny>()?;
136                    }
137                }
138                Ok(Doc(order))
139            }
140        }
141        impl<'de> Deserialize<'de> for Doc {
142            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
143                d.deserialize_map(DocVisitor)
144            }
145        }
146        Ok(RuleOrder(Doc::deserialize(d)?.0))
147    }
148}
149
150/// An object's keys, in text order, with the values skipped.
151struct KeysOnly(Vec<String>);
152
153impl<'de> Deserialize<'de> for KeysOnly {
154    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
155        struct V;
156        impl<'de> Visitor<'de> for V {
157            type Value = KeysOnly;
158            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159                f.write_str("an object")
160            }
161            fn visit_map<A: MapAccess<'de>>(self, mut m: A) -> Result<KeysOnly, A::Error> {
162                let mut keys = Vec::new();
163                while let Some(k) = m.next_key::<String>()? {
164                    m.next_value::<IgnoredAny>()?;
165                    // A repeated key keeps its last value in the map, so list
166                    // it once, at its first position.
167                    if !keys.contains(&k) {
168                        keys.push(k);
169                    }
170                }
171                Ok(KeysOnly(keys))
172            }
173        }
174        d.deserialize_map(V)
175    }
176}
177
178/// If `name`'s body is a single `SYMBOL` (a trivial `_x ::= y` wrapper), return
179/// the target rule name. Such wrappers are collapsed: they never appear as their
180/// own production, and references to them render as the target's display name.
181fn trivial_wrapper_target<'a>(rules: Rules<'a>, name: &str) -> Option<&'a str> {
182    let body = rules.get(name)?;
183    if body.get("type").and_then(Value::as_str) == Some("SYMBOL") {
184        body.get("name").and_then(Value::as_str)
185    } else {
186        None
187    }
188}
189
190/// The readable display name of a grammar rule: collapse a trivial-wrapper chain
191/// to its target, apply any override, else strip a single leading underscore.
192fn display_name_in(rules: Rules<'_>, name: &str) -> String {
193    if let Some(target) = trivial_wrapper_target(rules, name) {
194        return display_name_in(rules, target);
195    }
196    if let Some((_, disp)) = OVERRIDES.iter().find(|(k, _)| *k == name) {
197        return (*disp).to_string();
198    }
199    name.strip_prefix('_').unwrap_or(name).to_string()
200}
201
202/// Render a grammar node to EBNF text plus a precedence level:
203/// 0 = choice (`a | b`), 1 = sequence (`a b`), 2 = atom / postfix (`x`, `(…)*`).
204/// Nonterminal (`SYMBOL`) references are rendered with their display name.
205fn render(rules: Rules<'_>, node: &Value) -> (String, u8) {
206    match node.get("type").and_then(Value::as_str).unwrap_or("") {
207        "SYMBOL" => (
208            display_name_in(rules, node["name"].as_str().unwrap_or("?")),
209            2,
210        ),
211        "STRING" => (format!("\"{}\"", node["value"].as_str().unwrap_or("")), 2),
212        "PATTERN" => (format!("/{}/", node["value"].as_str().unwrap_or("")), 2),
213        "BLANK" => ("ε".to_string(), 2),
214        // Wrappers that don't affect the surface grammar: render their content.
215        "PREC" | "PREC_LEFT" | "PREC_RIGHT" | "PREC_DYNAMIC" | "TOKEN" | "IMMEDIATE_TOKEN"
216        | "FIELD" | "ALIAS" => render(rules, &node["content"]),
217        "REPEAT" => (format!("{}*", wrap_atom(rules, &node["content"])), 2),
218        "REPEAT1" => (format!("{}+", wrap_atom(rules, &node["content"])), 2),
219        "SEQ" => {
220            let parts: Vec<String> = members(node).iter().map(|m| wrap(rules, m, 1)).collect();
221            (parts.join(" "), 1)
222        }
223        "CHOICE" => {
224            let all = members(node);
225            let has_blank = all
226                .iter()
227                .any(|m| m.get("type").and_then(Value::as_str) == Some("BLANK"));
228            let non_blank: Vec<&Value> = all
229                .iter()
230                .filter(|m| m.get("type").and_then(Value::as_str) != Some("BLANK"))
231                .collect();
232            if has_blank {
233                // An optional: `X?`.
234                if non_blank.len() == 1 {
235                    (format!("{}?", wrap_atom(rules, non_blank[0])), 2)
236                } else {
237                    let inner: Vec<String> = non_blank.iter().map(|m| render(rules, m).0).collect();
238                    (format!("({})?", inner.join(" | ")), 2)
239                }
240            } else {
241                let inner: Vec<String> = non_blank.iter().map(|m| render(rules, m).0).collect();
242                (inner.join(" | "), 0)
243            }
244        }
245        other => (format!("/* {other} */"), 2),
246    }
247}
248
249fn members(node: &Value) -> Vec<Value> {
250    node["members"].as_array().cloned().unwrap_or_default()
251}
252
253/// Wrap so the result can be a postfix operand (`*`, `+`, `?`): needs an atom.
254fn wrap_atom(rules: Rules<'_>, node: &Value) -> String {
255    wrap(rules, node, 2)
256}
257
258/// Wrap `node`'s rendering in parens if its level is below `min`.
259fn wrap(rules: Rules<'_>, node: &Value, min: u8) -> String {
260    let (s, level) = render(rules, node);
261    if level < min { format!("({s})") } else { s }
262}
263
264fn render_extra(node: &Value) -> String {
265    match node.get("type").and_then(Value::as_str).unwrap_or("") {
266        "SYMBOL" => format!("`{}`", node["name"].as_str().unwrap_or("?")),
267        "PATTERN" => format!("`/{}/`", node["value"].as_str().unwrap_or("")),
268        "STRING" => format!("`\"{}\"`", node["value"].as_str().unwrap_or("")),
269        _ => "?".to_string(),
270    }
271}
272
273/// Render the complete grammar reference appendix
274/// (`site/src/content/docs/reference/grammar-appendix.md`): the
275/// generated-file header, the
276/// notation note, the full `ebnf` block of every production (display names,
277/// trivial wrappers collapsed), and the Tokens & trivia section.
278pub fn render_appendix(grammar_json: &str) -> String {
279    let grammar = Grammar::parse(grammar_json).expect("grammar.json parses");
280
281    let mut out = String::new();
282    out.push_str("# Complete grammar (appendix)\n\n");
283    out.push_str(
284        "<!-- GENERATED FILE — do not edit by hand.\n     \
285         Source: tree-sitter-bynk/src/grammar.json, via xtask/tests/docs_consistency/grammar_reference.rs.\n     \
286         Regenerate with: BYNK_BLESS=1 cargo test -p xtask --test docs_consistency grammar_reference:: -->\n\n",
287    );
288    out.push_str(
289        "The complete Bynk grammar, generated from the `tree-sitter-bynk` grammar. \
290         For the annotated, per-construct reference see [Syntax & grammar](grammar.md).\n\n",
291    );
292    out.push_str("**Notation.** ");
293    out.push_str(
294        "`\"x\"` a literal token · `/x/` a regular expression · `( … )?` optional · \
295         `( … )*` zero or more · `( … )+` one or more · `a | b` choice · `ε` empty. \
296         Rule names are the readable display names (a leading `_` denotes an \
297         internal helper rule; trivial wrappers are collapsed). `doc_block` is an \
298         external token — a `--- … ---` documentation block.\n\n",
299    );
300
301    out.push_str("```ebnf\n");
302    if let Some(rules) = grammar.rules() {
303        for (name, body) in rules.iter() {
304            // Trivial wrappers are collapsed into their target.
305            if trivial_wrapper_target(rules, name).is_some() {
306                continue;
307            }
308            let (rendered, _) = render(rules, body);
309            out.push_str(&format!(
310                "{} ::= {rendered}\n",
311                display_name_in(rules, name)
312            ));
313        }
314    }
315    out.push_str("```\n\n");
316
317    out.push_str("## Tokens & trivia\n\n");
318    if let Some(word) = grammar.doc.get("word").and_then(Value::as_str) {
319        out.push_str(&format!("- **Word token:** `{word}`\n"));
320    }
321    if let Some(extras) = grammar.doc.get("extras").and_then(Value::as_array) {
322        let rendered: Vec<String> = extras.iter().map(render_extra).collect();
323        out.push_str(&format!(
324            "- **Ignored between tokens:** {}\n",
325            rendered.join(", ")
326        ));
327    }
328    if let Some(externals) = grammar.doc.get("externals").and_then(Value::as_array) {
329        let rendered: Vec<String> = externals.iter().map(render_extra).collect();
330        out.push_str(&format!("- **External tokens:** {}\n", rendered.join(", ")));
331    }
332
333    out
334}
335
336/// Look up a rule body by name, erroring if the grammar is unparseable or the
337/// rule is not a top-level production.
338fn rule_body<'a>(rules: Rules<'a>, name: &str) -> Result<&'a Value, GrammarError> {
339    rules
340        .get(name)
341        .ok_or_else(|| GrammarError::UnknownRule(name.to_string()))
342}
343
344/// Render a single production's right-hand side (display names applied), exactly
345/// as it appears after `<name> ::= ` in the appendix's EBNF block.
346///
347/// Errors if the grammar JSON cannot be parsed, or if `name` is not a top-level
348/// rule of the grammar.
349pub fn render_rule(grammar_json: &str, name: &str) -> Result<String, GrammarError> {
350    let grammar = Grammar::parse(grammar_json).map_err(|e| GrammarError::Parse(e.to_string()))?;
351    let rules = grammar
352        .rules()
353        .ok_or_else(|| GrammarError::UnknownRule(name.to_string()))?;
354    let body = rule_body(rules, name)?;
355    Ok(render(rules, body).0)
356}
357
358/// Render a complete production line, `<display name> ::= <rhs>`, as it appears
359/// in the appendix (no surrounding fence). This is what `{{#grammar <rule>}}`
360/// embeds.
361pub fn render_production(grammar_json: &str, name: &str) -> Result<String, GrammarError> {
362    let grammar = Grammar::parse(grammar_json).map_err(|e| GrammarError::Parse(e.to_string()))?;
363    let rules = grammar
364        .rules()
365        .ok_or_else(|| GrammarError::UnknownRule(name.to_string()))?;
366    let body = rule_body(rules, name)?;
367    Ok(format!(
368        "{} ::= {}",
369        display_name_in(rules, name),
370        render(rules, body).0
371    ))
372}
373
374/// Every top-level rule that should have exactly one `{{#grammar}}` entry in the
375/// annotated reference: all rules **except** the trivial wrappers the display
376/// layer collapses (so this can never disagree with what is rendered). Grammar
377/// rule order is preserved. Returns an empty vector if the JSON is unparseable.
378pub fn embeddable_rules(grammar_json: &str) -> Vec<String> {
379    let Ok(grammar) = Grammar::parse(grammar_json) else {
380        return Vec::new();
381    };
382    let Some(rules) = grammar.rules() else {
383        return Vec::new();
384    };
385    rules
386        .keys()
387        .filter(|name| trivial_wrapper_target(rules, name.as_str()).is_none())
388        .cloned()
389        .collect()
390}
391
392/// The readable display name for a top-level rule. Errors if the grammar is
393/// unparseable or `name` is not a top-level rule.
394pub fn display_name(grammar_json: &str, name: &str) -> Result<String, GrammarError> {
395    let grammar = Grammar::parse(grammar_json).map_err(|e| GrammarError::Parse(e.to_string()))?;
396    let rules = grammar
397        .rules()
398        .ok_or_else(|| GrammarError::UnknownRule(name.to_string()))?;
399    if !rules.contains_key(name) {
400        return Err(GrammarError::UnknownRule(name.to_string()));
401    }
402    Ok(display_name_in(rules, name))
403}
404
405/// Render the grammar as the JSON document the documentation site consumes. The
406/// `{{#grammar}}` remark directive looks each rule up in `productions` (the same
407/// `<name> ::= <rhs>` line [`render_production`] embeds, over [`embeddable_rules`]),
408/// and the full-grammar page reads `appendix` ([`render_appendix`]). Because both
409/// come from the same renderer as the mdBook preprocessor, the site cannot drift
410/// from the book. Object keys preserve grammar order (read from the source text, not from
411/// `serde_json`'s map).
412///
413/// The committed artifact (`site/src/generated/grammar.json`) is drift-guarded by
414/// `xtask/tests/docs_consistency/generated_grammar_json.rs`; regenerate with `BYNK_BLESS=1`.
415pub fn render_site_json(grammar_json: &str) -> String {
416    /// A JSON object written in the order given, whatever `serde_json`'s map is.
417    struct Ordered(Vec<(String, String)>);
418    impl Serialize for Ordered {
419        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
420            s.collect_map(self.0.iter().map(|(k, v)| (k, v)))
421        }
422    }
423    /// Fields serialise in declaration order.
424    #[derive(Serialize)]
425    struct SiteDoc {
426        _generated: &'static str,
427        productions: Ordered,
428        appendix: String,
429    }
430
431    let mut productions = Vec::new();
432    for rule in embeddable_rules(grammar_json) {
433        if let Ok(production) = render_production(grammar_json, &rule) {
434            productions.push((rule, production));
435        }
436    }
437    let doc = SiteDoc {
438        _generated: "GENERATED from tree-sitter-bynk/src/grammar.json. Do not edit by hand. \
439             Regenerate with: BYNK_BLESS=1 cargo test -p xtask --test docs_consistency generated_grammar_json::",
440        productions: Ordered(productions),
441        appendix: render_appendix(grammar_json),
442    };
443    let mut out = serde_json::to_string_pretty(&doc).expect("serialise grammar JSON");
444    out.push('\n');
445    out
446}
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451    use std::collections::HashMap;
452    use std::fs;
453    use std::path::PathBuf;
454
455    fn grammar_json() -> String {
456        let path =
457            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../tree-sitter-bynk/src/grammar.json");
458        fs::read_to_string(path).expect("read grammar.json")
459    }
460
461    #[test]
462    fn render_rule_uses_display_names() {
463        let g = grammar_json();
464        // `_pattern`/`_expression` render without their leading underscore.
465        // #472: a match arm's pattern is `pattern | refined_pattern` (the
466        // latter admitted only here, not through `_pattern` generally).
467        assert_eq!(
468            render_rule(&g, "match_arm").unwrap(),
469            "(pattern | refined_pattern) (\"if\" expression)? \"=>\" expression \",\"?"
470        );
471        // `http_method` is a plain choice, unchanged.
472        assert_eq!(
473            render_rule(&g, "http_method").unwrap(),
474            "\"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\""
475        );
476        // `http_handler` references `_type_ref` and `block` — display, not raw.
477        let http = render_rule(&g, "http_handler").unwrap();
478        assert!(http.contains("type_ref"), "{http}");
479        assert!(!http.contains("_type_ref"), "{http}");
480        assert!(http.contains("block"), "{http}");
481    }
482
483    #[test]
484    fn embeddable_rules_excludes_trivial_wrappers() {
485        let g = grammar_json();
486        let rules = embeddable_rules(&g);
487        // v0.17 added: adapter_decl, _adapter_body_item, binding_decl,
488        // binding_requirement. v0.20a added: function_type_ref, lambda_expr,
489        // lambda_param. v0.20b added: list_literal. v0.21 added:
490        // float_literal. v0.43 added: string_interpolation. v0.44 added:
491        // service_protocol. v0.45 added: actor_decl, scheme, by_clause. v0.51
492        // added: scheme_config, scheme_arg. v0.79 added: effect_send_stmt. v0.80
493        // added: invariant_decl. v0.81 added: store_field, store_kind,
494        // assign_stmt. v0.85 added: store_annotation, annotation_arg. v0.96
495        // removed: state_decl, commit_stmt (parity cutover, ADR 0123).
496        // v0.103 added: ws_open_handler, ws_close_handler (the `from websocket`
497        // lifecycle handlers; `on message` reuses queue_handler). v0.114 added:
498        // property_decl, for_all, for_all_binding (generative tests); mock_expr/
499        // mock_arg renamed to val_expr/val_arg (no count change). v0.115 added:
500        // requires_clause, ensures_clause (function contracts). v0.116 added:
501        // transition_decl (agent step invariants). v0.117 added: observation_expr,
502        // trace_expr (the observation surface; the call-count matcher is inlined).
503        // v0.118 (testing track slice 6) removed: mocks_decl, integration_decl,
504        // wires_decl, _integration_body_item (mocks/integration/wires retired) and
505        // added: provides_clause (the test-scope stub; the `as <tier>` clause and
506        // the stub right-hand side are inlined). Net -3. (#548 renamed
507        // provides_clause → stub_clause with the `stub` keyword — no count change.)
508        // v0.130 added:
509        // literal_pattern (literal match-arm patterns). v0.131 (ADR 0159) added:
510        // cors_policy, cors_field (the CORS service policy). Net +3. v0.141
511        // (ADR 0164) added: security_policy, security_field (the security-headers
512        // service policy). Net +2. v0.142 (ADR 0165) added: limits_policy,
513        // limits_field (the request-body-size service policy). Net +2. v0.145
514        // (ADR 0169) removed: positional_binding — a variant payload is now a
515        // full `_pattern` (recursion), so a positional binding is a payload-less
516        // `variant_pattern`, not a dedicated node. Net -1. v0.146 (ADR 0170)
517        // added: do_stmt (the `do e` effect statement). Net +1. v0.157 (ADR
518        // 0183) added: applied_type_ref (a user generic-type application
519        // `Name[Arg, …]`). Net +1.
520        // v0.184 (ADR 0205) added: call_site_actor (the test-body
521        // `by <Actor>(<identity>)` clause). Net +1.
522        // Slice C added: wire_expr (the `Wire(<String>)` raw system-tier
523        // argument). Net +1.
524        // #472 added: refined_pattern (`_ where <predicate>` match-arm
525        // patterns, admitted only at a match arm's top-level pattern). Net +1.
526        // #474 added: or_pattern (`p₁ | p₂`) and paren_pattern (transparent
527        // grouping around a pattern, e.g. after `is`). Net +2.
528        // message-bundles slice 1 (#859) added: messages_decl, message_entry
529        // (the `messages <tag> { "code" => "template" }` construct). Net +2.
530        // Events track slice 0/1 (spine #936) added: event_decl (`event Name =
531        // { fields }`), event_handler (`on event(...)`), event_pattern,
532        // event_pattern_field, event_pattern_value (the slice-1 subscription
533        // filter `from Events(E { field: value, .. })`; `service_protocol`
534        // itself was extended in place, no new rule for it). Net +5.
535        // Events track slice 4 (spine #936) added: schema_dispatch_clause
536        // (the `via schema(N)` envelope-version dispatch clause; nested
537        // inside `service_protocol`'s Events arm, extended in place). Net +1.
538        // #1706 added: faults_expr (the `expect <call> faults` fault claim).
539        // Net +1.
540        // #1888 added: doc_line (the `--|` one-line doc token, an extra).
541        // Net +1.
542        // #1883 (static assets, slice 1a) added: asset_decl. Net +1.
543        // #2010 added: let_else_stmt, let_else_match (`let <pattern> … else …`),
544        // and _let_pattern, _let_variant_pattern, _let_or_pattern (the patterns
545        // that may open one, so a bare name after `let` stays a binding). Net +5.
546        // #2137 added: advance_stmt (`advance Clock by <Duration>`). Net +1.
547        // #2134 added: env_clause, env_entry (a suite's or case's
548        // `env { NAME = "value" … }`). Net +2.
549        // #2203 removed: doc_line (the one-line doc is an external token now,
550        // scanned with the doc-block). Net -1.
551        // #2224 added: migrate_decl, migrate_drop (an agent's `migrate from N`
552        // step and its `drop` item). Net +2.
553        // #2248 added: removed_agent_decl (`removed agent Old`). Net +1.
554        // #2341 added: rejected_handler (`on rejected(why: …)`). Net +1.
555        // #2347 follow-up added: _contextual_identifier (`trace`/`advance` as
556        // ordinary identifiers outside their keyword shapes). Net +1.
557        // #2387 (embedded text, slice 1) added: embed_decl. Net +1.
558        // #2641 (record patterns) added: record_pattern, record_pattern_field,
559        // and _is_pattern, _is_base_pattern, _is_or_pattern (the patterns an
560        // `is` takes unparenthesised, which exclude a record pattern). Net +5.
561        // #2617 (named constants) added: const_decl. Net +1.
562        // #2640 (concurrent effects, slice 0) added: par_stmt (the `par { … }`
563        // binding block) and _par_statement (what it may hold: every statement
564        // but a `let … else`). Net +2.
565        // Constrained generics slice 0 added: type_param, where_clause,
566        // where_bound (`constraint` is a trivial wrapper over `identifier`,
567        // so the display layer collapses it). Net +3.
568        // #2654 (`let` destructuring) added: _let_paren_record_pattern (the
569        // parenthesised record pattern of an `else`-less `let`). Net +1.
570        // Named constants (#2617) added const_decl. Net +1.
571        // #2618 (private declarations) added: visibility_modifier. Net +1.
572        // #2680 (list patterns) added: list_pattern and list_rest. Net +2.
573        // #2699 (range patterns) added: int_range. Net +1.
574        // #2712 (lambda record-pattern parameters) added: _lambda_record_pattern and
575        // _lambda_record_field. Net +2.
576        // #2619 (raw and multi-line strings) added: escape_sequence (the
577        // external `raw_string` token is not a rule). Net +1.
578        // #2622 (`Decimal`) added: decimal_literal. Net +1.
579        // #2841 (suite `fixture`) added: fixture_decl. Net +1.
580        // #2842 (snapshot claims) added: snapshot_expr. Net +1.
581        // #2858 (plain-JSON responses) added: json_policy, json_field (the
582        // response-JSON service policy). Net +2.
583        // #2890 (the `consumes_item` wrapper) added: consumes_item. Net +1.
584        // #2958 (multi-line string language tags) added: _multiline_opener_rest,
585        // string_tag, string_body, and raw_string (now a rule over the external
586        // `_raw_string_line` / `_raw_triple_open` / `raw_string_body` tokens).
587        // Net +4.
588        // #3386 (`SignedCookie`) added: scheme_duration (`ttl = 12.hours` in a
589        // scheme config). Net +1.
590        // #3443 (removal of `~>`) removed: effect_send_stmt. Net -1.
591        assert_eq!(rules.len(), 196);
592        assert!(rules.iter().any(|r| r == "http_handler"));
593        assert!(rules.iter().any(|r| r == "_type_ref"));
594        // The two trivial wrappers the display layer collapses are excluded.
595        assert!(!rules.iter().any(|r| r == "_base_type"));
596        assert!(!rules.iter().any(|r| r == "pred_atom"));
597        // Unparseable JSON yields no rules rather than panicking.
598        assert!(embeddable_rules("not json").is_empty());
599    }
600
601    #[test]
602    fn render_production_includes_display_head() {
603        let g = grammar_json();
604        assert_eq!(
605            render_production(&g, "match_arm").unwrap(),
606            "match_arm ::= (pattern | refined_pattern) (\"if\" expression)? \"=>\" expression \",\"?"
607        );
608    }
609
610    #[test]
611    fn display_name_collapses_and_strips() {
612        let g = grammar_json();
613        // Trivial wrapper `_base_type ::= base_type` collapses to its target.
614        assert_eq!(display_name(&g, "_base_type").unwrap(), "base_type");
615        // Helper rules strip the leading underscore.
616        assert_eq!(display_name(&g, "_expression").unwrap(), "expression");
617        assert_eq!(display_name(&g, "_type_ref").unwrap(), "type_ref");
618        // An ordinary rule is unchanged.
619        assert_eq!(display_name(&g, "http_handler").unwrap(), "http_handler");
620    }
621
622    #[test]
623    fn render_rule_unknown_rule_errors() {
624        let g = grammar_json();
625        assert_eq!(
626            render_rule(&g, "no_such_rule"),
627            Err(GrammarError::UnknownRule("no_such_rule".to_string()))
628        );
629    }
630
631    #[test]
632    fn render_rule_invalid_json_errors() {
633        assert!(matches!(
634            render_rule("not json", "match_arm"),
635            Err(GrammarError::Parse(_))
636        ));
637    }
638
639    #[test]
640    fn override_keys_are_real_rules() {
641        let g = grammar_json();
642        for (key, _) in OVERRIDES {
643            assert!(
644                display_name(&g, key).is_ok(),
645                "override key `{key}` is not a top-level rule"
646            );
647        }
648    }
649
650    /// The display transform must not map two displayed productions to the same
651    /// name — that would make the reference ambiguous. Trivial wrappers are
652    /// collapsed and so excluded.
653    #[test]
654    fn display_names_are_unique() {
655        let g = grammar_json();
656        let grammar = Grammar::parse(&g).unwrap();
657        let rules = grammar.rules().unwrap();
658        let mut seen: HashMap<String, String> = HashMap::new();
659        for name in rules.keys() {
660            if trivial_wrapper_target(rules, name).is_some() {
661                continue;
662            }
663            let disp = display_name_in(rules, name);
664            if let Some(prev) = seen.insert(disp.clone(), name.clone()) {
665                panic!("display name `{disp}` for `{name}` collides with `{prev}`");
666            }
667        }
668    }
669
670    /// Pins the two renderers to one implementation: every displayed rule's
671    /// production line must appear verbatim in the appendix, and the appendix
672    /// has exactly one production per non-wrapper rule (wrappers are collapsed,
673    /// nothing is duplicated).
674    #[test]
675    fn every_displayed_rule_matches_the_appendix() {
676        let g = grammar_json();
677        let appendix = render_appendix(&g);
678        let grammar = Grammar::parse(&g).unwrap();
679        let rules = grammar.rules().unwrap();
680
681        let mut displayed = 0;
682        for name in rules.keys() {
683            if trivial_wrapper_target(rules, name).is_some() {
684                continue;
685            }
686            displayed += 1;
687            let line = render_production(&g, name).unwrap();
688            assert!(
689                appendix.contains(&line),
690                "production for `{name}` not found in appendix:\n{line}"
691            );
692        }
693
694        // One `::=` per displayed rule — collapsed wrappers added no lines and
695        // no production is duplicated. (No grammar token contains `::=`.)
696        assert_eq!(appendix.matches("::=").count(), displayed);
697    }
698
699    /// Rule order is the source order of the text, not the (key-sorted) order
700    /// of `serde_json`'s map, so it can't depend on which crates share a build.
701    #[test]
702    fn rule_order_follows_the_source_text() {
703        let g = r#"{"rules":{"zeta":{"type":"BLANK"},"alpha":{"type":"BLANK"},"mid":{"type":"BLANK"}}}"#;
704        assert_eq!(embeddable_rules(g), ["zeta", "alpha", "mid"]);
705        let appendix = render_appendix(g);
706        let z = appendix.find("zeta ::=").unwrap();
707        let a = appendix.find("alpha ::=").unwrap();
708        let m = appendix.find("mid ::=").unwrap();
709        assert!(z < a && a < m);
710        let site = render_site_json(g);
711        let z = site.find("\"zeta\"").unwrap();
712        let a = site.find("\"alpha\"").unwrap();
713        let m = site.find("\"mid\"").unwrap();
714        assert!(z < a && a < m);
715    }
716
717    /// A grammar with no object `rules` still parses; it just has no rules.
718    #[test]
719    fn non_object_rules_parse_as_no_rules() {
720        assert!(embeddable_rules(r#"{"rules":[]}"#).is_empty());
721        assert!(matches!(
722            render_rule(r#"{"rules":3}"#, "x"),
723            Err(GrammarError::UnknownRule(_))
724        ));
725        assert!(render_appendix("[]").contains("```ebnf"));
726    }
727}