tabnas_directive/lib.rs
1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3//! Directive syntax plugin for the [tabnas](https://github.com/tabnas/parser)
4//! parser engine.
5//!
6//! A *directive* is a token sequence — `@name` (open-only) or `add<1,2>`
7//! (open + close) — that pushes into a dedicated rule and fires an action
8//! to transform the parsed body. This crate is **not a parser of its own**:
9//! it layers onto whatever host grammar supplies the standard `val` /
10//! `list` / `map` / `pair` / `elem` rules, adds open/close tokens, modifies
11//! those host rules, and installs one rule named after the directive.
12//!
13//! ```no_run
14//! use tabnas::{Tabnas, Value};
15//! use tabnas_directive::{apply, DirectiveOptions};
16//!
17//! let mut parser = Tabnas::new();
18//! // ... install a host grammar supplying val/list/map/pair/elem ...
19//! apply(
20//! &mut parser,
21//! DirectiveOptions::new("upper", "@").with_action(|rule, _ctx| {
22//! let body = match &rule.child_node {
23//! Value::String(text) => text.to_uppercase(),
24//! other => other.to_string().to_uppercase(),
25//! };
26//! tabnas_directive::set_node(rule, Value::String(body));
27//! Ok(())
28//! }),
29//! )?;
30//! # Ok::<(), tabnas_directive::DirectiveError>(())
31//! ```
32//!
33//! TypeScript is canonical: `ts/src/directive.ts` defines behaviour,
34//! option names, defaults and the order of alts. The shared fixtures in
35//! `test/spec/*.tsv` are the parity contract across TypeScript, Go and
36//! Rust. Intentional differences are tabulated in `docs/reference.md`.
37
38use std::cell::RefCell;
39use std::collections::BTreeMap;
40use std::fmt;
41use std::rc::Rc;
42use std::sync::Arc;
43
44use indexmap::IndexMap;
45use serde_json::{json, Map as JsonMap, Value as JsonValue};
46
47use tabnas::{
48 ActionError, Context, GrammarSetting, GrammarSpec, Plugin, PluginError, Rule, RuleSnapshot,
49 Tabnas, Tin, Token, Value,
50};
51
52/// VERSION is this crate's version. It MUST equal `ts/package.json`
53/// "version" and the `version` field in `rs/Cargo.toml`: the release
54/// orchestrator rewrites all of them, and `tests/version_test.rs` fails
55/// the build if they drift. Mirrors `VERSION` in `ts/src/directive.ts`
56/// and `const VERSION` in `go/directive.go`.
57pub const VERSION: &str = "0.5.13";
58
59/// The default host rules a directive modifies for its OPEN token.
60const DEFAULT_OPEN_RULES: &str = "val";
61
62/// The default host rules a directive modifies for its CLOSE token.
63const DEFAULT_CLOSE_RULES: &str = "list,elem,map,pair";
64
65/// A directive registration failure: an unusable name, a duplicate open
66/// token, or a grammar that the engine refused to install.
67///
68/// The TypeScript plugin *throws* for the last two (it does not validate
69/// the name); the Rust port returns them, exactly as the Go port does. The plugin itself never panics — a panic
70/// raised inside a user callback is contained by the engine and surfaces
71/// as a [`PluginError`].
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct DirectiveError(pub String);
74
75impl fmt::Display for DirectiveError {
76 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
77 formatter.write_str(&self.0)
78 }
79}
80
81impl std::error::Error for DirectiveError {}
82
83impl From<PluginError> for DirectiveError {
84 fn from(error: PluginError) -> Self {
85 Self(error.0)
86 }
87}
88
89impl From<DirectiveError> for PluginError {
90 fn from(error: DirectiveError) -> Self {
91 Self(error.0)
92 }
93}
94
95/// A directive action that transforms the parsed body.
96///
97/// The body is `rule.child_node`; the result is written to `rule.node` —
98/// through [`set_node`], which handles the shared-node cell correctly.
99/// Returning `Err(ActionError)` aborts the parse with that code — the Rust
100/// spelling of a TypeScript action returning an *error* token.
101pub type ActionFn = Arc<dyn Fn(&mut Rule, &mut Context) -> Result<(), ActionError> + Send + Sync>;
102
103/// A directive action that may hand a token back to the engine, mirroring
104/// the TypeScript `bc` hook's `Token | void` return. A token carrying an
105/// error code halts the parse; any other token is forwarded and otherwise
106/// ignored.
107pub type TokenActionFn =
108 Arc<dyn Fn(&mut Rule, &mut Context) -> Result<Option<Token>, ActionError> + Send + Sync>;
109
110/// An alternate condition gating where a directive is recognised.
111pub type ConditionFn = Arc<dyn Fn(&mut Rule, &mut Context) -> bool + Send + Sync>;
112
113/// Extra customization of the parser once the directive rule exists.
114pub type CustomFn = Arc<dyn Fn(&mut Tabnas, &DirectiveConfig) + Send + Sync>;
115
116/// The resolved token identities for a directive, handed to a
117/// [`CustomFn`] callback.
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub struct DirectiveConfig {
120 /// The directive's OPEN token.
121 pub open: Tin,
122 /// The directive's CLOSE token, when it has one.
123 pub close: Option<Tin>,
124 /// The directive (and rule) name.
125 pub name: String,
126}
127
128/// Set a rule's node value.
129///
130/// A rule pushed by the engine SHARES its parent's node cell, so writing
131/// through `rule.node.borrow_mut()` would overwrite the parent's node too.
132/// Assigning a result — what `rule.node = …` means in the canonical
133/// TypeScript engine — has to install a fresh cell instead, which is what
134/// this does. Reach for `rule.node.borrow_mut()` only to mutate a
135/// container the rule genuinely shares (pushing onto an enclosing list,
136/// say).
137///
138/// Every directive action wanting to produce a value should go through
139/// here.
140pub fn set_node(rule: &mut Rule, value: Value) {
141 rule.node = Rc::new(RefCell::new(value));
142}
143
144/// How a directive transforms its parsed body.
145///
146/// Mirrors the TypeScript `action: StateAction | string` option: a
147/// callback, or a dotted path resolved against the parser options when the
148/// directive fires.
149#[derive(Clone, Default)]
150pub enum DirectiveAction {
151 /// No action — the directive's node stays the empty map seeded by the
152 /// rule's `bo` hook.
153 #[default]
154 None,
155 /// A classic action: set `rule.node` to the result value.
156 Call(ActionFn),
157 /// An action that may return a token for the close hook to forward.
158 Token(TokenActionFn),
159 /// A dotted path resolved against the parser options at
160 /// directive-execution time; the resolved value becomes the
161 /// directive's node.
162 ///
163 /// The TypeScript options object is open, so TS resolves the path from
164 /// its top level. The Rust `Options` struct is closed — like Go's —
165 /// so the path is resolved in the plugin-options namespace
166 /// (TS `options.plugin`): `"custom.x"` reads
167 /// `parser.plugin_options("custom")["x"]`.
168 Path(String),
169}
170
171impl fmt::Debug for DirectiveAction {
172 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
173 match self {
174 Self::None => formatter.write_str("DirectiveAction::None"),
175 Self::Call(_) => formatter.write_str("DirectiveAction::Call(<function>)"),
176 Self::Token(_) => formatter.write_str("DirectiveAction::Token(<function>)"),
177 Self::Path(path) => write!(formatter, "DirectiveAction::Path({path:?})"),
178 }
179 }
180}
181
182impl DirectiveAction {
183 /// Run the action in the directive rule's `bc` hook.
184 fn run(&self, rule: &mut Rule, context: &mut Context) -> Result<Option<Token>, ActionError> {
185 match self {
186 Self::None => Ok(None),
187 Self::Call(action) => action(rule, context).map(|()| None),
188 Self::Token(action) => action(rule, context),
189 Self::Path(path) => {
190 let value = option_prop(context, path);
191 set_node(rule, value);
192 Ok(None)
193 }
194 }
195 }
196}
197
198/// Resolve a dotted path within the parse's plugin-options namespace.
199///
200/// The lookup happens when the directive fires, against the parse's own
201/// resolved options, so options set after plugin registration are seen —
202/// matching the TypeScript closure over `tabnas.options`. A missing
203/// segment resolves to `Value::Undefined`.
204fn option_prop(context: &Context, path: &str) -> Value {
205 let mut parts = path.split('.');
206 let Some(head) = parts.next() else {
207 return Value::Undefined;
208 };
209 let mut current = match context.options.plugin.get(&head.to_lowercase()) {
210 Some(value) => value.clone(),
211 None => return Value::Undefined,
212 };
213 for part in parts {
214 let Value::Object(map) = current else {
215 return Value::Undefined;
216 };
217 current = match map.get(part) {
218 Some(value) => value.clone(),
219 None => return Value::Undefined,
220 };
221 }
222 current
223}
224
225/// How a directive integrates with one existing grammar rule.
226#[derive(Clone, Default)]
227pub struct RuleMod {
228 /// An optional condition that must hold for the directive to match
229 /// within this rule.
230 pub c: Option<ConditionFn>,
231}
232
233impl RuleMod {
234 /// A rule modification with no extra condition.
235 pub fn new() -> Self {
236 Self::default()
237 }
238
239 /// A rule modification gated by `condition`.
240 pub fn when(
241 condition: impl Fn(&mut Rule, &mut Context) -> bool + Send + Sync + 'static,
242 ) -> Self {
243 Self {
244 c: Some(Arc::new(condition)),
245 }
246 }
247}
248
249impl fmt::Debug for RuleMod {
250 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
251 formatter
252 .debug_struct("RuleMod")
253 .field("c", &self.c.as_ref().map(|_| "<function>"))
254 .finish()
255 }
256}
257
258/// Which grammar rules a directive modifies.
259///
260/// `open` rules detect the directive's open token and push to the
261/// directive rule; `close` rules detect the close token (when there is
262/// one) so it also ends sibling parsing.
263///
264/// Rules are held in a [`BTreeMap`] so a directive installs its grammar in
265/// a deterministic order.
266#[derive(Clone, Debug, Default)]
267pub struct RulesOption {
268 pub open: BTreeMap<String, RuleMod>,
269 pub close: BTreeMap<String, RuleMod>,
270}
271
272impl RulesOption {
273 /// A rules option that modifies nothing. Passed to
274 /// [`DirectiveOptions::with_rules`] it suppresses the defaults
275 /// entirely — which leaves the open token unrecognised.
276 pub fn new() -> Self {
277 Self::default()
278 }
279
280 /// Set the open-side rules from a comma-separated list of rule names.
281 pub fn open_rules(mut self, rules: &str) -> Self {
282 self.open = parse_rule_list(rules);
283 self
284 }
285
286 /// Set the close-side rules from a comma-separated list of rule names.
287 pub fn close_rules(mut self, rules: &str) -> Self {
288 self.close = parse_rule_list(rules);
289 self
290 }
291
292 /// Add one open-side rule, optionally gated by a condition.
293 pub fn open_rule(mut self, name: impl Into<String>, modification: RuleMod) -> Self {
294 self.open.insert(name.into(), modification);
295 self
296 }
297
298 /// Add one close-side rule, optionally gated by a condition.
299 pub fn close_rule(mut self, name: impl Into<String>, modification: RuleMod) -> Self {
300 self.close.insert(name.into(), modification);
301 self
302 }
303}
304
305/// Split a comma-separated rule list, dropping empty names — the Rust
306/// spelling of the TypeScript `resolveRules` string form.
307fn parse_rule_list(rules: &str) -> BTreeMap<String, RuleMod> {
308 rules
309 .split(',')
310 .map(str::trim)
311 .filter(|name| !name.is_empty())
312 .map(|name| (name.to_string(), RuleMod::new()))
313 .collect()
314}
315
316/// Configuration for one directive.
317///
318/// Built with [`DirectiveOptions::new`] plus the `with_*` methods, then
319/// handed to [`apply`] or [`plugin`].
320#[derive(Clone)]
321pub struct DirectiveOptions {
322 /// The directive name, used as the rule name and token-name suffix.
323 /// It must be non-empty and contain no whitespace — registration
324 /// rejects anything else, because the serialized grammar could not
325 /// name the token.
326 pub name: String,
327
328 /// The character sequence that starts the directive. It must be
329 /// unique — re-registering an existing fixed token is an error.
330 pub open: String,
331
332 /// The optional character sequence that ends the directive. Without
333 /// one the directive consumes a single value after the open token.
334 pub close: Option<String>,
335
336 /// How the parsed body is transformed.
337 pub action: DirectiveAction,
338
339 /// Which existing grammar rules are modified. `None` selects the
340 /// defaults (open `val`, close `list,elem,map,pair`); `Some(value)`
341 /// is a complete override, so `Some(RulesOption::new())` modifies no
342 /// rules.
343 ///
344 /// TypeScript *deep-merges* its defaults into whatever `rules` is
345 /// passed, so a partial `rules` there keeps the default of the
346 /// direction it omits. Rust, like Go, cannot express that merge over a
347 /// typed option and treats any `Some` as complete. This is an
348 /// intentional divergence — see `docs/reference.md`.
349 pub rules: Option<RulesOption>,
350
351 /// Extra parser customization once the directive rule exists.
352 pub custom: Option<CustomFn>,
353}
354
355impl fmt::Debug for DirectiveOptions {
356 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
357 formatter
358 .debug_struct("DirectiveOptions")
359 .field("name", &self.name)
360 .field("open", &self.open)
361 .field("close", &self.close)
362 .field("action", &self.action)
363 .field("rules", &self.rules)
364 .field("custom", &self.custom.as_ref().map(|_| "<function>"))
365 .finish()
366 }
367}
368
369impl DirectiveOptions {
370 /// A directive named `name`, opened by the token source `open`.
371 pub fn new(name: impl Into<String>, open: impl Into<String>) -> Self {
372 Self {
373 name: name.into(),
374 open: open.into(),
375 close: None,
376 action: DirectiveAction::None,
377 rules: None,
378 custom: None,
379 }
380 }
381
382 /// Give the directive a close token.
383 pub fn with_close(mut self, close: impl Into<String>) -> Self {
384 self.close = Some(close.into());
385 self
386 }
387
388 /// Set a classic action: write the result to `rule.node`.
389 pub fn with_action(
390 mut self,
391 action: impl Fn(&mut Rule, &mut Context) -> Result<(), ActionError> + Send + Sync + 'static,
392 ) -> Self {
393 self.action = DirectiveAction::Call(Arc::new(action));
394 self
395 }
396
397 /// Set an action that may return a token for the close hook to
398 /// forward.
399 pub fn with_token_action(
400 mut self,
401 action: impl Fn(&mut Rule, &mut Context) -> Result<Option<Token>, ActionError>
402 + Send
403 + Sync
404 + 'static,
405 ) -> Self {
406 self.action = DirectiveAction::Token(Arc::new(action));
407 self
408 }
409
410 /// Set a dotted-path action resolved against the plugin options when
411 /// the directive fires. See [`DirectiveAction::Path`].
412 pub fn with_action_path(mut self, path: impl Into<String>) -> Self {
413 self.action = DirectiveAction::Path(path.into());
414 self
415 }
416
417 /// Override which host rules are modified.
418 pub fn with_rules(mut self, rules: RulesOption) -> Self {
419 self.rules = Some(rules);
420 self
421 }
422
423 /// Run `custom` once the directive rule exists.
424 pub fn with_custom(
425 mut self,
426 custom: impl Fn(&mut Tabnas, &DirectiveConfig) + Send + Sync + 'static,
427 ) -> Self {
428 self.custom = Some(Arc::new(custom));
429 self
430 }
431
432 /// The close token source, when there is a non-empty one.
433 fn close_source(&self) -> Option<&str> {
434 self.close.as_deref().filter(|close| !close.is_empty())
435 }
436
437 /// The open and close rule maps, applying the defaults when `rules` is
438 /// absent.
439 fn resolved_rules(&self) -> (BTreeMap<String, RuleMod>, BTreeMap<String, RuleMod>) {
440 match &self.rules {
441 Some(rules) => (rules.open.clone(), rules.close.clone()),
442 None => (
443 parse_rule_list(DEFAULT_OPEN_RULES),
444 parse_rule_list(DEFAULT_CLOSE_RULES),
445 ),
446 }
447 }
448}
449
450/// Build the directive plugin for `options`.
451///
452/// The returned [`Plugin`] can be installed with
453/// [`Tabnas::use_plugin`], and — like every native plugin — re-runs
454/// against a derived instance's options. Most callers want [`apply`].
455///
456/// Typed option data lives in the returned closure rather than in the
457/// engine's serialized plugin-option bag, because a directive's action,
458/// conditions and custom hook are Rust callbacks and no [`Value`] can
459/// carry them.
460pub fn plugin(options: DirectiveOptions) -> Plugin {
461 Plugin::new("Directive", move |parser, _plugin_options| {
462 install(parser, &options).map_err(PluginError::from)
463 })
464}
465
466/// Register a directive on `parser`.
467///
468/// The convenience constructor mirroring the TypeScript
469/// `j.use(Directive, options)` call: it forwards to
470/// [`Tabnas::use_plugin`] so the directive is re-applied to derived
471/// instances. Registration failures — a duplicate open token, a grammar
472/// the engine refused — are returned rather than panicking.
473pub fn apply(parser: &mut Tabnas, options: DirectiveOptions) -> Result<(), DirectiveError> {
474 parser
475 .use_plugin(plugin(options), None)
476 .map(|_| ())
477 .map_err(DirectiveError::from)
478}
479
480/// Install one directive's tokens, refs and grammar on `parser`.
481fn install(parser: &mut Tabnas, options: &DirectiveOptions) -> Result<(), DirectiveError> {
482 let name = options.name.clone();
483 let open = options.open.clone();
484 let close = options.close_source().map(str::to_string);
485 let (open_rules, close_rules) = options.resolved_rules();
486
487 // The name doubles as the rule name and the token-name suffix, and
488 // the serialized grammar below names that token in a whitespace-split
489 // `s` string, so a name holding whitespace would split into unrelated
490 // tokens and the open alt could never match; an empty name has the
491 // same fate. (TypeScript names tokens by resolved Tin and does not
492 // validate the name.) Reject it before anything is registered, rather
493 // than install a directive that silently never fires.
494 if name.is_empty() || name.chars().any(char::is_whitespace) {
495 return Err(DirectiveError(format!(
496 "Directive name must be non-empty and contain no whitespace: {name:?}"
497 )));
498 }
499
500 // The OPEN token must be unique. (TypeScript throws here; the Rust
501 // port returns the error, which `use_plugin` propagates.)
502 if parser.fixed(&open).is_some() {
503 return Err(DirectiveError(format!(
504 "Directive open token already in use: {open}"
505 )));
506 }
507
508 // Register the open fixed token.
509 let open_tn = format!("#OD_{name}");
510 let open_tin = parser.token_with_source(&open_tn, &open);
511
512 // Register or look up the close fixed token. A close token already
513 // claimed by another directive is reused, so `foo<…>` and `bar<…>`
514 // can share `>`.
515 let mut close_tin = None;
516 let mut close_tn = None;
517 if let Some(close) = close.as_deref() {
518 if let Some(existing) = parser.fixed(close) {
519 close_tin = Some(existing);
520 close_tn = Some(parser.token_name(existing));
521 } else {
522 let token_name = format!("#CD_{name}");
523 close_tin = Some(parser.token_with_source(&token_name, close));
524 close_tn = Some(token_name);
525 }
526 }
527 register_lifecycle_refs(parser, &name, options.action.clone());
528
529 let document = build_grammar(
530 parser,
531 &name,
532 &open_tn,
533 close_tn.as_deref(),
534 &open_rules,
535 &close_rules,
536 );
537
538 // Clear any pre-existing alts and lifecycle actions on the directive
539 // rule, so the install below lays down a clean set.
540 parser.define_rule(name.clone(), |spec| {
541 spec.clear();
542 });
543
544 let spec =
545 GrammarSpec::from_value(document).map_err(|error| DirectiveError(error.to_string()))?;
546 parser
547 .grammar_with_setting(&spec, &GrammarSetting::groups("directive"))
548 .map_err(|error| DirectiveError(error.to_string()))?;
549
550 if let Some(custom) = options.custom.clone() {
551 let config = DirectiveConfig {
552 open: open_tin,
553 // close_tin is Some exactly when close_tn is.
554 close: close_tin,
555 name: name.clone(),
556 };
557 custom(parser, &config);
558 }
559
560 Ok(())
561}
562
563/// Register the directive rule's `bo` and `bc` hooks under the engine's
564/// `@<rule>-<phase>` reference convention, so installing the `<name>` rule
565/// wires them automatically.
566fn register_lifecycle_refs(parser: &mut Tabnas, name: &str, action: DirectiveAction) {
567 // bo: seed the directive rule's node with an empty map.
568 parser.state_action_with_next_ref(format!("@{name}-bo"), |rule, _context, _next, _out| {
569 set_node(rule, Value::object(IndexMap::new()));
570 Ok(None)
571 });
572
573 // bc: run the action. A returned token is forwarded to the engine,
574 // which halts the parse when it carries an error code and otherwise
575 // passes it through — exactly as the TypeScript `bc` hook does.
576 parser.state_action_with_next_ref(
577 format!("@{name}-bc"),
578 move |rule: &mut Rule,
579 context: &mut Context,
580 _next: Option<&RuleSnapshot>,
581 _out: Option<Token>| { action.run(rule, context) },
582 );
583}
584
585/// Build the serialized grammar document covering every host-rule
586/// modification plus the directive rule's own alts.
587///
588/// Conditions are registered on `parser` as `@dr-*` references and named
589/// from the document, the Rust spelling of the TypeScript spec's inline
590/// `c` functions.
591fn build_grammar(
592 parser: &mut Tabnas,
593 name: &str,
594 open_tn: &str,
595 close_tn: Option<&str>,
596 open_rules: &BTreeMap<String, RuleMod>,
597 close_rules: &BTreeMap<String, RuleMod>,
598) -> JsonValue {
599 let counter = format!("dr_{name}");
600 let mut rules = JsonMap::new();
601
602 // ---- Host rules that detect the OPEN token ----
603
604 for (rule_name, modification) in open_rules {
605 let mut open_alts: Vec<JsonValue> = Vec::new();
606 let mut close_alts: Vec<JsonValue> = Vec::new();
607
608 if let Some(close_tn) = close_tn {
609 // The more specific OPEN+CLOSE alt (an empty directive) is
610 // tried before OPEN alone.
611 open_alts.push(json!({
612 "s": format!("{open_tn} {close_tn}"),
613 "b": 1,
614 "p": name,
615 "n": { counter.clone(): 1 },
616 "g": "start,end",
617 }));
618 close_alts.push(json!({ "s": close_tn, "b": 1, "g": "end" }));
619 }
620
621 let mut open_alt = json!({
622 "s": open_tn,
623 "p": name,
624 "n": { counter.clone(): 1 },
625 "g": "start",
626 });
627 if let Some(condition) = modification.c.clone() {
628 let reference = format!("@dr-open-c-{name}-{rule_name}");
629 parser.alt_condition(reference.clone(), move |rule, context| {
630 condition(rule, context)
631 });
632 insert_field(&mut open_alt, "c", JsonValue::String(reference));
633 }
634 open_alts.push(open_alt);
635
636 let entry = rule_entry(&mut rules, rule_name);
637 insert_field(entry, "open", JsonValue::Array(open_alts));
638 if !close_alts.is_empty() {
639 insert_field(entry, "close", JsonValue::Array(close_alts));
640 }
641 }
642
643 // ---- Host rules that detect the CLOSE token ----
644
645 if let Some(close_tn) = close_tn {
646 for (rule_name, modification) in close_rules {
647 let close_reference = format!("@dr-close-c-{name}-{rule_name}");
648 let condition = modification.c.clone();
649 let close_counter = counter.clone();
650 parser.alt_condition(close_reference.clone(), move |rule, context| {
651 if rule.n.get(&close_counter).copied().unwrap_or(0) != 1 {
652 return false;
653 }
654 match &condition {
655 Some(condition) => condition(rule, context),
656 None => true,
657 }
658 });
659
660 let comma_reference = format!("@dr-close-ca-c-{name}-{rule_name}");
661 let comma_counter = counter.clone();
662 parser.alt_condition(comma_reference.clone(), move |rule, _context| {
663 rule.n.get(&comma_counter).copied().unwrap_or(0) == 1
664 });
665
666 let entry = rule_entry(&mut rules, rule_name);
667 insert_field(
668 entry,
669 "close",
670 json!([
671 { "s": close_tn, "c": close_reference, "b": 1, "g": "end" },
672 {
673 "s": format!("#CA {close_tn}"),
674 "c": comma_reference,
675 "b": 1,
676 "g": "end,comma",
677 },
678 ]),
679 );
680 }
681 }
682
683 // ---- The directive rule's own alts ----
684
685 let mut directive_open: Vec<JsonValue> = Vec::new();
686 if let Some(close_tn) = close_tn {
687 // An immediate close is an empty directive.
688 directive_open.push(json!({ "s": close_tn, "b": 1 }));
689 }
690 // Push to `val` to parse the directive's body. The counters control
691 // implicit list/map creation: with a close token implicits are
692 // permitted (they are bounded by the close), without one they are
693 // suppressed so the directive does not eat its following siblings.
694 let counters = if close_tn.is_some() {
695 json!({ "dlist": 0, "dmap": 0 })
696 } else {
697 json!({ "dlist": 1, "dmap": 1 })
698 };
699 directive_open.push(json!({ "p": "val", "n": counters }));
700
701 let entry = rule_entry(&mut rules, name);
702 insert_field(entry, "open", JsonValue::Array(directive_open));
703 if let Some(close_tn) = close_tn {
704 insert_field(
705 entry,
706 "close",
707 json!([{ "s": close_tn }, { "s": format!("#CA {close_tn}") }]),
708 );
709 }
710
711 json!({ "rule": JsonValue::Object(rules) })
712}
713
714/// The grammar document entry for one rule, created on first use. A rule
715/// named in both the open and close sets reuses the same entry.
716fn rule_entry<'a>(rules: &'a mut JsonMap<String, JsonValue>, name: &str) -> &'a mut JsonValue {
717 rules
718 .entry(name.to_string())
719 .or_insert_with(|| JsonValue::Object(JsonMap::new()))
720}
721
722/// Set one field on a JSON object built above. Every call site constructs
723/// the object itself, so the target is always an object.
724fn insert_field(target: &mut JsonValue, key: &str, value: JsonValue) {
725 if let Some(object) = target.as_object_mut() {
726 object.insert(key.to_string(), value);
727 }
728}