Skip to main content

dbt_antlr_runtime/
tree.rs

1//! General AST
2use std::any::Any;
3
4use std::fmt::{Debug, Formatter};
5use std::marker::PhantomData;
6
7use crate::char_stream::InputData;
8use crate::errors::ANTLRError;
9use crate::int_stream::EOF;
10use crate::interval_set::Interval;
11use crate::parser_rule_context::ParserRuleContext;
12use crate::rule_context::RuleContext;
13use crate::token::{CommonToken, Token};
14use crate::{cast_unchecked, token_factory, Arena};
15
16#[allow(missing_docs)]
17pub trait Tree<'arena>: Sized {
18    fn get_parent(&self) -> Option<&'arena Self>;
19
20    fn has_parent(&self) -> bool;
21
22    fn get_payload(&self) -> Box<dyn Any> {
23        unimplemented!()
24    }
25
26    fn get_child(&self, _i: usize) -> Option<&'arena Self>;
27
28    fn get_child_count(&self) -> usize;
29
30    fn get_children<'a>(&'a self) -> Box<dyn Iterator<Item = &'arena Self> + 'a>;
31}
32
33/// Tree that knows about underlying text
34pub trait ParseTree<'input, 'arena>: Tree<'arena> {
35    /// Return an {@link Interval} indicating the index in the
36    /// {@link TokenStream} of the first and last token associated with this
37    /// subtree. If this node is a leaf, then the interval represents a single
38    /// token and has interval i..i for token index i.
39    fn get_source_interval(&self) -> Interval;
40
41    /// Return combined text of this AST node.
42    /// To create resulting string it does traverse whole subtree,
43    /// also it includes only tokens added to the parse tree
44    ///
45    /// Since tokens on hidden channels (e.g. whitespace or comments) are not
46    /// added to the parse trees, they will not appear in the output of this
47    /// method.
48    fn get_text(&self) -> String;
49}
50
51/// Helper trait, implemented for all rule context types that can be wrapped
52/// inside [TreeNode].
53pub trait NodeInner<'input, 'arena, Node, Tok = CommonToken<'input>>
54where
55    'input: 'arena,
56    Node: NodeKindType<'arena, Tok>,
57    Tok: Token + 'input,
58{
59    /// Extract a reference to self from a reference to [TreeNode].
60    ///
61    /// Used for safe downcasting.
62    fn cast_from<'a>(node: &'a TreeNode<'input, 'arena, Node, Tok>) -> Option<&'a Self>
63    where
64        Self: Sized;
65
66    /// Extract a mutable reference to self from a mutable reference to
67    /// [TreeNode].
68    ///
69    /// Used for safe downcasting.
70    fn cast_from_mut<'a>(node: &'a mut TreeNode<'input, 'arena, Node, Tok>) -> Option<&'a mut Self>
71    where
72        Self: Sized;
73
74    /// Upcast &self back to a `&'arena Node`.
75    fn as_node(&self) -> &TreeNode<'input, 'arena, Node, Tok>;
76
77    fn as_node_mut(&mut self) -> &mut TreeNode<'input, 'arena, Node, Tok>;
78
79    /// Iterate over children as [TreeNode]s
80    fn iter_child_nodes<'a>(
81        &'a self,
82    ) -> Box<dyn Iterator<Item = &'arena TreeNode<'input, 'arena, Node, Tok>> + 'a>;
83}
84
85pub type CtxPtr<'input, 'arena> = *mut (&'input (), *mut &'arena ());
86
87pub trait NodeKindType<'arena, Tok = CommonToken<'arena>>:
88    Copy + Debug + PartialEq + Eq + 'static
89where
90    Tok: Token + 'arena,
91{
92    type Listener: ParseTreeListener<'arena, Self, Tok> + ?Sized;
93
94    fn cast_to_ctx<'n, 'input: 'arena>(
95        node: &'n TreeNode<'input, 'arena, Self, Tok>,
96    ) -> &'n dyn ParserRuleContext<'input, 'arena>;
97
98    fn cast_to_ctx_mut<'n, 'input: 'arena>(
99        node: &'n mut TreeNode<'input, 'arena, Self, Tok>,
100    ) -> &'n mut dyn ParserRuleContext<'input, 'arena>;
101
102    fn set_alt_number<'input: 'arena>(
103        node: &mut TreeNode<'input, 'arena, Self, Tok>,
104        alt_number: i32,
105    );
106
107    fn get_rule_index<'input: 'arena>(node: &TreeNode<'input, 'arena, Self, Tok>) -> usize;
108
109    fn get_alt_number<'input: 'arena>(node: &TreeNode<'input, 'arena, Self, Tok>) -> i32;
110
111    fn terminal() -> Self;
112
113    fn error() -> Self;
114
115    fn is_context(&self) -> bool;
116
117    fn enter_rule<'input: 'arena>(
118        node: &TreeNode<'input, 'arena, Self, Tok>,
119        listener: &mut Self::Listener,
120    ) -> Result<(), ANTLRError>;
121
122    fn exit_rule<'input: 'arena>(
123        node: &TreeNode<'input, 'arena, Self, Tok>,
124        listener: &mut Self::Listener,
125    ) -> Result<(), ANTLRError>;
126
127    #[inline]
128    fn is_terminal(&self) -> bool {
129        *self == Self::terminal()
130    }
131
132    #[inline]
133    fn is_error(&self) -> bool {
134        *self == Self::error()
135    }
136}
137#[repr(C, align(8))]
138struct ParserRuleContextCommonLayout<'input, 'arena, Node, Tok = CommonToken<'input>>
139where
140    'input: 'arena,
141    Node: NodeKindType<'arena, Tok>,
142    Tok: Token + 'input,
143{
144    // --- BaseParserRuleContext fields ---
145    start: Option<&'arena Tok>,
146    stop: Option<&'arena Tok>,
147    children: bumpalo::collections::Vec<'arena, &'arena TreeNode<'input, 'arena, Node, Tok>>,
148    // --- BaseRuleContext fields ---
149    parent: Option<&'arena TreeNode<'input, 'arena, Node, Tok>>,
150}
151
152#[derive(Debug)]
153#[repr(C, align(8))]
154pub struct TreeNode<'input, 'arena, NodeKind, Tok = CommonToken<'input>>
155where
156    'input: 'arena,
157    NodeKind: NodeKindType<'arena, Tok>,
158    Tok: Token + 'input,
159{
160    pub(crate) label_tag: u16,
161    pub node_tag: NodeKind,
162    invoking_state: i32,
163    body: (),
164
165    _mark: PhantomData<(&'input Tok, *mut &'arena ())>,
166}
167
168impl<'input, 'arena, NodeKind, Tok> TreeNode<'input, 'arena, NodeKind, Tok>
169where
170    'input: 'arena,
171    NodeKind: NodeKindType<'arena, Tok>,
172    Tok: Token + 'input,
173{
174    pub fn create_token_node(arena: &'arena Arena, symbol: &'arena Tok) -> *mut Self {
175        let header = TreeNode {
176            node_tag: NodeKind::terminal(),
177            label_tag: 0,
178            invoking_state: -1,
179            body: (),
180            _mark: PhantomData,
181        };
182        let leaf = TerminalNode::new(symbol);
183        arena.alloc_node(header, leaf)
184    }
185
186    pub fn create_error_node(arena: &'arena Arena, symbol: &'arena Tok) -> *mut Self {
187        let header = TreeNode {
188            node_tag: NodeKind::error(),
189            label_tag: 0,
190            invoking_state: -1,
191            body: (),
192            _mark: PhantomData,
193        };
194        let leaf = ErrorNode::new(symbol);
195        arena.alloc_node(header, leaf)
196    }
197
198    #[inline]
199    pub fn node_tag(&self) -> NodeKind {
200        self.node_tag
201    }
202
203    /// Return the [ParserRuleContext] object associated with this rule node.
204    pub fn get_rule_context(&self) -> &dyn ParserRuleContext<'input, 'arena> {
205        NodeKind::cast_to_ctx(self)
206    }
207
208    /// Return mutable reference to the [ParserRuleContext] object associated
209    /// with this rule node.
210    pub fn get_rule_context_mut(&mut self) -> &mut dyn ParserRuleContext<'input, 'arena> {
211        NodeKind::cast_to_ctx_mut(self)
212    }
213
214    #[inline]
215    pub fn ctx_ptr(&self) -> CtxPtr<'input, 'arena> {
216        &self.body as *const _ as *mut (&'input (), *mut &'arena ())
217    }
218
219    pub(crate) fn get_start_token(&self) -> Option<&'arena Tok> {
220        self.as_rule_context_common().and_then(|ctx| ctx.start)
221    }
222
223    #[allow(dead_code)]
224    pub(crate) fn get_stop_token(&self) -> Option<&'arena Tok> {
225        self.as_rule_context_common().and_then(|ctx| ctx.stop)
226    }
227
228    /// # Safety
229    /// Caller must ensure that the provided pointer is a valid pointer to a
230    /// properly instantiated [NodeInner] object:
231    /// - For leaf nodes, it must be created via [TreeNode::create_token_node]
232    ///   or [TreeNode::create_error_node];
233    /// - For rule context nodes, it must be created via
234    ///   [BaseParserRuleContext::create].
235    #[inline]
236    pub(crate) unsafe fn from_ctx_ptr(ctx_ptr: CtxPtr<'input, 'arena>) -> &'arena Self {
237        &*((ctx_ptr as *const u8).sub(std::mem::offset_of!(Self, body)) as *const Self)
238    }
239
240    /// # Safety
241    /// Caller must ensure that the provided pointer is a valid pointer to a
242    /// properly instantiated [NodeInner] object:
243    /// - For leaf nodes, it must be created via [TreeNode::create_token_node]
244    ///   or [TreeNode::create_error_node];
245    /// - For rule context nodes, it must be created via
246    ///   [BaseParserRuleContext::create].
247    #[inline]
248    pub(crate) unsafe fn from_ctx_ptr_mut(ctx_ptr: CtxPtr<'input, 'arena>) -> &'arena mut Self {
249        &mut *((ctx_ptr as *const u8).sub(std::mem::offset_of!(Self, body)) as *mut Self)
250    }
251
252    #[inline]
253    fn as_rule_context_common(
254        &self,
255    ) -> Option<&ParserRuleContextCommonLayout<'input, 'arena, NodeKind, Tok>> {
256        if self.node_tag.is_context() {
257            Some(
258                cast_unchecked!(self.ctx_ptr() => ParserRuleContextCommonLayout<'input, 'arena, NodeKind, Tok>),
259            )
260        } else {
261            None
262        }
263    }
264
265    #[inline]
266    fn as_rule_context_common_mut(
267        &mut self,
268    ) -> Option<&mut ParserRuleContextCommonLayout<'input, 'arena, NodeKind, Tok>> {
269        if self.node_tag.is_context() {
270            Some(
271                cast_unchecked!(self.ctx_ptr() => mut ParserRuleContextCommonLayout<'input, 'arena, NodeKind, Tok>),
272            )
273        } else {
274            None
275        }
276    }
277
278    /// Attempt to downcast this node to specific [ParserRuleContext] type
279    pub fn as_rule_context<T>(&self) -> Option<&T>
280    where
281        T: ParserRuleContext<'input, 'arena> + NodeInner<'input, 'arena, NodeKind, Tok>,
282    {
283        T::cast_from(self)
284    }
285
286    /// Attempt to downcast this node to specific [ParserRuleContext] type
287    pub fn as_rule_context_mut<T>(&mut self) -> Option<&mut T>
288    where
289        T: ParserRuleContext<'input, 'arena> + NodeInner<'input, 'arena, NodeKind, Tok>,
290    {
291        T::cast_from_mut(self)
292    }
293
294    /// Downcast this node to terminal node, if the associated context is a
295    /// terminal node
296    pub fn as_terminal_node(&self) -> Option<&TerminalNode<'input, 'arena, Tok>> {
297        TerminalNode::cast_from(self)
298    }
299
300    /// Downcast this node to terminal node, if the associated context is a
301    /// terminal node
302    pub fn as_terminal_node_mut(&mut self) -> Option<&mut TerminalNode<'input, 'arena, Tok>> {
303        TerminalNode::cast_from_mut(self)
304    }
305
306    /// Downcast this node to error node, if the associated context is an error
307    /// node
308    pub fn as_error_node(&self) -> Option<&ErrorNode<'input, 'arena, Tok>> {
309        ErrorNode::cast_from(self)
310    }
311
312    /// Downcast this node to error node, if the associated context is an error
313    /// node
314    pub fn as_error_node_mut(&mut self) -> Option<&mut ErrorNode<'input, 'arena, Tok>> {
315        ErrorNode::cast_from_mut(self)
316    }
317
318    // pub fn add_token_node(&self, token: TerminalNode<'input, Self::TF>) { }
319    // pub fn add_error_node(&self, bad_token: ErrorNode<'input, Self::TF>) { }
320
321    pub fn set_exception(&self, _e: ANTLRError, _arena: &'arena Arena) {}
322
323    /// Sets internal parser state
324    pub fn set_invoking_state(&mut self, s: i32) {
325        self.invoking_state = s;
326    }
327
328    pub fn set_alt_number(&mut self, _alt_number: i32) {
329        NodeKind::set_alt_number(self, _alt_number);
330    }
331
332    pub fn set_start(&mut self, t: Option<&'arena Tok>) {
333        let Some(ctx) = self.as_rule_context_common_mut() else {
334            return;
335        };
336
337        ctx.start = t;
338    }
339
340    pub fn set_stop(&mut self, t: Option<&'arena Tok>) {
341        let Some(ctx) = self.as_rule_context_common_mut() else {
342            return;
343        };
344
345        ctx.stop = t;
346    }
347
348    pub fn remove_last_child(&mut self) {
349        let Some(ctx) = self.as_rule_context_common_mut() else {
350            return;
351        };
352        ctx.children.pop();
353    }
354
355    /// Drops every child after the first `len` children.
356    pub fn truncate_children(&mut self, len: usize) {
357        let Some(ctx) = self.as_rule_context_common_mut() else {
358            return;
359        };
360        ctx.children.truncate(len);
361    }
362
363    pub fn add_child(&mut self, _child: &'arena Self) {
364        let Some(ctx) = self.as_rule_context_common_mut() else {
365            return;
366        };
367        ctx.children.push(_child);
368    }
369
370    pub fn set_parent(&mut self, parent: Option<&'arena Self>) {
371        let Some(ctx) = self.as_rule_context_common_mut() else {
372            return;
373        };
374        ctx.parent = parent;
375    }
376
377    pub fn enter_rule(&self, listener: &mut NodeKind::Listener) -> Result<(), ANTLRError> {
378        NodeKind::enter_rule(self, listener)
379    }
380
381    pub fn exit_rule(&self, listener: &mut NodeKind::Listener) -> Result<(), ANTLRError> {
382        NodeKind::exit_rule(self, listener)
383    }
384}
385
386impl<'input, 'arena, NodeKind, Tok> Tree<'arena> for TreeNode<'input, 'arena, NodeKind, Tok>
387where
388    'input: 'arena,
389    NodeKind: NodeKindType<'arena, Tok>,
390    Tok: Token + 'input,
391{
392    #[inline]
393    fn get_parent(&self) -> Option<&'arena Self> {
394        self.as_rule_context_common().and_then(|ctx| ctx.parent)
395    }
396
397    fn has_parent(&self) -> bool {
398        self.get_parent().is_some()
399    }
400
401    fn get_child(&self, i: usize) -> Option<&'arena Self> {
402        self.as_rule_context_common()
403            .and_then(|ctx| ctx.children.get(i).copied())
404    }
405
406    #[inline]
407    fn get_child_count(&self) -> usize {
408        self.as_rule_context_common()
409            .map_or(0, |ctx| ctx.children.len())
410    }
411
412    #[inline]
413    fn get_children<'a>(&'a self) -> Box<dyn Iterator<Item = &'arena Self> + 'a> {
414        if let Some(ctx) = self.as_rule_context_common() {
415            Box::new(ctx.children.iter().copied())
416        } else {
417            Box::new(std::iter::empty())
418        }
419    }
420}
421
422impl<'input, 'arena, Node, Tok> ParseTree<'input, 'arena> for TreeNode<'input, 'arena, Node, Tok>
423where
424    'input: 'arena,
425    Node: NodeKindType<'arena, Tok>,
426    Tok: Token,
427{
428    fn get_source_interval(&self) -> Interval {
429        if let Some(terminal) = self.as_terminal_node() {
430            Interval::new(
431                terminal.symbol.get_start_index() as i32,
432                terminal.symbol.get_stop_index() as i32,
433            )
434        } else if let Some(error) = self.as_error_node() {
435            Interval::new(
436                error.symbol.get_start_index() as i32,
437                error.symbol.get_stop_index() as i32,
438            )
439        } else {
440            let ctx = self
441                .as_rule_context_common()
442                .expect("Can only be rule context at this point");
443            match (ctx.start, ctx.stop) {
444                (Some(start), Some(stop)) => {
445                    Interval::new(start.get_start_index() as i32, stop.get_stop_index() as i32)
446                }
447                _ => Interval::invalid(),
448            }
449        }
450    }
451
452    fn get_text(&self) -> String {
453        if let Some(terminal) = self.as_terminal_node() {
454            return terminal.get_text();
455        } else if let Some(error) = self.as_error_node() {
456            return error.get_text();
457        }
458
459        let mut result = String::new();
460        for child in self.get_children() {
461            result.push_str(&ParseTree::get_text(child));
462        }
463        result
464    }
465}
466
467impl<'input, 'arena, NodeKind, Tok> RuleContext<'arena> for TreeNode<'input, 'arena, NodeKind, Tok>
468where
469    'input: 'arena,
470    NodeKind: NodeKindType<'arena, Tok>,
471    Tok: Token,
472{
473    fn get_rule_index(&self) -> usize {
474        NodeKind::get_rule_index(self)
475    }
476
477    fn get_alt_number(&self) -> i32 {
478        NodeKind::get_alt_number(self)
479    }
480
481    #[inline]
482    fn get_invoking_state(&self) -> i32 {
483        self.invoking_state
484    }
485
486    fn get_parent_ctx(&self) -> Option<&'arena dyn RuleContext<'arena>> {
487        self.get_parent()
488            .map(|p| p as &'arena dyn RuleContext<'arena>)
489    }
490
491    fn get_node_text(&self, rule_names: &[&str]) -> String {
492        NodeKind::cast_to_ctx(self).get_node_text(rule_names)
493    }
494}
495
496impl<'input, 'arena, Node, Tok> ParserRuleContext<'input, 'arena>
497    for TreeNode<'input, 'arena, Node, Tok>
498where
499    'input: 'arena,
500    Node: NodeKindType<'arena, Tok>,
501    Tok: Token,
502{
503    fn get_text(&self) -> String {
504        ParseTree::get_text(self)
505    }
506
507    fn get_child_count(&self) -> usize {
508        Tree::get_child_count(self)
509    }
510
511    fn start(&self) -> &'arena dyn Token {
512        if let Some(terminal) = self.as_terminal_node() {
513            return terminal.symbol;
514        } else if let Some(error) = self.as_error_node() {
515            return error.symbol;
516        }
517        let ctx = self
518            .as_rule_context_common()
519            .expect("Can only be rule context at this point");
520        ctx.start.map_or_else(
521            || token_factory::invalid() as &dyn Token,
522            |t| t as &dyn Token,
523        )
524    }
525
526    fn stop(&self) -> &'arena dyn Token {
527        if let Some(terminal) = self.as_terminal_node() {
528            return terminal.symbol;
529        } else if let Some(error) = self.as_error_node() {
530            return error.symbol;
531        }
532        let ctx = self
533            .as_rule_context_common()
534            .expect("Can only be rule context at this point");
535        ctx.stop.map_or_else(
536            || token_factory::invalid() as &dyn Token,
537            |t| t as &dyn Token,
538        )
539    }
540
541    fn get_parent_ctx(&self) -> Option<&'arena dyn ParserRuleContext<'input, 'arena>> {
542        self.get_parent()
543            .map(|p| p as &'arena dyn ParserRuleContext<'input, 'arena>)
544    }
545
546    fn get_child_ctx(&self, i: usize) -> Option<&'arena dyn ParserRuleContext<'input, 'arena>> {
547        self.get_child(i)
548            .map(|child| child.get_rule_context() as &dyn ParserRuleContext<'input, 'arena>)
549    }
550
551    fn iter_children<'a>(
552        &'a self,
553    ) -> Box<dyn Iterator<Item = &'arena dyn ParserRuleContext<'input, 'arena>> + 'a>
554    where
555        'input: 'a,
556        'arena: 'a,
557    {
558        let Some(ctx) = self.as_rule_context_common() else {
559            return Box::new(std::iter::empty());
560        };
561        Box::new(
562            ctx.children
563                .iter()
564                .map(|child| child.get_rule_context() as &dyn ParserRuleContext<'input, 'arena>),
565        )
566    }
567
568    fn get_token(&self, _ttype: i32, _pos: usize) -> Option<&dyn Token> {
569        let ctx = self.as_rule_context_common()?;
570        ctx.children
571            .iter()
572            .filter_map(|child| child.as_terminal_node())
573            .filter(|t| t.symbol.get_token_type() == _ttype)
574            .nth(_pos)
575            .map(|t| t.symbol as &dyn Token)
576    }
577
578    fn get_tokens(&self, _ttype: i32) -> Vec<&dyn Token> {
579        let Some(ctx) = self.as_rule_context_common() else {
580            return vec![];
581        };
582        ctx.children
583            .iter()
584            .filter_map(|child| child.as_terminal_node())
585            .filter(|t| t.symbol.get_token_type() == _ttype)
586            .map(|t| t.symbol as &dyn Token)
587            .collect()
588    }
589
590    fn to_string_tree(&self, rule_names: &[&str]) -> String {
591        crate::trees::string_tree(self, rule_names)
592    }
593}
594
595#[doc(hidden)]
596#[derive(Debug)]
597pub struct NoError;
598
599#[doc(hidden)]
600#[derive(Debug)]
601pub struct IsError;
602
603/// Generic leaf AST node
604pub struct LeafNodeInner<'input, 'arena, E, Tok>
605where
606    'input: 'arena,
607    Tok: Token + 'input,
608    E: 'static,
609{
610    /// Token, this leaf consist of
611    pub symbol: &'arena Tok,
612    iserror: PhantomData<(E, &'input ())>,
613}
614
615impl<'input, 'arena, E, Tok> RuleContext<'arena> for LeafNodeInner<'input, 'arena, E, Tok>
616where
617    'input: 'arena,
618    E: 'static,
619    Tok: Token + 'input,
620{
621    fn get_rule_index(&self) -> usize {
622        usize::MAX
623    }
624
625    fn get_alt_number(&self) -> i32 {
626        crate::atn::INVALID_ALT
627    }
628
629    fn get_node_text(&self, _rule_names: &[&str]) -> String {
630        self.symbol.get_text().to_display()
631    }
632
633    fn get_invoking_state(&self) -> i32 {
634        -1
635    }
636
637    fn get_parent_ctx(&self) -> Option<&'arena dyn RuleContext<'arena>> {
638        None
639    }
640}
641
642impl<'input, 'arena, E, Tok> ParserRuleContext<'input, 'arena>
643    for LeafNodeInner<'input, 'arena, E, Tok>
644where
645    'input: 'arena,
646    E: 'static,
647    Tok: Token + 'input,
648{
649    fn get_text(&self) -> String {
650        self.symbol.get_text().to_display()
651    }
652
653    fn get_child_count(&self) -> usize {
654        0
655    }
656
657    fn iter_children<'a>(
658        &'a self,
659    ) -> Box<dyn Iterator<Item = &'arena dyn ParserRuleContext<'input, 'arena>> + 'a>
660    where
661        'input: 'a,
662        'arena: 'a,
663    {
664        Box::new(std::iter::empty())
665    }
666
667    fn get_token(&self, _ttype: i32, _pos: usize) -> Option<&dyn Token> {
668        None
669    }
670
671    fn get_tokens(&self, _ttype: i32) -> Vec<&dyn Token> {
672        vec![]
673    }
674}
675
676impl<'input, 'arena, Node, Tok> NodeInner<'input, 'arena, Node, Tok>
677    for LeafNodeInner<'input, 'arena, NoError, Tok>
678where
679    'input: 'arena,
680    Node: NodeKindType<'arena, Tok>,
681    Tok: Token + 'input,
682{
683    fn cast_from<'a>(node: &'a TreeNode<'input, 'arena, Node, Tok>) -> Option<&'a Self>
684    where
685        Self: Sized,
686    {
687        if node.node_tag.is_terminal() {
688            Some(unsafe { &*(node.ctx_ptr() as *const Self) })
689        } else {
690            None
691        }
692    }
693
694    fn cast_from_mut<'a>(node: &'a mut TreeNode<'input, 'arena, Node, Tok>) -> Option<&'a mut Self>
695    where
696        Self: Sized,
697    {
698        if node.node_tag.is_terminal() {
699            Some(unsafe { &mut *(node.ctx_ptr() as *mut Self) })
700        } else {
701            None
702        }
703    }
704
705    fn as_node(&self) -> &TreeNode<'input, 'arena, Node, Tok> {
706        // SAFETY: All [NodeInner] instances are allocated by
707        // [Arena::alloc_node] with a valid [RuleNodeImpl] header
708        unsafe { TreeNode::from_ctx_ptr(self as *const Self as CtxPtr<'input, 'arena>) }
709    }
710
711    fn as_node_mut(&mut self) -> &mut TreeNode<'input, 'arena, Node, Tok> {
712        // SAFETY: All [NodeInner] instances are allocated by
713        // [Arena::alloc_node] with a valid [RuleNodeImpl] header
714        unsafe { TreeNode::from_ctx_ptr_mut(self as *mut Self as CtxPtr<'input, 'arena>) }
715    }
716
717    fn iter_child_nodes<'a>(
718        &'a self,
719    ) -> Box<dyn Iterator<Item = &'arena TreeNode<'input, 'arena, Node, Tok>> + 'a> {
720        Box::new(std::iter::empty())
721    }
722}
723
724impl<'input, 'arena, Node, Tok> NodeInner<'input, 'arena, Node, Tok>
725    for LeafNodeInner<'input, 'arena, IsError, Tok>
726where
727    'input: 'arena,
728    Node: NodeKindType<'arena, Tok>,
729    Tok: Token + 'input,
730{
731    fn cast_from<'a>(node: &'a TreeNode<'input, 'arena, Node, Tok>) -> Option<&'a Self>
732    where
733        Self: Sized,
734    {
735        if node.node_tag.is_error() {
736            Some(unsafe { &*(node.ctx_ptr() as *const Self) })
737        } else {
738            None
739        }
740    }
741
742    fn cast_from_mut<'a>(node: &'a mut TreeNode<'input, 'arena, Node, Tok>) -> Option<&'a mut Self>
743    where
744        Self: Sized,
745    {
746        if node.node_tag.is_error() {
747            Some(unsafe { &mut *(node.ctx_ptr() as *mut Self) })
748        } else {
749            None
750        }
751    }
752
753    fn as_node(&self) -> &TreeNode<'input, 'arena, Node, Tok> {
754        // SAFETY: All [NodeInner] instances are allocated by
755        // [Arena::alloc_node] with a valid [RuleNodeImpl] header
756        unsafe { TreeNode::from_ctx_ptr(self as *const Self as CtxPtr<'input, 'arena>) }
757    }
758
759    fn as_node_mut(&mut self) -> &mut TreeNode<'input, 'arena, Node, Tok> {
760        // SAFETY: All [NodeInner] instances are allocated by
761        // [Arena::alloc_node] with a valid [RuleNodeImpl] header
762        unsafe { TreeNode::from_ctx_ptr_mut(self as *mut Self as CtxPtr<'input, 'arena>) }
763    }
764
765    fn iter_child_nodes<'a>(
766        &'a self,
767    ) -> Box<dyn Iterator<Item = &'arena TreeNode<'input, 'arena, Node, Tok>> + 'a> {
768        Box::new(std::iter::empty())
769    }
770}
771
772impl<'input, 'arena, E, Tok> Debug for LeafNodeInner<'input, 'arena, E, Tok>
773where
774    E: 'static,
775    Tok: Token + 'input,
776{
777    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
778        if self.symbol.get_token_type() == EOF {
779            f.write_str("<EOF>")
780        } else {
781            let a = self.symbol.get_text().to_display();
782            f.write_str(&a)
783        }
784    }
785}
786
787impl<'input, 'arena, E, Tok> LeafNodeInner<'input, 'arena, E, Tok>
788where
789    'input: 'arena,
790    E: 'static,
791    Tok: Token + 'input,
792{
793    /// Creates new leaf node
794    ///
795    /// Note: [LeafNodeInner] can not exist as a standalone entity, this
796    /// constructor can only be called from [RuleNodeImpl::create_token_node] or
797    /// [RuleNodeImpl::create_error_node]
798    fn new(symbol: &'arena Tok) -> Self {
799        Self {
800            symbol,
801            iserror: Default::default(),
802        }
803    }
804}
805
806/// non-error AST leaf node
807pub type TerminalNode<'input, 'arena, Tok = CommonToken<'input>> =
808    LeafNodeInner<'input, 'arena, NoError, Tok>;
809
810/// # Error Leaf
811/// Created for each token created or consumed during recovery
812pub type ErrorNode<'input, 'arena, Tok = CommonToken<'input>> =
813    LeafNodeInner<'input, 'arena, IsError, Tok>;
814
815pub trait ParseTreeVisitor<'input, 'arena, Node, Tok>
816where
817    'input: 'arena,
818    Node: NodeKindType<'arena, Tok>,
819    Tok: Token + 'input,
820{
821    type Return: Default;
822
823    fn visit(
824        &mut self,
825        node: &TreeNode<'input, 'arena, Node, Tok>,
826    ) -> Result<Self::Return, ANTLRError>;
827
828    /// Called on terminal(leaf) node
829    fn visit_terminal(
830        &mut self,
831        _node: &TerminalNode<'input, 'arena, Tok>,
832    ) -> Result<Self::Return, ANTLRError> {
833        Ok(Self::Return::default())
834    }
835
836    /// Called on error node
837    fn visit_error_node(
838        &mut self,
839        _node: &ErrorNode<'input, 'arena, Tok>,
840    ) -> Result<Self::Return, ANTLRError> {
841        Ok(Self::Return::default())
842    }
843
844    fn visit_children(
845        &mut self,
846        node: &dyn NodeInner<'input, 'arena, Node, Tok>,
847    ) -> Result<Self::Return, ANTLRError> {
848        let mut result = Self::Return::default();
849        for child in node.iter_child_nodes() {
850            if !self.should_visit_next_child(child, &result) {
851                break;
852            }
853
854            let child_result = self.visit(child)?;
855            result = self.aggregate_results(result, child_result)?;
856        }
857        Ok(result)
858    }
859
860    fn aggregate_results(
861        &self,
862        _aggregate: Self::Return,
863        next: Self::Return,
864    ) -> Result<Self::Return, ANTLRError> {
865        Ok(next)
866    }
867
868    fn should_visit_next_child(
869        &self,
870        _node: &TreeNode<'input, 'arena, Node, Tok>,
871        _current: &Self::Return,
872    ) -> bool {
873        true
874    }
875}
876
877/// Base parse listener interface
878pub trait ParseTreeListener<'arena, Node, Tok>
879where
880    Node: NodeKindType<'arena, Tok>,
881    Tok: Token + 'arena,
882{
883    /// Called when parser creates terminal node
884    fn visit_terminal(&mut self, _node: &TerminalNode<'_, 'arena, Tok>) -> Result<(), ANTLRError> {
885        Ok(())
886    }
887
888    /// Called when parser creates error node
889    fn visit_error_node(&mut self, _node: &ErrorNode<'_, 'arena, Tok>) -> Result<(), ANTLRError> {
890        Ok(())
891    }
892
893    /// Called when parser enters any rule node
894    fn enter_every_rule(
895        &mut self,
896        _ctx: &TreeNode<'_, 'arena, Node, Tok>,
897    ) -> Result<(), ANTLRError> {
898        Ok(())
899    }
900
901    /// Called when parser exits any rule node
902    fn exit_every_rule(
903        &mut self,
904        _ctx: &TreeNode<'_, 'arena, Node, Tok>,
905    ) -> Result<(), ANTLRError> {
906        Ok(())
907    }
908}
909
910/// Helper struct to accept parse listener on already generated tree
911#[derive(Debug)]
912pub struct ParseTreeWalker;
913
914impl ParseTreeWalker {
915    /// Walks recursively over tree `t` with `listener`
916    pub fn walk<'input, 'arena, Node, Tok>(
917        mut listener: Box<Node::Listener>,
918        t: &TreeNode<'input, 'arena, Node, Tok>,
919    ) -> Result<Box<Node::Listener>, ANTLRError>
920    where
921        'input: 'arena,
922        Node: NodeKindType<'arena, Tok>,
923        Tok: Token + 'input,
924    {
925        if let Some(terminal) = t.as_terminal_node() {
926            listener.visit_terminal(terminal)?;
927            return Ok(listener);
928        }
929        if let Some(error) = t.as_error_node() {
930            listener.visit_error_node(error)?;
931            return Ok(listener);
932        }
933
934        Self::enter_rule(&mut *listener, t)?;
935        for child in t.get_children() {
936            listener = Self::walk(listener, child)?;
937        }
938        Self::exit_rule(&mut *listener, t)?;
939
940        Ok(listener)
941    }
942
943    fn enter_rule<'input, 'arena, Node, Tok>(
944        listener: &mut Node::Listener,
945        t: &TreeNode<'input, 'arena, Node, Tok>,
946    ) -> Result<(), ANTLRError>
947    where
948        'input: 'arena,
949        Node: NodeKindType<'arena, Tok>,
950        Tok: Token + 'input,
951    {
952        listener.enter_every_rule(t)?;
953        t.enter_rule(listener)
954    }
955
956    fn exit_rule<'input, 'arena, Node, Tok>(
957        listener: &mut Node::Listener,
958        t: &TreeNode<'input, 'arena, Node, Tok>,
959    ) -> Result<(), ANTLRError>
960    where
961        'input: 'arena,
962        Node: NodeKindType<'arena, Tok>,
963        Tok: Token + 'input,
964    {
965        t.exit_rule(listener)?;
966        listener.exit_every_rule(t)
967    }
968}