Skip to main content

tabnas_debug/
lib.rs

1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3//! Tracing and introspection plugin for the
4//! [tabnas](https://github.com/tabnas/parser) parser engine.
5//!
6//! This is the developer tool the rest of the tabnas fleet's test suites
7//! consume. It provides four things:
8//!
9//! - [`describe()`] — a human-readable dump of a live [`Tabnas`] instance:
10//!   its tag, tokens, token sets, rules, alternates, lexer matchers,
11//!   config, plugins, and an ABNF rendering of the grammar.
12//! - [`model()`] — the *structured* counterpart: the same information as a
13//!   typed, serialisable [`DebugModel`], so tools and tests can consume
14//!   the grammar programmatically.
15//! - [`abnf()`] — a re-compilable ABNF rendering of the instance's live
16//!   grammar.
17//! - **parse tracing** that logs events as the parser runs (see
18//!   [`TraceKinds`]).
19//!
20//! The plugin is a developer tool, **not part of the parse path**.
21//!
22//! ```no_run
23//! use tabnas::Tabnas;
24//! use tabnas_debug::{apply, describe, DebugOptions};
25//!
26//! let mut parser = Tabnas::new();
27//! // ... install a grammar ...
28//! apply(&mut parser, DebugOptions::quiet())?;
29//! println!("{}", describe(&parser));
30//! # Ok::<(), tabnas::PluginError>(())
31//! ```
32//!
33//! TypeScript is canonical: `ts/src/debug.ts` is the source of truth for
34//! behaviour, option names, defaults, output format and section ordering.
35//! The shared fixtures in `test/spec/*.tsv` are the parity contract.
36//! Intentional differences are recorded in `docs/reference.md`.
37//!
38//! ## Free functions, not instance methods
39//!
40//! TypeScript attaches these as instance methods (`tn.debug.describe()`).
41//! Rust cannot add methods to a type it does not own, so — exactly as the
42//! Go port does — they are free functions taking the instance. They are
43//! also infallible here: the Go port returns `(value, error)` because its
44//! engine accessors can fail, while the Rust accessors cannot.
45
46pub mod abnf;
47pub mod describe;
48pub mod model;
49pub mod trace;
50
51use tabnas::{Plugin, PluginError, Tabnas, Value};
52
53pub use abnf::abnf;
54pub use describe::{describe, SECTIONS};
55pub use model::{
56    model, DebugAltInfo, DebugConfigInfo, DebugLexMatcher, DebugModel, DebugPluginInfo,
57    DebugRuleEdges, DebugRuleInfo, DebugSeqItem, DebugTokenInfo, DebugTokenSet,
58};
59pub use trace::{TraceKinds, TRACE_BANNER};
60
61/// The README's Rust examples run as doctests, so a stale one fails the
62/// gate rather than misleading the reader. Its `toml` and `bash` fences
63/// are skipped; rustdoc runs only the `rust` ones.
64#[cfg(doctest)]
65#[doc = include_str!("../README.md")]
66mod readme_examples {}
67
68/// VERSION is this crate's version. It MUST equal `ts/package.json`
69/// "version" and the `version` field in `rs/Cargo.toml`: the release
70/// orchestrator rewrites them, and `tests/version_test.rs` fails the
71/// build if they drift. Mirrors `VERSION` in `ts/src/debug.ts` and
72/// `const VERSION` in `go/debug.go`.
73pub const VERSION: &str = "0.3.11";
74
75/// The decoration key under which the plugin records its `print` setting,
76/// so [`use_plugin`] can honour it later.
77const PRINT_DECORATION: &str = "debug.print";
78
79/// How the debug plugin behaves once installed.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct DebugOptions {
82    /// Dump [`describe()`] after each plugin installed through
83    /// [`use_plugin`]. Default `true`.
84    pub print: bool,
85    /// Which trace kinds to log, or `None` to trace nothing. Default: all
86    /// kinds.
87    pub trace: Option<TraceKinds>,
88}
89
90impl Default for DebugOptions {
91    fn default() -> Self {
92        Self {
93            print: true,
94            trace: Some(TraceKinds::all()),
95        }
96    }
97}
98
99impl DebugOptions {
100    /// The canonical defaults: printing on, every trace kind on.
101    pub fn new() -> Self {
102        Self::default()
103    }
104
105    /// Introspection only — no `USE:` dumps and no tracing. This is what
106    /// a test suite that only wants [`describe()`] / [`model()`] / [`abnf()`]
107    /// should install.
108    pub fn quiet() -> Self {
109        Self {
110            print: false,
111            trace: None,
112        }
113    }
114
115    /// Set the `print` flag.
116    pub fn with_print(mut self, print: bool) -> Self {
117        self.print = print;
118        self
119    }
120
121    /// Trace exactly these kinds.
122    pub fn with_trace(mut self, kinds: TraceKinds) -> Self {
123        self.trace = Some(kinds);
124        self
125    }
126
127    /// Trace nothing.
128    pub fn without_trace(mut self) -> Self {
129        self.trace = None;
130        self
131    }
132}
133
134/// Build the debug plugin for `options`.
135///
136/// The returned [`Plugin`] can be installed with
137/// [`Tabnas::use_plugin`], and — like every native plugin — re-runs
138/// against a derived instance's options. Most callers want [`apply`].
139pub fn plugin(options: DebugOptions) -> Plugin {
140    Plugin::new("Debug", move |parser, _plugin_options| {
141        install(parser, options)
142    })
143}
144
145/// Install the debug plugin on `parser`.
146///
147/// The convenience constructor mirroring the TypeScript
148/// `j.use(Debug, options)` call.
149pub fn apply(parser: &mut Tabnas, options: DebugOptions) -> Result<(), PluginError> {
150    parser.use_plugin(plugin(options), None).map(|_| ())
151}
152
153fn install(parser: &mut Tabnas, options: DebugOptions) -> Result<(), PluginError> {
154    parser.decorate(PRINT_DECORATION, options.print);
155    // Always call through, including for `None`: re-applying the plugin
156    // must be able to turn a previously installed trace OFF, not just
157    // widen it. `trace::install` registers its callbacks once per
158    // instance and updates the live selection thereafter.
159    trace::install(parser, options.trace)
160}
161
162/// Install `plugin` on `parser`, dumping [`describe()`] afterwards when the
163/// debug plugin was installed with `print` on.
164///
165/// TypeScript reassigns `tabnas.use` to wrap it; neither Go's `(*Tabnas).Use`
166/// nor Rust's [`Tabnas::use_plugin`] is a reassignable field, so both ports
167/// expose the wrapper as a function instead. A plugin installed directly
168/// through [`Tabnas::use_plugin`] therefore does not trigger the `USE:`
169/// dump.
170pub fn use_plugin(
171    parser: &mut Tabnas,
172    plugin: Plugin,
173    options: Option<Value>,
174) -> Result<(), PluginError> {
175    let name = plugin.name.clone();
176    parser.use_plugin(plugin, options)?;
177    if parser.decoration::<bool>(PRINT_DECORATION).copied() == Some(true) {
178        let dump = describe(parser);
179        parser
180            .options
181            .debug
182            .write(&format!("USE: {name}\n\n{dump}"));
183    }
184    Ok(())
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn defaults_match_the_canonical_runtime() {
193        let options = DebugOptions::default();
194        assert!(options.print);
195        assert_eq!(options.trace, Some(TraceKinds::all()));
196    }
197
198    #[test]
199    fn quiet_turns_everything_off() {
200        let options = DebugOptions::quiet();
201        assert!(!options.print);
202        assert_eq!(options.trace, None);
203    }
204
205    #[test]
206    fn builders_compose() {
207        let options = DebugOptions::new()
208            .with_print(false)
209            .with_trace(TraceKinds {
210                lex: true,
211                ..TraceKinds::none()
212            });
213        assert!(!options.print);
214        assert_eq!(options.trace.map(|kinds| kinds.lex), Some(true));
215        assert!(DebugOptions::new().without_trace().trace.is_none());
216    }
217}