eure-tree 0.1.9

Eure tree data structure
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
mod span;

use ahash::HashMap;
use std::{collections::BTreeMap, convert::Infallible};
use thiserror::Error;

pub use span::*;

use crate::{
    CstConstructError,
    node_kind::{NodeKind, NonTerminalKind, TerminalKind},
    nodes::{BlockComment, LineComment, NewLine, RootHandle, Whitespace},
    visitor::{BuiltinTerminalVisitor, CstVisitor},
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
/// A dynamic token id that provided by the user land.
pub struct DynamicTokenId(pub u32);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CstNodeData<T, Nt> {
    /// A terminal node with its kind and span
    Terminal { kind: T, data: TerminalData },
    /// A non-terminal node with its kind
    NonTerminal { kind: Nt, data: NonTerminalData },
}

impl<T, Nt> CstNodeData<T, Nt> {
    pub fn new_terminal(kind: T, data: TerminalData) -> Self {
        Self::Terminal { kind, data }
    }

    pub fn new_non_terminal(kind: Nt, data: NonTerminalData) -> Self {
        Self::NonTerminal { kind, data }
    }

    pub fn is_terminal(&self) -> bool {
        matches!(self, CstNodeData::Terminal { .. })
    }

    pub fn is_non_terminal(&self) -> bool {
        matches!(self, CstNodeData::NonTerminal { .. })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TerminalData {
    Input(InputSpan),
    Dynamic(DynamicTokenId),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NonTerminalData {
    Input(InputSpan),
    Dynamic,
}

impl<T, Nt> CstNodeData<T, Nt>
where
    T: Copy,
    Nt: Copy,
{
    pub fn node_kind(&self) -> NodeKind<T, Nt> {
        match self {
            CstNodeData::Terminal { kind, .. } => NodeKind::Terminal(*kind),
            CstNodeData::NonTerminal { kind, .. } => NodeKind::NonTerminal(*kind),
        }
    }
}

impl<T, Nt> CstNodeData<T, Nt>
where
    T: PartialEq + Copy,
    Nt: PartialEq + Copy,
{
    pub fn expected_terminal_or_error(
        &self,
        node: CstNodeId,
        expected: T,
    ) -> Result<(T, TerminalData), ViewConstructionError<T, Nt>> {
        match self {
            CstNodeData::Terminal { kind, data } if *kind == expected => Ok((*kind, *data)),
            _ => Err(ViewConstructionError::UnexpectedNode {
                node,
                data: *self,
                expected_kind: NodeKind::Terminal(expected),
            }),
        }
    }

    pub fn expected_non_terminal_or_error(
        &self,
        node: CstNodeId,
        expected: Nt,
    ) -> Result<(Nt, NonTerminalData), ViewConstructionError<T, Nt>> {
        match self {
            CstNodeData::NonTerminal { kind, data } if *kind == expected => Ok((*kind, *data)),
            _ => Err(ViewConstructionError::UnexpectedNode {
                node,
                data: *self,
                expected_kind: NodeKind::NonTerminal(expected),
            }),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct CstNodeId(pub usize);

impl std::fmt::Display for CstNodeId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A generic concrete syntax tree with stable child ordering
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConcreteSyntaxTree<T, Nt> {
    nodes: Vec<CstNodeData<T, Nt>>,
    children: HashMap<CstNodeId, Vec<CstNodeId>>,
    parent: HashMap<CstNodeId, CstNodeId>,
    dynamic_tokens: BTreeMap<DynamicTokenId, String>,
    next_dynamic_token_id: u32,
    root: CstNodeId,
}

impl<T, Nt> ConcreteSyntaxTree<T, Nt>
where
    T: Clone,
    Nt: Clone,
{
    pub fn new(root_data: CstNodeData<T, Nt>) -> Self {
        let nodes = vec![root_data];
        let root = CstNodeId(0);

        Self {
            nodes,
            children: HashMap::default(),
            parent: HashMap::default(),
            dynamic_tokens: BTreeMap::new(),
            next_dynamic_token_id: 0,
            root,
        }
    }

    pub fn root(&self) -> CstNodeId {
        self.root
    }

    pub fn set_root(&mut self, new_root: CstNodeId) {
        self.root = new_root;
    }

    pub fn change_parent(&mut self, id: CstNodeId, new_parent: CstNodeId) {
        // Remove from old parent's children
        if let Some(old_parent) = self.parent.get(&id).copied()
            && let Some(children) = self.children.get_mut(&old_parent)
        {
            children.retain(|&child| child != id);
        }

        // Add to new parent's children
        self.children.entry(new_parent).or_default().push(id);
        self.parent.insert(id, new_parent);
    }

    pub fn add_node(&mut self, data: CstNodeData<T, Nt>) -> CstNodeId {
        let id = CstNodeId(self.nodes.len());
        self.nodes.push(data);
        id
    }

    pub fn add_node_with_parent(
        &mut self,
        data: CstNodeData<T, Nt>,
        parent: CstNodeId,
    ) -> CstNodeId {
        let node = self.add_node(data);
        self.add_child(parent, node);
        node
    }

    pub fn add_child(&mut self, parent: CstNodeId, child: CstNodeId) {
        self.children.entry(parent).or_default().push(child);
        self.parent.insert(child, parent);
    }

    pub fn has_no_children(&self, node: CstNodeId) -> bool {
        self.children
            .get(&node)
            .is_none_or(|children| children.is_empty())
    }

    pub fn children(&self, node: CstNodeId) -> impl DoubleEndedIterator<Item = CstNodeId> + '_ {
        self.children
            .get(&node)
            .into_iter()
            .flat_map(|children| children.iter().copied())
    }

    pub fn parent(&self, node: CstNodeId) -> Option<CstNodeId> {
        self.parent.get(&node).copied()
    }

    pub fn get_str<'a: 'c, 'b: 'c, 'c>(
        &'a self,
        terminal: TerminalData,
        input: &'b str,
    ) -> Option<&'c str> {
        match terminal {
            TerminalData::Input(span) => Some(span.as_str(input)),
            TerminalData::Dynamic(id) => self.dynamic_token(id),
        }
    }

    pub fn dynamic_token(&self, id: DynamicTokenId) -> Option<&str> {
        self.dynamic_tokens.get(&id).map(|s| s.as_str())
    }

    pub fn update_node(
        &mut self,
        id: CstNodeId,
        data: CstNodeData<T, Nt>,
    ) -> Option<CstNodeData<T, Nt>> {
        if id.0 < self.nodes.len() {
            Some(std::mem::replace(&mut self.nodes[id.0], data))
        } else {
            None
        }
    }

    pub fn update_children(
        &mut self,
        id: CstNodeId,
        new_children: impl IntoIterator<Item = CstNodeId>,
    ) {
        let new_children: Vec<_> = new_children.into_iter().collect();

        // Update parent pointers for old children (remove this parent)
        if let Some(old_children) = self.children.get(&id) {
            for &child in old_children {
                self.parent.remove(&child);
            }
        }

        // Update parent pointers for new children
        for &child in &new_children {
            self.parent.insert(child, id);
        }

        // Set new children
        if new_children.is_empty() {
            self.children.remove(&id);
        } else {
            self.children.insert(id, new_children);
        }
    }

    pub fn insert_dynamic_terminal(&mut self, data: impl Into<String>) -> DynamicTokenId {
        let id = DynamicTokenId(self.next_dynamic_token_id);
        self.dynamic_tokens.insert(id, data.into());
        self.next_dynamic_token_id += 1;
        id
    }
}

impl<T, Nt> ConcreteSyntaxTree<T, Nt>
where
    T: Copy,
    Nt: Copy,
{
    pub fn node_data(&self, node: CstNodeId) -> Option<CstNodeData<T, Nt>> {
        self.nodes.get(node.0).copied()
    }

    /// Remove a node from the tree by removing it from all parent-child relationships.
    /// The node data remains in the vector but becomes unreachable through tree traversal.
    pub fn remove_node(&mut self, id: CstNodeId) {
        // Remove from parent's children list
        if let Some(parent_id) = self.parent.remove(&id)
            && let Some(parent_children) = self.children.get_mut(&parent_id)
        {
            parent_children.retain(|&child| child != id);
        }

        // Remove children mapping (but don't delete child nodes recursively)
        self.children.remove(&id);
    }
}

impl TerminalKind {
    fn auto_ws_is_off(&self, _index: usize) -> bool {
        matches!(
            self,
            TerminalKind::Ws | TerminalKind::GrammarNewline | TerminalKind::Text
        )
    }
}

impl ConcreteSyntaxTree<TerminalKind, NonTerminalKind> {
    pub fn get_non_terminal(
        &self,
        id: CstNodeId,
        kind: NonTerminalKind,
    ) -> Result<NonTerminalData, CstConstructError> {
        let node_data = self
            .node_data(id)
            .ok_or(ViewConstructionError::NodeIdNotFound { node: id })?;
        let (_, data) = node_data.expected_non_terminal_or_error(id, kind)?;
        Ok(data)
    }

    pub fn get_terminal(
        &self,
        id: CstNodeId,
        kind: TerminalKind,
    ) -> Result<TerminalData, CstConstructError> {
        let node_data = self
            .node_data(id)
            .ok_or(ViewConstructionError::NodeIdNotFound { node: id })?;
        let (_, data) = node_data.expected_terminal_or_error(id, kind)?;
        Ok(data)
    }

    pub fn collect_nodes<
        'v,
        const N: usize,
        V: BuiltinTerminalVisitor<E, F>,
        O,
        E,
        F: CstFacade,
    >(
        &self,
        facade: &F,
        parent: CstNodeId,
        nodes: [NodeKind<TerminalKind, NonTerminalKind>; N],
        mut visitor: impl FnMut(
            [CstNodeId; N],
            &'v mut V,
        ) -> Result<(O, &'v mut V), CstConstructError<E>>,
        visit_ignored: &'v mut V,
    ) -> Result<O, CstConstructError<E>> {
        let children = self.children(parent).collect::<Vec<_>>();
        let mut children = children.into_iter();
        let mut result = Vec::with_capacity(N);
        let mut ignored = Vec::with_capacity(N);
        'outer: for expected_kind in nodes {
            'inner: for (idx, child) in children.by_ref().enumerate() {
                let child_data = self
                    .node_data(child)
                    .ok_or(ViewConstructionError::NodeIdNotFound { node: child })?;
                match child_data {
                    CstNodeData::Terminal { kind, data } => {
                        if NodeKind::Terminal(kind) == expected_kind {
                            result.push(child);
                            continue 'outer;
                        } else if kind.is_builtin_whitespace() || kind.is_builtin_new_line() {
                            if kind.auto_ws_is_off(idx) {
                                return Err(ViewConstructionError::UnexpectedNode {
                                    node: child,
                                    data: child_data,
                                    expected_kind,
                                });
                            }
                            ignored.push((child, kind, data));
                            continue 'inner;
                        } else if kind.is_builtin_line_comment() || kind.is_builtin_block_comment()
                        {
                            ignored.push((child, kind, data));
                            continue 'inner;
                        } else {
                            return Err(ViewConstructionError::UnexpectedNode {
                                node: child,
                                data: child_data,
                                expected_kind,
                            });
                        }
                    }
                    CstNodeData::NonTerminal { kind, .. } => {
                        if NodeKind::NonTerminal(kind) == expected_kind {
                            result.push(child);
                            continue 'outer;
                        } else {
                            return Err(ViewConstructionError::UnexpectedNode {
                                node: child,
                                data: child_data,
                                expected_kind,
                            });
                        }
                    }
                }
            }
            return Err(ViewConstructionError::UnexpectedEndOfChildren { parent });
        }
        for (child, kind, data) in ignored {
            match kind {
                TerminalKind::Whitespace => visit_ignored.visit_builtin_whitespace_terminal(
                    Whitespace(child),
                    data,
                    facade,
                )?,
                TerminalKind::NewLine => {
                    visit_ignored.visit_builtin_new_line_terminal(NewLine(child), data, facade)?
                }
                TerminalKind::LineComment => visit_ignored.visit_builtin_line_comment_terminal(
                    LineComment(child),
                    data,
                    facade,
                )?,
                TerminalKind::BlockComment => visit_ignored.visit_builtin_block_comment_terminal(
                    BlockComment(child),
                    data,
                    facade,
                )?,
                _ => unreachable!(),
            }
        }
        let (result, visit_ignored) = visitor(
            result
                .try_into()
                .expect("Result should have the same length as nodes"),
            visit_ignored,
        )?;
        for child in children.by_ref() {
            let child_data = self
                .node_data(child)
                .ok_or(ViewConstructionError::NodeIdNotFound { node: child })?;
            match child_data {
                CstNodeData::Terminal { kind, data } => {
                    if kind.is_builtin_terminal() {
                        match kind {
                            TerminalKind::Whitespace => visit_ignored
                                .visit_builtin_whitespace_terminal(
                                    Whitespace(child),
                                    data,
                                    facade,
                                )?,
                            TerminalKind::NewLine => visit_ignored
                                .visit_builtin_new_line_terminal(NewLine(child), data, facade)?,
                            TerminalKind::LineComment => visit_ignored
                                .visit_builtin_line_comment_terminal(
                                    LineComment(child),
                                    data,
                                    facade,
                                )?,
                            TerminalKind::BlockComment => visit_ignored
                                .visit_builtin_block_comment_terminal(
                                    BlockComment(child),
                                    data,
                                    facade,
                                )?,
                            _ => unreachable!(),
                        }
                    } else {
                        return Err(ViewConstructionError::UnexpectedNode {
                            node: child,
                            data: child_data,
                            expected_kind: NodeKind::Terminal(kind),
                        });
                    }
                }
                CstNodeData::NonTerminal { kind, .. } => {
                    return Err(ViewConstructionError::UnexpectedNode {
                        node: child,
                        data: child_data,
                        expected_kind: NodeKind::NonTerminal(kind),
                    });
                }
            }
        }
        Ok(result)
    }

    pub fn root_handle(&self) -> RootHandle {
        RootHandle(self.root())
    }

    pub fn visit_from_root<V: CstVisitor<Self>>(&self, visitor: &mut V) -> Result<(), V::Error> {
        visitor.visit_root_handle(self.root_handle(), self)
    }
}

pub trait CstFacade: Sized {
    fn get_str<'a: 'c, 'b: 'c, 'c>(
        &'a self,
        terminal: TerminalData,
        input: &'b str,
    ) -> Option<&'c str>;

    fn node_data(&self, node: CstNodeId) -> Option<CstNodeData<TerminalKind, NonTerminalKind>>;

    fn has_no_children(&self, node: CstNodeId) -> bool;

    fn children(&self, node: CstNodeId) -> impl DoubleEndedIterator<Item = CstNodeId>;

    fn get_terminal(
        &self,
        node: CstNodeId,
        kind: TerminalKind,
    ) -> Result<TerminalData, CstConstructError>;

    fn get_non_terminal(
        &self,
        node: CstNodeId,
        kind: NonTerminalKind,
    ) -> Result<NonTerminalData, CstConstructError>;

    fn collect_nodes<'v, const N: usize, V: BuiltinTerminalVisitor<E, Self>, O, E>(
        &self,
        parent: CstNodeId,
        nodes: [NodeKind<TerminalKind, NonTerminalKind>; N],
        visitor: impl FnMut([CstNodeId; N], &'v mut V) -> Result<(O, &'v mut V), CstConstructError<E>>,
        visit_ignored: &'v mut V,
    ) -> Result<O, CstConstructError<E>>;

    fn dynamic_token(&self, id: DynamicTokenId) -> Option<&str>;

    fn parent(&self, node: CstNodeId) -> Option<CstNodeId>;

    fn root_handle(&self) -> RootHandle;

    /// Returns the string representation of a terminal. Returns None if the terminal is a dynamic token and not found.
    fn get_terminal_str<'a: 'c, 'b: 'c, 'c, T: TerminalHandle>(
        &'a self,
        input: &'b str,
        handle: T,
    ) -> Result<Result<&'c str, DynamicTokenId>, CstConstructError> {
        let data = self.get_terminal(handle.node_id(), handle.kind())?;
        match data {
            TerminalData::Input(input_span) => Ok(Ok(
                &input[input_span.start as usize..input_span.end as usize]
            )),
            TerminalData::Dynamic(id) => Ok(self.dynamic_token(id).ok_or(id)),
        }
    }

    /// Returns a span that excludes leading and trailing trivia (whitespace, newlines, comments).
    ///
    /// For terminal nodes:
    /// - Always returns the input span (even for trivia terminals like whitespace/comments)
    /// - Returns None only for dynamic terminals
    ///
    /// For non-terminal nodes:
    /// - Recursively finds the first and last non-trivia descendant spans
    /// - Returns the merged span of those two endpoints
    /// - Falls back to the original span if all descendants are trivia
    ///
    /// This is useful when you want to get the "meaningful" span of a syntax node,
    /// excluding any surrounding whitespace or comments.
    fn span(&self, node_id: CstNodeId) -> Option<InputSpan> {
        match self.node_data(node_id)? {
            CstNodeData::Terminal { data, .. } => {
                // Always return the span for terminals (including trivia)
                match data {
                    TerminalData::Input(span) => Some(span),
                    TerminalData::Dynamic(_) => None,
                }
            }
            CstNodeData::NonTerminal { data, .. } => {
                // Find first non-trivia span
                let first_span = self
                    .children(node_id)
                    .find_map(|child| self.find_first_non_trivia_span(child));

                // Find last non-trivia span
                let last_span = self
                    .children(node_id)
                    .rev()
                    .find_map(|child| self.find_last_non_trivia_span(child));

                match (first_span, last_span) {
                    (Some(first), Some(last)) => Some(first.merge(last)),
                    (Some(span), None) | (None, Some(span)) => Some(span),
                    (None, None) => {
                        // All children are trivia or no children - fall back to original span
                        match data {
                            NonTerminalData::Input(span) if span != InputSpan::EMPTY => Some(span),
                            _ => None,
                        }
                    }
                }
            }
        }
    }

    /// Returns the span of a node, including the trivia.
    fn concrete_span(&self, node_id: CstNodeId) -> Option<InputSpan> {
        match self.node_data(node_id)? {
            CstNodeData::NonTerminal {
                data: NonTerminalData::Input(span),
                ..
            } => Some(span),
            CstNodeData::Terminal { data, .. } => match data {
                TerminalData::Input(span) => Some(span),
                TerminalData::Dynamic(_) => None,
            },
            _ => None,
        }
    }

    /// Helper: finds the first non-trivia span by depth-first search from the start.
    fn find_first_non_trivia_span(&self, node_id: CstNodeId) -> Option<InputSpan> {
        match self.node_data(node_id)? {
            CstNodeData::Terminal { kind, data } => {
                if kind.is_builtin_terminal() {
                    None
                } else {
                    match data {
                        TerminalData::Input(span) => Some(span),
                        TerminalData::Dynamic(_) => None,
                    }
                }
            }
            CstNodeData::NonTerminal { .. } => self
                .children(node_id)
                .find_map(|child| self.find_first_non_trivia_span(child)),
        }
    }

    /// Helper: finds the last non-trivia span by depth-first search from the end.
    fn find_last_non_trivia_span(&self, node_id: CstNodeId) -> Option<InputSpan> {
        match self.node_data(node_id)? {
            CstNodeData::Terminal { kind, data } => {
                if kind.is_builtin_terminal() {
                    None
                } else {
                    match data {
                        TerminalData::Input(span) => Some(span),
                        TerminalData::Dynamic(_) => None,
                    }
                }
            }
            CstNodeData::NonTerminal { .. } => self
                .children(node_id)
                .rev()
                .find_map(|child| self.find_last_non_trivia_span(child)),
        }
    }
}

impl CstFacade for ConcreteSyntaxTree<TerminalKind, NonTerminalKind> {
    fn get_str<'a: 'c, 'b: 'c, 'c>(
        &'a self,
        terminal: TerminalData,
        input: &'b str,
    ) -> Option<&'c str> {
        ConcreteSyntaxTree::get_str(self, terminal, input)
    }

    fn node_data(&self, node: CstNodeId) -> Option<CstNodeData<TerminalKind, NonTerminalKind>> {
        ConcreteSyntaxTree::node_data(self, node)
    }

    fn has_no_children(&self, node: CstNodeId) -> bool {
        ConcreteSyntaxTree::has_no_children(self, node)
    }

    fn children(&self, node: CstNodeId) -> impl DoubleEndedIterator<Item = CstNodeId> {
        ConcreteSyntaxTree::children(self, node)
    }

    fn get_terminal(
        &self,
        node: CstNodeId,
        kind: TerminalKind,
    ) -> Result<TerminalData, CstConstructError> {
        ConcreteSyntaxTree::get_terminal(self, node, kind)
    }

    fn get_non_terminal(
        &self,
        node: CstNodeId,
        kind: NonTerminalKind,
    ) -> Result<NonTerminalData, CstConstructError> {
        ConcreteSyntaxTree::get_non_terminal(self, node, kind)
    }

    fn collect_nodes<'v, const N: usize, V: BuiltinTerminalVisitor<E, Self>, O, E>(
        &self,
        parent: CstNodeId,
        nodes: [NodeKind<TerminalKind, NonTerminalKind>; N],
        visitor: impl FnMut([CstNodeId; N], &'v mut V) -> Result<(O, &'v mut V), CstConstructError<E>>,
        visit_ignored: &'v mut V,
    ) -> Result<O, CstConstructError<E>> {
        ConcreteSyntaxTree::collect_nodes(self, self, parent, nodes, visitor, visit_ignored)
    }

    fn dynamic_token(&self, id: DynamicTokenId) -> Option<&str> {
        ConcreteSyntaxTree::dynamic_token(self, id)
    }

    fn parent(&self, node: CstNodeId) -> Option<CstNodeId> {
        ConcreteSyntaxTree::parent(self, node)
    }

    fn root_handle(&self) -> RootHandle {
        ConcreteSyntaxTree::root_handle(self)
    }
}

#[derive(Debug, Clone, Error)]
/// Error that occurs when constructing a view from a [NonTerminalHandle].
pub enum ViewConstructionError<T, Nt, E = Infallible> {
    /// Expected a specific kind of terminal node, but got an invalid node
    #[error("Unexpected node for expected kind: {expected_kind:?} but got {data:?}")]
    UnexpectedNode {
        /// The index of the node.
        node: CstNodeId,
        /// The data of the node.
        data: CstNodeData<T, Nt>,
        /// The expected kind.
        expected_kind: NodeKind<T, Nt>,
    },
    /// Expected an extra node, but got an invalid node
    #[error("Unexpected extra node")]
    UnexpectedExtraNode {
        /// The index of the node.
        node: CstNodeId,
    },
    /// Unexpected end of children
    #[error("Unexpected end of children")]
    UnexpectedEndOfChildren {
        /// The index of the node.
        parent: CstNodeId,
    },
    /// Unexpected empty children for a non-terminal
    #[error("Unexpected empty children for a non-terminal: {node}")]
    UnexpectedEmptyChildren {
        /// The index of the node.
        node: CstNodeId,
    },
    /// The node ID not found in the tree
    #[error("Node ID not found in the tree: {node}")]
    NodeIdNotFound {
        /// The index of the node.
        node: CstNodeId,
    },
    /// Error that occurs when constructing a view from a [NonTerminalHandle].
    #[error(transparent)]
    Error(#[from] E),
}

impl<T, Nt, E> ViewConstructionError<T, Nt, E> {
    pub fn extract_error(self) -> Result<E, ViewConstructionError<T, Nt, Infallible>> {
        match self {
            ViewConstructionError::Error(e) => Ok(e),
            ViewConstructionError::UnexpectedNode {
                node,
                data,
                expected_kind,
            } => Err(ViewConstructionError::UnexpectedNode {
                node,
                data,
                expected_kind,
            }),
            ViewConstructionError::UnexpectedExtraNode { node } => {
                Err(ViewConstructionError::UnexpectedExtraNode { node })
            }
            ViewConstructionError::UnexpectedEndOfChildren { parent } => {
                Err(ViewConstructionError::UnexpectedEndOfChildren { parent })
            }
            ViewConstructionError::UnexpectedEmptyChildren { node } => {
                Err(ViewConstructionError::UnexpectedEmptyChildren { node })
            }
            ViewConstructionError::NodeIdNotFound { node } => {
                Err(ViewConstructionError::NodeIdNotFound { node })
            }
        }
    }
}

impl<T, Nt> ViewConstructionError<T, Nt, Infallible> {
    pub fn into_any_error<E>(self) -> ViewConstructionError<T, Nt, E> {
        match self {
            ViewConstructionError::UnexpectedNode {
                node,
                data,
                expected_kind,
            } => ViewConstructionError::UnexpectedNode {
                node,
                data,
                expected_kind,
            },
            ViewConstructionError::UnexpectedExtraNode { node } => {
                ViewConstructionError::UnexpectedExtraNode { node }
            }
            ViewConstructionError::UnexpectedEndOfChildren { parent } => {
                ViewConstructionError::UnexpectedEndOfChildren { parent }
            }
            ViewConstructionError::UnexpectedEmptyChildren { node } => {
                ViewConstructionError::UnexpectedEmptyChildren { node }
            }
            ViewConstructionError::NodeIdNotFound { node } => {
                ViewConstructionError::NodeIdNotFound { node }
            }
        }
    }
}

impl<T, Nt> ViewConstructionError<T, Nt, Infallible>
where
    T: Copy,
    Nt: Copy,
{
    pub fn unexpected_node(&self) -> Option<UnexpectedNode<T, Nt>> {
        match self {
            ViewConstructionError::UnexpectedNode {
                node,
                data,
                expected_kind,
            } => Some(UnexpectedNode {
                node: *node,
                data: *data,
                expected_kind: *expected_kind,
            }),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnexpectedNode<T, Nt> {
    node: CstNodeId,
    data: CstNodeData<T, Nt>,
    expected_kind: NodeKind<T, Nt>,
}

struct DummyTerminalVisitor;

impl<F: CstFacade> CstVisitor<F> for DummyTerminalVisitor {
    type Error = Infallible;
    fn visit_new_line_terminal(
        &mut self,
        _terminal: crate::nodes::NewLine,
        _data: TerminalData,
        _tree: &F,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    fn visit_whitespace_terminal(
        &mut self,
        _terminal: crate::nodes::Whitespace,
        _data: TerminalData,
        _tree: &F,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    fn visit_line_comment_terminal(
        &mut self,
        _terminal: crate::nodes::LineComment,
        _data: TerminalData,
        _tree: &F,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    fn visit_block_comment_terminal(
        &mut self,
        _terminal: crate::nodes::BlockComment,
        _data: TerminalData,
        _tree: &F,
    ) -> Result<(), Self::Error> {
        Ok(())
    }
}

pub trait TerminalHandle {
    /// Node ID of the terminal.
    fn node_id(&self) -> CstNodeId;
    /// Kind of the terminal.
    fn kind(&self) -> TerminalKind;
    /// Data of the terminal.
    fn get_data<F: CstFacade>(&self, tree: &F) -> Result<TerminalData, CstConstructError> {
        tree.get_terminal(self.node_id(), self.kind())
    }
}

/// A trait that all generated non-terminal handles implements.
pub trait NonTerminalHandle: Sized {
    /// The type of the view for this non-terminal.
    type View;

    /// Node ID of the non-terminal.
    fn node_id(&self) -> CstNodeId;

    /// Create a new non-terminal handle from a node.
    fn new<F: CstFacade>(index: CstNodeId, tree: &F) -> Result<Self, CstConstructError> {
        Self::new_with_visit(index, tree, &mut DummyTerminalVisitor)
    }

    fn new_with_visit<F: CstFacade, E>(
        index: CstNodeId,
        tree: &F,
        visit_ignored: &mut impl BuiltinTerminalVisitor<E, F>,
    ) -> Result<Self, CstConstructError<E>>;

    /// Get the view of the non-terminal.
    fn get_view<C: CstFacade>(&self, tree: &C) -> Result<Self::View, CstConstructError> {
        self.get_view_with_visit(
            tree,
            |view, visit_ignored| (view, visit_ignored),
            &mut DummyTerminalVisitor,
        )
    }

    /// Get the view of the non-terminal.
    fn get_view_with_visit<'v, F: CstFacade, V: BuiltinTerminalVisitor<E, F>, O, E>(
        &self,
        tree: &F,
        visit: impl FnMut(Self::View, &'v mut V) -> (O, &'v mut V),
        visit_ignored: &'v mut V,
    ) -> Result<O, CstConstructError<E>>;

    /// Get the kind of the non-terminal.
    fn kind(&self) -> NonTerminalKind;
}

/// A trait that generated recursive views implements.
pub trait RecursiveView<F: CstFacade> {
    /// The type of the item in the view.
    type Item;
    fn get_all(&self, tree: &F) -> Result<Vec<Self::Item>, CstConstructError> {
        self.get_all_with_visit(tree, &mut DummyTerminalVisitor)
    }

    fn get_all_with_visit<E>(
        &self,
        tree: &F,
        visit_ignored: &mut impl BuiltinTerminalVisitor<E, F>,
    ) -> Result<Vec<Self::Item>, CstConstructError<E>>;
}