laburnum 1.17.0

An LSP framework for building language servers and compilers, powered by an incremental query tree with content-addressed storage, task-based dataflow, and parallel 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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
// Copyright Two Neutron Stars Incorporated and contributors
// SPDX-License-Identifier: BlueOak-1.0.0

// -- node_db ------------------------------------------------------------------
//
// Generates a complete node database system for chumsky parsers.
//
// This macro generates all the infrastructure needed for a CST/AST node
// database with parser backtracking support, span-based lookups, and
// bluegum visualization.
//
// # Parameters
//
// - `$db_name`: Identifier prefix (e.g., `Cst`, `Ast`) - used to generate type names
// - `nodes`: List of node type paths (must start with `crate::`)
//
// # Generated Types
//
// Given `db_name: Cst`, the macro generates:
//
// - `Node` - Tagged union enum of all node types with span, leading, trailing
// - `CstNodeId` - Strongly-typed node references with span and key
// - `CstCheckpoint` - Backtracking checkpoint capturing vector lengths
// - `CstNodeDb` - Database enum with Parser (Vec) and Query (IndexMap) variants
// - `CstState` - Parser state enum with Detect/Collect variants
// - `CstParserMapExtraExt` - Extension trait for chumsky's MapExtra
// - `Printer` - Bluegum printer for visualization
// - `item::*` - Internal storage structs (struct-of-arrays pattern)
//
// # Required External Crates
//
// The consuming crate's Cargo.toml must include:
// - `laburnum` - For `Span`, `SpanCache`, `SourceKey`, `chumsky::State`
// - `bluegum` - For `Bluegum`, `BluegumWithState`, `Builder`
// - `chumsky` - For parser integration (`MapExtra`, `ParserExtra`, `Input`)
// - `indexmap` - For `IndexMap` in Query variant
// - `owo-colors` - For colored printing in Printer
//
// # Error Integration
//
// The macro does NOT generate error type integration. If you need to convert
// `{db_name}NodeId` to your error system's node ID type, implement the
// conversion in your crate:
//
// ```ignore
// impl From<CstNodeId> for my_error::NodeId {
//     fn from(id: CstNodeId) -> Self {
//         my_error::NodeId::Cst(id.span())
//     }
// }
// ```
//
// # Required Node Type Traits
//
// Each node type in the `nodes` list must implement:
// - `Clone`
// - `PartialEq`
// - `std::fmt::Debug`
// - `bluegum::BluegumWithState<Printer<'_>>`
// - Have a `.span` field of type `laburnum::Span`
//
// # Example
//
// ```ignore
// laburnum::chumsky::define_node_db! { Cst =>
//     crate::errata::Error,
//     crate::errata::Todo,
//     crate::symbol::Ident,
//     // ... more node types
// }
// ```
//
// This generates `CstNodeId`, `CstCheckpoint`, `CstNodeDb`, `CstState`,
// `CstParserMapExtraExt`, `Node`, `Printer`, and `item::*` types.

#[allow(clippy::crate_in_macro_def)]
#[macro_export]
macro_rules! define_node_db {
  (
    $db_name:ident =>
    $(
      crate::$($node_name:ident)::+
    ),* $(,)?
  ) => {
    paste::paste! {
      // -- Node enum ------------------------------------------------------------

      #[derive(Clone, PartialEq)]
      pub enum Node {
        $(
          [< $($node_name:camel)+ >] {
            span: laburnum::Span,
            leading: Option<[< $db_name NodeId >]>,
            node: crate:: $($node_name)::+,
            trailing: Option<[< $db_name NodeId >]>,
          },
        )*
      }

      // -- std::fmt -------------------------------------------------------------

      impl std::fmt::Display for Node {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
          match self {
          $(
           |  Node :: [< $($node_name:camel)+ >] {
               ..
             } => {
               write!(f,
                "{}",
                  stringify!([< $($node_name:camel)+ >]),
                )
              },
            )*
          }
        }
      }

      impl std::fmt::Debug for Node {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
          $(
           |  Node :: [< $($node_name:camel)+ >] {
               leading,
               node,
               trailing,
               ..
             } => {
              f.debug_struct(
                stringify!([< $($node_name:camel)+ >])
              )
                .field("leading", leading)
                .field("node", node)
                .field("trailing", trailing)
                .finish()
              },
            )*
          }
        }
      }

      // -- bluegum --------------------------------------------------------------

      impl bluegum::Bluegum for Node {
        fn node(&self, b: &mut bluegum::Builder) {
          b.name("Node")
            .field("id", format!("{:?}",&self))
            .debug("Help", "For the full node use `node_with_state`");
        }
      }

      impl<'state> bluegum::BluegumWithState<Printer<'state>> for Node {
          #[allow(unused)]
        fn node_with_state(
          &self,
          b: &mut bluegum::Builder,
          state: &Printer<'state>,
        ) {
          match self {
            $(
             | Node::[< $($node_name:camel)+ >] {
                      leading,
                      node,
                      trailing,
                      ..
                  } => {
                 if let Some(l) = leading {
                   b.add_node_with_state(state, "leading_meta", l);
                 }

                 node.node_with_state(b,state);

                 if let Some(t) = trailing {
                    b.add_node_with_state(state, "trailing_meta", t);
                 }
               },
            )*
          }
        }
      }

      #[allow(unused)]
      impl Node {
          #[allow(unused)]
        $(
          pub fn [< match_ $($node_name:snake)_+ >] (
            &self,
          ) -> Option<&crate::$($node_name)::+>
          {
            match self {
              | Node::[< $($node_name:camel)+ >] {
                node,
                ..
              } => Some(node),
              _ => None,
            }
          }
        )*

        pub fn span(&self) -> laburnum::Span {
          match &self {
          $(
            |  Node :: [< $($node_name:camel)+ >]
            {
              span,
              ..
            } => *span,
          )*
          }
        }


        pub fn leading(&self) -> Option<[< $db_name NodeId >]> {
          match &self {
          $(
            |  Node :: [< $($node_name:camel)+ >]
            {
              leading,
              ..
            } => leading.clone(),
          )*
          }
        }


        pub fn trailing(&self) -> Option<[< $db_name NodeId >]> {
          match &self {
          $(
            |  Node :: [< $($node_name:camel)+ >]
            {
              trailing,
              ..
            } => trailing.clone(),
          )*
          }
        }
      }

      // -- item -----------------------------------------------------------------
      //
      // Item is a internal concrete struct for each variant that is used to
      // store the values in a struct-of-arrays format.

      pub mod item {
        $(
          #[derive(Clone, Debug)]
          pub struct [< $($node_name:camel)+ >]
          {
            pub(crate) span: laburnum::Span,
            pub(crate) leading: Option<super::[< $db_name NodeId >]>,
            pub(crate) node:  crate::$($node_name)::+ ,
            pub(crate) trailing: Option<super::[< $db_name NodeId >]>,
          }
        )*
      }

      // -- NodeId ---------------------------------------------------------------

      #[derive(Clone,Copy, PartialEq, Eq, Ord, PartialOrd)]
      pub enum [< $db_name NodeId >] {
          $(
            [< $($node_name:camel)+ >]
            {
              span: laburnum::Span,
              key: u64,
            },
          )*
        }

      impl [< $db_name NodeId >] {
        /// Returns the span associated with this node in the source code.
        pub fn span(&self) -> laburnum::Span {
          match self {
            $(
              | [< $db_name NodeId >] :: [< $($node_name:camel)+ >] { span, .. } => *span,
            )*
          }
        }

        /// Returns the unique key/index used to identify this node in the database.
        pub fn key(&self) -> u64 {
          match self {
            $(
              | [< $db_name NodeId >] :: [< $($node_name:camel)+ >] { key, .. } => *key,
            )*
          }
        }
      }

      impl std::hash::Hash for [< $db_name NodeId >] {
        fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
          match self {
            $(
              | [< $db_name NodeId >] :: [< $($node_name:camel)+ >] { span, .. } => span.hash(state),
            )*
          }
        }
      }

      impl std::fmt::Display for [< $db_name NodeId >] {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
          match self {
            $(
              | [< $db_name NodeId >] :: [< $($node_name:camel)+ >] { span, key } => {
                write!(f,
                  "[{}NodeId({span})::{ty}({key})]",
                  stringify!($db_name),
                  ty=stringify!(
                    [< $($node_name:camel)+ >]
                  ),
                )
              },
            )*
          }
        }
      }

      impl std::fmt::Debug for [< $db_name NodeId >] {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
          match self {
            $(
              | [< $db_name NodeId >] :: [< $($node_name:camel)+ >] { span, key } => {
              write!(f,
                "[{}NodeId({span})::{ty}({key})]",
                stringify!($db_name),
                ty=stringify!(
                  [< $($node_name:camel)+ >]
                ),
              )},
            )*
          }
        }
      }

      impl [< $db_name NodeId >] {
        pub fn load<'node, 'id: 'node, 'state: 'id>(
          &'id self,
          state: &'state mut [< $db_name State >]<'_>,
        ) -> Option<Node> {
          state.[< $db_name:snake >]().get(*self)
        }
      }

      impl bluegum::Bluegum for [< $db_name NodeId >] {
        fn node(&self, b: &mut bluegum::Builder) {
          match self {
            $(
              | [< $db_name NodeId >] :: [< $($node_name:camel)+ >] { span, key } => {
                b.name(concat!(stringify!($db_name), "NodeId"))
                  .debug("ty",  stringify!([< $($node_name:camel)+ >]))
                  .debug("span",span)
                  .debug("key", key);
              },
            )*
          }
        }
      }

      // -- Checkpoint -----------------------------------------------------------

      /// Checkpoint for node database state during parsing.
      /// Captures the lengths of all node vectors for O(1) truncation on backtrack.
      #[derive(Clone, Debug)]
      pub struct [< $db_name Checkpoint >] {
        spans_len: usize,
        $(
          [<node_ $($node_name:snake)_+ _len>]: usize,
        )*
      }

      // -- NodeDb ---------------------------------------------------------------
      //
      // Two distinct types per phase, split via type-state:
      // - Parser: Uses Vec for O(1) truncate during backtracking
      // - Query:  Uses IndexMap for fast span lookups after parsing
      //
      // Shared read access goes through the NodeDbRead trait below.

      /// Parser-mode node database. Optimized for append + truncate during
      /// backtracking. Convert to query mode with [`into_query`] when parsing
      /// completes.
      #[derive(Clone, Debug, Default)]
      pub struct [< $db_name NodeDbParser >] {
        /// Global spans as Vec for O(1) truncate
        pub spans: Vec<(laburnum::Span, [< $db_name NodeId >])>,
        $(
          pub [<node_ $($node_name:snake)_+ >]: Vec<item::[< $($node_name:camel)+ >]>,
        )*
      }

      /// Query-mode node database. Optimized for span lookups after parsing.
      /// Constructed from [`{db_name}NodeDbParser::into_query`].
      #[derive(Clone, Debug)]
      pub struct [< $db_name NodeDbQuery >] {
        pub spans: indexmap::IndexMap<laburnum::Span, [< $db_name NodeId >]>,
        $(
          pub [<node_ $($node_name:snake)_+ >]: Vec<item::[< $($node_name:camel)+ >]>,
        )*
      }

      impl [< $db_name NodeDbParser >] {
        pub fn new() -> Self {
          Self::default()
        }

        /// Convert this parser-mode database into a query-mode database with
        /// fast span lookups via IndexMap. Consumes self.
        pub fn into_query(self) -> [< $db_name NodeDbQuery >] {
          [< $db_name NodeDbQuery >] {
            spans: self.spans.into_iter().collect(),
            $( [<node_ $($node_name:snake)_+ >]: self.[<node_ $($node_name:snake)_+ >], )*
          }
        }

        /// Create a checkpoint of current node vector lengths.
        /// Used by the Inspector trait to support backtracking.
        pub fn checkpoint(&self) -> [< $db_name Checkpoint >] {
          [< $db_name Checkpoint >] {
            spans_len: self.spans.len(),
            $( [<node_ $($node_name:snake)_+ _len>]: self.[<node_ $($node_name:snake)_+ >].len(), )*
          }
        }

        /// Restore to a previous checkpoint, truncating nodes added after.
        /// Used by the Inspector trait to clean up nodes on backtrack.
        pub fn restore(&mut self, cp: &[< $db_name Checkpoint >]) {
          self.spans.truncate(cp.spans_len);
          $( self.[<node_ $($node_name:snake)_+ >].truncate(cp.[<node_ $($node_name:snake)_+ _len>]); )*
        }
      }

      impl [< $db_name NodeDbQuery >] {
        /// Look up the node id covering an exact span.
        pub fn lookup_by_span(&self, span: laburnum::Span) -> Option<[< $db_name NodeId >]> {
          self.spans.get(&span).copied()
        }
      }

      /// Shared read API across parser- and query-mode databases.
      ///
      /// Both [`{db_name}NodeDbParser`] and [`{db_name}NodeDbQuery`] implement
      /// this trait. Use it as a bound when you want to operate on either.
      pub trait [< $db_name NodeDbRead >] {
        $(
          fn [<node_ $($node_name:snake)_+ >](&self) -> &[item::[< $($node_name:camel)+ >]];
        )*

        fn get(&self, id: [< $db_name NodeId >]) -> Option<Node> {
          match id {
            $(
              | [< $db_name NodeId >]::[< $($node_name:camel)+ >] { key, .. } => {
                self.[<node_ $($node_name:snake)_+ >]().get(key as usize).map(|nd| crate::node::Node::[< $($node_name:camel)+ >]{
                  span: nd.span,
                  node: nd.node.clone(),
                  leading: nd.leading.clone(),
                  trailing: nd.trailing.clone(),
                })
              },
            )*
          }
        }

        fn print_nodes(&self) -> String {
          let mut output = String::new();
          $(
            let nodes = self.[<node_ $($node_name:snake)_+ >]();
            if !nodes.is_empty() {
              output.push_str(
                &format!(
                  "\n--{:-<100}\n",
                  format!(" {} ", stringify!([< $($node_name:camel)+ >]))
                )
              );
            }
            for (i, node) in nodes.iter().enumerate() {
              output.push_str(&format!("{:03}: {} — {:?}\n", i, node.span, node))
            }
          )*
          output
        }
      }

      impl [< $db_name NodeDbRead >] for [< $db_name NodeDbParser >] {
        $(
          fn [<node_ $($node_name:snake)_+ >](&self) -> &[item::[< $($node_name:camel)+ >]] {
            &self.[<node_ $($node_name:snake)_+ >]
          }
        )*
      }

      impl [< $db_name NodeDbRead >] for [< $db_name NodeDbQuery >] {
        $(
          fn [<node_ $($node_name:snake)_+ >](&self) -> &[item::[< $($node_name:camel)+ >]] {
            &self.[<node_ $($node_name:snake)_+ >]
          }
        )*
      }

      // -- ParserMapExtraExt ----------------------------------------------------

      pub trait [< $db_name ParserMapExtraExt >]<'tokens, I, E>
      where
        I: chumsky::input::Input<'tokens, Span = chumsky::span::SimpleSpan>,
        E: chumsky::extra::ParserExtra<'tokens, I, State = [< $db_name State >]<'tokens>>,
      {
        $(
           fn [<insert_ $($node_name:snake)_+ >]<F>(
              &mut self,
              leading: Option<[< $db_name NodeId >]>,
              node: F,
              trailing: Option<[< $db_name NodeId >]>,
            ) -> [< $db_name NodeId >]
           where
             F: FnOnce(laburnum::Span, &mut [< $db_name State >]<'tokens>) -> crate::$($node_name)::+;
        )*
      }

      impl<'tokens, 'b, I, E> [< $db_name ParserMapExtraExt >]<'tokens, I, E>
        for chumsky::input::MapExtra<'tokens, 'b, I, E>
      where
      I: chumsky::input::Input<'tokens, Span = chumsky::span::SimpleSpan>,
        E: chumsky::extra::ParserExtra<'tokens, I, State = [< $db_name State >]<'tokens>>,
        Self: laburnum::chumsky::LaburnumSpanExt<'tokens, 'b, I, E>,
      {
        $(
          fn [<insert_ $($node_name:snake)_+ >]<F>(
            &mut self,
            leading: Option<[< $db_name NodeId >]>,
            f: F,
            trailing: Option<[< $db_name NodeId >]>,
          ) -> [< $db_name NodeId >]
          where
            F: FnOnce(laburnum::Span, &mut [< $db_name State >]<'tokens>) -> crate::$($node_name)::+,
          {
            let span = self.create_span();
            let state = self.state();

            let node = f(span, &mut *state);

            let db = state.[< $db_name:snake _mut >]();

            // Linear scan for duplicate span detection during parsing.
            // Reverse iteration finds duplicates near the end first — the most
            // common case when appending sequentially.
            let existing_key = db.[<node_ $($node_name:snake)_+ >]
              .iter()
              .enumerate()
              .rev()
              .find(|(_, n)| n.span == node.span)
              .map(|(i, _)| i as u64);

            let next_key = if let Some(key) = existing_key {
              db.[<node_ $($node_name:snake)_+ >][key as usize] = item::[< $($node_name:camel)+ >] {
                span,
                node,
                leading,
                trailing,
              };
              key
            } else {
              let next_key = db.[<node_ $($node_name:snake)_+ >].len();
              db.[<node_ $($node_name:snake)_+ >].push(item::[< $($node_name:camel)+ >] {
                span,
                node,
                leading,
                trailing,
              });
              next_key as u64
            };

            let id = [< $db_name NodeId >]::[< $($node_name:camel)+ >] {
              span,
              key: next_key,
            };

            db.spans.push((span, id));

            id
          }
        )*
      }

      // -- State ----------------------------------------------------------------

      /// Parser state enum - variants have only the fields needed for that mode.
      /// This prevents accessing wrong fields and the mode can't change during parsing.
      ///
      /// This follows a two-pass parsing pattern:
      /// - First pass: Detect mode with `EmptyErr` for fast parsing
      /// - Second pass: Collect mode with `Rich` errors for detailed diagnostics
      pub enum [< $db_name State >]<'tokens> {
        /// Fast pass - just detect if there are errors
        Detect {
          inner: laburnum::chumsky::State<'tokens>,
          [< $db_name:snake >]: [< $db_name NodeDbParser >],
          source_key: laburnum::SourceKey,
          did_see_error: bool,
        },
        /// Collect pass - actually collect errors
        Collect {
          inner: laburnum::chumsky::State<'tokens>,
          [< $db_name:snake >]: [< $db_name NodeDbParser >],
          source_key: laburnum::SourceKey,
        },
      }

      impl std::fmt::Debug for [< $db_name State >]<'_> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
          match self {
            | Self::Detect {
              [< $db_name:snake >],
              source_key,
              did_see_error,
              ..
            } => f
              .debug_struct(concat!(stringify!($db_name), "State::Detect"))
              .field(stringify!([< $db_name:snake >]), [< $db_name:snake >])
              .field("source_key", source_key)
              .field("did_see_error", did_see_error)
              .finish(),
            | Self::Collect {
              [< $db_name:snake >], source_key, ..
            } => f
              .debug_struct(concat!(stringify!($db_name), "State::Collect"))
              .field(stringify!([< $db_name:snake >]), [< $db_name:snake >])
              .field("source_key", source_key)
              .finish(),
          }
        }
      }

      impl<'tokens> [< $db_name State >]<'tokens> {
        /// Create state in Detect mode (fast pass)
        pub fn new_detect(
          source_key: laburnum::SourceKey,
          span_cache: &'tokens mut laburnum::SpanCache,
        ) -> Self {
          Self::Detect {
            inner: laburnum::chumsky::State::new(source_key, span_cache),
            [< $db_name:snake >]: [< $db_name NodeDbParser >]::new(),
            source_key,
            did_see_error: false,
          }
        }

        /// Create state in Collect mode (second pass with error collection)
        pub fn new_collect(
          source_key: laburnum::SourceKey,
          span_cache: &'tokens mut laburnum::SpanCache,
        ) -> Self {
          Self::Collect {
            inner: laburnum::chumsky::State::new(source_key, span_cache),
            [< $db_name:snake >]: [< $db_name NodeDbParser >]::new(),
            source_key,
          }
        }

        /// Get reference to inner laburnum state
        pub fn inner(&self) -> &laburnum::chumsky::State<'tokens> {
          match self {
            | Self::Detect { inner, .. } | Self::Collect { inner, .. } => inner,
          }
        }

        /// Get mutable reference to inner laburnum state
        pub fn inner_mut(&mut self) -> &mut laburnum::chumsky::State<'tokens> {
          match self {
            | Self::Detect { inner, .. } | Self::Collect { inner, .. } => inner,
          }
        }

        /// Get reference to the node database
        pub fn [< $db_name:snake >](&self) -> &[< $db_name NodeDbParser >] {
          match self {
            | Self::Detect { [< $db_name:snake >], .. } | Self::Collect { [< $db_name:snake >], .. } => [< $db_name:snake >],
          }
        }

        /// Get mutable reference to the node database
        pub fn [< $db_name:snake _mut >](&mut self) -> &mut [< $db_name NodeDbParser >] {
          match self {
            | Self::Detect { [< $db_name:snake >], .. } | Self::Collect { [< $db_name:snake >], .. } => [< $db_name:snake >],
          }
        }

        /// Get the source key
        pub fn source_key(&self) -> laburnum::SourceKey {
          match self {
            | Self::Detect { source_key, .. } | Self::Collect { source_key, .. } => {
              *source_key
            },
          }
        }

        /// Get reference to the span cache
        pub fn span_cache(&self) -> &laburnum::SpanCache {
          self.inner().span_cache
        }

        /// Mark that an error was seen (only affects Detect variant)
        pub fn mark_error(&mut self) {
          if let Self::Detect { did_see_error, .. } = self {
            *did_see_error = true;
          }
        }

        /// Check if we saw an error (only valid for Detect variant)
        pub fn did_see_error(&self) -> bool {
          match self {
            | Self::Detect { did_see_error, .. } => *did_see_error,
            | Self::Collect { .. } => false,
          }
        }

        /// Consume state and return the query-mode node database with fast
        /// span lookups.
        pub fn finish(self) -> std::sync::Arc<[< $db_name NodeDbQuery >]> {
          match self {
            | Self::Detect { [< $db_name:snake >], .. } | Self::Collect { [< $db_name:snake >], .. } => {
              std::sync::Arc::new([< $db_name:snake >].into_query())
            },
          }
        }

        // -- Printing -----------------------------------------------------------

        pub fn print_tree(
          &self,
          source: &str,
          span_cache: &laburnum::SpanCache,
          root: [< $db_name NodeId >],
        ) -> String {
          let p = Printer::new(self.[< $db_name:snake >](), source, span_cache, root);
          p.print()
        }

        pub fn print_nodes(&self) -> String {
          self.[< $db_name:snake >]().print_nodes()
        }

        // -- Tree Roots ---------------------------------------------------------

        pub fn syntax_tree(&self, root: [< $db_name NodeId >]) -> Option<Node> {
          self.get_syntax_node(root)
        }

        // -- Node Access --------------------------------------------------------

        pub fn get_syntax_node(&self, id: [< $db_name NodeId >]) -> Option<Node> {
          self.[< $db_name:snake >]().get(id)
        }

        pub fn get_syntax_node_mut(
          &mut self,
          _id: [< $db_name NodeId >],
        ) -> Option<&mut Node> {
          None
        }
      }

      // Implement Inspector trait for State.
      // This enables proper cleanup of nodes when the parser backtracks.
      impl<'tokens, I: chumsky::input::Input<'tokens>>
        chumsky::inspector::Inspector<'tokens, I> for [< $db_name State >]<'tokens>
      {
        type Checkpoint = [< $db_name Checkpoint >];

        #[inline(always)]
        fn on_token(
          &mut self,
          _token: &<I as chumsky::input::Input<'tokens>>::Token,
        ) {
        }

        #[inline(always)]
        fn on_save<'parse>(
          &self,
          _cursor: &chumsky::input::Cursor<'tokens, 'parse, I>,
        ) -> Self::Checkpoint {
          self.[< $db_name:snake >]().checkpoint()
        }

        #[inline(always)]
        fn on_rewind<'parse>(
          &mut self,
          checkpoint: &chumsky::input::Checkpoint<
            'tokens,
            'parse,
            I,
            Self::Checkpoint,
          >,
        ) {
          self.[< $db_name:snake _mut >]().restore(checkpoint.inspector());
        }
      }

      // Implement SpanCreator for State by delegating to inner state
      impl laburnum::chumsky::SpanCreator for [< $db_name State >]<'_> {
        fn span_from(&mut self, span: chumsky::prelude::SimpleSpan) -> laburnum::Span {
          self
            .inner_mut()
            .span_cache
            .create_span(span.start, span.end - span.start)
        }
      }

      // -- Printer --------------------------------------------------------------

      /// Printer for visualizing the syntax tree with bluegum.
      ///
      /// Holds the node database via a `&dyn` reference so the same Printer
      /// type works for both parser-mode (`{db_name}NodeDbParser`) and
      /// query-mode (`{db_name}NodeDbQuery`) databases.
      pub struct Printer<'state> {
        nodes: &'state (dyn [< $db_name NodeDbRead >] + 'state),
        source: &'state str,
        span_cache: &'state laburnum::SpanCache,
        root: [< $db_name NodeId >],
      }

      impl<'state> Printer<'state> {
        pub fn new(
          nodes: &'state (impl [< $db_name NodeDbRead >] + 'state),
          source: &'state str,
          span_cache: &'state laburnum::SpanCache,
          root: [< $db_name NodeId >],
        ) -> Self {
          Self {
            nodes,
            source,
            span_cache,
            root,
          }
        }

        /// Consume this Printer and return a string representation of the tree
        /// with ANSI color codes.
        pub fn print(self) -> String {
          let mut p = bluegum::Printer::new(bluegum::Styles {
            ..bluegum::Styles::default()
          })
          .set_title(concat!(stringify!($db_name), " Syntax Tree"));

          p.render(&self).with_color().to_string()
        }

        pub fn print_plain(self) -> String {
          let mut p = bluegum::Printer::new(bluegum::Styles {
            ..bluegum::Styles::default()
          })
          .set_title(concat!(stringify!($db_name), " Syntax Tree"));

          p.render(&self).strip_color().to_string()
        }

        pub fn get(&self, id: [< $db_name NodeId >]) -> Option<Node> {
          self.nodes.get(id)
        }

        pub fn span_text(&self, span: &laburnum::Span) -> &str {
          span.text(self.span_cache, self.source).unwrap_or("")
        }
      }

      impl<'state> bluegum::Bluegum for Printer<'state> {
        fn node(&self, b: &mut bluegum::Builder) {
          b.name(env!("CARGO_PKG_NAME"));
          b.add_node_with_state(self, concat!(stringify!($db_name), " Syntax Tree"), &self.root);
        }
      }
    }
  };
}

pub use define_node_db;