Skip to main content

dbt_antlr_runtime/
lib.rs

1#![crate_type = "lib"]
2// #![warn(missing_docs)] // warn if there is missing docs
3// #![warn(missing_debug_implementations)]
4// #![warn(trivial_numeric_casts)]
5
6//! # dbt-antlr-runtime runtime
7//!
8//! This is a Rust runtime for [ANTLR4] parser generator.
9//! It is required to use parsers and lexers generated by [ANTLR4] parser generator
10//!
11//! This documentation refers to particular api used by generated parsers,lexers and syntax trees.
12//!
13//! For info on what is [ANTLR4] and how to generate parser please refer to:
14//!  - [ANTLR4] main repository
15//!  - [README] for Rust target
16//!
17//! [ANTLR4]: https://github.com/antlr/antlr4
18//! [README]: https://github.com/sdf-labs/antlr4/blob/dev/runtime/Rust/README.md
19//!
20//! Documentation for this crate is still a work in progress, but you can find
21//! some docs in the source code, and also refer to the Java runtime
22//! documentation for general concepts and architecture of the runtime, as well
23//! as for documentation of internal modules that are not yet documented in
24//! Rust.
25//!
26//! [`CharStream`]: crate::char_stream::CharStream
27//! [`TokenFactory`]: crate::token_factory::TokenFactory
28//! [`Token`]: crate::token::Token
29//! [`TokenStream`]: crate::token_stream::TokenStream
30//! [`ParserRuleContext`]: crate::parser_rule_context::ParserRuleContext
31
32#[doc(inline)]
33pub use error_strategy::{BailErrorStrategy, DefaultErrorStrategy, ErrorStrategy};
34
35pub use input_stream::InputStream;
36
37pub mod predict_timing;
38
39#[doc(inline)]
40pub use lexer::{BaseLexer, Lexer};
41#[doc(inline)]
42pub use parser::{BaseParser, ListenerId, Parser};
43#[doc(hidden)]
44pub use prediction_context::PredictionContextCache;
45#[doc(inline)]
46pub use token_source::TokenSource;
47
48#[doc(inline)]
49pub use prediction_mode::PredictionMode;
50
51#[doc(inline)]
52pub use arena::Arena;
53#[cfg(feature = "arena-allocation-limit")]
54#[doc(inline)]
55pub use arena::{get_default_arena_alloc_limit, set_default_arena_alloc_limit};
56
57mod arena;
58#[doc(hidden)]
59pub mod atn_config;
60#[doc(hidden)]
61pub mod atn_simulator;
62pub mod int_stream;
63#[doc(hidden)]
64pub mod lexer_action;
65mod ll1_analyzer;
66#[doc(hidden)]
67pub mod recognizer;
68pub mod token_factory;
69//pub mod tokenstream_rewriter;
70#[doc(hidden)]
71pub mod atn_deserialization_options;
72#[doc(hidden)]
73pub mod atn_state;
74pub mod char_stream;
75#[doc(hidden)]
76pub mod interval_set;
77pub mod parser_rule_context;
78mod prediction_context;
79#[doc(hidden)]
80pub mod semantic_context;
81mod token_source;
82pub mod token_stream;
83//pub mod trace_listener;
84#[doc(hidden)]
85pub mod dfa;
86#[doc(hidden)]
87pub mod transition;
88pub mod tree;
89//pub mod file_stream;
90#[doc(hidden)]
91pub mod atn;
92#[doc(hidden)]
93pub mod atn_config_set;
94#[doc(hidden)]
95pub mod atn_deserializer;
96#[cfg(feature = "atn-dump")]
97#[doc(hidden)]
98pub mod atn_dump;
99#[doc(hidden)]
100pub mod atn_packed_deserializer;
101pub mod common_token_stream;
102pub mod error_listener;
103pub mod error_strategy;
104pub mod errors;
105pub mod input_stream;
106pub mod interpreter_rule_context;
107pub mod lexer;
108#[doc(hidden)]
109pub mod lexer_action_executor;
110pub mod lexer_atn_simulator;
111pub mod lexer_interpreter;
112pub mod parser;
113pub mod parser_atn_simulator;
114pub mod parser_interpreter;
115mod prediction_mode;
116pub mod token;
117pub mod trees;
118mod utils;
119//pub mod tokenstream_rewriter_test;
120#[doc(hidden)]
121pub mod atn_type;
122// mod context_factory;
123#[cfg(feature = "static-dfa-build")]
124pub mod analysis;
125pub mod prelude;
126pub mod rule_context;
127pub mod vocabulary;
128
129// ======= Re-exports ========
130#[cfg(feature = "stacker")]
131pub use stacker;
132
133pub const VERSION_MAJOR: &str = env!("CARGO_PKG_VERSION_MAJOR");
134pub const VERSION_MINOR: &str = env!("CARGO_PKG_VERSION_MINOR");
135
136// ======= Macros =======
137
138pub const fn version_str_eq(a: &str, b: &str) -> bool {
139    if a.len() != b.len() {
140        return false;
141    }
142    let (a, b) = (a.as_bytes(), b.as_bytes());
143    let mut i = 0;
144    while i < a.len() {
145        if a[i] != b[i] {
146            return false;
147        }
148        i += 1;
149    }
150    true
151}
152/// Parses a numeric version component (e.g. `"13"`) in const context.
153///
154/// Public only so [`check_version!`] can reference it from downstream crates.
155#[doc(hidden)]
156pub const fn version_str_to_u64(s: &str) -> u64 {
157    let bytes = s.as_bytes();
158    let mut n: u64 = 0;
159    let mut i = 0;
160    while i < bytes.len() {
161        let b = bytes[i];
162        assert!(b >= b'0' && b <= b'9', "version component is not numeric");
163        n = n * 10 + (b - b'0') as u64;
164        i += 1;
165    }
166    n
167}
168
169/// Compile-time compatibility gate between generated code and the runtime.
170///
171/// Generated parsers embed `check_version!("<major>", "<minor>")` naming the
172/// runtime version the generating tool was built against. The check passes
173/// when the linked runtime has the same major version and a minor version
174/// greater than or equal to the generated one: additive runtime releases never
175/// break previously generated code, while a runtime older than the generator
176/// (or a different major) fails to compile with a clear message.
177#[macro_export]
178macro_rules! check_version {
179    ($major:literal, $minor:literal) => {
180        const _: () = assert!(
181            $crate::version_str_eq($major, $crate::VERSION_MAJOR)
182                && $crate::version_str_to_u64($crate::VERSION_MINOR)
183                    >= $crate::version_str_to_u64($minor),
184            "Generated parser is not compatible with the current runtime version: \
185             it requires the same major version of dbt-antlr-runtime and at least \
186             the minor version used at generation time. Update the runtime \
187             dependency, or regenerate using an older ANTLR tool version."
188        );
189    };
190}
191#[macro_export]
192macro_rules! impl_tree {
193    // Pattern: EnumName { Variant1, Variant2, ... }
194    ($enum_name:ident { $($variant:ident,)+ }) => {
195        impl<'input, 'arena> Tree<'arena> for $enum_name<'input, 'arena> {
196            fn get_parent(&self) -> Option<&'arena Self> {
197                match self {
198                    $( $enum_name::$variant(inner) => inner.get_parent(), )+
199                    _ => None,
200                }
201            }
202
203            fn has_parent(&self) -> bool {
204                match self {
205                    $( $enum_name::$variant(inner) => inner.has_parent(), )+
206                    _ => false,
207                }
208            }
209
210            // fn get_payload(&self) -> Box<dyn std::any::Any> {
211            //     match self {
212            //         $( $enum_name::$variant(inner) => Tree::get_payload(inner), )+
213            //     }
214            // }
215
216            fn get_child(&self, i: usize) -> Option<&'arena Self> {
217                match self {
218                    $( $enum_name::$variant(inner) => inner.get_child(i), )+
219                    _ => None,
220                }
221            }
222
223            fn get_child_count(&self) -> usize {
224                match self {
225                    $( $enum_name::$variant(inner) => inner.get_child_count(), )+
226                    _ => 0,
227                }
228            }
229
230            fn get_children<'a>(&'a self) -> Box<dyn Iterator<Item = &'arena Self> + 'a> {
231                match self {
232                    $( $enum_name::$variant(inner) => inner.get_children(), )+
233                    _ => Box::new(std::iter::empty()) as Box<dyn Iterator<Item = &'arena Self>>,
234                }
235            }
236
237            // fn to_string_tree(&self) -> String {
238            //     match self {
239            //         $( $enum_name::$variant(inner) => Tree::to_string_tree(inner), )+
240            //     }
241            // }
242        }
243    };
244}
245
246#[macro_export]
247macro_rules! impl_node_kind_common {
248    // Pattern: EnumName { Variant1, Variant2, ... }
249    ($node_kind:ident { $($labeled_variant:ident($inner:ident),)* ; $($variant:ident),* }) => {
250        fn cast_to_ctx<'n, 'input: 'arena>(
251            node: &'n TreeNode<'input, 'arena, Self, Tok>,
252        ) -> &'n dyn ParserRuleContext<'input, 'arena> {
253            match node.node_tag() {
254                $( $node_kind::$labeled_variant => $crate::cast_unchecked!(node => $inner<'input, 'arena, Tok>), )*
255                $( $node_kind::$variant => $crate::cast_unchecked!(node.ctx_ptr() => $variant<'input, 'arena, Tok>), )*
256                $node_kind::Terminal => $crate::cast_unchecked!(node.ctx_ptr() => TerminalNode<'input, 'arena, Tok>),
257                $node_kind::Error => $crate::cast_unchecked!(node.ctx_ptr() => ErrorNode<'input, 'arena, Tok>),
258            }
259        }
260
261        fn cast_to_ctx_mut<'n, 'input: 'arena>(
262            node: &'n mut TreeNode<'input, 'arena, Self, Tok>,
263        ) -> &'n mut dyn ParserRuleContext<'input, 'arena> {
264            match node.node_tag() {
265                $( $node_kind::$labeled_variant => $crate::cast_unchecked!(node => mut $inner<'input, 'arena, Tok>), )*
266                $( $node_kind::$variant => $crate::cast_unchecked!(node.ctx_ptr() => mut $variant<'input, 'arena, Tok>), )*
267                $node_kind::Terminal => $crate::cast_unchecked!(node.ctx_ptr() => mut TerminalNode<'input, 'arena, Tok>),
268                $node_kind::Error => $crate::cast_unchecked!(node.ctx_ptr() => mut ErrorNode<'input, 'arena, Tok>),
269            }
270        }
271
272        fn set_alt_number<'input: 'arena>(node: &mut TreeNode<'input, 'arena, Self, Tok>, alt_number: i32) {
273            match node.node_tag() {
274                $( $node_kind::$labeled_variant => $crate::cast_unchecked!(node => mut $inner<'input, 'arena, Tok>).set_alt_number(alt_number), )*
275                $( $node_kind::$variant => $crate::cast_unchecked!(node.ctx_ptr() => mut $variant<'input, 'arena, Tok>).set_alt_number(alt_number), )*
276                _ => {}
277            }
278        }
279
280        fn get_rule_index<'input: 'arena>(node: &TreeNode<'input, 'arena, Self, Tok>) -> usize {
281            match node.node_tag() {
282                $( $node_kind::$labeled_variant => $crate::cast_unchecked!(node => $inner<'input, 'arena, Tok>).get_rule_index(), )*
283                $( $node_kind::$variant => $crate::cast_unchecked!(node.ctx_ptr() => $variant<'input, 'arena, Tok>).get_rule_index(), )*
284                _ => 0,
285            }
286        }
287
288        fn get_alt_number<'input: 'arena>(node: &TreeNode<'input, 'arena, Self, Tok>) -> i32 {
289            match node.node_tag() {
290                $( $node_kind::$labeled_variant => $crate::cast_unchecked!(node => $inner<'input, 'arena, Tok>).get_alt_number(), )*
291                $( $node_kind::$variant => $crate::cast_unchecked!(node.ctx_ptr() => $variant<'input, 'arena, Tok>).get_alt_number(), )*
292                _ => INVALID_ALT,
293            }
294        }
295
296        #[inline]
297        fn terminal() -> Self {
298            Self::Terminal
299        }
300
301        #[inline]
302        fn error() -> Self {
303            Self::Error
304        }
305
306        #[inline]
307        fn is_context(&self) -> bool {
308            !matches!(self, Self::Terminal | Self::Error)
309        }
310    };
311}
312
313#[macro_export]
314macro_rules! impl_node_kind {
315    // No Listener and no Visitor
316    //
317    // The template still emits the empty visit-method slot per variant
318    // (`SContext()`), so the arm accepts both spellings.
319    ($enum_name:ident { $($labeled_variant:ident($inner:ident),)* ; $($variant:ident $(())?,)* }; ) => {
320        impl<'arena, Tok: Token + 'arena> NodeKindType<'arena, Tok> for $enum_name {
321            type Listener = dyn ParseTreeListener<'arena, Self, Tok>;
322
323            $crate::impl_node_kind_common! { $enum_name { $($labeled_variant($inner),)* ; $($variant),* } }
324
325            fn enter_rule<'input: 'arena>(_node: &TreeNode<'input, 'arena, Self, Tok>, _listener: &mut Self::Listener) -> Result<(), ANTLRError> {
326                Ok(())
327            }
328
329            fn exit_rule<'input: 'arena>(_node: &TreeNode<'input, 'arena, Self, Tok>, _listener: &mut Self::Listener) -> Result<(), ANTLRError> {
330                Ok(())
331            }
332        }
333    };
334
335    // Just Visitor
336    ($enum_name:ident { $($labeled_variant:ident($inner:ident),)*; $($variant:ident($visit_method:ident),)* }; visitor = $visitor:ty, ) => {
337        impl<'arena, Tok: Token + 'arena> NodeKindType<'arena, Tok> for $enum_name {
338            type Listener = dyn ParseTreeListener<'arena, Self, Tok>;
339
340            $crate::impl_node_kind_common! { $enum_name { $( $labeled_variant($inner),)*; $($variant),* } }
341
342            fn enter_rule(_node: &TreeNode<'input, 'arena, Self, Tok>, _listener: &mut Self::Listener) -> Result<(), ANTLRError> {
343                Ok(())
344            }
345
346            fn exit_rule(_node: &TreeNode<'input, 'arena, Self, Tok>, _listener: &mut Self::Listener) -> Result<(), ANTLRError> {
347                Ok(())
348            }
349
350            // fn accept(&self, visitor: &mut Self::Visitor) -> Result<<Self::Visitor as ParseTreeVisitor<'input, 'arena, Self>>::Return, ANTLRError>
351            // {
352            //     match self {
353            //         $( $enum_name::$labeled_variant(inner) => inner.dispatch_visit(visitor), )*
354            //         $( $enum_name::$variant(inner) => visitor.$visit_method(inner), )*
355            //         $enum_name::Terminal(inner) => { visitor.visit_terminal(inner) },
356            //         $enum_name::Error(inner) => { visitor.visit_error_node(inner) },
357            //     }
358            // }
359        }
360    };
361
362    // Just Listener
363    ($enum_name:ident { $($labeled_variant:ident($inner:ident),)*; $($variant:ident($enter_method:ident, $exit_method:ident, ),)* }; listener = $listener:ty, ) => {
364        impl<'arena, Tok: Token + 'arena> NodeKindType<'arena, Tok> for $enum_name {
365            type Listener = $listener;
366
367            $crate::impl_node_kind_common! { $enum_name { $( $labeled_variant($inner),)*; $($variant),* } }
368
369            fn enter_rule<'input: 'arena>(node: &TreeNode<'input, 'arena, Self, Tok>, listener: &mut Self::Listener) -> Result<(), ANTLRError> {
370                match node.node_tag() {
371                    $( $enum_name::$labeled_variant => $crate::cast_unchecked!(node => $inner<'input, 'arena, Tok>).dispatch_enter(listener), )*
372                    $( $enum_name::$variant => listener.$enter_method($crate::cast_unchecked!(node.ctx_ptr() => $variant<'input, 'arena, Tok>)), )*
373                    $enum_name::Terminal => { listener.visit_terminal($crate::cast_unchecked!(node.ctx_ptr() => TerminalNode<'input, 'arena, Tok>)) },
374                    $enum_name::Error => { listener.visit_error_node($crate::cast_unchecked!(node.ctx_ptr() => ErrorNode<'input, 'arena, Tok>)) },
375                }
376            }
377
378            fn exit_rule<'input: 'arena>(node: &TreeNode<'input, 'arena, Self, Tok>, listener: &mut Self::Listener) -> Result<(), ANTLRError> {
379                match node.node_tag() {
380                    $( $enum_name::$labeled_variant => $crate::cast_unchecked!(node => $inner<'input, 'arena, Tok>).dispatch_exit(listener), )*
381                    $( $enum_name::$variant => listener.$exit_method($crate::cast_unchecked!(node.ctx_ptr() => $variant<'input, 'arena, Tok>)), )*
382                    $enum_name::Terminal => { listener.visit_terminal($crate::cast_unchecked!(node.ctx_ptr() => TerminalNode<'input, 'arena, Tok>)) },
383                    $enum_name::Error => { listener.visit_error_node($crate::cast_unchecked!(node.ctx_ptr() => ErrorNode<'input, 'arena, Tok>)) },
384                }
385            }
386        }
387    };
388
389    // Both listener and visitor
390    ($enum_name:ident { $($labeled_variant:ident($inner:ident),)*; $($variant:ident($enter_method:ident, $exit_method:ident, $visit_method:ident),)* }; listener = $listener:ty, visitor = $visitor:ident, ) => {
391        impl<'arena, Tok: Token + 'arena> NodeKindType<'arena, Tok> for $enum_name {
392            type Listener = $listener;
393
394            $crate::impl_node_kind_common! { $enum_name { $($labeled_variant($inner),)*; $($variant),* } }
395
396            fn enter_rule<'input: 'arena>(node: &TreeNode<'input, 'arena, Self, Tok>, listener: &mut Self::Listener) -> Result<(), ANTLRError> {
397                match node.node_tag() {
398                    $( $enum_name::$labeled_variant => $crate::cast_unchecked!(node => $inner<'input, 'arena, Tok>).dispatch_enter(listener), )*
399                    $( $enum_name::$variant => listener.$enter_method($crate::cast_unchecked!(node.ctx_ptr() => $variant<'input, 'arena, Tok>)), )*
400                    $enum_name::Terminal => { listener.visit_terminal($crate::cast_unchecked!(node.ctx_ptr() => TerminalNode<'input, 'arena, Tok>)) },
401                    $enum_name::Error => { listener.visit_error_node($crate::cast_unchecked!(node.ctx_ptr() => ErrorNode<'input, 'arena, Tok>)) },
402                }
403            }
404
405            fn exit_rule<'input: 'arena>(node: &TreeNode<'input, 'arena, Self, Tok>, listener: &mut Self::Listener) -> Result<(), ANTLRError> {
406                match node.node_tag() {
407                    $( $enum_name::$labeled_variant => $crate::cast_unchecked!(node => $inner<'input, 'arena, Tok>).dispatch_exit(listener), )*
408                    $( $enum_name::$variant => listener.$exit_method($crate::cast_unchecked!(node.ctx_ptr() => $variant<'input, 'arena, Tok>)), )*
409                    $enum_name::Terminal => { listener.visit_terminal($crate::cast_unchecked!(node.ctx_ptr() => TerminalNode<'input, 'arena, Tok>)) },
410                    $enum_name::Error => { listener.visit_error_node($crate::cast_unchecked!(node.ctx_ptr() => ErrorNode<'input, 'arena, Tok>)) },
411                }
412            }
413        }
414
415        impl<'input, 'arena, Tok: Token + 'arena> Visitable<'input, 'arena, Tok> for TreeNode<'input, 'arena, $enum_name, Tok>
416        where
417            'input: 'arena,
418        {
419            fn accept<V>(&'arena self, visitor: &mut V) -> Result<V::Return, ANTLRError>
420            where
421                V: $visitor<'input, 'arena, Tok> + ?Sized,
422            {
423                match self.node_tag() {
424                    $( $enum_name::$labeled_variant => $crate::cast_unchecked!(self => $inner<'input, 'arena, Tok>).accept(visitor), )*
425                    $( $enum_name::$variant => visitor.$visit_method($crate::cast_unchecked!(self.ctx_ptr() => $variant<'input, 'arena, Tok>)), )+
426                    $enum_name::Terminal => { visitor.visit_terminal($crate::cast_unchecked!(self.ctx_ptr() => TerminalNode<'input, 'arena, Tok>)) },
427                    $enum_name::Error => { visitor.visit_error_node($crate::cast_unchecked!(self.ctx_ptr() => ErrorNode<'input, 'arena, Tok>)) },
428                }
429            }
430        }
431    };
432}
433
434#[macro_export]
435macro_rules! impl_listener_dispatch {
436    // Pattern: EnumName { Variant1, Variant2, ... }
437    ($listener:ident::$node_name:ident::$enum_name:ident { $($variant:ident($enter_method:ident, $exit_method:ident),)+ }) => {
438        impl<'input, 'arena, Tok: Token + 'input> $enum_name<'input, 'arena, Tok>
439        where
440            'input: 'arena,
441        {
442            fn dispatch_enter(&self, listener: &mut (dyn $listener<'arena, Tok> + 'static)) -> Result<(), ANTLRError>
443            {
444                match self {
445                    $( $enum_name::$variant(inner) => listener.$enter_method(inner), )+
446                    $enum_name::Error(_) => Ok(()),
447                }
448            }
449
450            fn dispatch_exit(&self, listener: &mut (dyn $listener<'arena, Tok> + 'static)) -> Result<(), ANTLRError>
451            {
452                match self {
453                    $( $enum_name::$variant(inner) => listener.$exit_method(inner), )+
454                    $enum_name::Error(_) => Ok(()),
455                }
456            }
457        }
458    };
459}
460
461#[macro_export]
462macro_rules! impl_visitable {
463    // Pattern: EnumName { Variant1, Variant2, ... }
464    ($visitor:ident::$enum_name:ident { $($variant:ident($visit_method:ident),)+ }) => {
465        impl<'input, 'arena, Tok: Token + 'input> Visitable<'input, 'arena, Tok> for $enum_name<'input, 'arena, Tok> {
466            fn accept<V>(&'arena self, visitor: &mut V) -> Result<V::Return, ANTLRError>
467            where
468                V: $visitor<'input, 'arena, Tok> + ?Sized,
469            {
470                match self {
471                    $( $enum_name::$variant(inner) => visitor.$visit_method(inner), )+
472                    $enum_name::Error(_) => Ok(Default::default()),
473                }
474            }
475        }
476    };
477    ($visitor:ident::$ctx_name:ident($visit_method:ident)) => {
478        impl<'input, 'arena, Tok: Token + 'input> Visitable<'input, 'arena, Tok> for $ctx_name<'input, 'arena, Tok> {
479            fn accept<V>(&'arena self, visitor: &mut V) -> Result<V::Return, ANTLRError>
480            where
481                V: $visitor<'input, 'arena, Tok> + ?Sized,
482            {
483                visitor.$visit_method(self)
484            }
485        }
486    };
487}
488
489#[macro_export]
490macro_rules! impl_rule_context {
491    // Pattern: EnumName { Variant1, Variant2, ... }
492    ($enum_name:ident { $($ref_variant:ident,)* } $({ $($inline_variant:ident,)+ })?) => {
493        impl<'input, 'arena, Tok> RuleContext<'arena> for $enum_name<'input, 'arena, Tok>
494        where
495            'input: 'arena,
496            Tok: Token + 'input,
497        {
498            fn get_rule_index(&self) -> usize {
499                match self {
500                    // Generate a match arm for every variant
501                    $( $enum_name::$ref_variant(inner) => RuleContext::get_rule_index(&**inner), )*
502                    $($( $enum_name::$inline_variant(inner) => RuleContext::get_rule_index(inner), )+)?
503                }
504            }
505
506            fn get_alt_number(&self) -> i32 {
507                match self {
508                    $( $enum_name::$ref_variant(inner) => RuleContext::get_alt_number(&**inner), )*
509                    $($( $enum_name::$inline_variant(inner) => RuleContext::get_alt_number(inner), )+)?
510                }
511            }
512
513            fn get_invoking_state(&self) -> i32 {
514                match self {
515                    $( $enum_name::$ref_variant(inner) => RuleContext::get_invoking_state(&**inner), )*
516                    $($( $enum_name::$inline_variant(inner) => RuleContext::get_invoking_state(inner), )+)?
517                }
518            }
519
520            fn get_parent_ctx(&self) -> Option<&'arena dyn RuleContext<'arena>> {
521                match self {
522                    $( $enum_name::$ref_variant(inner) => RuleContext::get_parent_ctx(&**inner), )*
523                    $($( $enum_name::$inline_variant(inner) => RuleContext::get_parent_ctx(inner), )+)?
524                }
525            }
526
527            fn get_node_text(&self, rule_names: &[&str]) -> String {
528                match self {
529                    $( $enum_name::$ref_variant(inner) => RuleContext::get_node_text(&**inner, rule_names), )*
530                    $($( $enum_name::$inline_variant(inner) => RuleContext::get_node_text(inner, rule_names), )+)?
531                }
532            }
533
534        }
535    };
536}
537
538#[macro_export]
539macro_rules! impl_parser_rule_context {
540    // Pattern: EnumName { Variant1, Variant2, ... }
541    ($enum_name:ident { $($ref_variant:ident,)* } $({ $($inline_variant:ident,)+ })?) => {
542        impl<'input, 'arena, Tok> ParserRuleContext<'input, 'arena> for $enum_name<'input, 'arena, Tok>
543        where
544            'input: 'arena,
545            Tok: Token + 'input,
546        {
547            fn start(&self) -> &'arena dyn $crate::token::Token {
548                match self {
549                    $( $enum_name::$ref_variant(inner) => ParserRuleContext::start(&**inner), )*
550                    $($( $enum_name::$inline_variant(inner) => ParserRuleContext::start(inner), )+)?
551                }
552            }
553
554            fn stop(&self) -> &'arena dyn $crate::token::Token {
555                match self {
556                    $( $enum_name::$ref_variant(inner) => ParserRuleContext::stop(&**inner), )*
557                    $($( $enum_name::$inline_variant(inner) => ParserRuleContext::stop(inner), )+)?
558                }
559            }
560
561            fn get_parent_ctx(&self) -> Option<&'arena dyn ParserRuleContext<'input, 'arena>> {
562                match self {
563                    $( $enum_name::$ref_variant(inner) => ParserRuleContext::get_parent_ctx(&**inner), )*
564                    $($( $enum_name::$inline_variant(inner) => ParserRuleContext::get_parent_ctx(inner), )+)?
565                }
566            }
567
568            fn get_child_ctx(&self, _i: usize) -> Option<&'arena dyn ParserRuleContext<'input, 'arena>> {
569                match self {
570                    $( $enum_name::$ref_variant(inner) => ParserRuleContext::get_child_ctx(&**inner, _i), )*
571                    $($( $enum_name::$inline_variant(inner) => ParserRuleContext::get_child_ctx(inner, _i), )+)?
572                }
573            }
574
575            fn get_child_count(&self) -> usize {
576                match self {
577                    $( $enum_name::$ref_variant(inner) => ParserRuleContext::get_child_count(&**inner), )*
578                    $($( $enum_name::$inline_variant(inner) => ParserRuleContext::get_child_count(inner), )+)?
579                }
580            }
581
582            fn iter_children<'a>(
583                &'a self,
584            ) -> Box<dyn Iterator<Item = &'arena dyn ParserRuleContext<'input, 'arena>> + 'a>
585            where
586                'input: 'a,
587                'arena: 'a,
588            {
589                match self {
590                    $( $enum_name::$ref_variant(inner) => ParserRuleContext::iter_children(&**inner), )*
591                    $($( $enum_name::$inline_variant(inner) => ParserRuleContext::iter_children(inner), )+)?
592                }
593            }
594
595            fn get_token(&self, _ttype: i32, _pos: usize) -> Option<&dyn $crate::token::Token> {
596                match self {
597                    $( $enum_name::$ref_variant(inner) => ParserRuleContext::get_token(&**inner, _ttype, _pos), )*
598                    $($( $enum_name::$inline_variant(inner) => ParserRuleContext::get_token(inner, _ttype, _pos), )+)?
599                }
600            }
601
602            fn get_tokens(&self, _ttype: i32) -> Vec<&dyn $crate::token::Token> {
603                match self {
604                    $( $enum_name::$ref_variant(inner) => ParserRuleContext::get_tokens(&**inner, _ttype), )*
605                    $($( $enum_name::$inline_variant(inner) => ParserRuleContext::get_tokens(inner, _ttype), )+)?
606                }
607            }
608
609            fn get_text(&self) -> String {
610                match self {
611                    $( $enum_name::$ref_variant(inner) => ParserRuleContext::get_text(&**inner), )*
612                    $($( $enum_name::$inline_variant(inner) => ParserRuleContext::get_text(inner), )+)?
613                }
614            }
615       }
616    };
617}
618
619#[macro_export]
620macro_rules! impl_tree_trait_delegates {
621    ($node_kind:ident::$enum_name:ident { $($variant:ident),+ $(,)? }) => {
622        impl<'input, 'arena, Tok> $enum_name<'input, 'arena, Tok>
623        where
624            'input: 'arena,
625            Tok: Token + 'input,
626        {
627            // fn get_parent(&self) -> Option<&'arena TreeNode<'input, 'arena, $node_kind>> {
628            //     match self {
629            //         $( $enum_name::$variant(inner) => inner.get_parent(), )+
630            //     }
631            // }
632
633            // fn has_parent(&self) -> bool {
634            //     match self {
635            //         $( $enum_name::$variant(inner) => inner.has_parent(), )+
636            //     }
637            // }
638
639            // fn get_child(&self, i: usize) -> Option<&'arena TreeNode<'input, 'arena, $node_kind>> {
640            //     match self {
641            //         $( $enum_name::$variant(inner) => inner.get_child(i), )+
642            //     }
643            // }
644
645            // fn get_child_count(&self) -> usize {
646            //     match self {
647            //         $( $enum_name::$variant(inner) => inner.get_child_count(), )+
648            //     }
649            // }
650
651            // fn get_children<'a>(&'a self) -> Box<dyn Iterator<Item = &'arena TreeNode<'input, 'arena, $node_kind>> + 'a> {
652            //     match self {
653            //         $( $enum_name::$variant(inner) => inner.get_children(), )+
654            //     }
655            // }
656
657            // fn set_start(&mut self, t: Option<&'arena dyn $crate::token::Token>) {
658            //     match self {
659            //         $( $enum_name::$variant(inner) => inner.set_start(t), )+
660            //     }
661            // }
662
663            // fn set_stop(&mut self, t: Option<&'arena dyn $crate::token::Token>) {
664            //     match self {
665            //         $( $enum_name::$variant(inner) => inner.set_stop(t), )+
666            //     }
667            // }
668
669            // fn set_parent(&mut self, parent: Option<&'arena TreeNode<'input, 'arena, $node_kind>>) {
670            //     match self {
671            //         $( $enum_name::$variant(inner) => inner.set_parent(parent), )+
672            //     }
673            // }
674
675            // fn set_invoking_state(&mut self, t: i32) {
676            //     match self {
677            //         $( $enum_name::$variant(inner) => inner.set_invoking_state(t), )+
678            //     }
679            // }
680
681            fn set_alt_number(&mut self, alt_number: i32) {
682                match self {
683                    $( $enum_name::$variant(inner) => inner.set_alt_number(alt_number), )+
684                }
685            }
686
687            // fn set_exception(&self, e: $crate::errors::ANTLRError, arena: &'arena $crate::Arena) {
688            //     match self {
689            //         $( $enum_name::$variant(inner) => inner.set_exception(e, arena), )+
690            //     }
691            // }
692
693            // fn remove_last_child(&mut self) {
694            //     match self {
695            //         $( $enum_name::$variant(inner) => inner.remove_last_child(), )+
696            //     }
697            // }
698
699            // fn add_child(&mut self, child: &'arena TreeNode<'input, 'arena, $node_kind>) {
700            //     match self {
701            //         $( $enum_name::$variant(inner) => inner.add_child(child), )+
702            //     }
703            // }
704        }
705    };
706}
707
708#[macro_export]
709macro_rules! impl_node_inner {
710    ($node_kind:ident::$node_variant:ident::$context_all:ident { $($variant:ident),+ $(,)? }) => {
711        impl<'input, 'arena, Tok> NodeInner<'input, 'arena, $node_kind, Tok>
712            for $context_all<'input, 'arena, Tok>
713        where
714            'input: 'arena,
715            Tok: Token + 'input,
716        {
717            fn cast_from<'a>(node: &'a TreeNode<'input, 'arena, $node_kind, Tok>) -> Option<&'a Self> {
718                match node.node_tag() {
719                    $node_kind::$node_variant => Some($crate::cast_unchecked!(node => Self)),
720                    _ => None,
721                }
722            }
723
724            fn cast_from_mut<'a>(node: &'a mut TreeNode<'input, 'arena, $node_kind, Tok>) -> Option<&'a mut Self>
725            where
726                Self: Sized,
727            {
728                match node.node_tag() {
729                    $node_kind::$node_variant => Some($crate::cast_unchecked!(node => mut Self)),
730                    _ => None,
731                }
732            }
733
734            fn as_node(&self) -> &TreeNode<'input, 'arena, $node_kind, Tok> {
735                $crate::cast_unchecked!(self => TreeNode<'input, 'arena, $node_kind, Tok>)
736            }
737
738            fn as_node_mut(&mut self) -> &mut TreeNode<'input, 'arena, $node_kind, Tok> {
739                $crate::cast_unchecked!(self => mut TreeNode<'input, 'arena, $node_kind, Tok>)
740            }
741
742            fn iter_child_nodes<'a>(&'a self) -> Box<dyn Iterator<Item = &'arena TreeNode<'input, 'arena, $node_kind, Tok>> + 'a> {
743                match self {
744                    $( $context_all::$variant(inner) => inner.get_children(), )+
745                }
746            }
747        }
748    };
749}
750
751#[macro_export]
752macro_rules! impl_token_source {
753    ($lexer:ident) => {
754        impl<'input, 'arena, Input, TF> $crate::TokenSource<'input, 'arena, TF>
755            for $lexer<'input, 'arena, Input, TF>
756        where
757            TF: $crate::token_factory::TokenFactory<'input, 'arena> + 'arena,
758            Input: $crate::char_stream::CharStream<'input>,
759        {
760            fn next_token(&mut self) -> &'arena mut TF::Tok {
761                self.base.next_token()
762            }
763
764            fn get_line(&self) -> u32 {
765                self.base.get_line()
766            }
767
768            fn get_char_position_in_line(&self) -> i32 {
769                self.base.get_char_position_in_line()
770            }
771
772            fn get_input_stream(&mut self) -> Option<&mut dyn $crate::int_stream::IntStream> {
773                self.base.get_input_stream()
774            }
775
776            fn get_source_name(&self) -> String {
777                self.base.get_source_name()
778            }
779
780            fn get_token_factory(&self) -> &TF {
781                self.base.get_token_factory()
782            }
783
784            fn get_dfa_string(&self) -> String {
785                self.base.get_dfa_string()
786            }
787        }
788    };
789}
790
791#[macro_export]
792macro_rules! impl_deref {
793    (parser => $parser_name:ident) => {
794        impl<'input, 'arena, Input, TF> Deref for $parser_name<'input, 'arena, Input, TF>
795        where
796            'input: 'arena,
797            TF: TokenFactory<'input, 'arena> + 'arena,
798            Input: TokenStream<'input, 'arena, TF> + 'arena,
799        {
800            type Target = BaseParserType<'input, 'arena, Input, TF>;
801            fn deref(&self) -> &Self::Target {
802                &self.base
803            }
804        }
805
806        impl<'input, 'arena, Input, TF> DerefMut for $parser_name<'input, 'arena, Input, TF>
807        where
808            'input: 'arena,
809            TF: TokenFactory<'input, 'arena> + 'arena,
810            Input: TokenStream<'input, 'arena, TF> + 'arena,
811        {
812            fn deref_mut(&mut self) -> &mut Self::Target {
813                &mut self.base
814            }
815        }
816    };
817    (lexer => $lexer_name:ident) => {
818        impl<'input, 'arena, Input, TF> Deref for $lexer_name<'input, 'arena, Input, TF>
819        where
820            'input: 'arena,
821            TF: TokenFactory<'input, 'arena> + 'arena,
822            Input: CharStream<'input> + 'arena,
823        {
824            type Target = BaseLexerType<'input, 'arena, Input, TF>;
825            fn deref(&self) -> &Self::Target {
826                &self.base
827            }
828        }
829
830        impl<'input, 'arena, Input, TF> DerefMut for $lexer_name<'input, 'arena, Input, TF>
831        where
832            'input: 'arena,
833            TF: TokenFactory<'input, 'arena> + 'arena,
834            Input: CharStream<'input> + 'arena,
835        {
836            fn deref_mut(&mut self) -> &mut Self::Target {
837                &mut self.base
838            }
839        }
840    };
841}
842
843pub const STACKER_RED_ZONE_BYTES: usize = 64 * 1024;
844pub const STACKER_GROWTH_BYTES: usize = 1024 * 1024;
845
846#[cfg(feature = "stacker")]
847#[macro_export]
848macro_rules! maybe_grow_stack {
849    ($body:block) => {
850        $crate::stacker::maybe_grow(
851            $crate::STACKER_RED_ZONE_BYTES,
852            $crate::STACKER_GROWTH_BYTES,
853            || $body,
854        )
855    };
856}
857#[cfg(not(feature = "stacker"))]
858#[macro_export]
859macro_rules! maybe_grow_stack {
860    ($body:block) => {
861        $body
862    };
863}
864
865#[macro_export]
866macro_rules! cast_unchecked {
867    ($ptr:expr => $target:ty) => {{
868        let ptr = ($ptr as *const _ as *const ()).cast::<$target>();
869        unsafe { &*ptr }
870    }};
871    ($ptr:expr => mut $target:ty) => {{
872        let ptr = ($ptr as *mut _ as *mut ()).cast::<$target>();
873        unsafe { &mut *ptr }
874    }};
875}
876
877#[macro_export]
878macro_rules! impl_ctx {
879    ($nodekind:ident, $ctx:ident, $ext:ident, $rule:expr) => {
880        pub type $ctx<'input, 'arena, Tok = $crate::token::CommonToken<'input>> =
881            $crate::parser_rule_context::BaseParserRuleContext<
882                'input,
883                'arena,
884                $ext<'input, 'arena, Tok>,
885                $nodekind,
886                Tok,
887            >;
888
889        #[derive(Debug)]
890        pub struct $ext<'input: 'arena, 'arena, Tok: $crate::token::Token + 'input = $crate::token::CommonToken<'input>> {
891            ph: ::std::marker::PhantomData<(&'arena (), &'input Tok)>,
892        }
893
894        impl<'input: 'arena, 'arena, Tok: $crate::token::Token + 'input> $ext<'input, 'arena, Tok> {
895            fn create(
896                arena: &'arena $crate::Arena,
897                parent: ::std::option::Option<
898                    &'arena $crate::tree::TreeNode<'input, 'arena, $nodekind, Tok>,
899                >,
900                invoking_state: i32,
901            ) -> ::std::result::Result<
902                &'arena mut $crate::tree::TreeNode<'input, 'arena, $nodekind, Tok>,
903                $crate::errors::ANTLRError,
904            > {
905                $crate::parser_rule_context::BaseParserRuleContext::create(
906                    arena,
907                    parent,
908                    invoking_state,
909                    $ext {
910                        ph: ::std::marker::PhantomData,
911                    },
912                )
913            }
914        }
915
916        $crate::impl_ctx!(@plain $nodekind::$ctx, $ext, $rule);
917    };
918
919    (@plain $nodekind:ident::$variant:ident, $ext:ident, $rule:expr) => {
920        impl<'input: 'arena, 'arena, Tok> $crate::rule_context::CustomRuleContext<'input, 'arena, Tok>
921            for $ext<'input, 'arena, Tok>
922        where
923            Tok: $crate::token::Token + 'input,
924        {
925            type NodeKind = $nodekind;
926
927            fn node_tag() -> $nodekind {
928                $nodekind::$variant
929            }
930
931            fn get_rule_index(&self) -> usize {
932                $rule
933            }
934
935            fn make_node(
936                arena: &'arena $crate::Arena,
937                ctx: $crate::parser_rule_context::BaseParserRuleContext<
938                    'input,
939                    'arena,
940                    Self,
941                    Self::NodeKind,
942                    Tok,
943                >,
944            ) -> *mut $crate::tree::TreeNode<'input, 'arena, Self::NodeKind, Tok> {
945                arena.alloc_zeroed_node(ctx)
946            }
947
948            fn cast_from<'a>(
949                node: &'a $crate::tree::TreeNode<'input, 'arena, Self::NodeKind, Tok>,
950            ) -> ::std::option::Option<
951                &'a $crate::parser_rule_context::BaseParserRuleContext<
952                    'input,
953                    'arena,
954                    Self,
955                    Self::NodeKind,
956                    Tok,
957                >,
958            > {
959                if node.node_tag()
960                    == <Self as $crate::rule_context::CustomRuleContext<'input, 'arena, Tok>>::node_tag()
961                {
962                    ::std::option::Option::Some($crate::cast_unchecked!(node.ctx_ptr() => $crate::parser_rule_context::BaseParserRuleContext<'input, 'arena, Self, Self::NodeKind, Tok>))
963                } else {
964                    ::std::option::Option::None
965                }
966            }
967
968            fn cast_from_mut<'a>(
969                node: &'a mut $crate::tree::TreeNode<'input, 'arena, Self::NodeKind, Tok>,
970            ) -> ::std::option::Option<
971                &'a mut $crate::parser_rule_context::BaseParserRuleContext<
972                    'input,
973                    'arena,
974                    Self,
975                    Self::NodeKind,
976                    Tok,
977                >,
978            > {
979                if node.node_tag()
980                    == <Self as $crate::rule_context::CustomRuleContext<'input, 'arena, Tok>>::node_tag()
981                {
982                    ::std::option::Option::Some($crate::cast_unchecked!(node.ctx_ptr() => mut $crate::parser_rule_context::BaseParserRuleContext<'input, 'arena, Self, Self::NodeKind, Tok>))
983                } else {
984                    ::std::option::Option::None
985                }
986            }
987        }
988    };
989
990    (@labeled $nodekind:ident::$variant:ident, $ctxall:ident, $ext:ident, $rule:expr) => {
991        impl<'input: 'arena, 'arena, Tok> $crate::rule_context::CustomRuleContext<'input, 'arena, Tok>
992            for $ext<'input, 'arena, Tok>
993        where
994            Tok: $crate::token::Token + 'input,
995        {
996            type NodeKind = $nodekind;
997
998            fn node_tag() -> $nodekind {
999                $nodekind::$variant
1000            }
1001
1002            fn get_rule_index(&self) -> usize {
1003                $rule
1004            }
1005
1006            fn make_node(
1007                arena: &'arena $crate::Arena,
1008                ctx: $crate::parser_rule_context::BaseParserRuleContext<
1009                    'input,
1010                    'arena,
1011                    Self,
1012                    Self::NodeKind,
1013                    Tok,
1014                >,
1015            ) -> *mut $crate::tree::TreeNode<'input, 'arena, Self::NodeKind, Tok> {
1016                arena.alloc_labeled_node($ctxall::Error(ctx))
1017            }
1018
1019            fn cast_from<'a>(
1020                node: &'a $crate::tree::TreeNode<'input, 'arena, Self::NodeKind, Tok>,
1021            ) -> ::std::option::Option<
1022                &'a $crate::parser_rule_context::BaseParserRuleContext<
1023                    'input,
1024                    'arena,
1025                    Self,
1026                    Self::NodeKind,
1027                    Tok,
1028                >,
1029            > {
1030                if node.node_tag()
1031                    == <Self as $crate::rule_context::CustomRuleContext<'input, 'arena, Tok>>::node_tag()
1032                {
1033                    ::std::option::Option::Some($crate::cast_unchecked!(node.ctx_ptr() => $crate::parser_rule_context::BaseParserRuleContext<'input, 'arena, Self, Self::NodeKind, Tok>))
1034                } else {
1035                    ::std::option::Option::None
1036                }
1037            }
1038
1039            fn cast_from_mut<'a>(
1040                node: &'a mut $crate::tree::TreeNode<'input, 'arena, Self::NodeKind, Tok>,
1041            ) -> ::std::option::Option<
1042                &'a mut $crate::parser_rule_context::BaseParserRuleContext<
1043                    'input,
1044                    'arena,
1045                    Self,
1046                    Self::NodeKind,
1047                    Tok,
1048                >,
1049            > {
1050                if node.node_tag()
1051                    == <Self as $crate::rule_context::CustomRuleContext<'input, 'arena, Tok>>::node_tag()
1052                {
1053                    ::std::option::Option::Some($crate::cast_unchecked!(node.ctx_ptr() => mut $crate::parser_rule_context::BaseParserRuleContext<'input, 'arena, Self, Self::NodeKind, Tok>))
1054                } else {
1055                    ::std::option::Option::None
1056                }
1057            }
1058        }
1059    };
1060
1061    (@alt $nodekind:ident::$base:ident, $ctxall:ident::$variant:ident, $ext:ident, $rule:expr) => {
1062        impl<'input: 'arena, 'arena, Tok> $crate::rule_context::CustomRuleContext<'input, 'arena, Tok>
1063            for $ext<'input, 'arena, Tok>
1064        where
1065            Tok: $crate::token::Token + 'input,
1066        {
1067            type NodeKind = $nodekind;
1068
1069            fn node_tag() -> $nodekind {
1070                $nodekind::$base
1071            }
1072
1073            fn get_rule_index(&self) -> usize {
1074                $rule
1075            }
1076
1077            fn make_node(
1078                arena: &'arena $crate::Arena,
1079                ctx: $crate::parser_rule_context::BaseParserRuleContext<
1080                    'input,
1081                    'arena,
1082                    Self,
1083                    Self::NodeKind,
1084                    Tok,
1085                >,
1086            ) -> *mut $crate::tree::TreeNode<'input, 'arena, Self::NodeKind, Tok> {
1087                arena.alloc_labeled_node($ctxall::$variant(ctx))
1088            }
1089
1090            fn cast_from<'a>(
1091                node: &'a $crate::tree::TreeNode<'input, 'arena, Self::NodeKind, Tok>,
1092            ) -> ::std::option::Option<
1093                &'a $crate::parser_rule_context::BaseParserRuleContext<
1094                    'input,
1095                    'arena,
1096                    Self,
1097                    Self::NodeKind,
1098                    Tok,
1099                >,
1100            > {
1101                if node.node_tag()
1102                    == <Self as $crate::rule_context::CustomRuleContext<'input, 'arena, Tok>>::node_tag()
1103                {
1104                    match $crate::cast_unchecked!(node => $ctxall<'input, 'arena, Tok>) {
1105                        $ctxall::$variant(ctx) => ::std::option::Option::Some(ctx),
1106                        _ => ::std::option::Option::None,
1107                    }
1108                } else {
1109                    ::std::option::Option::None
1110                }
1111            }
1112
1113            fn cast_from_mut<'a>(
1114                node: &'a mut $crate::tree::TreeNode<'input, 'arena, Self::NodeKind, Tok>,
1115            ) -> ::std::option::Option<
1116                &'a mut $crate::parser_rule_context::BaseParserRuleContext<
1117                    'input,
1118                    'arena,
1119                    Self,
1120                    Self::NodeKind,
1121                    Tok,
1122                >,
1123            > {
1124                if node.node_tag()
1125                    == <Self as $crate::rule_context::CustomRuleContext<'input, 'arena, Tok>>::node_tag()
1126                {
1127                    match $crate::cast_unchecked!(node => mut $ctxall<'input, 'arena, Tok>) {
1128                        $ctxall::$variant(ctx) => ::std::option::Option::Some(ctx),
1129                        _ => ::std::option::Option::None,
1130                    }
1131                } else {
1132                    ::std::option::Option::None
1133                }
1134            }
1135        }
1136    };
1137}
1138
1139#[macro_export]
1140macro_rules! parse_rule {
1141    (catch rec $recog:ident = $self:expr, $parentctx:ident, $parentstate:ident, $ctx:ty, $rule:expr, $state:expr, $create:expr; $prec:ident; $body:block; [$($exceptions:tt)*]; [$($finally:tt)*]) => {
1142        $crate::maybe_grow_stack!({
1143            let $recog = $self;
1144            let $parentctx = $recog.base.take_ctx();
1145            let $parentstate = $recog.base.get_state();
1146            $recog
1147                .base
1148                .enter_recursion_rule(($create)($parentctx)?, $state, $rule, $prec)?;
1149            let result: ::std::result::Result<(), $crate::errors::ANTLRError> = (|| {
1150                $body
1151                ::std::result::Result::Ok(())
1152            })();
1153            match result {
1154                ::std::result::Result::Ok(_) => {}
1155                $($exceptions)*
1156                ::std::result::Result::Err(e) => {
1157                    if !e.is_recoverable() {
1158                        return ::std::result::Result::Err(e);
1159                    }
1160                    $recog.err_handler.report_error(&mut $recog.base, &e);
1161                    $recog.err_handler.recover(&mut $recog.base, &e)?;
1162                }
1163            }
1164            $($finally)*
1165            $recog
1166                .base
1167                .unroll_recursion_context($parentctx)
1168                .map(|ctx| ctx.as_rule_context().unwrap())
1169        })
1170    };
1171
1172    (catch $recog:ident = $self:expr, $parentctx:ident, $ctx:ty, $rule:expr, $state:expr, $create:expr; $body:block; [$($exceptions:tt)*]; [$($finally:tt)*]) => {
1173        $crate::maybe_grow_stack!({
1174            let $recog = $self;
1175            let $parentctx = $recog.base.take_ctx();
1176            $recog.base.enter_rule(($create)($parentctx)?, $state, $rule)?;
1177            let result: ::std::result::Result<(), $crate::errors::ANTLRError> = (|| {
1178                $body
1179                ::std::result::Result::Ok(())
1180            })();
1181            match result {
1182                ::std::result::Result::Ok(_) => {}
1183                $($exceptions)*
1184                ::std::result::Result::Err(e) => {
1185                    if !e.is_recoverable() {
1186                        return ::std::result::Result::Err(e);
1187                    }
1188                    $recog.err_handler.report_error(&mut $recog.base, &e);
1189                    $recog.err_handler.recover(&mut $recog.base, &e)?;
1190                }
1191            }
1192            $($finally)*
1193            $recog
1194                .base
1195                .exit_rule()
1196                .map(|ctx: &'arena _| ctx.as_rule_context().unwrap())
1197        })
1198    };
1199
1200    (rec $recog:ident = $self:expr, $parentctx:ident, $parentstate:ident, $ctx:ty, $rule:expr, $state:expr, $create:expr; $prec:ident; $body:block) => {
1201        $crate::maybe_grow_stack!({
1202            let $recog = $self;
1203            let $parentctx = $recog.base.take_ctx();
1204            let $parentstate = $recog.base.get_state();
1205            $recog
1206                .base
1207                .enter_recursion_rule(($create)($parentctx)?, $state, $rule, $prec)?;
1208            let result: ::std::result::Result<(), $crate::errors::ANTLRError> = (|| {
1209                $body
1210                ::std::result::Result::Ok(())
1211            })();
1212            match result {
1213                ::std::result::Result::Ok(_) => {}
1214                ::std::result::Result::Err(e) => {
1215                    if !e.is_recoverable() {
1216                        return ::std::result::Result::Err(e);
1217                    }
1218                    $recog.err_handler.report_error(&mut $recog.base, &e);
1219                    $recog.err_handler.recover(&mut $recog.base, &e)?;
1220                }
1221            }
1222            $recog
1223                .base
1224                .unroll_recursion_context($parentctx)
1225                .map(|ctx| ctx.as_rule_context().unwrap())
1226        })
1227    };
1228
1229    ($recog:ident = $self:expr, $parentctx:ident, $ctx:ty, $rule:expr, $state:expr, $create:expr; $body:block) => {
1230        $crate::maybe_grow_stack!({
1231            let $recog = $self;
1232            let $parentctx = $recog.base.take_ctx();
1233            $recog.base.enter_rule(($create)($parentctx)?, $state, $rule)?;
1234            let result: ::std::result::Result<(), $crate::errors::ANTLRError> = (|| {
1235                $body
1236                ::std::result::Result::Ok(())
1237            })();
1238            match result {
1239                ::std::result::Result::Ok(_) => {}
1240                ::std::result::Result::Err(e) => {
1241                    if !e.is_recoverable() {
1242                        return ::std::result::Result::Err(e);
1243                    }
1244                    $recog.err_handler.report_error(&mut $recog.base, &e);
1245                    $recog.err_handler.recover(&mut $recog.base, &e)?;
1246                }
1247            }
1248            $recog
1249                .base
1250                .exit_rule()
1251                .map(|ctx: &'arena _| ctx.as_rule_context().unwrap())
1252        })
1253    };
1254}
1255
1256/// The arm of one shared-descent group in a generated `DescentAltBlock`.
1257///
1258/// Evaluates to the member alternative to parse. The arm parses the shared
1259/// rule once with parse listeners muted (see
1260/// [`BaseParser::begin_neutral_parse`](crate::parser::BaseParser::begin_neutral_parse)),
1261/// reads the token after it, and selects the member alternative whose tail
1262/// starts with that token (or `default` otherwise). The subtree is kept for
1263/// the re-descent of that member (see `resume_take`).
1264#[doc(hidden)]
1265#[macro_export]
1266macro_rules! shared_descent {
1267    (
1268        $recog:ident,
1269        call_sites: $call_sites:expr,
1270        prefix: $prefix:expr,
1271        rule: $rule:expr,
1272        invoke: $invoke:ident ( $($arg:expr),* ),
1273        tails: { $($tail:pat => $tail_alt:expr),* $(,)? },
1274        default: $default:expr,
1275        fallback: $fallback:expr $(,)?
1276    ) => {{
1277        if !$recog.base.descent_ready() {
1278            $fallback
1279        } else {
1280            let neutral = $recog.base.begin_neutral_parse($call_sites, $prefix);
1281            match $recog.$invoke($($arg),*) {
1282                ::std::result::Result::Ok(node) => {
1283                    let token = $crate::int_stream::IntStream::la(&mut $recog.base.input, 1);
1284                    let alt: i32 = match token {
1285                        $($tail => $tail_alt,)*
1286                        _ => $default,
1287                    };
1288                    $recog.base.resume_neutral_parse(
1289                        neutral,
1290                        $crate::tree::NodeInner::as_node(node),
1291                        $rule,
1292                    );
1293                    alt
1294                }
1295                ::std::result::Result::Err(err) => {
1296                    $recog.base.abort_neutral_parse(neutral);
1297                    return ::std::result::Result::Err(err);
1298                }
1299            }
1300        }
1301    }};
1302}
1303
1304#[macro_export]
1305macro_rules! impl_parser_recog {
1306    ($ext:ident, $nodekind:ident, $file:literal
1307     $(; sempred ($node:ty, $parser:ident) { $($srule:expr => $sfn:ident,)* })?
1308    ) => {
1309        impl<'input, 'arena, Input, TF>
1310            $crate::parser::ParserRecog<
1311                'input,
1312                'arena,
1313                $crate::parser::BaseParser<'input, 'arena, $ext<'input, 'arena>, $nodekind, Input, TF>,
1314                TF::Tok,
1315            > for $ext<'input, 'arena>
1316        where
1317            'input: 'arena,
1318            TF: $crate::token_factory::TokenFactory<'input, 'arena> + 'arena,
1319            Input: $crate::token_stream::TokenStream<'input, 'arena, TF> + 'arena,
1320        {
1321            fn get_atn_simulator_man(
1322                &self,
1323            ) -> &'static $crate::atn_simulator::ParserATNSimulatorManager {
1324                &ATN_SIMULATOR_MANAGER
1325            }
1326        }
1327
1328        impl<'input, 'arena, Input, TF>
1329            $crate::recognizer::Actions<
1330                'input,
1331                'arena,
1332                $crate::parser::BaseParser<'input, 'arena, $ext<'input, 'arena>, $nodekind, Input, TF>,
1333                TF::Tok,
1334            > for $ext<'input, 'arena>
1335        where
1336            'input: 'arena,
1337            TF: $crate::token_factory::TokenFactory<'input, 'arena> + 'arena,
1338            Input: $crate::token_stream::TokenStream<'input, 'arena, TF> + 'arena,
1339        {
1340            fn get_grammar_file_name(&self) -> &str {
1341                $file
1342            }
1343
1344            fn get_rule_names(&self) -> &[&str] {
1345                &ruleNames
1346            }
1347
1348            fn get_vocabulary(&self) -> &dyn $crate::vocabulary::Vocabulary {
1349                &**VOCABULARY
1350            }
1351
1352            $(
1353            fn sempred(
1354                _localctx: ::std::option::Option<&'arena $node>,
1355                rule_index: i32,
1356                pred_index: i32,
1357                recog: &mut $crate::parser::BaseParser<
1358                    'input,
1359                    'arena,
1360                    $ext<'input, 'arena>,
1361                    $nodekind,
1362                    Input,
1363                    TF,
1364                >,
1365            ) -> bool {
1366                match rule_index {
1367                    $(
1368                    $srule => $parser::<'input, 'arena, Input, TF>::$sfn(
1369                        _localctx.and_then(|x| x.as_rule_context()),
1370                        pred_index,
1371                        recog,
1372                    ),
1373                    )*
1374                    _ => true,
1375                }
1376            }
1377            )?
1378        }
1379    };
1380}
1381
1382#[macro_export]
1383macro_rules! impl_lexer_recog {
1384    ($actions:ident, $file:literal
1385     $(; action { $($arule:expr => $afn:ident,)* })?
1386     $(; sempred { $($srule:expr => $sfn:ident,)* })?
1387     $(; extend { $($extend:item)* })?
1388    ) => {
1389        impl<'input, 'arena, Input, TF>
1390            $crate::recognizer::Actions<
1391                'input,
1392                'arena,
1393                BaseLexerType<'input, 'arena, Input, TF>,
1394                TF::Tok,
1395            > for $actions
1396        where
1397            'input: 'arena,
1398            Input: $crate::char_stream::CharStream<'input>,
1399            TF: $crate::token_factory::TokenFactory<'input, 'arena> + 'arena,
1400        {
1401            $(
1402            fn action(
1403                _localctx: ::std::option::Option<
1404                    &'arena $crate::rule_context::EmptyRuleNode<'input, 'arena, TF::Tok>,
1405                >,
1406                rule_index: i32,
1407                action_index: i32,
1408                recog: &mut BaseLexerType<'input, 'arena, Input, TF>,
1409            ) {
1410                match rule_index {
1411                    $(
1412                    $arule => $actions::$afn(action_index, recog),
1413                    )*
1414                    _ => {}
1415                }
1416            }
1417            )?
1418
1419            $(
1420            fn sempred(
1421                _localctx: ::std::option::Option<
1422                    &'arena $crate::rule_context::EmptyRuleNode<'input, 'arena, TF::Tok>,
1423                >,
1424                rule_index: i32,
1425                pred_index: i32,
1426                recog: &mut BaseLexerType<'input, 'arena, Input, TF>,
1427            ) -> bool {
1428                match rule_index {
1429                    $(
1430                    $srule => $actions::$sfn(pred_index, recog),
1431                    )*
1432                    _ => true,
1433                }
1434            }
1435            )?
1436        }
1437
1438        impl<'input, 'arena, Input, TF>
1439            $crate::lexer::LexerRecog<'input, 'arena, TF, BaseLexerType<'input, 'arena, Input, TF>>
1440            for $actions
1441        where
1442            'input: 'arena,
1443            Input: $crate::char_stream::CharStream<'input>,
1444            TF: $crate::token_factory::TokenFactory<'input, 'arena> + 'arena,
1445        {
1446            $($($extend)*)?
1447
1448            fn get_rule_names(&self) -> &'static [&'static str] {
1449                &ruleNames
1450            }
1451
1452            fn get_literal_names(&self) -> &[::std::option::Option<&str>] {
1453                &_LITERAL_NAMES
1454            }
1455
1456            fn get_symbolic_names(&self) -> &[::std::option::Option<&str>] {
1457                &_SYMBOLIC_NAMES
1458            }
1459
1460            fn get_grammar_file_name(&self) -> &'static str {
1461                $file
1462            }
1463
1464            fn get_atn_simulator_man(
1465                &self,
1466            ) -> &'static $crate::atn_simulator::LexerATNSimulatorManager {
1467                &ATN_SIMULATOR_MANAGER
1468            }
1469        }
1470    };
1471}