Skip to main content

antlr4_runtime/
generated.rs

1use std::sync::{Arc, OnceLock};
2
3use crate::atn::parser_atn::ParserAtn;
4use crate::atn::serialized::SerializedAtn;
5use crate::recognizer::{RecognizerData, RecognizerMetadata};
6use crate::vocabulary::Vocabulary;
7
8/// Defines the grammar-independent storage, conversion, and accessor mechanics
9/// for one generated typed parser context.
10#[doc(hidden)]
11#[macro_export]
12macro_rules! __antlr4_rust_context {
13    (
14        pub struct $context:ident {
15            rule_index: $rule_index:expr,
16            context_kind: $kind_mode:ident $(($kind:expr))?,
17            attributes: {
18                $(
19                    $attrs:ident {
20                        $($field:ident: $field_ty:ty),+ $(,)?
21                    }
22                )?
23            },
24            methods: {
25                rule_node: $rule_node_method:ident,
26                child_count: $child_count_method:ident,
27                direct_terminals: $direct_terminals_method:ident,
28                start: $start_method:ident,
29                text: $text_method:ident $(,)?
30            }
31        }
32    ) => {
33        #[allow(non_camel_case_types, dead_code)]
34        #[derive(Clone)]
35        pub struct $context<'a, State = StoredTreeContext> {
36            __node: __GeneratedRuleContext<'a>,
37            __invocation_states: Option<Vec<isize>>,
38            __state: std::marker::PhantomData<State>,
39            $(
40                $(pub $field: $field_ty,)+
41            )?
42        }
43
44        impl<'a> $crate::FromRuleNode<'a> for $context<'a> {
45            fn from_rule_node(node: $crate::RuleNodeView<'a>) -> Option<Self> {
46                if node.rule_index() != $rule_index
47                    || $crate::__antlr4_rust_context!(
48                        @stored_kind_mismatch $kind_mode $(($kind))?, node
49                    )
50                {
51                    return None;
52                }
53                Some(Self::__from_node(node))
54            }
55        }
56
57        impl<'a> $crate::AsRuleNode<'a> for $context<'a> {
58            fn as_rule_node(&self) -> $crate::RuleNodeView<'a> {
59                self.$rule_node_method()
60            }
61        }
62
63        impl<'a> $context<'a> {
64            pub fn $rule_node_method(&self) -> $crate::RuleNodeView<'a> {
65                match self.__node {
66                    __GeneratedRuleContext::Stored(node) => node,
67                    __GeneratedRuleContext::Active { .. } => {
68                        unreachable!("stored context type contains an active parser context")
69                    }
70                }
71            }
72        }
73
74        impl<'a> __FromActiveRuleContext<'a> for $context<'a, __ActiveParserContext> {
75            fn __from_active(
76                context: &'a $crate::ParserRuleContext,
77                live_attrs: Option<&dyn std::any::Any>,
78                invocation_states: Vec<isize>,
79                storage: &'a $crate::ParseTreeStorage,
80                tokens: &'a $crate::TokenStore,
81            ) -> Option<Self> {
82                if context.rule_index() != $rule_index
83                    || $crate::__antlr4_rust_context!(
84                        @active_kind_mismatch
85                        $kind_mode $(($kind))?,
86                        context,
87                        storage,
88                        tokens
89                    )
90                {
91                    return None;
92                }
93                $(
94                    let __default = <$attrs>::default();
95                    let __attrs = match live_attrs {
96                        Some(live_attrs) => live_attrs
97                            .downcast_ref::<$attrs>()
98                            .expect("active context attributes match the parser rule"),
99                        None => context
100                            .generated_attrs::<$attrs>()
101                            .unwrap_or(&__default),
102                    };
103                )?
104                Some(Self {
105                    __node: __GeneratedRuleContext::Active {
106                        context,
107                        storage,
108                        tokens,
109                    },
110                    __invocation_states: Some(invocation_states),
111                    __state: std::marker::PhantomData,
112                    $(
113                        $($field: __attrs.$field.clone(),)+
114                    )?
115                })
116            }
117        }
118
119        impl<'a> FromValidatedRuleNode<'a> for $context<'a, ValidatedTreeContext> {
120            fn from_validated_rule_node(node: ValidatedRuleNode<'a>) -> Option<Self> {
121                let node = node.rule_node();
122                if node.rule_index() != $rule_index
123                    || $crate::__antlr4_rust_context!(
124                        @stored_kind_mismatch $kind_mode $(($kind))?, node
125                    )
126                {
127                    return None;
128                }
129                Some(Self::__from_validated_node(node))
130            }
131        }
132
133        impl<'a> $crate::AsRuleNode<'a> for $context<'a, ValidatedTreeContext> {
134            fn as_rule_node(&self) -> $crate::RuleNodeView<'a> {
135                self.$rule_node_method()
136            }
137        }
138
139        #[allow(dead_code, clippy::all)]
140        impl<'a> $context<'a> {
141            fn __from_node(node: $crate::RuleNodeView<'a>) -> Self {
142                Self::__from_node_with_invocation_states(node, None)
143            }
144
145            fn __from_child_node(
146                node: $crate::RuleNodeView<'a>,
147                parent_invocation_states: Option<&[isize]>,
148            ) -> Self {
149                let invocation_states = parent_invocation_states.map(|states| {
150                    let mut invocation_states = Vec::with_capacity(states.len() + 1);
151                    invocation_states.push(node.invoking_state());
152                    invocation_states.extend_from_slice(states);
153                    invocation_states
154                });
155                Self::__from_node_with_invocation_states(node, invocation_states)
156            }
157
158            fn __from_listener_node(
159                node: $crate::RuleNodeView<'a>,
160                invocation_states: Option<&[isize]>,
161            ) -> Self {
162                Self::__from_node_with_invocation_states(
163                    node,
164                    invocation_states.map(<[isize]>::to_vec),
165                )
166            }
167
168            fn __from_node_with_invocation_states(
169                node: $crate::RuleNodeView<'a>,
170                invocation_states: Option<Vec<isize>>,
171            ) -> Self {
172                $(
173                    let __default = <$attrs>::default();
174                    let __attrs = node.generated_attrs::<$attrs>().unwrap_or(&__default);
175                )?
176                Self {
177                    __node: __GeneratedRuleContext::Stored(node),
178                    __invocation_states: invocation_states,
179                    __state: std::marker::PhantomData,
180                    $(
181                        $($field: __attrs.$field.clone(),)+
182                    )?
183                }
184            }
185        }
186
187        #[allow(dead_code, clippy::all)]
188        impl<'a, State> $context<'a, State> {
189            pub fn $child_count_method(&self) -> usize {
190                match &self.__node {
191                    __GeneratedRuleContext::Stored(node) => node.child_count(),
192                    __GeneratedRuleContext::Active { context, .. } => context.child_count(),
193                }
194            }
195
196            /// Iterates terminals owned directly by this context without
197            /// descending into nested rule contexts.
198            ///
199            /// Recovered trees expose inserted and deleted recovery tokens as
200            /// error nodes through the same `TerminalNode` surface. Use
201            /// `TerminalNode::is_error()` to identify recovery nodes and
202            /// `TerminalNode::is_missing()` to identify inserted synthetic
203            /// tokens.
204            pub fn $direct_terminals_method(
205                &self,
206            ) -> impl Iterator<Item = TerminalNode<'a>> + 'a + use<'a, State> {
207                __terminal_children(self.__node).map(TerminalNode::new)
208            }
209
210            pub fn $start_method(&self) -> __GeneratedTokenView {
211                let token = match &self.__node {
212                    __GeneratedRuleContext::Stored(node) => node.start(),
213                    __GeneratedRuleContext::Active {
214                        context, tokens, ..
215                    } => context.start(tokens),
216                };
217                __GeneratedTokenView {
218                    text: token
219                        .map(|token| token.text_or_empty().to_owned())
220                        .unwrap_or_default(),
221                }
222            }
223
224            pub fn $text_method(&self) -> String {
225                match &self.__node {
226                    __GeneratedRuleContext::Stored(node) => node.text(),
227                    __GeneratedRuleContext::Active {
228                        context,
229                        storage,
230                        tokens,
231                    } => context.text(storage, tokens),
232                }
233            }
234        }
235
236        #[allow(dead_code, clippy::all)]
237        impl<'a> $context<'a, ValidatedTreeContext> {
238            fn __from_validated_node(node: $crate::RuleNodeView<'a>) -> Self {
239                Self::__from_validated_node_with_invocation_states(node, None)
240            }
241
242            fn __from_validated_child_node(
243                node: $crate::RuleNodeView<'a>,
244                parent_invocation_states: Option<&[isize]>,
245            ) -> Self {
246                let invocation_states = parent_invocation_states.map(|states| {
247                    let mut invocation_states = Vec::with_capacity(states.len() + 1);
248                    invocation_states.push(node.invoking_state());
249                    invocation_states.extend_from_slice(states);
250                    invocation_states
251                });
252                Self::__from_validated_node_with_invocation_states(node, invocation_states)
253            }
254
255            fn __from_validated_listener_node(
256                node: $crate::RuleNodeView<'a>,
257                invocation_states: Option<&[isize]>,
258            ) -> Self {
259                Self::__from_validated_node_with_invocation_states(
260                    node,
261                    invocation_states.map(<[isize]>::to_vec),
262                )
263            }
264
265            fn __from_validated_node_with_invocation_states(
266                node: $crate::RuleNodeView<'a>,
267                invocation_states: Option<Vec<isize>>,
268            ) -> Self {
269                $(
270                    let __default = <$attrs>::default();
271                    let __attrs = node.generated_attrs::<$attrs>().unwrap_or(&__default);
272                )?
273                Self {
274                    __node: __GeneratedRuleContext::Stored(node),
275                    __invocation_states: invocation_states,
276                    __state: std::marker::PhantomData,
277                    $(
278                        $($field: __attrs.$field.clone(),)+
279                    )?
280                }
281            }
282
283            pub fn $rule_node_method(&self) -> $crate::RuleNodeView<'a> {
284                match self.__node {
285                    __GeneratedRuleContext::Stored(node) => node,
286                    __GeneratedRuleContext::Active { .. } => {
287                        unreachable!("validated context contains an active parser context")
288                    }
289                }
290            }
291        }
292
293        impl<State> std::fmt::Display for $context<'_, State> {
294            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
295                match &self.__invocation_states {
296                    Some(states) => __write_invocation_states(f, states.iter().copied()),
297                    None => match self.__node {
298                        __GeneratedRuleContext::Stored(node) => {
299                            __write_invocation_states(f, node.invocation_states())
300                        }
301                        __GeneratedRuleContext::Active { .. } => {
302                            unreachable!("active context is missing invocation states")
303                        }
304                    },
305                }
306            }
307        }
308    };
309    (@stored_kind_mismatch any, $node:expr) => {
310        false
311    };
312    (@stored_kind_mismatch exact($kind:expr), $node:expr) => {
313        __context_kind($node) != $kind
314    };
315    (@active_kind_mismatch any, $context:expr, $storage:expr, $tokens:expr) => {
316        false
317    };
318    (@active_kind_mismatch exact($kind:expr), $context:expr, $storage:expr, $tokens:expr) => {
319        __active_context_kind($context, $storage, $tokens) != $kind
320    };
321}
322
323/// Defines the grammar-independent facade and trait delegation for one
324/// generated lexer.
325#[doc(hidden)]
326#[macro_export]
327macro_rules! __antlr4_rust_lexer_facade {
328    (
329        type: $lexer:ident<$input:ident, $hooks:ident>,
330        fields: {
331            base: $base:ident,
332            hooks: $hooks_field:ident $(,)?
333        },
334        metadata: $metadata:path,
335        next_token($this:ident, $sink:ident) $next_token:block
336        $(,)?
337    ) => {
338        impl<$input, $hooks> $lexer<$input, $hooks>
339        where
340            $input: $crate::char_stream::CharStream,
341            $hooks: $crate::parser::SemanticHooks,
342        {
343            pub fn metadata() -> &'static $crate::generated::GrammarMetadata {
344                $metadata()
345            }
346
347            /// Adds a listener for lexer diagnostics.
348            pub fn add_error_listener<T>(&mut self, listener: T)
349            where
350                T: for<'a> $crate::errors::ErrorListener<dyn $crate::recognizer::Recognizer + 'a>
351                    + ::core::marker::Send
352                    + 'static,
353            {
354                $crate::recognizer::Recognizer::add_error_listener(&mut self.$base, listener);
355            }
356
357            /// Removes every lexer error listener, including the default console listener.
358            pub fn remove_error_listeners(&mut self) {
359                $crate::recognizer::Recognizer::remove_error_listeners(&mut self.$base);
360            }
361
362            /// Routes every token through ATN interpretation instead of the compiled
363            /// lexer DFA, so the learned-DFA trace (`lexer_dfa_string`) observes each
364            /// match.
365            pub fn set_force_interpreted(&mut self, force_interpreted: bool) {
366                self.$base.set_force_interpreted(force_interpreted);
367            }
368
369            /// Resets this lexer and any caller-owned lifecycle state for reuse.
370            pub fn reset(&mut self) {
371                if <$hooks as $crate::parser::SemanticHooks>::ENABLES_LEXER_LIFECYCLE {
372                    $crate::atn::lexer::reset_with_semantic_hooks(
373                        &mut self.$base,
374                        &mut self.$hooks_field,
375                    );
376                } else {
377                    self.$base.reset();
378                }
379            }
380
381            /// Replaces the input stream and resets runtime and lifecycle state.
382            pub fn set_input_stream(&mut self, input: $input) {
383                if <$hooks as $crate::parser::SemanticHooks>::ENABLES_LEXER_LIFECYCLE {
384                    $crate::atn::lexer::set_input_stream_with_semantic_hooks(
385                        &mut self.$base,
386                        &mut self.$hooks_field,
387                        input,
388                    );
389                } else {
390                    self.$base.set_input_stream(input);
391                }
392            }
393
394            /// Clears the learned lexer DFA shared by this grammar.
395            pub fn clear_dfa(&self) {
396                self.$base.clear_dfa();
397            }
398        }
399
400        impl<$input, $hooks> $crate::generated::GeneratedLexer for $lexer<$input, $hooks>
401        where
402            $input: $crate::char_stream::CharStream,
403            $hooks: $crate::parser::SemanticHooks,
404        {
405            fn metadata() -> &'static $crate::generated::GrammarMetadata {
406                $metadata()
407            }
408        }
409
410        impl<$input, $hooks> $crate::recognizer::Recognizer for $lexer<$input, $hooks>
411        where
412            $input: $crate::char_stream::CharStream,
413            $hooks: $crate::parser::SemanticHooks,
414        {
415            fn data(&self) -> &$crate::recognizer::RecognizerData {
416                $crate::recognizer::Recognizer::data(&self.$base)
417            }
418
419            fn data_mut(&mut self) -> &mut $crate::recognizer::RecognizerData {
420                $crate::recognizer::Recognizer::data_mut(&mut self.$base)
421            }
422        }
423
424        impl<$input, $hooks> $crate::lexer::Lexer for $lexer<$input, $hooks>
425        where
426            $input: $crate::char_stream::CharStream,
427            $hooks: $crate::parser::SemanticHooks,
428        {
429            fn mode(&self) -> i32 {
430                $crate::lexer::Lexer::mode(&self.$base)
431            }
432
433            fn set_mode(&mut self, mode: i32) {
434                $crate::lexer::Lexer::set_mode(&mut self.$base, mode);
435            }
436
437            fn push_mode(&mut self, mode: i32) {
438                $crate::lexer::Lexer::push_mode(&mut self.$base, mode);
439            }
440
441            fn pop_mode(&mut self) -> ::core::option::Option<i32> {
442                $crate::lexer::Lexer::pop_mode(&mut self.$base)
443            }
444        }
445
446        impl<$input, $hooks> $crate::token::TokenSource for $lexer<$input, $hooks>
447        where
448            $input: $crate::char_stream::CharStream,
449            $hooks: $crate::parser::SemanticHooks,
450        {
451            fn next_token(
452                &mut self,
453                $sink: &mut $crate::token::TokenSink<'_>,
454            ) -> ::core::result::Result<$crate::token::TokenId, $crate::token::TokenStoreError>
455            {
456                let $this = self;
457                $next_token
458            }
459
460            fn line(&self) -> usize {
461                self.$base.line()
462            }
463
464            fn column(&self) -> usize {
465                self.$base.column()
466            }
467
468            fn source_name(&self) -> &str {
469                self.$base.source_name()
470            }
471
472            fn source_text(&self) -> ::core::option::Option<::std::rc::Rc<str>> {
473                self.$base.source_text()
474            }
475
476            fn drain_errors(&mut self) -> ::std::vec::Vec<$crate::token::TokenSourceError> {
477                self.$base.drain_errors()
478            }
479
480            fn report_error(&self, source_error: &$crate::token::TokenSourceError) -> bool {
481                $crate::recognizer::Recognizer::notify_error_listeners(self, source_error.into());
482                true
483            }
484
485            fn lexer_dfa_string(&self) -> ::std::string::String {
486                self.$base.lexer_dfa_string()
487            }
488        }
489    };
490}
491
492/// Defines the grammar-independent facade and trait delegation for one
493/// generated parser.
494#[doc(hidden)]
495#[macro_export]
496macro_rules! __antlr4_rust_parser_facade {
497    (
498        type: $parser:ident<$source:ident, $hooks:ident>,
499        fields: {
500            base: $base:ident,
501            simulator: $simulator:ident,
502            generated_only: $generated_only:ident $(,)?
503        },
504        metadata: $metadata:path,
505        parser_atn: $parser_atn:path,
506        reset($this:ident) $reset:block
507        $(,)?
508    ) => {
509        impl<$source, $hooks> $parser<$source, $hooks>
510        where
511            $source: $crate::token::TokenSource,
512            $hooks: $crate::parser::SemanticHooks,
513        {
514            pub fn metadata() -> &'static $crate::generated::GrammarMetadata {
515                $metadata()
516            }
517
518            /// Adds a listener for parser diagnostics.
519            pub fn add_error_listener<T>(&mut self, listener: T)
520            where
521                T: for<'a> $crate::errors::ErrorListener<dyn $crate::recognizer::Recognizer + 'a>
522                    + ::core::marker::Send
523                    + 'static,
524            {
525                $crate::recognizer::Recognizer::add_error_listener(&mut self.$base, listener);
526            }
527
528            /// Removes every parser error listener, including the default console listener.
529            pub fn remove_error_listeners(&mut self) {
530                $crate::recognizer::Recognizer::remove_error_listeners(&mut self.$base);
531            }
532
533            /// Registers a listener for committed rule enter/exit events during
534            /// recognition (ANTLR's `addParseListener`). See
535            /// [`antlr4_runtime::ParseListener`] for the delivery contract.
536            pub fn add_parse_listener<T>(&mut self, listener: T)
537            where
538                T: $crate::parser::ParseListener + 'static,
539            {
540                self.$base.add_parse_listener(listener);
541            }
542
543            /// Removes every registered parse listener and returns them, dropping
544            /// any sticky abort a removed listener had requested.
545            pub fn remove_parse_listeners(
546                &mut self,
547            ) -> ::std::vec::Vec<::std::boxed::Box<dyn $crate::parser::ParseListener>> {
548                self.$base.remove_parse_listeners()
549            }
550
551            /// Fully resets parser-owned state and rewinds the current token stream.
552            pub fn reset(&mut self) {
553                self.$base.reset();
554                if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
555                    simulator.reset();
556                }
557                let $this = &mut *self;
558                $reset
559            }
560
561            /// Replaces the token stream and fully resets parser-owned state.
562            pub fn set_token_stream(
563                &mut self,
564                input: $crate::token_stream::CommonTokenStream<$source>,
565            ) {
566                self.$base.set_token_stream(input);
567                if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
568                    simulator.reset();
569                }
570                let $this = &mut *self;
571                $reset
572            }
573
574            #[must_use]
575            pub const fn token_stream(&self) -> &$crate::token_stream::CommonTokenStream<$source> {
576                self.$base.token_stream()
577            }
578
579            #[must_use]
580            pub const fn token_stream_mut(
581                &mut self,
582            ) -> &mut $crate::token_stream::CommonTokenStream<$source> {
583                self.$base.token_stream_mut()
584            }
585
586            #[must_use]
587            pub const fn token_store(&self) -> &$crate::token::TokenStore {
588                self.$base.token_store()
589            }
590
591            #[must_use]
592            pub const fn parse_tree_storage(&self) -> &$crate::tree::ParseTreeStorage {
593                self.$base.parse_tree_storage()
594            }
595
596            #[must_use]
597            pub fn prediction_context_stats(&self) -> $crate::prediction::PredictionContextStats {
598                self.$simulator.as_ref().map_or_else(
599                    $crate::prediction::PredictionContextStats::default,
600                    $crate::atn::parser::ParserAtnSimulator::prediction_context_stats,
601                )
602            }
603
604            #[must_use]
605            pub fn parser_dfa_stats(&self) -> $crate::dfa::ParserDfaStats {
606                self.$simulator.as_ref().map_or_else(
607                    $crate::dfa::ParserDfaStats::default,
608                    $crate::atn::parser::ParserAtnSimulator::parser_dfa_stats,
609                )
610            }
611
612            /// Clears this grammar's learned parser decision DFAs.
613            pub fn clear_dfa(&mut self) {
614                if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
615                    simulator.clear_dfa();
616                } else {
617                    $crate::atn::parser::ParserAtnSimulator::clear_shared_dfa($parser_atn());
618                }
619                let $this = &mut *self;
620                $reset
621            }
622
623            #[must_use]
624            pub fn node(&self, id: $crate::tree::NodeId) -> $crate::tree::Node<'_> {
625                self.$base.node(id)
626            }
627
628            #[must_use]
629            pub fn into_token_stream(self) -> $crate::token_stream::CommonTokenStream<$source> {
630                self.$base.into_token_stream()
631            }
632
633            #[must_use]
634            pub fn into_token_store(self) -> $crate::token::TokenStore {
635                self.$base.into_token_store()
636            }
637
638            #[must_use]
639            pub fn into_parsed_file(self, root: $crate::tree::NodeId) -> $crate::tree::ParsedFile {
640                self.$base.into_parsed_file(root)
641            }
642
643            /// Compiles a tree pattern rooted at parser rule `rule_index`.
644            ///
645            /// Mirrors ANTLR's `Parser.compileParseTreePattern`. Literal chunks of
646            /// `pattern` are lexed with a fresh lexer built by `make_lexer`.
647            pub fn compile_parse_tree_pattern<PL>(
648                &self,
649                pattern: &str,
650                rule_index: usize,
651                mut make_lexer: impl ::core::ops::FnMut($crate::char_stream::InputStream) -> PL,
652            ) -> ::core::result::Result<
653                $crate::tree_pattern::ParseTreePattern,
654                $crate::tree_pattern::ParseTreePatternError,
655            >
656            where
657                PL: $crate::token::TokenSource,
658            {
659                static PATTERN_DATA: ::std::sync::OnceLock<$crate::recognizer::RecognizerData> =
660                    ::std::sync::OnceLock::new();
661                static PATTERN_MATCHER: ::std::sync::OnceLock<
662                    $crate::tree_pattern::ParseTreePatternMatcher<'static>,
663                > = ::std::sync::OnceLock::new();
664                let matcher = match PATTERN_MATCHER.get() {
665                    ::core::option::Option::Some(matcher) => matcher,
666                    ::core::option::Option::None => {
667                        let data = PATTERN_DATA.get_or_init(|| $metadata().recognizer_data());
668                        let matcher = $crate::tree_pattern::ParseTreePatternMatcher::new(
669                            $parser_atn(),
670                            data,
671                        )?;
672                        PATTERN_MATCHER.get_or_init(|| matcher)
673                    }
674                };
675                matcher.compile(pattern, rule_index, move |text: &str| {
676                    $crate::tree_pattern::lex_pattern_chunk(text, &mut make_lexer)
677                })
678            }
679
680            #[allow(dead_code)]
681            fn simulator(&mut self) -> &mut $crate::atn::parser::ParserAtnSimulator<'static> {
682                self.$simulator.get_or_insert_with(|| {
683                    $crate::atn::parser::ParserAtnSimulator::new_shared($parser_atn())
684                })
685            }
686
687            #[allow(dead_code)]
688            fn generated_only(&self) -> bool {
689                self.$generated_only
690            }
691        }
692
693        impl<$source, $hooks> $crate::generated::GeneratedParser for $parser<$source, $hooks>
694        where
695            $source: $crate::token::TokenSource,
696            $hooks: $crate::parser::SemanticHooks,
697        {
698            fn metadata() -> &'static $crate::generated::GrammarMetadata {
699                $metadata()
700            }
701
702            fn parser_atn() -> &'static $crate::atn::parser_atn::ParserAtn {
703                $parser_atn()
704            }
705        }
706
707        impl<$source, $hooks> $crate::recognizer::Recognizer for $parser<$source, $hooks>
708        where
709            $source: $crate::token::TokenSource,
710            $hooks: $crate::parser::SemanticHooks,
711        {
712            fn data(&self) -> &$crate::recognizer::RecognizerData {
713                $crate::recognizer::Recognizer::data(&self.$base)
714            }
715
716            fn data_mut(&mut self) -> &mut $crate::recognizer::RecognizerData {
717                $crate::recognizer::Recognizer::data_mut(&mut self.$base)
718            }
719        }
720
721        impl<$source, $hooks> $crate::parser::Parser for $parser<$source, $hooks>
722        where
723            $source: $crate::token::TokenSource,
724            $hooks: $crate::parser::SemanticHooks,
725        {
726            fn build_parse_trees(&self) -> bool {
727                $crate::parser::Parser::build_parse_trees(&self.$base)
728            }
729
730            fn set_build_parse_trees(&mut self, build: bool) {
731                $crate::parser::Parser::set_build_parse_trees(&mut self.$base, build);
732            }
733
734            fn number_of_syntax_errors(&self) -> usize {
735                $crate::parser::Parser::number_of_syntax_errors(&self.$base)
736            }
737
738            fn report_diagnostic_errors(&self) -> bool {
739                $crate::parser::Parser::report_diagnostic_errors(&self.$base)
740            }
741
742            fn set_report_diagnostic_errors(&mut self, report: bool) {
743                $crate::parser::Parser::set_report_diagnostic_errors(&mut self.$base, report);
744            }
745
746            fn prediction_mode(&self) -> $crate::parser::PredictionMode {
747                $crate::parser::Parser::prediction_mode(&self.$base)
748            }
749
750            fn set_prediction_mode(&mut self, mode: $crate::parser::PredictionMode) {
751                $crate::parser::Parser::set_prediction_mode(&mut self.$base, mode);
752            }
753
754            fn max_rule_depth(&self) -> ::core::option::Option<usize> {
755                $crate::parser::Parser::max_rule_depth(&self.$base)
756            }
757
758            fn set_max_rule_depth(&mut self, depth: ::core::option::Option<usize>) {
759                $crate::parser::Parser::set_max_rule_depth(&mut self.$base, depth);
760            }
761
762            fn add_parse_listener(
763                &mut self,
764                listener: ::std::boxed::Box<dyn $crate::parser::ParseListener>,
765            ) {
766                $crate::parser::Parser::add_parse_listener(&mut self.$base, listener);
767            }
768
769            fn remove_parse_listeners(
770                &mut self,
771            ) -> ::std::vec::Vec<::std::boxed::Box<dyn $crate::parser::ParseListener>> {
772                $crate::parser::Parser::remove_parse_listeners(&mut self.$base)
773            }
774        }
775    };
776}
777
778#[derive(Debug)]
779pub struct GrammarMetadata {
780    grammar_file_name: &'static str,
781    rule_names: &'static [&'static str],
782    literal_names: &'static [Option<&'static str>],
783    symbolic_names: &'static [Option<&'static str>],
784    display_names: &'static [Option<&'static str>],
785    channel_names: &'static [&'static str],
786    mode_names: &'static [&'static str],
787    serialized_atn: &'static [i32],
788    recognizer_metadata: OnceLock<Arc<RecognizerMetadata>>,
789}
790
791impl Clone for GrammarMetadata {
792    fn clone(&self) -> Self {
793        Self {
794            grammar_file_name: self.grammar_file_name,
795            rule_names: self.rule_names,
796            literal_names: self.literal_names,
797            symbolic_names: self.symbolic_names,
798            display_names: self.display_names,
799            channel_names: self.channel_names,
800            mode_names: self.mode_names,
801            serialized_atn: self.serialized_atn,
802            recognizer_metadata: OnceLock::from(Arc::clone(self.cached_recognizer_metadata())),
803        }
804    }
805}
806
807impl GrammarMetadata {
808    /// Creates static grammar metadata emitted by the Rust target generator.
809    #[allow(clippy::too_many_arguments)]
810    pub const fn new(
811        grammar_file_name: &'static str,
812        rule_names: &'static [&'static str],
813        literal_names: &'static [Option<&'static str>],
814        symbolic_names: &'static [Option<&'static str>],
815        display_names: &'static [Option<&'static str>],
816        channel_names: &'static [&'static str],
817        mode_names: &'static [&'static str],
818        serialized_atn: &'static [i32],
819    ) -> Self {
820        Self {
821            grammar_file_name,
822            rule_names,
823            literal_names,
824            symbolic_names,
825            display_names,
826            channel_names,
827            mode_names,
828            serialized_atn,
829            recognizer_metadata: OnceLock::new(),
830        }
831    }
832
833    pub const fn grammar_file_name(&self) -> &'static str {
834        self.grammar_file_name
835    }
836
837    pub const fn rule_names(&self) -> &'static [&'static str] {
838        self.rule_names
839    }
840
841    pub const fn channel_names(&self) -> &'static [&'static str] {
842        self.channel_names
843    }
844
845    pub const fn mode_names(&self) -> &'static [&'static str] {
846        self.mode_names
847    }
848
849    pub fn vocabulary(&self) -> Vocabulary {
850        Vocabulary::new(
851            self.literal_names.iter().copied(),
852            self.symbolic_names.iter().copied(),
853            self.display_names.iter().copied(),
854        )
855    }
856
857    /// Creates per-instance recognizer state backed by this grammar's cached
858    /// immutable metadata.
859    pub fn recognizer_data(&self) -> RecognizerData {
860        RecognizerData::from_shared(Arc::clone(self.cached_recognizer_metadata()))
861    }
862
863    fn cached_recognizer_metadata(&self) -> &Arc<RecognizerMetadata> {
864        self.recognizer_metadata.get_or_init(|| {
865            Arc::new(RecognizerMetadata::from_static(
866                self.grammar_file_name,
867                self.rule_names,
868                self.channel_names,
869                self.mode_names,
870                self.vocabulary(),
871            ))
872        })
873    }
874
875    /// Borrows the serialized ATN values for deserialization by the runtime
876    /// simulators without copying generated static data.
877    pub const fn serialized_atn(&self) -> SerializedAtn<'_> {
878        SerializedAtn::from_i32(self.serialized_atn)
879    }
880}
881
882pub trait GeneratedLexer {
883    fn metadata() -> &'static GrammarMetadata;
884}
885
886pub trait GeneratedParser {
887    fn metadata() -> &'static GrammarMetadata;
888
889    /// Borrows the validated packed ATN embedded by the matching generator.
890    fn parser_atn() -> &'static ParserAtn;
891}
892
893#[cfg(test)]
894mod tests {
895    use super::*;
896
897    static META: GrammarMetadata = GrammarMetadata::new(
898        "Mini.g4",
899        &["file"],
900        &[None, Some("'x'")],
901        &[None, Some("X")],
902        &[None, None],
903        &["DEFAULT_TOKEN_CHANNEL", "HIDDEN"],
904        &["DEFAULT_MODE"],
905        &[4, 1, 1, 0, 0, 0],
906    );
907
908    // Compile-only fixture: successful expansion of both facade macros with
909    // invocation-site prelude names shadowed is the assertion.
910    #[allow(dead_code, unreachable_pub)]
911    mod facade_hygiene {
912        struct Box;
913        struct FnMut;
914        struct None;
915        struct Option;
916        struct Rc;
917        struct Result;
918        struct Send;
919        struct Some;
920        struct String;
921        struct Vec;
922
923        struct HygieneLexer<I, H> {
924            base: crate::lexer::BaseLexer<I>,
925            hooks: H,
926        }
927
928        struct HygieneParser<S, H> {
929            base: crate::parser::BaseParser<S, H>,
930            simulator: ::core::option::Option<crate::atn::parser::ParserAtnSimulator<'static>>,
931            generated_only: bool,
932        }
933
934        fn metadata() -> &'static crate::generated::GrammarMetadata {
935            &super::META
936        }
937
938        fn parser_atn() -> &'static crate::atn::parser_atn::ParserAtn {
939            panic!("compile-only facade hygiene fixture")
940        }
941
942        crate::__antlr4_rust_lexer_facade! {
943            type: HygieneLexer<I, H>,
944            fields: {
945                base: base,
946                hooks: hooks,
947            },
948            metadata: metadata,
949            next_token(_lexer, _sink) {
950                panic!("compile-only facade hygiene fixture")
951            }
952        }
953
954        crate::__antlr4_rust_parser_facade! {
955            type: HygieneParser<S, H>,
956            fields: {
957                base: base,
958                simulator: simulator,
959                generated_only: generated_only,
960            },
961            metadata: metadata,
962            parser_atn: parser_atn,
963            reset(_parser) {}
964        }
965    }
966
967    #[test]
968    fn metadata_builds_vocabulary() {
969        assert_eq!(META.grammar_file_name(), "Mini.g4");
970        assert_eq!(META.vocabulary().display_name(1), "'x'");
971    }
972
973    #[test]
974    fn cloned_metadata_shares_the_cache_before_explicit_initialization() {
975        let original = GrammarMetadata::new(
976            "Clone.g4",
977            &["start"],
978            &[None, Some("'x'")],
979            &[None, Some("X")],
980            &[None, None],
981            &["DEFAULT_TOKEN_CHANNEL"],
982            &["DEFAULT_MODE"],
983            &[],
984        );
985        let cloned = original.clone();
986        let first = original.recognizer_data();
987        let second = cloned.recognizer_data();
988
989        assert!(std::ptr::eq(first.rule_names(), second.rule_names()));
990        assert!(std::ptr::eq(first.vocabulary(), second.vocabulary()));
991    }
992}