Skip to main content

tabnas_bnf/
spec.rs

1// Copyright (c) 2026 Richard Rodger and other contributors, MIT License
2
3//! The emitted grammar: an in-memory `GrammarSpec` with typed alternates
4//! (so marks and closure descriptors have somewhere to live), its wire
5//! form (the engine's own pure-data document), and the spec-level
6//! transforms: pure and recognition reductions, jsonic serialisation, and
7//! user semantic actions. Mirrors `ts/src/spec.ts` plus the `GrammarSpec`
8//! shape the TypeScript emitter builds.
9
10use std::cell::RefCell;
11use std::fmt;
12use std::rc::Rc;
13use std::sync::Arc;
14
15use indexmap::IndexMap;
16use serde_json::{json, Map, Value};
17use tabnas::{Context, GrammarError, Rule, Tabnas};
18
19use crate::ir::{diag_name, NodeKind};
20
21/// A user semantic action: run after the compiler's own action on the alt
22/// it is attached to, with the engine's rule and context.
23pub type ActionFn =
24    Arc<dyn Fn(&mut Rule, &mut Context) -> Result<(), tabnas::ActionError> + Send + Sync>;
25
26/// Action refs to attach: `@<rule>:<phase>` (bo/ao/bc/ac) or
27/// `@<rule>:o|c:<mark>`, each with the functions to run in order.
28pub type ActionsMap = Vec<(String, Vec<ActionFn>)>;
29
30/// What a `@`-ref in the spec's `ref` map stands for. In closure mode the
31/// emitter registers one of these per tree-building or probe-control
32/// action instead of a `$`-builtin; [`GrammarSpec::bind`] turns them into
33/// engine closures by name. User actions land here too.
34#[derive(Clone)]
35pub enum RefAction {
36    /// Allocate (when `init`) and accumulate the tree node: the closure
37    /// twin of `@node$`.
38    Node {
39        init: bool,
40        rule: String,
41        kind: NodeKind,
42        nterms: usize,
43    },
44    /// Merge the returned child's node into this rule's: `@capture$`.
45    Capture { rule: String, kind: NodeKind },
46    /// Lift the committed child's node up: `@bubble$`.
47    Bubble,
48    /// Fold a tail-repeat iteration into its parent: `@fold$`.
49    Fold { c_n: usize },
50    /// Probe dispatch phase 0 open: mark the position: `@probeInit$`.
51    ProbeInit,
52    /// Probe dispatch phase 0 close: peek, rewind, decide: `@probeDecide$`.
53    ProbeDecide { disambiguator: String },
54    /// A probe phase condition: `@probePhaseN$`.
55    ProbePhase(u8),
56    /// A user action attached to an alt (`@bnf_userN`).
57    User(ActionFn),
58    /// User actions composed onto a rule-phase hook (`@<rule>-<phase>`).
59    Phase(Vec<ActionFn>),
60}
61
62impl fmt::Debug for RefAction {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        match self {
65            RefAction::Node {
66                init,
67                rule,
68                kind,
69                nterms,
70            } => write!(f, "Node({init}, {rule}, {}, {nterms})", kind.as_str()),
71            RefAction::Capture { rule, kind } => write!(f, "Capture({rule}, {})", kind.as_str()),
72            RefAction::Bubble => write!(f, "Bubble"),
73            RefAction::Fold { c_n } => write!(f, "Fold({c_n})"),
74            RefAction::ProbeInit => write!(f, "ProbeInit"),
75            RefAction::ProbeDecide { disambiguator } => write!(f, "ProbeDecide({disambiguator})"),
76            RefAction::ProbePhase(n) => write!(f, "ProbePhase({n})"),
77            RefAction::User(_) => write!(f, "User(fn)"),
78            RefAction::Phase(fns) => write!(f, "Phase({} fns)", fns.len()),
79        }
80    }
81}
82
83/// One emitted alternate: the engine's alt fields in the order they were
84/// written, plus the compiler-internal mark `m`, which never reaches the
85/// wire.
86///
87/// The fields are kept as an insertion-ordered map with JavaScript
88/// assignment semantics (`set` on an existing key updates it in place, on
89/// a new key appends it), because the canonical compiler builds each
90/// alternate as an object literal and the serialised text is byte-stable
91/// only when this port writes the keys in the same order at every site.
92#[derive(Debug, Clone, Default, PartialEq)]
93pub struct AltSpec {
94    fields: Map<String, Value>,
95    pub m: Option<String>,
96}
97
98impl AltSpec {
99    pub fn new() -> Self {
100        Self::default()
101    }
102
103    /// `{ g: tag }`, the shape most alternates start from.
104    pub fn with_tag(tag: &str) -> Self {
105        let mut alt = Self::default();
106        alt.set("g", tag);
107        alt
108    }
109
110    /// Assign a field: an existing key keeps its position, a new one is
111    /// appended.
112    pub fn set(&mut self, key: &str, value: impl Into<Value>) -> &mut Self {
113        self.fields.insert(key.to_string(), value.into());
114        self
115    }
116
117    pub fn remove(&mut self, key: &str) -> Option<Value> {
118        self.fields.shift_remove(key)
119    }
120
121    pub fn get(&self, key: &str) -> Option<&Value> {
122        self.fields.get(key)
123    }
124
125    pub fn contains(&self, key: &str) -> bool {
126        self.fields.contains_key(key)
127    }
128
129    /// Copy every field of `other` onto this alternate, in `other`'s
130    /// order: the JavaScript spread `{ ...this, ...other }`.
131    pub fn assign_from(&mut self, other: &AltSpec) -> &mut Self {
132        for (key, value) in &other.fields {
133            self.fields.insert(key.clone(), value.clone());
134        }
135        self
136    }
137
138    fn str_field(&self, key: &str) -> Option<&str> {
139        self.fields.get(key).and_then(Value::as_str)
140    }
141
142    /// The token sequence this alternate matches.
143    pub fn s(&self) -> Option<&str> {
144        self.str_field("s")
145    }
146
147    /// The rule this alternate pushes.
148    pub fn p(&self) -> Option<&str> {
149        self.str_field("p")
150    }
151
152    /// The rule this alternate replaces itself with.
153    pub fn r(&self) -> Option<&str> {
154        self.str_field("r")
155    }
156
157    /// The group tag.
158    pub fn g(&self) -> Option<&str> {
159        self.str_field("g")
160    }
161
162    /// How many matched tokens are pushed back.
163    pub fn b(&self) -> Option<u64> {
164        self.fields.get("b").and_then(Value::as_u64)
165    }
166
167    /// The action refs, as a list: a scalar `a` is one, an array is each.
168    pub fn actions(&self) -> Vec<String> {
169        match self.fields.get("a") {
170            Some(Value::String(a)) => vec![a.clone()],
171            Some(Value::Array(list)) => list
172                .iter()
173                .filter_map(|v| v.as_str().map(str::to_string))
174                .collect(),
175            _ => Vec::new(),
176        }
177    }
178
179    /// Assign the action refs: none removes `a`, one is a scalar on the
180    /// wire, several are an array.
181    pub fn set_actions(&mut self, actions: &[&str]) {
182        match actions {
183            [] => {
184                self.remove("a");
185            }
186            [one] => {
187                self.set("a", *one);
188            }
189            many => {
190                self.set("a", Value::Array(many.iter().map(|s| json!(s)).collect()));
191            }
192        }
193    }
194
195    /// Append an action ref, producing the engine's array-`a` form so the
196    /// alt's own action runs first.
197    pub fn append_action(&mut self, added: &str) {
198        let next = match self.fields.get("a") {
199            None | Some(Value::Null) => json!(added),
200            Some(Value::Array(list)) => {
201                let mut out = list.clone();
202                out.push(json!(added));
203                Value::Array(out)
204            }
205            Some(existing) => Value::Array(vec![existing.clone(), json!(added)]),
206        };
207        self.set("a", next);
208    }
209
210    /// The builtin config bag.
211    pub fn k(&self) -> Option<&Map<String, Value>> {
212        self.fields.get("k").and_then(Value::as_object)
213    }
214
215    pub fn k_mut(&mut self) -> Option<&mut Map<String, Value>> {
216        self.fields.get_mut("k").and_then(Value::as_object_mut)
217    }
218
219    /// The alternate as the engine reads it, marks stripped.
220    pub fn to_value(&self) -> Value {
221        Value::Object(self.fields.clone())
222    }
223}
224
225/// One emitted rule: its open alternates and, when it captures or
226/// replaces, its close alternates.
227#[derive(Debug, Clone, Default, PartialEq)]
228pub struct RuleSpec {
229    pub open: Vec<AltSpec>,
230    pub close: Option<Vec<AltSpec>>,
231}
232
233impl RuleSpec {
234    pub fn to_value(&self) -> Value {
235        let mut m = Map::new();
236        m.insert(
237            "open".into(),
238            Value::Array(self.open.iter().map(AltSpec::to_value).collect()),
239        );
240        if let Some(close) = &self.close {
241            m.insert(
242                "close".into(),
243                Value::Array(close.iter().map(AltSpec::to_value).collect()),
244            );
245        }
246        Value::Object(m)
247    }
248
249    pub(crate) fn alts_mut(&mut self, phase: &str) -> &mut Vec<AltSpec> {
250        if phase == "open" {
251            &mut self.open
252        } else {
253            self.close.get_or_insert_with(Vec::new)
254        }
255    }
256
257    pub(crate) fn alts(&self, phase: &str) -> &[AltSpec] {
258        if phase == "open" {
259            &self.open
260        } else {
261            self.close.as_deref().unwrap_or(&[])
262        }
263    }
264}
265
266/// The emitted grammar.
267///
268/// `options` is the engine's options block as data (`fixed.token`,
269/// `match.token`, `rule.start`, `lex.empty`, `tokenSet`); a front-end may
270/// add its own lexer settings to it. `rule` maps each rule name to its
271/// spec, or to `None` for a removal. `refs` holds the closure descriptors
272/// of a closure-mode emit and any attached user actions; it is empty for
273/// a `builtins: true` emit with no actions attached, which is what makes
274/// the spec pure data.
275#[derive(Debug, Clone, Default)]
276pub struct GrammarSpec {
277    pub refs: IndexMap<String, RefAction>,
278    pub options: Map<String, Value>,
279    pub rule: IndexMap<String, Option<RuleSpec>>,
280    /// Engine-ignored tool metadata: `{ "provenance": { generated: origin } }`.
281    pub meta: Option<Value>,
282    /// `<all> = <remove>`: wipe the instance before applying the rest.
283    pub clear: bool,
284}
285
286impl GrammarSpec {
287    /// The `rule` block as data, marks stripped.
288    fn rules_value(&self) -> Value {
289        let mut m = Map::new();
290        for (name, rule) in &self.rule {
291            m.insert(
292                name.clone(),
293                match rule {
294                    Some(r) => r.to_value(),
295                    None => Value::Null,
296                },
297            );
298        }
299        Value::Object(m)
300    }
301
302    /// The document the engine loads: `options`, `rule`, `meta` and
303    /// `clear`. Closure refs are names in the alternates and nothing more;
304    /// [`bind`](Self::bind) registers what they stand for.
305    pub fn to_value(&self) -> Value {
306        let mut m = Map::new();
307        m.insert("options".into(), Value::Object(self.options.clone()));
308        m.insert("rule".into(), self.rules_value());
309        if let Some(meta) = &self.meta {
310            m.insert("meta".into(), meta.clone());
311        }
312        if self.clear {
313            m.insert("clear".into(), json!(true));
314        }
315        Value::Object(m)
316    }
317
318    /// The document as the engine's own type.
319    pub fn to_engine(&self) -> Result<tabnas::GrammarSpec, GrammarError> {
320        tabnas::GrammarSpec::from_value(self.to_value())
321    }
322
323    /// Whether the spec still names functions: a closure-mode emit, or
324    /// user actions attached by [`attach_actions`].
325    pub fn has_closures(&self) -> bool {
326        !self.refs.is_empty()
327    }
328
329    /// Register every `@`-ref this spec names as an engine callback, so
330    /// the document loads. Call before `grammar()`; [`install`](Self::install)
331    /// does both.
332    pub fn bind(&self, parser: &mut Tabnas) {
333        for (name, action) in &self.refs {
334            bind_ref(parser, name, action);
335        }
336    }
337
338    /// Bind the refs and install the grammar on a parser.
339    pub fn install(&self, parser: &mut Tabnas) -> Result<(), GrammarError> {
340        self.bind(parser);
341        let engine = self.to_engine()?;
342        parser.grammar(&engine)?;
343        Ok(())
344    }
345}
346
347fn ast_node(rule: &str, kind: NodeKind) -> tabnas::Value {
348    let mut node = IndexMap::new();
349    if kind == NodeKind::User {
350        node.insert("rule".to_string(), tabnas::Value::String(rule.to_string()));
351    }
352    node.insert("src".to_string(), tabnas::Value::String(String::new()));
353    node.insert("kids".to_string(), tabnas::Value::array(Vec::new()));
354    tabnas::Value::object(node)
355}
356
357fn append_src(node: &mut IndexMap<String, tabnas::Value>, source: &str) {
358    if let Some(tabnas::Value::String(current)) = node.get_mut("src") {
359        current.push_str(source);
360    }
361}
362
363fn append_kid(node: &mut IndexMap<String, tabnas::Value>, child: tabnas::Value) {
364    if let Some(kids) = node.get_mut("kids").and_then(tabnas::Value::as_array_mut) {
365        kids.push(child);
366    }
367}
368
369/// Merge a returned child node into a rule's own: tagged children (user
370/// rules) are pushed verbatim into `kids`; untagged ones flatten, their
371/// `src` appending and their `kids` extending.
372fn capture_child(node: &mut IndexMap<String, tabnas::Value>, child: tabnas::Value) {
373    if let tabnas::Value::Object(child_map) = &child {
374        if let Some(tabnas::Value::String(source)) = child_map.get("src") {
375            append_src(node, source);
376            if child_map
377                .get("rule")
378                .is_some_and(|v| !matches!(v, tabnas::Value::String(r) if r.is_empty()))
379            {
380                append_kid(node, child);
381            } else if let Some(tabnas::Value::Array(children)) = child_map.get("kids") {
382                for nested in children.iter() {
383                    append_kid(node, nested.clone());
384                }
385            }
386            return;
387        }
388    }
389    // Legacy shape: wrap as a leaf kid.
390    append_kid(node, child);
391}
392
393fn phase_of(rule: &Rule) -> u8 {
394    match rule.k.get("pd_phase") {
395        Some(tabnas::Value::Number(n)) => *n as u8,
396        _ => 0,
397    }
398}
399
400/// Register one closure-mode ref on the parser. Each closure is the twin
401/// of the engine builtin it stands in for, so closure mode and builtins
402/// mode produce the same tree.
403fn bind_ref(parser: &mut Tabnas, name: &str, action: &RefAction) {
404    match action.clone() {
405        RefAction::Node {
406            init,
407            rule,
408            kind,
409            nterms,
410        } => {
411            parser.action(name, move |r: &mut Rule| {
412                if init {
413                    r.node = Rc::new(RefCell::new(ast_node(&rule, kind)));
414                }
415                let sources: Vec<String> =
416                    r.o.iter().take(nterms).map(|t| t.src.to_string()).collect();
417                if let Some(node) = r.node.borrow_mut().as_object_mut() {
418                    for src in &sources {
419                        append_src(node, src);
420                    }
421                }
422            });
423        }
424        RefAction::Capture { rule, kind } => {
425            parser.action(name, move |r: &mut Rule| {
426                if r.node.borrow().is_undefined() {
427                    r.node = Rc::new(RefCell::new(ast_node(&rule, kind)));
428                }
429                if r.child_node.is_undefined() {
430                    return;
431                }
432                let child = r.child_node.clone();
433                if let Some(node) = r.node.borrow_mut().as_object_mut() {
434                    capture_child(node, child);
435                }
436            });
437        }
438        RefAction::Bubble => {
439            parser.action(name, |r: &mut Rule| {
440                if !r.child_node.is_undefined() {
441                    r.node = Rc::new(RefCell::new(r.child_node.clone()));
442                }
443            });
444        }
445        RefAction::Fold { c_n } => {
446            parser.action(name, move |r: &mut Rule| {
447                if let Some(parent_node) = r.parent_node.clone() {
448                    let same_node = Rc::ptr_eq(&parent_node, &r.node);
449                    let own = r.node.borrow().clone();
450                    let closes: Vec<String> =
451                        r.c.iter().take(c_n).map(|t| t.src.to_string()).collect();
452                    if let Some(parent) = parent_node.borrow_mut().as_object_mut() {
453                        if parent.contains_key("src") {
454                            if !same_node {
455                                if let tabnas::Value::Object(own_map) = &own {
456                                    if own_map.contains_key("src") {
457                                        capture_child(parent, own);
458                                    }
459                                }
460                            }
461                            for src in &closes {
462                                append_src(parent, src);
463                            }
464                        }
465                    }
466                }
467                r.node = Rc::new(RefCell::new(tabnas::Value::Undefined));
468            });
469        }
470        RefAction::ProbeInit => {
471            parser.action_with_context(name, |r: &mut Rule, ctx: &mut Context| {
472                r.k_mut()
473                    .insert("pd_phase".into(), tabnas::Value::Number(0.0));
474                let mark = tabnas::Value::Number(ctx.mark() as f64);
475                r.k_mut().insert("pd_mark".into(), mark);
476                // The passes until the decision are the probe's, never the
477                // document's: open it, so the engine flags them
478                // (`RuleDone::probe`) as it does for its own `@probeInit$`.
479                ctx.probe_open(r);
480                Ok(())
481            });
482        }
483        RefAction::ProbeDecide { disambiguator } => {
484            parser.action_with_context(name, move |r: &mut Rule, ctx: &mut Context| {
485                // The first token the probe did not consume. The probe
486                // never fails, so this always reflects a real position.
487                let peek = ctx.t0().map(|t| t.name.to_string());
488                let mark = match r.k.get("pd_mark") {
489                    Some(tabnas::Value::Number(m)) => *m as usize,
490                    _ => ctx.mark(),
491                };
492                ctx.rewind(mark)?;
493                let matched = peek.as_deref() == Some(disambiguator.as_str());
494                r.k_mut().insert(
495                    "pd_phase".into(),
496                    tabnas::Value::Number(if matched { 1.0 } else { 2.0 }),
497                );
498                // The probe is decided and rewound: close it, as the
499                // engine's `@probeDecide$` does. This pass is still the
500                // probe's; the next is the document's again.
501                ctx.probe_close();
502                Ok(())
503            });
504        }
505        RefAction::ProbePhase(phase) => {
506            parser.alt_condition(name, move |r: &mut Rule, _ctx: &mut Context| {
507                phase_of(r) == phase
508            });
509        }
510        RefAction::User(f) => {
511            parser.action_with_context(name, move |r: &mut Rule, ctx: &mut Context| f(r, ctx));
512        }
513        RefAction::Phase(fns) => {
514            parser.state_action_ref(name, move |r: &mut Rule, ctx: &mut Context| {
515                for f in &fns {
516                    f(r, ctx)?;
517                }
518                Ok(())
519            });
520        }
521    }
522}
523
524/// A grammar that cannot be reduced to pure data.
525#[derive(Debug, Clone, PartialEq, Eq)]
526pub struct CompileError {
527    pub message: String,
528    pub rules: Vec<String>,
529}
530
531impl fmt::Display for CompileError {
532    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
533        f.write_str(&self.message)
534    }
535}
536
537impl std::error::Error for CompileError {}
538
539/// Hook fields whose string value is a `@`-ref into the spec's `ref`
540/// map: the AST-building actions recognition mode drops.
541const REF_FIELDS: [&str; 3] = ["a", "bo", "bc"];
542
543/// Output-building `$`-builtins, dropped when a spec is reduced to pure
544/// recognition. The value builders belong here for the same reason the
545/// tree builders do: a recognition-only grammar must recognise and build
546/// nothing.
547const TREE_BUILTINS: [&str; 11] = [
548    "@node$",
549    "@capture$",
550    "@bubble$",
551    "@fold$",
552    "@object$",
553    "@array$",
554    "@reset$",
555    "@key$",
556    "@setval$",
557    "@push$",
558    "@value$",
559];
560const TREE_CONFIG_KEYS: [&str; 9] = [
561    "node$", "capture$", "fold$", "object$", "array$", "key$", "setval$", "push$", "value$",
562];
563
564/// Like a plain deep copy, but dropping the AST-building hooks: `a`
565/// fields that point at a dropped action, and the now-orphaned tree
566/// config in `k`. Control builtins and structural fields are preserved.
567fn clone_recognition(v: &Value, is_dropped: &dyn Fn(&str) -> bool) -> Value {
568    match v {
569        Value::Array(items) => Value::Array(
570            items
571                .iter()
572                .map(|x| clone_recognition(x, is_dropped))
573                .collect(),
574        ),
575        Value::Object(map) => {
576            let mut o = Map::new();
577            for (k, x) in map {
578                if REF_FIELDS.contains(&k.as_str()) {
579                    match x {
580                        Value::String(s) => {
581                            if is_dropped(s) {
582                                continue;
583                            }
584                        }
585                        Value::Array(list) => {
586                            // Array-`a` composition: filter the dropped
587                            // actions out of the list rather than keeping
588                            // the whole list because it is not a string.
589                            let kept: Vec<Value> = list
590                                .iter()
591                                .filter(|e| !matches!(e, Value::String(s) if is_dropped(s)))
592                                .cloned()
593                                .collect();
594                            if kept.is_empty() {
595                                continue;
596                            }
597                            o.insert(
598                                k.clone(),
599                                if kept.len() == 1 {
600                                    kept[0].clone()
601                                } else {
602                                    Value::Array(kept)
603                                },
604                            );
605                            continue;
606                        }
607                        _ => {}
608                    }
609                }
610                if k == "k" {
611                    if let Value::Object(_) = x {
612                        let kc = clone_recognition(x, is_dropped);
613                        let Value::Object(mut kc) = kc else {
614                            unreachable!()
615                        };
616                        for tk in TREE_CONFIG_KEYS {
617                            kc.remove(tk);
618                        }
619                        if kc.is_empty() {
620                            continue;
621                        }
622                        o.insert(k.clone(), Value::Object(kc));
623                        continue;
624                    }
625                }
626                o.insert(k.clone(), clone_recognition(x, is_dropped));
627            }
628            Value::Object(o)
629        }
630        _ => v.clone(),
631    }
632}
633
634/// Rules that reference the ref map from a field OTHER than the droppable
635/// AST hooks, which means control functions (probe guards and dispatch
636/// actions). Their presence means the grammar cannot be represented
637/// purely structurally.
638fn control_ref_rules(rules: &Value, is_ref: &dyn Fn(&str) -> bool) -> Vec<String> {
639    fn scan(o: &Value, rule: &str, is_ref: &dyn Fn(&str) -> bool, offenders: &mut Vec<String>) {
640        match o {
641            Value::Array(items) => {
642                for x in items {
643                    scan(x, rule, is_ref, offenders);
644                }
645            }
646            Value::Object(map) => {
647                for (k, x) in map {
648                    match x {
649                        Value::String(s) if !REF_FIELDS.contains(&k.as_str()) && is_ref(s) => {
650                            if !offenders.iter().any(|r| r == rule) {
651                                offenders.push(rule.to_string());
652                            }
653                        }
654                        _ => scan(x, rule, is_ref, offenders),
655                    }
656                }
657            }
658            _ => {}
659        }
660    }
661    let mut offenders: Vec<String> = Vec::new();
662    if let Value::Object(rules) = rules {
663        for (name, spec) in rules {
664            scan(spec, name, is_ref, &mut offenders);
665        }
666    }
667    offenders.sort_by_key(|s| s.encode_utf16().collect::<Vec<u16>>());
668    offenders
669}
670
671fn carry_meta(from: &GrammarSpec, to: &mut Map<String, Value>) {
672    if let Some(meta) = &from.meta {
673        to.insert("meta".into(), meta.clone());
674    }
675}
676
677/// Strip a converted spec down to a function-free recognition grammar,
678/// dropping the tree and value builders. Fails for grammars whose
679/// control logic is still closures (a probe dispatcher converted without
680/// `builtins`).
681pub fn to_recognition_spec(spec: &GrammarSpec) -> Result<Value, CompileError> {
682    let is_ref = |s: &str| spec.refs.contains_key(s);
683    let rules = spec.rules_value();
684    let offenders = control_ref_rules(&rules, &is_ref);
685    if !offenders.is_empty() {
686        return Err(CompileError {
687            message: format!(
688                "{}: grammar needs control functions (probe / unbounded lookahead) and \
689                 cannot be emitted as a pure recognition grammar; recompile with \
690                 `builtins: true`. Offending rule(s): {}",
691                diag_name(),
692                offenders.join(", ")
693            ),
694            rules: offenders,
695        });
696    }
697    let is_dropped = |s: &str| is_ref(s) || TREE_BUILTINS.contains(&s);
698    let mut doc = Map::new();
699    doc.insert("options".into(), Value::Object(spec.options.clone()));
700    doc.insert("rule".into(), rules);
701    let out = clone_recognition(&Value::Object(doc), &is_dropped);
702    let Value::Object(mut out) = out else {
703        unreachable!()
704    };
705    // Declare the builtin config-schema version so the engine can refuse
706    // a grammar that needs a newer schema than it implements.
707    out.insert("v".into(), json!(tabnas::grammar::BUILTIN_SCHEMA_VERSION));
708    carry_meta(spec, &mut out);
709    Ok(Value::Object(out))
710}
711
712/// Reduce a spec to a pure-data, function-free grammar that KEEPS the
713/// AST-building `$`-builtins. Requires a `builtins: true` conversion with
714/// no user actions attached: any remaining ref is refused.
715pub fn to_pure_spec(spec: &GrammarSpec) -> Result<Value, CompileError> {
716    if !spec.refs.is_empty() {
717        let closures: Vec<&str> = spec.refs.keys().map(String::as_str).take(3).collect();
718        return Err(CompileError {
719            message: format!(
720                "{}: spec still contains closures; convert with `builtins: true` for \
721                 pure-data output. Stray ref(s): {}",
722                diag_name(),
723                closures.join(", ")
724            ),
725            rules: Vec::new(),
726        });
727    }
728    let mut out = Map::new();
729    out.insert("options".into(), Value::Object(spec.options.clone()));
730    out.insert("rule".into(), spec.rules_value());
731    out.insert("v".into(), json!(tabnas::grammar::BUILTIN_SCHEMA_VERSION));
732    carry_meta(spec, &mut out);
733    Ok(Value::Object(out))
734}
735
736/// How [`to_jsonic`] writes its text.
737#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
738pub struct JsonicOptions {
739    /// Valid JSON (double quotes, comma-separated) rather than relaxed
740    /// jsonic (bare identifier keys, single quotes, newline-separated).
741    pub strict: bool,
742    /// Spaces per level (default 2).
743    pub indent: Option<usize>,
744}
745
746fn is_ident(k: &str) -> bool {
747    let mut chars = k.chars();
748    match chars.next() {
749        Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}
750        _ => return false,
751    }
752    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
753}
754
755/// The largest magnitude an integer can have and still be exactly a
756/// JavaScript number: 2^53 - 1.
757const JS_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
758
759/// JavaScript's `String(n)` for an `f64`, i.e. ECMAScript
760/// `Number::toString` with radix 10.
761///
762/// The canonical serialiser is `String(v)` (`ts/src/spec.ts`), so the
763/// emitted text only equals TypeScript's when this reproduces it. A
764/// narrowing `as i64` does not: it saturates every magnitude above
765/// `i64::MAX` to `9223372036854775807`, and it cannot express the
766/// switch to exponent form that JavaScript makes at `1e21`.
767///
768/// The shape is the spec's: take the shortest decimal digit string `s`
769/// (`k` digits) that reads back as the same `f64`, with `n` the
770/// position of the decimal point, then print plain decimal while `n`
771/// stays inside `(-6, 21]` and exponent form outside it.
772fn js_number(f: f64) -> String {
773    if f.is_nan() {
774        return "NaN".to_string();
775    }
776    if f.is_infinite() {
777        return if f > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
778    }
779    // Covers -0.0, which JavaScript prints as "0".
780    if f == 0.0 {
781        return "0".to_string();
782    }
783    let magnitude = f.abs();
784    // The spec's `s` and `n`: the fewest digits that read back as this
785    // same `f64`, correctly rounded. Rust's fixed-precision `{:e}` is
786    // correctly rounded and breaks ties to even, which is the rule the
787    // spec states for the case two digit strings are equally close, so
788    // the first width that round-trips gives the spec's digits. Plain
789    // `{:e}` (shortest) is NOT a substitute: it breaks those ties the
790    // other way, and prints 137839762462415.63 where JavaScript prints
791    // 137839762462415.62. Seventeen digits always suffice for an `f64`.
792    let (digits, exponent) = (0..17u32)
793        .map(|p| format!("{magnitude:.*e}", p as usize))
794        .find(|text| text.parse::<f64>() == Ok(magnitude))
795        .map(|text| {
796            let (mantissa, exponent) = text.split_once('e').expect("{:e} emits an exponent");
797            (
798                mantissa.chars().filter(|c| *c != '.').collect::<String>(),
799                exponent
800                    .parse::<i32>()
801                    .expect("{:e} emits an integer exponent"),
802            )
803        })
804        .expect("17 significant digits round-trip every finite f64");
805    let k = digits.len() as i32;
806    let n = exponent + 1;
807
808    let body = if k <= n && n <= 21 {
809        // 12 -> "12", 1e19 -> "10000000000000000000"
810        format!("{}{}", digits, "0".repeat((n - k) as usize))
811    } else if 0 < n && n <= 21 {
812        // 1.5 -> "1.5"
813        format!("{}.{}", &digits[..n as usize], &digits[n as usize..])
814    } else if -6 < n && n <= 0 {
815        // 1e-6 -> "0.000001"
816        format!("0.{}{}", "0".repeat(-n as usize), digits)
817    } else {
818        // 1e21 -> "1e+21", 1e-7 -> "1e-7"
819        let e = n - 1;
820        let head = if k == 1 {
821            digits.clone()
822        } else {
823            format!("{}.{}", &digits[..1], &digits[1..])
824        };
825        format!("{}e{}{}", head, if e < 0 { '-' } else { '+' }, e.abs())
826    };
827    if f < 0.0 {
828        format!("-{body}")
829    } else {
830        body
831    }
832}
833
834/// Serialise a (function-free) value as jsonic text. Regular expressions
835/// are already `@/pattern/flags` strings in the data.
836pub fn to_jsonic(value: &Value, opts: JsonicOptions) -> String {
837    let strict = opts.strict;
838    let ind = opts.indent.unwrap_or(2);
839    let sep = if strict { ",\n" } else { "\n" };
840    let pad = |n: usize| " ".repeat(ind * n);
841
842    // Every C0 control character has to be escaped, not just newline:
843    // strict mode promises valid JSON.
844    fn quote(s: &str, ch: char) -> String {
845        let mut out = String::with_capacity(s.len() + 2);
846        out.push(ch);
847        for c in s.chars() {
848            match c {
849                '\\' => out.push_str("\\\\"),
850                c if c == ch => {
851                    out.push('\\');
852                    out.push(ch);
853                }
854                '\u{8}' => out.push_str("\\b"),
855                '\t' => out.push_str("\\t"),
856                '\n' => out.push_str("\\n"),
857                '\u{c}' => out.push_str("\\f"),
858                '\r' => out.push_str("\\r"),
859                c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
860                c => out.push(c),
861            }
862        }
863        out.push(ch);
864        out
865    }
866    let str_ = |s: &str| {
867        if strict {
868            quote(s, '"')
869        } else {
870            quote(s, '\'')
871        }
872    };
873    let key = |k: &str| {
874        if !strict && is_ident(k) {
875            k.to_string()
876        } else {
877            quote(k, '"')
878        }
879    };
880
881    fn number(n: &serde_json::Number) -> String {
882        // An integer small enough to be a JavaScript number exactly
883        // prints the same either way, so keep the exact form. Beyond
884        // 2^53 the canonical compiler never HAD the exact value — its
885        // number is an `f64` — so round the way it did before printing.
886        if let Some(i) = n.as_i64() {
887            if i.unsigned_abs() <= JS_SAFE_INTEGER {
888                return i.to_string();
889            }
890            return js_number(i as f64);
891        }
892        if let Some(u) = n.as_u64() {
893            if u <= JS_SAFE_INTEGER {
894                return u.to_string();
895            }
896            return js_number(u as f64);
897        }
898        js_number(n.as_f64().unwrap_or(0.0))
899    }
900
901    fn ser(
902        v: &Value,
903        depth: usize,
904        sep: &str,
905        pad: &dyn Fn(usize) -> String,
906        str_: &dyn Fn(&str) -> String,
907        key: &dyn Fn(&str) -> String,
908    ) -> String {
909        match v {
910            Value::Null => "null".into(),
911            Value::Bool(b) => b.to_string(),
912            Value::Number(n) => number(n),
913            Value::String(s) => str_(s),
914            Value::Array(items) => {
915                if items.is_empty() {
916                    return "[]".into();
917                }
918                let lines: Vec<String> = items
919                    .iter()
920                    .map(|x| {
921                        format!(
922                            "{}{}",
923                            pad(depth + 1),
924                            ser(x, depth + 1, sep, pad, str_, key)
925                        )
926                    })
927                    .collect();
928                format!("[\n{}\n{}]", lines.join(sep), pad(depth))
929            }
930            Value::Object(map) => {
931                if map.is_empty() {
932                    return "{}".into();
933                }
934                let lines: Vec<String> = map
935                    .iter()
936                    .map(|(k, x)| {
937                        format!(
938                            "{}{}: {}",
939                            pad(depth + 1),
940                            key(k),
941                            ser(x, depth + 1, sep, pad, str_, key)
942                        )
943                    })
944                    .collect();
945                format!("{{\n{}\n{}}}", lines.join(sep), pad(depth))
946            }
947        }
948    }
949
950    ser(value, 0, sep, &pad, &str_, &key)
951}
952
953/// Options for [`compile_spec`].
954#[derive(Debug, Clone, Copy, PartialEq, Eq)]
955pub struct CompileOptions {
956    /// Emit a pure RECOGNITION grammar (tree building dropped). `false`
957    /// emits the full AST grammar with the tree builtins retained, still
958    /// pure data.
959    pub recognition: bool,
960    pub strict: bool,
961    pub indent: Option<usize>,
962}
963
964impl Default for CompileOptions {
965    fn default() -> Self {
966        Self {
967            recognition: true,
968            strict: false,
969            indent: None,
970        }
971    }
972}
973
974/// Serialise an already-converted spec as pure-data tabnas grammar text.
975/// A front-end converts with `builtins: true` first and passes the result
976/// here.
977pub fn compile_spec(spec: &GrammarSpec, opts: CompileOptions) -> Result<String, CompileError> {
978    let out = if opts.recognition {
979        to_recognition_spec(spec)?
980    } else {
981        to_pure_spec(spec)?
982    };
983    Ok(to_jsonic(
984        &out,
985        JsonicOptions {
986            strict: opts.strict,
987            indent: opts.indent,
988        },
989    ))
990}
991
992/// A malformed or unresolvable user action ref.
993#[derive(Debug, Clone, PartialEq, Eq)]
994pub struct ActionError {
995    pub message: String,
996}
997
998impl fmt::Display for ActionError {
999    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1000        f.write_str(&self.message)
1001    }
1002}
1003
1004impl std::error::Error for ActionError {}
1005
1006enum Target {
1007    Phase(String),
1008    Alts { phase: String, indices: Vec<usize> },
1009}
1010
1011const PHASES: [&str; 4] = ["bo", "ao", "bc", "ac"];
1012
1013/// Resolve `@<rule>:<sel>` against the spec: the matched alts (for o:/c:
1014/// selectors) or the rule-phase (for bo/ao/bc/ac).
1015fn resolve_target(spec: &GrammarSpec, key: &str) -> Result<(String, Target), ActionError> {
1016    // `$` is reserved for engine builtins; a user action ref may not
1017    // contain it.
1018    if key.contains('$') {
1019        return Err(ActionError {
1020            message: format!(
1021                "{}: '$' is reserved for engine builtins; user action ref '{}' may not contain '$'",
1022                diag_name(),
1023                key
1024            ),
1025        });
1026    }
1027    let malformed = || ActionError {
1028        message: format!(
1029            "{}: malformed action ref '{}' (expected @rule:phase or @rule:o|c:mark)",
1030            diag_name(),
1031            key
1032        ),
1033    };
1034    let body = key.strip_prefix('@').ok_or_else(malformed)?;
1035    let (rule, sel) = body.split_once(':').ok_or_else(malformed)?;
1036    if rule.is_empty() || sel.is_empty() {
1037        return Err(malformed());
1038    }
1039    let Some(Some(rs)) = spec.rule.get(rule) else {
1040        return Err(ActionError {
1041            message: format!(
1042                "{}: action ref '{}' targets unknown rule '{}'",
1043                diag_name(),
1044                key,
1045                rule
1046            ),
1047        });
1048    };
1049    if PHASES.contains(&sel) {
1050        return Ok((rule.to_string(), Target::Phase(sel.to_string())));
1051    }
1052    let (oc, mark) = match sel.split_once(':') {
1053        Some((oc @ ("o" | "c"), mark)) if !mark.is_empty() => (oc, mark),
1054        _ => {
1055            return Err(ActionError {
1056                message: format!("{}: malformed action ref '{}'", diag_name(), key),
1057            })
1058        }
1059    };
1060    let phase = if oc == "o" { "open" } else { "close" };
1061    let indices: Vec<usize> = rs
1062        .alts(phase)
1063        .iter()
1064        .enumerate()
1065        .filter(|(_, a)| a.m.as_deref() == Some(mark))
1066        .map(|(i, _)| i)
1067        .collect();
1068    if indices.is_empty() {
1069        return Err(ActionError {
1070            message: format!(
1071                "{}: action ref '{}' matches no {} alt with mark '{}' in rule '{}'",
1072                diag_name(),
1073                key,
1074                phase,
1075                mark,
1076                rule
1077            ),
1078        });
1079    }
1080    Ok((
1081        rule.to_string(),
1082        Target::Alts {
1083            phase: phase.to_string(),
1084            indices,
1085        },
1086    ))
1087}
1088
1089/// Attach user semantic actions to a spec, in place. Keys are
1090/// `@<rule>:<phase>` (bo/ao/bc/ac) or `@<rule>:o|c:<mark>`; the
1091/// functions run AFTER the compiler's own action, in attachment order.
1092/// Alt actions are injected as the engine's array-`a` form. Fails for a
1093/// ref matching no rule, hook or marked alt.
1094pub fn attach_actions(spec: &mut GrammarSpec, actions: ActionsMap) -> Result<(), ActionError> {
1095    // Start past whatever the ref map already holds, so a second call
1096    // cannot reuse a name the first handed out.
1097    let mut counter = 0;
1098    while spec.refs.contains_key(&format!("@bnf_user{counter}")) {
1099        counter += 1;
1100    }
1101
1102    for (key, fns) in actions {
1103        let (rule, target) = resolve_target(spec, &key)?;
1104        match target {
1105            Target::Phase(phase) => {
1106                // Rule-phase hook: reuse the engine's `@<rule>-<phase>`
1107                // auto-install.
1108                let fkey = format!("@{rule}-{phase}");
1109                match spec.refs.get_mut(&fkey) {
1110                    Some(RefAction::Phase(existing)) => existing.extend(fns),
1111                    _ => {
1112                        spec.refs.insert(fkey, RefAction::Phase(fns));
1113                    }
1114                }
1115            }
1116            Target::Alts { phase, indices } => {
1117                let fns_arc: Vec<ActionFn> = fns;
1118                let seq: ActionFn = if fns_arc.len() == 1 {
1119                    fns_arc[0].clone()
1120                } else {
1121                    Arc::new(move |r: &mut Rule, ctx: &mut Context| {
1122                        for f in &fns_arc {
1123                            f(r, ctx)?;
1124                        }
1125                        Ok(())
1126                    })
1127                };
1128                for i in indices {
1129                    let user_ref = format!("@bnf_user{counter}");
1130                    counter += 1;
1131                    spec.refs
1132                        .insert(user_ref.clone(), RefAction::User(seq.clone()));
1133                    let rs = spec
1134                        .rule
1135                        .get_mut(&rule)
1136                        .and_then(Option::as_mut)
1137                        .expect("resolved above");
1138                    rs.alts_mut(&phase)[i].append_action(&user_ref);
1139                }
1140            }
1141        }
1142    }
1143    Ok(())
1144}
1145
1146/// Declare user-action SLOTS on a (pure-data) spec without supplying
1147/// functions: each `@<rule>:o|c:<mark>` ref name is injected into the
1148/// matched alt's array-`a`, to be resolved at load time from a
1149/// user-supplied ref map. Fails on unknown targets and on rule-phase
1150/// refs.
1151pub fn attach_action_slots(spec: &mut GrammarSpec, ref_names: &[&str]) -> Result<(), ActionError> {
1152    for name in ref_names {
1153        let (rule, target) = resolve_target(spec, name)?;
1154        match target {
1155            Target::Phase(_) => {
1156                return Err(ActionError {
1157                    message: format!(
1158                    "{}: slot '{}' is a rule-phase ref; slots are for @rule:o|c:mark alt actions",
1159                    diag_name(),
1160                    name
1161                ),
1162                })
1163            }
1164            Target::Alts { phase, indices } => {
1165                let rs = spec
1166                    .rule
1167                    .get_mut(&rule)
1168                    .and_then(Option::as_mut)
1169                    .expect("resolved above");
1170                for i in indices {
1171                    rs.alts_mut(&phase)[i].append_action(name);
1172                }
1173            }
1174        }
1175    }
1176    Ok(())
1177}
1178
1179/// Human-readable listing of the marks the compiler assigned, one line
1180/// per marked alt: `<rule>  o|c:<mark>  s:<tokens> | p:<rule> | (empty)`.
1181pub fn mark_listing(spec: &GrammarSpec) -> String {
1182    let mut lines: Vec<String> = Vec::new();
1183    for (rule, entry) in &spec.rule {
1184        // A removal, not a rule: it has no alternates to mark.
1185        let Some(entry) = entry else { continue };
1186        for (phase, sym) in [("open", "o"), ("close", "c")] {
1187            for a in entry.alts(phase) {
1188                let Some(m) = &a.m else { continue };
1189                let what = match (a.s(), a.p()) {
1190                    (Some(s), _) if !s.is_empty() => format!("s:{s}"),
1191                    (_, Some(p)) if !p.is_empty() => format!("p:{p}"),
1192                    _ => "(empty)".to_string(),
1193                };
1194                lines.push(format!("{rule}  {sym}:{m}  {what}"));
1195            }
1196        }
1197    }
1198    lines.join("\n")
1199}