plotnik-vm 0.3.2

Runtime VM for executing compiled Plotnik queries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
//! Tracing infrastructure for debugging VM execution.
//!
//! # Design: Zero-Cost Abstraction
//!
//! The tracer is designed as a zero-cost abstraction. When `NoopTracer` is used:
//! - All trait methods are `#[inline(always)]` empty functions
//! - The compiler eliminates all tracer calls and their arguments
//! - No tracing-related state exists in core execution structures
//!
//! # Design: Tracer-Owned State
//!
//! Tracing-only state (like checkpoint creation IPs for backtrack display) is
//! maintained by the tracer itself, not in core structures like `Checkpoint`.
//! This keeps execution structures minimal and avoids "spilling" tracing concerns
//! into `exec`. For example:
//! - `trace_checkpoint_created(ip)` - tracer pushes to its own stack
//! - `trace_backtrack()` - tracer pops its stack to get the display IP
//!
//! `NoopTracer` ignores these calls (optimized away), while `PrintTracer`
//! maintains parallel state for display purposes.

use std::num::NonZeroU16;

use arborium_tree_sitter::Node;

use plotnik_bytecode::{
    EffectOpcode, Instruction, LineBuilder, Match, Module, Nav, NodeTypeIR, PredicateOp, Symbol,
    cols, format_effect, trace, truncate_text, width_for_count,
};
use plotnik_core::Colors;

use super::effect::RuntimeEffect;

/// Verbosity level for trace output.
///
/// Controls which sub-lines are shown and whether node text is included.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Verbosity {
    /// Default: match, backtrack, call/return. Kind only, no text.
    #[default]
    Default,
    /// Verbose (-v): all sub-lines. Text on match/failure.
    Verbose,
    /// Very verbose (-vv): all sub-lines. Text on everything including nav.
    VeryVerbose,
}

/// Tracer trait for VM execution instrumentation.
///
/// All methods receive raw data (IDs, nodes) that the VM already has.
/// Formatting and name resolution happen in the tracer implementation.
///
/// Each method is called at a specific point during execution:
/// - `trace_instruction` - before executing an instruction
/// - `trace_nav` - after navigation succeeds
/// - `trace_match_success/failure` - after type check
/// - `trace_field_success/failure` - after field check
/// - `trace_effect` - after emitting an effect
/// - `trace_call` - when entering a definition
/// - `trace_return` - when returning from a definition
/// - `trace_checkpoint_created` - when a checkpoint is pushed
/// - `trace_backtrack` - when restoring a checkpoint
/// - `trace_enter_entrypoint` - when entering an entrypoint (for labels)
pub trait Tracer {
    /// Called before executing an instruction.
    fn trace_instruction(&mut self, ip: u16, instr: &Instruction<'_>);

    /// Called after navigation succeeds.
    fn trace_nav(&mut self, nav: Nav, node: Node<'_>);

    /// Called when navigation fails (no child/sibling exists).
    fn trace_nav_failure(&mut self, nav: Nav);

    /// Called after type check succeeds.
    fn trace_match_success(&mut self, node: Node<'_>);

    /// Called after type check fails.
    fn trace_match_failure(&mut self, node: Node<'_>);

    /// Called after field check succeeds.
    fn trace_field_success(&mut self, field_id: NonZeroU16);

    /// Called after field check fails.
    fn trace_field_failure(&mut self, node: Node<'_>);

    /// Called after emitting an effect.
    fn trace_effect(&mut self, effect: &RuntimeEffect<'_>);

    /// Called when an effect is suppressed (inside @_ capture).
    fn trace_effect_suppressed(&mut self, opcode: EffectOpcode, payload: usize);

    /// Called for SuppressBegin/SuppressEnd control effects.
    /// `suppressed` is true if already inside another suppress scope.
    fn trace_suppress_control(&mut self, opcode: EffectOpcode, suppressed: bool);

    /// Called when entering a definition via Call.
    fn trace_call(&mut self, target_ip: u16);

    /// Called when returning from a definition.
    fn trace_return(&mut self);

    /// Called when a checkpoint is created.
    fn trace_checkpoint_created(&mut self, ip: u16);

    /// Called when backtracking occurs.
    fn trace_backtrack(&mut self);

    /// Called when entering an entrypoint (for section labels).
    fn trace_enter_entrypoint(&mut self, target_ip: u16);

    /// Called when entering the preamble (bootstrap wrapper).
    fn trace_enter_preamble(&mut self);
}

/// No-op tracer that gets optimized away completely.
pub struct NoopTracer;

impl Tracer for NoopTracer {
    #[inline(always)]
    fn trace_instruction(&mut self, _ip: u16, _instr: &Instruction<'_>) {}

    #[inline(always)]
    fn trace_nav(&mut self, _nav: Nav, _node: Node<'_>) {}

    #[inline(always)]
    fn trace_nav_failure(&mut self, _nav: Nav) {}

    #[inline(always)]
    fn trace_match_success(&mut self, _node: Node<'_>) {}

    #[inline(always)]
    fn trace_match_failure(&mut self, _node: Node<'_>) {}

    #[inline(always)]
    fn trace_field_success(&mut self, _field_id: NonZeroU16) {}

    #[inline(always)]
    fn trace_field_failure(&mut self, _node: Node<'_>) {}

    #[inline(always)]
    fn trace_effect(&mut self, _effect: &RuntimeEffect<'_>) {}

    #[inline(always)]
    fn trace_effect_suppressed(&mut self, _opcode: EffectOpcode, _payload: usize) {}

    #[inline(always)]
    fn trace_suppress_control(&mut self, _opcode: EffectOpcode, _suppressed: bool) {}

    #[inline(always)]
    fn trace_call(&mut self, _target_ip: u16) {}

    #[inline(always)]
    fn trace_return(&mut self) {}

    #[inline(always)]
    fn trace_checkpoint_created(&mut self, _ip: u16) {}

    #[inline(always)]
    fn trace_backtrack(&mut self) {}

    #[inline(always)]
    fn trace_enter_entrypoint(&mut self, _target_ip: u16) {}

    #[inline(always)]
    fn trace_enter_preamble(&mut self) {}
}

use std::collections::BTreeMap;

/// Tracer that collects execution trace for debugging.
pub struct PrintTracer<'s> {
    /// Source code for extracting node text.
    pub(crate) source: &'s [u8],
    /// Verbosity level for output filtering.
    pub(crate) verbosity: Verbosity,
    /// Collected trace lines.
    pub(crate) lines: Vec<String>,
    /// Line builder for formatting.
    pub(crate) builder: LineBuilder,
    /// Maps node type ID to name.
    pub(crate) node_type_names: BTreeMap<u16, String>,
    /// Maps node field ID to name.
    pub(crate) node_field_names: BTreeMap<u16, String>,
    /// Maps member index to name (for Set/Enum effect display).
    pub(crate) member_names: Vec<String>,
    /// All strings from StringTable (for predicate value display).
    pub(crate) all_strings: Vec<String>,
    /// Regex patterns indexed by RegexId (for predicate display).
    pub(crate) regex_patterns: Vec<String>,
    /// Maps entrypoint target IP to name (for labels and call/return).
    pub(crate) entrypoint_by_ip: BTreeMap<u16, String>,
    /// Parallel stack of checkpoint creation IPs (for backtrack display).
    pub(crate) checkpoint_ips: Vec<u16>,
    /// Stack of definition names (for return display).
    pub(crate) definition_stack: Vec<String>,
    /// Pending return instruction IP (for consolidated return line).
    pub(crate) pending_return_ip: Option<u16>,
    /// Step width for formatting.
    pub(crate) step_width: usize,
    /// Color palette.
    pub(crate) colors: Colors,
    /// Previous instruction IP (for cache line boundary detection).
    pub(crate) prev_ip: Option<u16>,
}

/// Builder for `PrintTracer`.
pub struct PrintTracerBuilder<'s, 'm> {
    source: &'s str,
    module: &'m Module,
    verbosity: Verbosity,
    colors: Colors,
}

impl<'s, 'm> PrintTracerBuilder<'s, 'm> {
    /// Create a new builder with required parameters.
    pub fn new(source: &'s str, module: &'m Module) -> Self {
        Self {
            source,
            module,
            verbosity: Verbosity::Default,
            colors: Colors::OFF,
        }
    }

    /// Set the verbosity level.
    pub fn verbosity(mut self, verbosity: Verbosity) -> Self {
        self.verbosity = verbosity;
        self
    }

    /// Set whether to use colored output.
    pub fn colored(mut self, enabled: bool) -> Self {
        self.colors = Colors::new(enabled);
        self
    }

    /// Build the PrintTracer.
    pub fn build(self) -> PrintTracer<'s> {
        let header = self.module.header();
        let strings = self.module.strings();
        let regexes = self.module.regexes();
        let types = self.module.types();
        let node_types = self.module.node_types();
        let node_fields = self.module.node_fields();
        let entrypoints = self.module.entrypoints();

        let mut node_type_names = BTreeMap::new();
        for i in 0..node_types.len() {
            let t = node_types.get(i);
            node_type_names.insert(t.id, strings.get(t.name).to_string());
        }

        let mut node_field_names = BTreeMap::new();
        for i in 0..node_fields.len() {
            let f = node_fields.get(i);
            node_field_names.insert(f.id, strings.get(f.name).to_string());
        }

        // Build member names lookup (index -> name)
        let member_names: Vec<String> = (0..types.members_count())
            .map(|i| strings.get(types.get_member(i).name).to_string())
            .collect();

        // Build all_strings for predicate value display (same as dump.rs)
        let all_strings: Vec<String> = (0..header.str_table_count as usize)
            .map(|i| strings.get_by_index(i).to_string())
            .collect();

        // Build regex patterns (indexed by RegexId → pattern string)
        // Index 0 is reserved, so we start with an empty string placeholder
        let mut regex_patterns = vec![String::new()];
        for i in 1..header.regex_table_count as usize {
            let string_id = regexes.get_string_id(i);
            regex_patterns.push(strings.get(string_id).to_string());
        }

        // Build entrypoint IP -> name lookup
        let mut entrypoint_by_ip = BTreeMap::new();
        for i in 0..entrypoints.len() {
            let e = entrypoints.get(i);
            entrypoint_by_ip.insert(e.target, strings.get(e.name).to_string());
        }

        let step_width = width_for_count(header.transitions_count as usize);

        PrintTracer {
            source: self.source.as_bytes(),
            verbosity: self.verbosity,
            lines: Vec::new(),
            builder: LineBuilder::new(step_width),
            node_type_names,
            node_field_names,
            member_names,
            all_strings,
            regex_patterns,
            entrypoint_by_ip,
            checkpoint_ips: Vec::new(),
            definition_stack: Vec::new(),
            pending_return_ip: None,
            step_width,
            colors: self.colors,
            prev_ip: None,
        }
    }
}

impl<'s> PrintTracer<'s> {
    /// Create a builder for PrintTracer.
    pub fn builder<'m>(source: &'s str, module: &'m Module) -> PrintTracerBuilder<'s, 'm> {
        PrintTracerBuilder::new(source, module)
    }

    fn node_type_name(&self, id: u16) -> &str {
        self.node_type_names.get(&id).map_or("?", |s| s.as_str())
    }

    fn node_field_name(&self, id: u16) -> &str {
        self.node_field_names.get(&id).map_or("?", |s| s.as_str())
    }

    fn member_name(&self, idx: u16) -> &str {
        self.member_names
            .get(idx as usize)
            .map_or("?", |s| s.as_str())
    }

    fn entrypoint_name(&self, ip: u16) -> &str {
        self.entrypoint_by_ip.get(&ip).map_or("?", |s| s.as_str())
    }

    /// Format kind without text content.
    ///
    /// - Named nodes: `kind` (e.g., `identifier`)
    /// - Anonymous nodes: `kind` dim green (e.g., `let`)
    fn format_kind_simple(&self, kind: &str, is_named: bool) -> String {
        if is_named {
            kind.to_string()
        } else {
            let c = &self.colors;
            format!("{}{}{}{}", c.dim, c.green, kind, c.reset)
        }
    }

    /// Format kind with source text, dynamically truncated to fit content width.
    ///
    /// - Named nodes: `kind text` (e.g., `identifier fetchData`)
    /// - Anonymous nodes: just `text` in green (kind == text, no redundancy)
    fn format_kind_with_text(&self, kind: &str, text: &str, is_named: bool) -> String {
        let c = &self.colors;

        // Available content width = TOTAL_WIDTH - prefix_width + step_width
        // prefix_width = INDENT + step_width + GAP + SYMBOL + GAP = 9 + step_width
        // +step_width because ellipsis can extend into the successors column
        // (sub-lines have no successors, so we use that space)
        // This simplifies to: TOTAL_WIDTH - 9 = 35
        let available = cols::TOTAL_WIDTH - 9;

        if is_named {
            // Named: show kind + text
            let text_budget = available.saturating_sub(kind.len() + 1).max(12);
            let truncated = truncate_text(text, text_budget);
            format!("{} {}{}{}{}", kind, c.dim, c.green, truncated, c.reset)
        } else {
            // Anonymous: just text dim green (kind == text, no redundancy)
            let truncated = truncate_text(text, available);
            format!("{}{}{}{}", c.dim, c.green, truncated, c.reset)
        }
    }

    /// Format a runtime effect for display.
    fn format_effect(&self, effect: &RuntimeEffect<'_>) -> String {
        use RuntimeEffect::*;
        match effect {
            Node(_) => "Node".to_string(),
            Text(_) => "Text".to_string(),
            Arr => "Arr".to_string(),
            Push => "Push".to_string(),
            EndArr => "EndArr".to_string(),
            Obj => "Obj".to_string(),
            EndObj => "EndObj".to_string(),
            Set(idx) => format!("Set \"{}\"", self.member_name(*idx)),
            Enum(idx) => format!("Enum \"{}\"", self.member_name(*idx)),
            EndEnum => "EndEnum".to_string(),
            Clear => "Clear".to_string(),
            Null => "Null".to_string(),
        }
    }

    /// Format a suppressed effect from opcode and payload.
    fn format_effect_from_opcode(&self, opcode: EffectOpcode, payload: usize) -> String {
        use EffectOpcode::*;
        match opcode {
            Node => "Node".to_string(),
            Text => "Text".to_string(),
            Arr => "Arr".to_string(),
            Push => "Push".to_string(),
            EndArr => "EndArr".to_string(),
            Obj => "Obj".to_string(),
            EndObj => "EndObj".to_string(),
            Set => format!("Set \"{}\"", self.member_name(payload as u16)),
            Enum => format!("Enum \"{}\"", self.member_name(payload as u16)),
            EndEnum => "EndEnum".to_string(),
            Clear => "Clear".to_string(),
            Null => "Null".to_string(),
            SuppressBegin | SuppressEnd => unreachable!(),
        }
    }

    /// Format match content for instruction line (matches dump format exactly).
    ///
    /// Order: [pre-effects] !neg_fields field: (type) predicate [post-effects]
    fn format_match_content(&self, m: &Match<'_>) -> String {
        let mut parts = Vec::new();

        // Pre-effects: [Effect1 Effect2]
        let pre: Vec<_> = m.pre_effects().map(|e| format_effect(&e)).collect();
        if !pre.is_empty() {
            parts.push(format!("[{}]", pre.join(" ")));
        }

        // Skip neg_fields and node pattern for epsilon (no node interaction)
        if !m.is_epsilon() {
            // Negated fields: !field1 !field2
            for field_id in m.neg_fields() {
                let name = self.node_field_name(field_id);
                parts.push(format!("!{name}"));
            }

            // Node pattern: field: (type) / (type) / field: _ / empty
            let node_part = self.format_node_pattern(m);
            if !node_part.is_empty() {
                parts.push(node_part);
            }

            // Predicate: == "value" or =~ /pattern/
            if let Some((op, is_regex, value_ref)) = m.predicate() {
                let op = PredicateOp::from_byte(op);
                let value = if is_regex {
                    let pattern = &self.regex_patterns[value_ref as usize];
                    format!("/{}/", pattern)
                } else {
                    let s = &self.all_strings[value_ref as usize];
                    format!("{:?}", s)
                };
                parts.push(format!("{} {}", op.as_str(), value));
            }
        }

        // Post-effects: [Effect1 Effect2]
        let post: Vec<_> = m.post_effects().map(|e| format_effect(&e)).collect();
        if !post.is_empty() {
            parts.push(format!("[{}]", post.join(" ")));
        }

        parts.join(" ")
    }

    /// Format node pattern: `field: (type)` or `(type)` or `field: _` or `"text"` or empty.
    fn format_node_pattern(&self, m: &Match<'_>) -> String {
        let mut result = String::new();

        if let Some(f) = m.node_field {
            result.push_str(self.node_field_name(f.get()));
            result.push_str(": ");
        }

        match m.node_type {
            NodeTypeIR::Any => {
                // Any node wildcard: `_`
                result.push('_');
            }
            NodeTypeIR::Named(None) => {
                // Named wildcard: any named node
                result.push_str("(_)");
            }
            NodeTypeIR::Named(Some(t)) => {
                // Specific named node type
                result.push('(');
                result.push_str(self.node_type_name(t.get()));
                result.push(')');
            }
            NodeTypeIR::Anonymous(None) => {
                // Anonymous wildcard: any anonymous node
                result.push_str("\"_\"");
            }
            NodeTypeIR::Anonymous(Some(t)) => {
                // Specific anonymous node (literal token)
                result.push('"');
                result.push_str(self.node_type_name(t.get()));
                result.push('"');
            }
        }

        result
    }

    /// Print all trace lines.
    pub fn print(&self) {
        for line in &self.lines {
            println!("{}", line);
        }
    }

    /// Add an instruction line.
    fn add_instruction(&mut self, ip: u16, symbol: Symbol, content: &str, successors: &str) {
        let prefix = format!("  {:0sw$} {} ", ip, symbol.format(), sw = self.step_width);
        let line = self
            .builder
            .pad_successors(format!("{prefix}{content}"), successors);
        self.lines.push(line);
    }

    /// Add a sub-line (blank step area + symbol + content).
    fn add_subline(&mut self, symbol: Symbol, content: &str) {
        let step_area = 2 + self.step_width + 1;
        let prefix = format!("{:step_area$}{} ", "", symbol.format());
        self.lines.push(format!("{prefix}{content}"));
    }

    /// Format definition name (blue). User definitions get parentheses, preamble doesn't.
    fn format_def_name(&self, name: &str) -> String {
        let c = self.colors;
        if name.starts_with('_') {
            // Preamble/internal names: no parentheses
            format!("{}{}{}", c.blue, name, c.reset)
        } else {
            // User definitions: wrap in parentheses
            format!("({}{}{})", c.blue, name, c.reset)
        }
    }

    /// Format definition label with colon (blue).
    fn format_def_label(&self, name: &str) -> String {
        let c = self.colors;
        format!("{}{}{}:", c.blue, name, c.reset)
    }

    /// Push a definition label, with empty line separator (except for first label).
    fn push_def_label(&mut self, name: &str) {
        if !self.lines.is_empty() {
            self.lines.push(String::new());
        }
        self.lines.push(self.format_def_label(name));
    }

    /// Format cache line boundary separator (full-width dashes, dimmed).
    fn format_cache_line_separator(&self) -> String {
        // Content spans TOTAL_WIDTH (same as instruction lines before successors)
        let c = self.colors;
        format!(
            "{:indent$}{}{}{}",
            "",
            c.dim,
            "-".repeat(cols::TOTAL_WIDTH),
            c.reset,
            indent = cols::INDENT,
        )
    }

    /// Check if IPs cross a cache line boundary and insert separator if so.
    ///
    /// Cache line = 64 bytes = 8 steps (each step is 8 bytes).
    /// Only shows separator in verbose modes (-v, -vv).
    fn check_cache_line_boundary(&mut self, ip: u16) {
        // Only show cache line separators in verbose modes
        if self.verbosity == Verbosity::Default {
            self.prev_ip = Some(ip);
            return;
        }

        const STEPS_PER_CACHE_LINE: u16 = 8;
        if let Some(prev) = self.prev_ip
            && prev / STEPS_PER_CACHE_LINE != ip / STEPS_PER_CACHE_LINE
        {
            self.lines.push(self.format_cache_line_separator());
        }
        self.prev_ip = Some(ip);
    }
}

impl Tracer for PrintTracer<'_> {
    fn trace_instruction(&mut self, ip: u16, instr: &Instruction<'_>) {
        // Check for cache line boundary crossing
        self.check_cache_line_boundary(ip);

        match instr {
            Instruction::Match(m) => {
                // Show ε for epsilon transitions, empty otherwise (nav shown in sublines)
                let symbol = if m.is_epsilon() {
                    Symbol::EPSILON
                } else {
                    Symbol::EMPTY
                };
                let content = self.format_match_content(m);
                let successors = format_match_successors(m);
                self.add_instruction(ip, symbol, &content, &successors);
            }
            Instruction::Call(c) => {
                let name = self.entrypoint_name(c.target.get());
                let content = self.format_def_name(name);
                let successors = format!("{:02} : {:02}", c.target.get(), c.next.get());
                self.add_instruction(ip, Symbol::EMPTY, &content, &successors);
            }
            Instruction::Return(_) => {
                self.pending_return_ip = Some(ip);
            }
            Instruction::Trampoline(t) => {
                // Trampoline shows as a call to the entrypoint target
                let content = "Trampoline";
                let successors = format!("{:02}", t.next.get());
                self.add_instruction(ip, Symbol::EMPTY, content, &successors);
            }
        }
    }

    fn trace_nav(&mut self, nav: Nav, node: Node<'_>) {
        // Navigation sub-lines hidden in default verbosity
        if self.verbosity == Verbosity::Default {
            return;
        }

        let kind = node.kind();
        let symbol = match nav {
            Nav::Epsilon => Symbol::EPSILON,
            Nav::Down | Nav::DownSkip | Nav::DownExact => trace::NAV_DOWN,
            Nav::Next | Nav::NextSkip | Nav::NextExact => trace::NAV_NEXT,
            Nav::Up(_) | Nav::UpSkipTrivia(_) | Nav::UpExact(_) => trace::NAV_UP,
            Nav::Stay | Nav::StayExact => Symbol::EMPTY,
        };

        // Text only in VeryVerbose
        if self.verbosity == Verbosity::VeryVerbose {
            let text = node.utf8_text(self.source).unwrap_or("?");
            let content = self.format_kind_with_text(kind, text, node.is_named());
            self.add_subline(symbol, &content);
        } else {
            let content = self.format_kind_simple(kind, node.is_named());
            self.add_subline(symbol, &content);
        }
    }

    fn trace_nav_failure(&mut self, nav: Nav) {
        // Navigation failure sub-lines hidden in default verbosity
        if self.verbosity == Verbosity::Default {
            return;
        }

        // Show the failed navigation direction
        let nav_symbol = match nav {
            Nav::Down | Nav::DownSkip | Nav::DownExact => "",
            Nav::Next | Nav::NextSkip | Nav::NextExact => "",
            Nav::Up(_) | Nav::UpSkipTrivia(_) | Nav::UpExact(_) => "",
            Nav::Stay | Nav::StayExact | Nav::Epsilon => "·",
        };

        self.add_subline(trace::MATCH_FAILURE, nav_symbol);
    }

    fn trace_match_success(&mut self, node: Node<'_>) {
        let kind = node.kind();

        // Text on match/failure in Verbose+
        if self.verbosity != Verbosity::Default {
            let text = node.utf8_text(self.source).unwrap_or("?");
            let content = self.format_kind_with_text(kind, text, node.is_named());
            self.add_subline(trace::MATCH_SUCCESS, &content);
        } else {
            let content = self.format_kind_simple(kind, node.is_named());
            self.add_subline(trace::MATCH_SUCCESS, &content);
        }
    }

    fn trace_match_failure(&mut self, node: Node<'_>) {
        let kind = node.kind();

        // Text on match/failure in Verbose+
        if self.verbosity != Verbosity::Default {
            let text = node.utf8_text(self.source).unwrap_or("?");
            let content = self.format_kind_with_text(kind, text, node.is_named());
            self.add_subline(trace::MATCH_FAILURE, &content);
        } else {
            let content = self.format_kind_simple(kind, node.is_named());
            self.add_subline(trace::MATCH_FAILURE, &content);
        }
    }

    fn trace_field_success(&mut self, field_id: NonZeroU16) {
        // Field success sub-lines hidden in default verbosity
        if self.verbosity == Verbosity::Default {
            return;
        }

        let name = self.node_field_name(field_id.get());
        self.add_subline(trace::MATCH_SUCCESS, &format!("{}:", name));
    }

    fn trace_field_failure(&mut self, _node: Node<'_>) {
        // Field failures are silent - we just backtrack
    }

    fn trace_effect(&mut self, effect: &RuntimeEffect<'_>) {
        // Effect sub-lines hidden in default verbosity
        if self.verbosity == Verbosity::Default {
            return;
        }

        let effect_str = self.format_effect(effect);
        self.add_subline(trace::EFFECT, &effect_str);
    }

    fn trace_effect_suppressed(&mut self, opcode: EffectOpcode, payload: usize) {
        // Effect sub-lines hidden in default verbosity
        if self.verbosity == Verbosity::Default {
            return;
        }

        let effect_str = self.format_effect_from_opcode(opcode, payload);
        self.add_subline(trace::EFFECT_SUPPRESSED, &effect_str);
    }

    fn trace_suppress_control(&mut self, opcode: EffectOpcode, suppressed: bool) {
        // Effect sub-lines hidden in default verbosity
        if self.verbosity == Verbosity::Default {
            return;
        }

        let name = match opcode {
            EffectOpcode::SuppressBegin => "SuppressBegin",
            EffectOpcode::SuppressEnd => "SuppressEnd",
            _ => unreachable!(),
        };
        let symbol = if suppressed {
            trace::EFFECT_SUPPRESSED
        } else {
            trace::EFFECT
        };
        self.add_subline(symbol, name);
    }

    fn trace_call(&mut self, target_ip: u16) {
        let name = self.entrypoint_name(target_ip).to_string();
        self.add_subline(trace::CALL, &self.format_def_name(&name));
        self.push_def_label(&name);
        self.definition_stack.push(name);
    }

    fn trace_return(&mut self) {
        let ip = self
            .pending_return_ip
            .take()
            .expect("trace_return without trace_instruction");
        let name = self
            .definition_stack
            .pop()
            .expect("trace_return requires balanced call stack");
        let content = self.format_def_name(&name);
        // Show ◼ when returning from top-level (stack now empty)
        let is_top_level = self.definition_stack.is_empty();
        let successor = if is_top_level { "" } else { "" };
        self.add_instruction(ip, trace::RETURN, &content, successor);
        // Print caller's label after return (if not top-level)
        if let Some(caller) = self.definition_stack.last().cloned() {
            self.push_def_label(&caller);
        }
    }

    fn trace_checkpoint_created(&mut self, ip: u16) {
        self.checkpoint_ips.push(ip);
    }

    fn trace_backtrack(&mut self) {
        let created_at = self
            .checkpoint_ips
            .pop()
            .expect("backtrack without checkpoint");
        let line = format!(
            "  {:0sw$} {}",
            created_at,
            trace::BACKTRACK.format(),
            sw = self.step_width
        );
        self.lines.push(line);
    }

    fn trace_enter_entrypoint(&mut self, target_ip: u16) {
        let name = self.entrypoint_name(target_ip).to_string();
        self.push_def_label(&name);
        self.definition_stack.push(name);
    }

    fn trace_enter_preamble(&mut self) {
        const PREAMBLE_NAME: &str = "_ObjWrap";
        self.push_def_label(PREAMBLE_NAME);
        self.definition_stack.push(PREAMBLE_NAME.to_string());
    }
}

/// Format match successors for instruction line.
fn format_match_successors(m: &Match<'_>) -> String {
    if m.is_terminal() {
        "".to_string()
    } else if m.succ_count() == 1 {
        format!("{:02}", m.successor(0).get())
    } else {
        let succs: Vec<_> = m.successors().map(|s| format!("{:02}", s.get())).collect();
        succs.join(", ")
    }
}