Skip to main content

tabnas_debug/
trace.rs

1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3//! Parse tracing: log events as the parser runs.
4//!
5//! The canonical TypeScript runtime defines SIX selectable kinds —
6//! `step`, `rule`, `lex`, `parse`, `node`, `stack` — driven by the
7//! engine's `ctx.log` callback. The Rust engine has no `ctx.log`; it
8//! exposes typed subscribers instead, so each kind is wired to the
9//! subscriber that carries its information:
10//!
11//! | Kind    | Rust source                                   |
12//! |---------|-----------------------------------------------|
13//! | `lex`   | `subscribe_lex`                               |
14//! | `rule`  | `subscribe_rules`                             |
15//! | `stack` | `subscribe_rules` (the context's rule stack)  |
16//! | `parse` | `subscribe_rule_done` (the matched alternate) |
17//! | `node`  | `subscribe_rule_done` (the completed node)    |
18//! | `step`  | **no engine hook** — see below                |
19//!
20//! `step` is the raw passthrough kind: in TypeScript the engine itself
21//! calls `ctx.log('step', …)` once per parse step. The Rust engine emits
22//! no such event, so selecting `step` here is accepted (the option name
23//! stays in step with the other runtimes) but nothing is ever logged for
24//! it. That is an engine-API limit, recorded in `docs/reference.md`.
25
26use std::sync::{Arc, Mutex};
27
28use tabnas::{ParsePrepare, PluginError, Tabnas};
29
30/// Which trace kinds are logged.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct TraceKinds {
33    /// Raw per-step passthrough. **Never fires in Rust** — the engine has
34    /// no step event. Kept for option-name parity.
35    pub step: bool,
36    /// Each rule as it opens and closes.
37    pub rule: bool,
38    /// Each token the lexer produces.
39    pub lex: bool,
40    /// The alternate a rule matched.
41    pub parse: bool,
42    /// A rule's node as the rule completes.
43    pub node: bool,
44    /// The rule stack at each rule event.
45    pub stack: bool,
46}
47
48impl TraceKinds {
49    /// Every kind on — the canonical default.
50    pub fn all() -> Self {
51        Self {
52            step: true,
53            rule: true,
54            lex: true,
55            parse: true,
56            node: true,
57            stack: true,
58        }
59    }
60
61    /// Every kind off. Build a selection with the field setters.
62    pub fn none() -> Self {
63        Self {
64            step: false,
65            rule: false,
66            lex: false,
67            parse: false,
68            node: false,
69            stack: false,
70        }
71    }
72
73    /// True when at least one kind that Rust can actually emit is on.
74    fn any_live(&self) -> bool {
75        self.rule || self.lex || self.parse || self.node || self.stack
76    }
77}
78
79impl Default for TraceKinds {
80    fn default() -> Self {
81        Self::all()
82    }
83}
84
85/// The banner written once at the start of each traced parse.
86pub const TRACE_BANNER: &str = "\n========= TRACE ==========";
87
88/// The decoration key under which the plugin keeps its LIVE trace
89/// selection.
90const TRACE_DECORATION: &str = "debug.trace";
91
92/// Per-instance trace state shared with that instance's callbacks.
93struct TraceRuntime {
94    instance_id: String,
95    kinds: Mutex<Option<TraceKinds>>,
96}
97
98/// The live selection, shared with the registered callbacks.
99type TraceState = Arc<TraceRuntime>;
100
101/// Read the current selection. A poisoned lock traces nothing rather than
102/// panicking: debugging must not make a parse less reliable.
103fn current(state: &TraceState, instance_id: &str) -> Option<TraceKinds> {
104    if state.instance_id != instance_id {
105        return None;
106    }
107    state.kinds.lock().ok().and_then(|kinds| *kinds)
108}
109
110/// Install the trace subscribers on `parser`, or update the selection if
111/// they are already installed.
112///
113/// The engine ACCUMULATES subscribers and parse-prepare hooks, so
114/// registering a second set would double every banner and every event —
115/// and a later, narrower selection could not switch the first set off.
116/// Applying the plugin twice is not hypothetical: `derive` re-runs a
117/// parent's plugins on the child. So the callbacks are registered exactly
118/// once per instance and read a shared selection that later installs
119/// update in place, which is how the canonical runtime's
120/// `__debugUseWrapped` guard behaves for its own wrapper.
121pub(crate) fn install(parser: &mut Tabnas, kinds: Option<TraceKinds>) -> Result<(), PluginError> {
122    if let Some(state) = parser.decoration::<TraceState>(TRACE_DECORATION).cloned() {
123        if state.instance_id == parser.id {
124            if let Ok(mut live) = state.kinds.lock() {
125                *live = kinds;
126            }
127            return Ok(());
128        }
129    }
130
131    // Derived parsers inherit decorations and option callbacks, but not
132    // subscribers. Replace the inherited state and named prepare hook with
133    // child-owned versions, then register the child's subscribers below.
134    let state: TraceState = Arc::new(TraceRuntime {
135        instance_id: parser.id.clone(),
136        kinds: Mutex::new(kinds),
137    });
138
139    // One banner per parse, as the canonical runtime emits it.
140    let live = state.clone();
141    parser.set_options(move |options| {
142        options.parse.named_prepare.insert(
143            "debug".to_string(),
144            ParsePrepare::Context(Arc::new(move |context| {
145                if current(&live, &context.instance.id).is_some_and(|kinds| kinds.any_live()) {
146                    context.options.debug.write(TRACE_BANNER);
147                }
148            })),
149        );
150    })?;
151
152    // Publish the initialized state only after the fallible options rebuild
153    // succeeds. Otherwise a retry would mistake a partial install for a
154    // complete one and skip registering the subscribers below.
155    parser.decorate_opaque(TRACE_DECORATION, state.clone());
156
157    {
158        let live = state.clone();
159        parser.subscribe_lex(move |token, rule, context| {
160            if !current(&live, &context.instance.id).is_some_and(|kinds| kinds.lex) {
161                return;
162            }
163            context.options.debug.write(&format!(
164                "lex   {}{} {} pos={} {}:{} src={}",
165                indent(rule.d),
166                token.name,
167                context.options.debug.format_source(&token.val),
168                token.site.pos,
169                token.site.ri,
170                token.site.ci,
171                quote(&token.src, context.options.debug.maxlen),
172            ));
173        });
174    }
175
176    {
177        let live = state.clone();
178        parser.subscribe_rules(move |rule, context| {
179            let Some(kinds) = current(&live, &context.instance.id) else {
180                return;
181            };
182            if kinds.rule {
183                context.options.debug.write(&format!(
184                    "rule  {}{}~{}/{:?} d={} node={}{}",
185                    indent(rule.d),
186                    rule.name,
187                    rule.i,
188                    rule.state,
189                    rule.d,
190                    context.options.debug.format_source(&rule.node.borrow()),
191                    counters(&rule.n),
192                ));
193            }
194            if kinds.stack {
195                let stack = context
196                    .rule_stack
197                    .iter()
198                    .map(|frame| format!("{}~{}", frame.name, frame.i))
199                    .collect::<Vec<_>>()
200                    .join("/");
201                context
202                    .options
203                    .debug
204                    .write(&format!("stack {}/{}", indent(rule.d), stack));
205            }
206        });
207    }
208
209    {
210        let live = state.clone();
211        parser.subscribe_rule_done(move |rule, context, done| {
212            let Some(kinds) = current(&live, &context.instance.id) else {
213                return;
214            };
215            if kinds.parse {
216                let matched = match &done.alt {
217                    Some(alt) => {
218                        let mut parts = Vec::new();
219                        if !alt.p.is_empty() {
220                            parts.push(format!("p:{}", alt.p));
221                        }
222                        if !alt.r.is_empty() {
223                            parts.push(format!("r:{}", alt.r));
224                        }
225                        if 0 != alt.b {
226                            parts.push(format!("b:{}", alt.b));
227                        }
228                        if !alt.g.is_empty() {
229                            parts.push(format!("g:{}", alt.g.join(",")));
230                        }
231                        if let Some(error) = &alt.err {
232                            parts.push(format!("err:{}", error.err));
233                        }
234                        format!("alt {}", parts.join(" "))
235                    }
236                    None => "no-alt".to_string(),
237                };
238                context.options.debug.write(&format!(
239                    "parse {}{}~{}/{:?} {}{}",
240                    indent(rule.d),
241                    rule.name,
242                    rule.i,
243                    done.state,
244                    matched,
245                    if done.forced { " forced" } else { "" },
246                ));
247            }
248            if kinds.node {
249                context.options.debug.write(&format!(
250                    "node  {}{}~{} <{}>",
251                    indent(rule.d),
252                    rule.name,
253                    rule.i,
254                    context.options.debug.format_source(&rule.node.borrow()),
255                ));
256            }
257        });
258    }
259
260    Ok(())
261}
262
263/// Depth indent, matching the canonical runtime's nesting cue.
264fn indent(depth: usize) -> String {
265    "  ".repeat(depth)
266}
267
268/// A rule's live counters, rendered only when it has any. The engine
269/// holds them unordered, so they are sorted for a stable trace.
270fn counters(values: &std::collections::HashMap<String, i32>) -> String {
271    if values.is_empty() {
272        return String::new();
273    }
274    let mut pairs: Vec<String> = values
275        .iter()
276        .filter(|(_, value)| 0 != **value)
277        .map(|(name, value)| format!("{name}={value}"))
278        .collect();
279    if pairs.is_empty() {
280        return String::new();
281    }
282    pairs.sort();
283    format!(" N<{}>", pairs.join(";"))
284}
285
286/// Source text for a trace line, kept on one line and bounded.
287///
288/// Quoted the way the canonical `ctx.F` (a JSON stringifier) quotes this
289/// very field: `{:?}` escapes a newline, tab or carriage return ONCE, as
290/// `\n` / `\t` / `\r`, which is what the engine's `format_source` shows
291/// for the value beside it. Escaping them by hand first and then
292/// formatting doubled the backslash, so a line token's `src=` read `"\\n"`
293/// next to a `val` of `"\n"`, and a source holding a real newline was
294/// indistinguishable from one holding the two characters `\` `n`.
295///
296/// Bounded the way `format_source` bounds the value and `ctx.F` bounds
297/// this field: the rendered form is cut at `maxlen` characters and marked
298/// with `...`. Without the cut a single long string token put its whole
299/// source on the line, so a traced parse of untrusted input cost as much
300/// output as the input itself, per token.
301fn quote(source: &str, maxlen: usize) -> String {
302    let rendered = format!("{source:?}");
303    let mut chars = rendered.chars();
304    let prefix: String = chars.by_ref().take(maxlen).collect();
305    if chars.next().is_some() {
306        format!("{prefix}...")
307    } else {
308        prefix
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    #[test]
317    fn kinds_presets() {
318        assert!(TraceKinds::all().any_live());
319        assert!(!TraceKinds::none().any_live());
320        // `step` alone has no Rust source, so it is not "live".
321        let step_only = TraceKinds {
322            step: true,
323            ..TraceKinds::none()
324        };
325        assert!(!step_only.any_live());
326    }
327
328    #[test]
329    fn counters_are_sorted_and_skip_zeroes() {
330        let mut values = std::collections::HashMap::new();
331        values.insert("zed".to_string(), 1);
332        values.insert("abc".to_string(), 2);
333        values.insert("nil".to_string(), 0);
334        assert_eq!(counters(&values), " N<abc=2;zed=1>");
335        assert_eq!(counters(&std::collections::HashMap::new()), "");
336    }
337
338    #[test]
339    fn quote_escapes_control_characters() {
340        // Escaped ONCE, as JSON (and the canonical `ctx.F`) renders them:
341        // the six characters `"a\nb"`, on one line.
342        assert_eq!(quote("a\nb", 99), "\"a\\nb\"");
343        assert_eq!(quote("\r\t", 99), "\"\\r\\t\"");
344        // A real newline and a literal backslash-n must not render alike.
345        assert_eq!(quote("a\\nb", 99), "\"a\\\\nb\"");
346        assert_ne!(quote("a\nb", 99), quote("a\\nb", 99));
347    }
348
349    #[test]
350    fn quote_is_bounded_by_maxlen() {
351        // Cut at `maxlen` characters of the rendered form and marked, as
352        // the engine's `format_source` does for the value beside it.
353        assert_eq!(quote("abcdef", 4), "\"abc...");
354        assert_eq!(quote("ab", 4), "\"ab\"");
355        // Multi-byte characters count as one each, never split.
356        assert_eq!(
357            quote("\u{1F600}\u{1F600}\u{1F600}", 3),
358            "\"\u{1F600}\u{1F600}..."
359        );
360    }
361}