Skip to main content

tabnas_debug/
model.rs

1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3//! The structured counterpart to [`crate::describe()`]: an instance and its
4//! grammar as typed, JSON-serialisable data, so tools and tests can
5//! consume the grammar programmatically.
6//!
7//! Mirrors the canonical TypeScript `tabnas.debug.model()` and its
8//! exported types in `ts/src/debug.ts` (`DebugModel`, `DebugTokenInfo`,
9//! `DebugTokenSet`, `DebugAltInfo`, `DebugRuleInfo`, `DebugRuleEdges`,
10//! `DebugLexMatcher`, `DebugConfigInfo`, `DebugPluginInfo`). The serde
11//! field names match the TS field names and the Go JSON tags, so a model
12//! decoded from any runtime is comparable with the others — the claim
13//! `test/spec/model.tsv` pins.
14
15use std::collections::BTreeMap;
16
17use indexmap::{IndexMap, IndexSet};
18use serde::Serialize;
19use tabnas::{AltSpec, RuleSpec, Tabnas, Tin, TIN_MAX};
20
21use crate::abnf::abnf;
22
23/// One row of the token table: the token's tin (token identification
24/// number), its name, and — for fixed (literal) tokens — the source text
25/// it matches.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
27pub struct DebugTokenInfo {
28    /// Token identification number.
29    pub tin: Tin,
30    /// Token name (e.g. `#NR`).
31    pub name: String,
32    /// Fixed source text, when a literal token.
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub fixed: Option<String>,
35}
36
37/// A named token set and its member tins.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
39pub struct DebugTokenSet {
40    /// Set name (`IGNORE`, `VAL`, `KEY`, …).
41    pub name: String,
42    /// Member tins, ascending.
43    pub tins: Vec<Tin>,
44}
45
46/// One lookahead position of an alternate's token sequence: a single
47/// token name, or the several names a multi-token position accepts.
48///
49/// Serialises untagged — a bare string or an array of strings — matching
50/// the TypeScript `(string | string[])[]` and the Go `[]any`.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
52#[serde(untagged)]
53pub enum DebugSeqItem {
54    /// A single-token position.
55    One(String),
56    /// A position accepting any of several tokens.
57    Any(Vec<String>),
58}
59
60/// The structured form of a single rule alternate — the data behind the
61/// `ALTS` text of [`crate::describe()`].
62#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
63pub struct DebugAltInfo {
64    /// Token name(s) per lookahead position.
65    pub seq: Vec<DebugSeqItem>,
66    /// `p` target rule (or `<fn>`).
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub push: Option<String>,
69    /// `r` target rule (or `<fn>`).
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub replace: Option<String>,
72    /// `b` token push-back.
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub back: Option<usize>,
75    /// `n` counter ops.
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub counters: Option<BTreeMap<String, i32>>,
78    /// `g` group tags.
79    pub groups: Vec<String>,
80    /// `a` present.
81    pub action: bool,
82    /// `c` present.
83    pub cond: bool,
84    /// `h` present.
85    pub modifier: bool,
86}
87
88/// One rule: its name and its open/close alternates as structured data.
89#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
90pub struct DebugRuleInfo {
91    /// Rule name.
92    pub name: String,
93    /// Open-phase alternates, in order.
94    pub open: Vec<DebugAltInfo>,
95    /// Close-phase alternates, in order.
96    pub close: Vec<DebugAltInfo>,
97}
98
99/// One rule's outgoing edges in the rule-reference graph: the distinct
100/// push/replace rule-name targets of its open and close alternates
101/// (function-valued targets recorded as `<fn>`).
102#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
103pub struct DebugRuleEdges {
104    /// Rule name.
105    pub name: String,
106    /// Distinct `p` targets of open alts.
107    #[serde(rename = "openPush")]
108    pub open_push: Vec<String>,
109    /// Distinct `r` targets of open alts.
110    #[serde(rename = "openReplace")]
111    pub open_replace: Vec<String>,
112    /// Distinct `p` targets of close alts.
113    #[serde(rename = "closePush")]
114    pub close_push: Vec<String>,
115    /// Distinct `r` targets of close alts.
116    #[serde(rename = "closeReplace")]
117    pub close_replace: Vec<String>,
118}
119
120/// One lexer matcher, in priority order.
121///
122/// The Rust engine enumerates only CUSTOM matchers; the built-in
123/// matchers appear as enable flags under [`DebugConfigInfo::lex`]
124/// instead — the same limit the Go port documents. `make` is the Go
125/// analogue of the TypeScript factory name and has no Rust counterpart
126/// (function values carry no name), so it is always empty.
127#[derive(Debug, Clone, PartialEq, Serialize)]
128pub struct DebugLexMatcher {
129    /// Priority (lower runs first).
130    ///
131    /// Kept as `f64`, the engine's own type: priorities are not
132    /// necessarily whole, and truncating would report `1.2` and `1.8` as
133    /// the same matcher order. The canonical TypeScript field is a plain
134    /// JavaScript number, so this matches it; the Go port's `int` is a Go
135    /// engine limit.
136    pub order: f64,
137    /// Registered matcher name.
138    pub matcher: String,
139    /// Matcher function name, when recoverable.
140    pub make: String,
141}
142
143/// The key parser settings: start rule, finish flag, safe-key, and the
144/// built-in per-lexer enable flags.
145#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
146pub struct DebugConfigInfo {
147    /// Starting rule name.
148    pub start: String,
149    /// Auto-close unclosed structures at end of source.
150    pub finish: bool,
151    /// Prevent `__proto__` keys.
152    #[serde(rename = "safeKey")]
153    pub safe_key: bool,
154    /// Built-in lexer enable flags, in the canonical order.
155    pub lex: IndexMap<String, bool>,
156}
157
158/// One applied plugin: its name, and its options when the instance holds
159/// a bag for it.
160#[derive(Debug, Clone, PartialEq, Serialize)]
161pub struct DebugPluginInfo {
162    /// Plugin name.
163    pub name: String,
164    /// Plugin options, when known.
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub options: Option<serde_json::Value>,
167}
168
169/// The full structured description of an instance: the token table, token
170/// sets, rules and alternates as data, the rule-reference graph, lexer
171/// matchers, config, plugins, and the ABNF text.
172#[derive(Debug, Clone, PartialEq, Serialize)]
173pub struct DebugModel {
174    /// Instance tag; the engine's default (`-`) when unset.
175    pub tag: String,
176    /// The token table.
177    pub tokens: Vec<DebugTokenInfo>,
178    /// Named token sets.
179    #[serde(rename = "tokenSets")]
180    pub token_sets: Vec<DebugTokenSet>,
181    /// Rules and their alternates.
182    pub rules: Vec<DebugRuleInfo>,
183    /// Per-rule push/replace edges.
184    pub graph: Vec<DebugRuleEdges>,
185    /// Lexer matchers, priority order.
186    pub lexer: Vec<DebugLexMatcher>,
187    /// Key parser settings.
188    pub config: DebugConfigInfo,
189    /// Applied plugins.
190    pub plugins: Vec<DebugPluginInfo>,
191    /// The re-compilable ABNF rendering of the live grammar.
192    pub abnf: String,
193}
194
195/// Build the structured model of `parser`.
196pub fn model(parser: &Tabnas) -> DebugModel {
197    let specs = parser.rule_specs();
198
199    DebugModel {
200        tag: parser.options.tag.clone(),
201        tokens: tokens(parser),
202        token_sets: token_sets(parser),
203        rules: specs
204            .iter()
205            .map(|spec| DebugRuleInfo {
206                name: spec.name.clone(),
207                open: spec.open.iter().map(|alt| alt_info(parser, alt)).collect(),
208                close: spec.close.iter().map(|alt| alt_info(parser, alt)).collect(),
209            })
210            .collect(),
211        graph: specs.iter().map(|spec| rule_edges(spec)).collect(),
212        lexer: lexer(parser),
213        config: config(parser),
214        plugins: plugins(parser),
215        abnf: abnf(parser),
216    }
217}
218
219/// Every token identity the instance knows, ascending by tin.
220///
221/// The TypeScript engine keeps one bidirectional token map to read this
222/// from. The Rust engine spreads the same information over the built-in
223/// range plus the fixed, match and named-identity tables, so they are
224/// merged here.
225pub(crate) fn tokens(parser: &Tabnas) -> Vec<DebugTokenInfo> {
226    let mut tins: IndexSet<Tin> = (1..TIN_MAX).collect();
227    tins.extend(parser.options.fixed.tokens.values().map(|token| token.tin));
228    tins.extend(parser.options.match_tokens.values().map(|token| token.tin));
229    tins.extend(parser.options.tokens.values().copied());
230
231    let mut tins: Vec<Tin> = tins.into_iter().collect();
232    tins.sort_unstable();
233    tins.into_iter()
234        .map(|tin| DebugTokenInfo {
235            tin,
236            name: parser.token_name(tin),
237            fixed: parser.fixed_source(tin).map(str::to_string),
238        })
239        .collect()
240}
241
242/// The named token sets, by name, each with its members ascending.
243///
244/// The Rust engine holds token sets in an unordered map, so both levels
245/// are sorted — as the Go port sorts — rather than left to iteration
246/// order.
247pub(crate) fn token_sets(parser: &Tabnas) -> Vec<DebugTokenSet> {
248    let mut names: Vec<&String> = parser.options.token_set.keys().collect();
249    names.sort();
250    names
251        .into_iter()
252        .map(|name| {
253            let mut tins = parser.options.token_set[name].clone();
254            tins.sort_unstable();
255            DebugTokenSet {
256                name: name.clone(),
257                tins,
258            }
259        })
260        .collect()
261}
262
263/// The structured form of one alternate.
264pub(crate) fn alt_info(parser: &Tabnas, alt: &AltSpec) -> DebugAltInfo {
265    let seq = alt
266        .s
267        .iter()
268        .map(|position| match position.len() {
269            // A position with no token constraint accepts anything; the
270            // canonical runtimes render it as the empty string.
271            0 => DebugSeqItem::One(String::new()),
272            1 => DebugSeqItem::One(parser.token_name(position[0])),
273            _ => DebugSeqItem::Any(position.iter().map(|tin| parser.token_name(*tin)).collect()),
274        })
275        .collect();
276
277    DebugAltInfo {
278        seq,
279        push: target_name(
280            alt.p.as_deref(),
281            alt.p_fn.is_some() || alt.p_match.is_some(),
282        ),
283        replace: target_name(
284            alt.r.as_deref(),
285            alt.r_fn.is_some() || alt.r_match.is_some(),
286        ),
287        // The TypeScript alt distinguishes "no `b`" from `b: 0`; the Rust
288        // and Go alts do not, so a zero push-back is omitted in both.
289        back: (0 != alt.b).then_some(alt.b),
290        counters: (!alt.n.is_empty()).then(|| {
291            alt.n
292                .iter()
293                .map(|(name, value)| (name.clone(), *value))
294                .collect()
295        }),
296        groups: groups(alt),
297        action: !alt.a.is_empty()
298            || !alt.action_fns.is_empty()
299            || !alt.matched_action_fns.is_empty(),
300        cond: !alt.c.is_empty()
301            || alt.c_ref.is_some()
302            || alt.c_fn.is_some()
303            || alt.c_match.is_some()
304            || alt.c_lex.is_some()
305            || alt.c_lex_match.is_some(),
306        modifier: alt.h.is_some() || alt.h_match.is_some(),
307    }
308}
309
310/// A named push/replace target, or `<fn>` for a function-valued one.
311fn target_name(name: Option<&str>, has_fn: bool) -> Option<String> {
312    match name {
313        Some(name) => Some(name.to_string()),
314        None if has_fn => Some("<fn>".to_string()),
315        None => None,
316    }
317}
318
319/// An alternate's group tags. The engine stores them as one comma string.
320pub(crate) fn groups(alt: &AltSpec) -> Vec<String> {
321    alt.g
322        .split(',')
323        .map(str::trim)
324        .filter(|tag| !tag.is_empty())
325        .map(str::to_string)
326        .collect()
327}
328
329/// The distinct push/replace rule targets of a rule's open/close alts.
330pub(crate) fn rule_edges(spec: &RuleSpec) -> DebugRuleEdges {
331    DebugRuleEdges {
332        name: spec.name.clone(),
333        open_push: edges(&spec.open, Step::Push),
334        open_replace: edges(&spec.open, Step::Replace),
335        close_push: edges(&spec.close, Step::Push),
336        close_replace: edges(&spec.close, Step::Replace),
337    }
338}
339
340#[derive(Clone, Copy)]
341pub(crate) enum Step {
342    Push,
343    Replace,
344}
345
346/// The distinct targets of one step across a list of alternates, in
347/// first-seen order.
348pub(crate) fn edges(alts: &[AltSpec], step: Step) -> Vec<String> {
349    let mut seen: IndexSet<String> = IndexSet::new();
350    for alt in alts {
351        let (name, has_fn) = match step {
352            Step::Push => (
353                alt.p.as_deref(),
354                alt.p_fn.is_some() || alt.p_match.is_some(),
355            ),
356            Step::Replace => (
357                alt.r.as_deref(),
358                alt.r_fn.is_some() || alt.r_match.is_some(),
359            ),
360        };
361        if let Some(target) = target_name(name, has_fn) {
362            seen.insert(target);
363        }
364    }
365    seen.into_iter().collect()
366}
367
368/// The custom lexer matchers, in priority order.
369pub(crate) fn lexer(parser: &Tabnas) -> Vec<DebugLexMatcher> {
370    let mut matchers: Vec<&tabnas::LexMatcher> = parser.options.lex.matchers.values().collect();
371    matchers.sort_by(|left, right| {
372        left.order
373            .partial_cmp(&right.order)
374            .unwrap_or(std::cmp::Ordering::Equal)
375            .then_with(|| left.name.cmp(&right.name))
376    });
377    matchers
378        .into_iter()
379        .map(|matcher| DebugLexMatcher {
380            order: matcher.order,
381            matcher: matcher.name.clone(),
382            make: String::new(),
383        })
384        .collect()
385}
386
387/// The key parser settings.
388pub(crate) fn config(parser: &Tabnas) -> DebugConfigInfo {
389    let options = &parser.options;
390    DebugConfigInfo {
391        start: options.rule.start.clone(),
392        finish: options.rule.finish,
393        safe_key: options.safe.key,
394        lex: lex_flags(parser),
395    }
396}
397
398/// The built-in lexer enable flags, in the canonical order the
399/// TypeScript `describe()` prints them.
400pub(crate) fn lex_flags(parser: &Tabnas) -> IndexMap<String, bool> {
401    let options = &parser.options;
402    [
403        ("fixed", options.fixed.lex),
404        ("space", options.space.lex),
405        ("line", options.line.lex),
406        ("text", options.text.lex),
407        ("number", options.number.lex),
408        ("comment", options.comment.lex),
409        ("string", options.string.lex),
410        ("value", options.value.lex),
411    ]
412    .into_iter()
413    .map(|(name, enabled)| (name.to_string(), enabled))
414    .collect()
415}
416
417/// The applied plugins, in application order, each with its option bag
418/// when the instance holds one.
419pub(crate) fn plugins(parser: &Tabnas) -> Vec<DebugPluginInfo> {
420    parser
421        .installed_plugins()
422        .into_iter()
423        .map(|plugin| {
424            let options = parser
425                .plugin_options(&plugin.name)
426                .filter(|value| !matches!(value, tabnas::Value::Undefined))
427                .map(|value| value.to_json());
428            DebugPluginInfo {
429                name: plugin.name,
430                options,
431            }
432        })
433        .collect()
434}