Skip to main content

antlr4_runtime/
generated.rs

1// SPDX-License-Identifier: BSD-3-Clause
2// Copyright (c) 2026 Konstantin Vyatkin
3use std::any::Any;
4use std::fmt;
5use std::sync::{Arc, OnceLock};
6
7use crate::atn::parser_atn::ParserAtn;
8use crate::atn::serialized::SerializedAtn;
9use crate::char_stream::{CharStream, InputStream};
10use crate::errors::AntlrError;
11use crate::int_stream::IntStream;
12use crate::parser::{BaseParser, SemanticHooks, grow_generated_rule_stack};
13use crate::recognizer::{RecognizerData, RecognizerMetadata};
14use crate::token::{Token as _, TokenSource, TokenStore, TokenView};
15use crate::token_stream::CommonTokenStream;
16use crate::tree::{
17    ErrorNodeView, Node, NodeId, NodeKind, ParseTreeStorage, ParserRuleContext, RuleNodeView,
18    TerminalNodeView,
19};
20use crate::validated::ValidationError;
21use crate::vocabulary::Vocabulary;
22
23/// Defines the grammar-independent storage, conversion, and accessor mechanics
24/// for one generated typed parser context.
25///
26/// The optional `validated_downcast: branded,` field selects the revision-10
27/// validated-downcast impl against the runtime-owned branded
28/// [`crate::validated`] surface; without it the expansion targets the
29/// module-local validated types that generated-code API revisions 9 and
30/// earlier declare themselves.
31#[doc(hidden)]
32#[macro_export]
33macro_rules! __antlr4_rust_context {
34    (
35        pub struct $context:ident {
36            rule_index: $rule_index:expr,
37            context_kind: $kind_mode:ident $(($kind:expr))?,
38            $(validated_downcast: $validated_downcast:ident,)?
39            attributes: {
40                $(
41                    $attrs:ident {
42                        $($field:ident: $field_ty:ty),+ $(,)?
43                    }
44                )?
45            },
46            methods: {
47                rule_node: $rule_node_method:ident,
48                child_count: $child_count_method:ident,
49                direct_terminals: $direct_terminals_method:ident,
50                start: $start_method:ident,
51                text: $text_method:ident $(,)?
52            }
53        }
54    ) => {
55        #[allow(non_camel_case_types, dead_code)]
56        #[derive(Clone)]
57        pub struct $context<'a, State = StoredTreeContext> {
58            __node: __GeneratedRuleContext<'a>,
59            __invocation_states: Option<Vec<isize>>,
60            __state: std::marker::PhantomData<State>,
61            $(
62                $(pub $field: $field_ty,)+
63            )?
64        }
65
66        impl<'a> $crate::FromRuleNode<'a> for $context<'a> {
67            fn from_rule_node(node: $crate::RuleNodeView<'a>) -> Option<Self> {
68                if node.rule_index() != $rule_index
69                    || $crate::__antlr4_rust_context!(
70                        @stored_kind_mismatch $kind_mode $(($kind))?, node
71                    )
72                {
73                    return None;
74                }
75                Some(Self::__from_node(node))
76            }
77        }
78
79        impl<'a> $crate::AsRuleNode<'a> for $context<'a> {
80            fn as_rule_node(&self) -> $crate::RuleNodeView<'a> {
81                self.$rule_node_method()
82            }
83        }
84
85        impl<'a> $context<'a> {
86            pub fn $rule_node_method(&self) -> $crate::RuleNodeView<'a> {
87                match self.__node {
88                    __GeneratedRuleContext::Stored(node) => node,
89                    __GeneratedRuleContext::Active { .. } => {
90                        unreachable!("stored context type contains an active parser context")
91                    }
92                }
93            }
94        }
95
96        impl<'a> __FromActiveRuleContext<'a> for $context<'a, __ActiveParserContext> {
97            fn __from_active(
98                context: &'a $crate::ParserRuleContext,
99                live_attrs: Option<&dyn std::any::Any>,
100                invocation_states: Vec<isize>,
101                storage: &'a $crate::ParseTreeStorage,
102                tokens: &'a $crate::TokenStore,
103            ) -> Option<Self> {
104                if context.rule_index() != $rule_index
105                    || $crate::__antlr4_rust_context!(
106                        @active_kind_mismatch
107                        $kind_mode $(($kind))?,
108                        context,
109                        storage,
110                        tokens
111                    )
112                {
113                    return None;
114                }
115                $(
116                    let __default = <$attrs>::default();
117                    let __attrs = match live_attrs {
118                        Some(live_attrs) => live_attrs
119                            .downcast_ref::<$attrs>()
120                            .expect("active context attributes match the parser rule"),
121                        None => context
122                            .generated_attrs::<$attrs>()
123                            .unwrap_or(&__default),
124                    };
125                )?
126                Some(Self {
127                    __node: __GeneratedRuleContext::Active {
128                        context,
129                        storage,
130                        tokens,
131                    },
132                    __invocation_states: Some(invocation_states),
133                    __state: std::marker::PhantomData,
134                    $(
135                        $($field: __attrs.$field.clone(),)+
136                    )?
137                })
138            }
139        }
140
141        $crate::__antlr4_rust_context!(
142            @from_validated $($validated_downcast)?,
143            $context,
144            $rule_index,
145            $kind_mode $(($kind))?
146        );
147
148        impl<'a> $crate::AsRuleNode<'a> for $context<'a, ValidatedTreeContext> {
149            fn as_rule_node(&self) -> $crate::RuleNodeView<'a> {
150                self.$rule_node_method()
151            }
152        }
153
154        #[allow(dead_code, clippy::all)]
155        impl<'a> $context<'a> {
156            fn __from_node(node: $crate::RuleNodeView<'a>) -> Self {
157                Self::__from_node_with_invocation_states(node, None)
158            }
159
160            fn __from_child_node(
161                node: $crate::RuleNodeView<'a>,
162                parent_invocation_states: Option<&[isize]>,
163            ) -> Self {
164                let invocation_states = parent_invocation_states.map(|states| {
165                    let mut invocation_states = Vec::with_capacity(states.len() + 1);
166                    invocation_states.push(node.invoking_state());
167                    invocation_states.extend_from_slice(states);
168                    invocation_states
169                });
170                Self::__from_node_with_invocation_states(node, invocation_states)
171            }
172
173            fn __from_listener_node(
174                node: $crate::RuleNodeView<'a>,
175                invocation_states: Option<&[isize]>,
176            ) -> Self {
177                Self::__from_node_with_invocation_states(
178                    node,
179                    invocation_states.map(<[isize]>::to_vec),
180                )
181            }
182
183            fn __from_node_with_invocation_states(
184                node: $crate::RuleNodeView<'a>,
185                invocation_states: Option<Vec<isize>>,
186            ) -> Self {
187                $(
188                    let __default = <$attrs>::default();
189                    let __attrs = node.generated_attrs::<$attrs>().unwrap_or(&__default);
190                )?
191                Self {
192                    __node: __GeneratedRuleContext::Stored(node),
193                    __invocation_states: invocation_states,
194                    __state: std::marker::PhantomData,
195                    $(
196                        $($field: __attrs.$field.clone(),)+
197                    )?
198                }
199            }
200        }
201
202        #[allow(dead_code, clippy::all)]
203        impl<'a, State> $context<'a, State> {
204            pub fn $child_count_method(&self) -> usize {
205                match &self.__node {
206                    __GeneratedRuleContext::Stored(node) => node.child_count(),
207                    __GeneratedRuleContext::Active { context, .. } => context.child_count(),
208                }
209            }
210
211            /// Iterates terminals owned directly by this context without
212            /// descending into nested rule contexts.
213            ///
214            /// Recovered trees expose inserted and deleted recovery tokens as
215            /// error nodes through the same `TerminalNode` surface. Use
216            /// `TerminalNode::is_error()` to identify recovery nodes and
217            /// `TerminalNode::is_missing()` to identify inserted synthetic
218            /// tokens.
219            pub fn $direct_terminals_method(
220                &self,
221            ) -> impl Iterator<Item = TerminalNode<'a>> + 'a + use<'a, State> {
222                __terminal_children(self.__node).map(TerminalNode::new)
223            }
224
225            pub fn $start_method(&self) -> __GeneratedTokenView {
226                let token = match &self.__node {
227                    __GeneratedRuleContext::Stored(node) => node.start(),
228                    __GeneratedRuleContext::Active {
229                        context, tokens, ..
230                    } => context.start(tokens),
231                };
232                __GeneratedTokenView {
233                    text: token
234                        .map(|token| token.text_or_empty().to_owned())
235                        .unwrap_or_default(),
236                }
237            }
238
239            pub fn $text_method(&self) -> String {
240                match &self.__node {
241                    __GeneratedRuleContext::Stored(node) => node.text(),
242                    __GeneratedRuleContext::Active {
243                        context,
244                        storage,
245                        tokens,
246                    } => context.text(storage, tokens),
247                }
248            }
249        }
250
251        #[allow(dead_code, clippy::all)]
252        impl<'a> $context<'a, ValidatedTreeContext> {
253            fn __from_validated_node(node: $crate::RuleNodeView<'a>) -> Self {
254                Self::__from_validated_node_with_invocation_states(node, None)
255            }
256
257            fn __from_validated_child_node(
258                node: $crate::RuleNodeView<'a>,
259                parent_invocation_states: Option<&[isize]>,
260            ) -> Self {
261                let invocation_states = parent_invocation_states.map(|states| {
262                    let mut invocation_states = Vec::with_capacity(states.len() + 1);
263                    invocation_states.push(node.invoking_state());
264                    invocation_states.extend_from_slice(states);
265                    invocation_states
266                });
267                Self::__from_validated_node_with_invocation_states(node, invocation_states)
268            }
269
270            fn __from_validated_listener_node(
271                node: $crate::RuleNodeView<'a>,
272                invocation_states: Option<&[isize]>,
273            ) -> Self {
274                Self::__from_validated_node_with_invocation_states(
275                    node,
276                    invocation_states.map(<[isize]>::to_vec),
277                )
278            }
279
280            fn __from_validated_node_with_invocation_states(
281                node: $crate::RuleNodeView<'a>,
282                invocation_states: Option<Vec<isize>>,
283            ) -> Self {
284                $(
285                    let __default = <$attrs>::default();
286                    let __attrs = node.generated_attrs::<$attrs>().unwrap_or(&__default);
287                )?
288                Self {
289                    __node: __GeneratedRuleContext::Stored(node),
290                    __invocation_states: invocation_states,
291                    __state: std::marker::PhantomData,
292                    $(
293                        $($field: __attrs.$field.clone(),)+
294                    )?
295                }
296            }
297
298            pub fn $rule_node_method(&self) -> $crate::RuleNodeView<'a> {
299                match self.__node {
300                    __GeneratedRuleContext::Stored(node) => node,
301                    __GeneratedRuleContext::Active { .. } => {
302                        unreachable!("validated context contains an active parser context")
303                    }
304                }
305            }
306        }
307
308        impl<State> std::fmt::Display for $context<'_, State> {
309            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310                match &self.__invocation_states {
311                    Some(states) => __write_invocation_states(f, states.iter().copied()),
312                    None => match self.__node {
313                        __GeneratedRuleContext::Stored(node) => {
314                            __write_invocation_states(f, node.invocation_states())
315                        }
316                        __GeneratedRuleContext::Active { .. } => {
317                            unreachable!("active context is missing invocation states")
318                        }
319                    },
320                }
321            }
322        }
323    };
324    // Legacy validated-downcast impl (generated-code API revisions 9 and
325    // earlier): `FromValidatedRuleNode` and `ValidatedRuleNode` resolve to the
326    // invoking module's own definitions.
327    (@from_validated , $context:ident, $rule_index:expr, $kind_mode:ident $(($kind:expr))?) => {
328        impl<'a> FromValidatedRuleNode<'a> for $context<'a, ValidatedTreeContext> {
329            fn from_validated_rule_node(node: ValidatedRuleNode<'a>) -> Option<Self> {
330                let node = node.rule_node();
331                if node.rule_index() != $rule_index
332                    || $crate::__antlr4_rust_context!(
333                        @stored_kind_mismatch $kind_mode $(($kind))?, node
334                    )
335                {
336                    return None;
337                }
338                Some(Self::__from_validated_node(node))
339            }
340        }
341    };
342    // Branded validated-downcast impl (revision 10 and later): the runtime
343    // owns the trait and node type, and the module-local
344    // `ValidatedTreeContext` marker brands them for this grammar so
345    // `downcast_ref` cannot resolve a node against another grammar's
346    // contexts.
347    (@from_validated branded, $context:ident, $rule_index:expr, $kind_mode:ident $(($kind:expr))?) => {
348        impl<'a> $crate::FromValidatedRuleNode<'a> for $context<'a, ValidatedTreeContext> {
349            type Grammar = ValidatedTreeContext;
350
351            fn from_validated_rule_node(
352                node: $crate::ValidatedRuleNode<'a, ValidatedTreeContext>,
353            ) -> Option<Self> {
354                let node = node.rule_node();
355                if node.rule_index() != $rule_index
356                    || $crate::__antlr4_rust_context!(
357                        @stored_kind_mismatch $kind_mode $(($kind))?, node
358                    )
359                {
360                    return None;
361                }
362                Some(Self::__from_validated_node(node))
363            }
364        }
365    };
366    (@stored_kind_mismatch any, $node:expr) => {
367        false
368    };
369    (@stored_kind_mismatch exact($kind:expr), $node:expr) => {
370        __context_kind($node) != $kind
371    };
372    (@active_kind_mismatch any, $context:expr, $storage:expr, $tokens:expr) => {
373        false
374    };
375    (@active_kind_mismatch exact($kind:expr), $context:expr, $storage:expr, $tokens:expr) => {
376        __active_context_kind($context, $storage, $tokens) != $kind
377    };
378}
379
380/// Expands one declarative accessor list into both state-variant impls of a
381/// generated typed parser context: the recovery-oriented impl (generic over
382/// the module's `__RecoveryContextState`, returning `Result<_,
383/// MissingChildError>` for required children) and the validated impl
384/// (`ValidatedTreeContext`, returning required children directly).
385///
386/// Accessor declarations, one per generated method:
387///
388/// ```text
389/// rule <method>: required(<ChildContext>[<child rule index>], "<child name>"),
390/// rule <method>: optional(<ChildContext>[<child rule index>]),
391/// rule <method>: many(<ChildContext>[<child rule index>]),
392/// token <method>: required(<token type>, "<token name>"),
393/// token <method>: optional(<token type>),
394/// token <method>: many(<token type>),
395/// label_rule <method>: required(<selector>, <ChildContext>[<child rule index>], "<label>"),
396/// label_rule <method>: optional(<selector>, <ChildContext>[<child rule index>]),
397/// label_rule <method>: many(skip(<n>), <ChildContext>[<child rule index>]),
398/// label_token <method>: required(<selector>, [<token types>], "<label>"),
399/// label_token <method>: optional(<selector>, [<token types>]),
400/// label_token <method>: many(skip(<n>), [<token types>]),
401/// ```
402///
403/// where `<selector>` is `nth(<n>)` or `last_after(<n>)`. All names, indices,
404/// and token types are grammar data supplied by the generated invocation. The
405/// support items (`__rule_children`, `__token_children`,
406/// `__labeled_token_children`, `__labeled_token_children_matching`,
407/// `TerminalNode`, `__RecoveryContextState`) are runtime-owned
408/// [`crate::generated`] items the generated module imports by name, and
409/// `ValidatedRuleNode`/`FromValidatedRuleNode` resolve in the generated
410/// module's scope (module-local definitions through generated-code API
411/// revision 9; from revision 10, a module-local alias of
412/// [`crate::validated::ValidatedRuleNode`] branded with the module's
413/// `ValidatedTreeContext` marker, plus a re-export of
414/// [`crate::validated::FromValidatedRuleNode`]); `ValidatedTreeContext` plus the
415/// `__from_child_node`/`__from_validated_child_node` constructors and the
416/// `__node`/`__invocation_states` context fields stay emitted per generated
417/// module (the validated marker must remain crate-local for the two impl
418/// blocks below to be coherent), exactly as `__antlr4_rust_context!` relies
419/// on.
420#[doc(hidden)]
421#[macro_export]
422macro_rules! __antlr4_rust_context_accessors {
423    (
424        $context:ident {
425            $( $kind:tt $method:ident: $card:tt $payload:tt ),* $(,)?
426        }
427    ) => {
428        #[allow(dead_code, private_bounds, clippy::all)]
429        impl<'a, State: __RecoveryContextState> $context<'a, State> {
430            $(
431                $crate::__antlr4_rust_context_accessors!(
432                    @recovered $context, $kind $card $method $payload
433                );
434            )*
435        }
436
437        #[allow(dead_code, clippy::all)]
438        impl<'a> $context<'a, ValidatedTreeContext> {
439            $(
440                $crate::__antlr4_rust_context_accessors!(
441                    @validated $context, $kind $card $method $payload
442                );
443            )*
444        }
445    };
446
447    // Recovery-oriented rule children.
448    (@recovered $context:ident, rule required $method:ident ($child:ident[$index:expr], $name:literal)) => {
449        pub fn $method(&self) -> Result<$child<'a>, $crate::MissingChildError> {
450            __rule_children(self.__node, $index)
451                .next()
452                .map(|node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
453                .ok_or_else(|| $crate::MissingChildError::new(stringify!($context), $name))
454        }
455    };
456    (@recovered $context:ident, rule optional $method:ident ($child:ident[$index:expr])) => {
457        pub fn $method(&self) -> Option<$child<'a>> {
458            __rule_children(self.__node, $index)
459                .next()
460                .map(|node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
461        }
462    };
463    (@recovered $context:ident, rule many $method:ident ($child:ident[$index:expr])) => {
464        pub fn $method(&self) -> impl Iterator<Item = $child<'a>> + '_ {
465            __rule_children(self.__node, $index)
466                .map(move |node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
467        }
468    };
469
470    // Recovery-oriented token children.
471    (@recovered $context:ident, token required $method:ident ($token_type:expr, $name:literal)) => {
472        pub fn $method(&self) -> Result<TerminalNode<'a>, $crate::MissingChildError> {
473            __token_children(self.__node, $token_type)
474                .next()
475                .map(TerminalNode::new)
476                .ok_or_else(|| $crate::MissingChildError::new(stringify!($context), $name))
477        }
478    };
479    (@recovered $context:ident, token optional $method:ident ($token_type:expr)) => {
480        pub fn $method(&self) -> Option<TerminalNode<'a>> {
481            __token_children(self.__node, $token_type)
482                .next()
483                .map(TerminalNode::new)
484        }
485    };
486    (@recovered $context:ident, token many $method:ident ($token_type:expr)) => {
487        pub fn $method(&self) -> impl Iterator<Item = TerminalNode<'a>> + '_ {
488            __token_children(self.__node, $token_type).map(TerminalNode::new)
489        }
490    };
491
492    // Recovery-oriented labeled rule children.
493    (@recovered $context:ident, label_rule required $method:ident ($sel:ident($selarg:expr), $child:ident[$index:expr], $name:literal)) => {
494        pub fn $method(&self) -> Result<$child<'a>, $crate::MissingChildError> {
495            $crate::__antlr4_rust_context_accessors!(
496                @selected(__rule_children(self.__node, $index)) $sel($selarg)
497            )
498            .map(|node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
499            .ok_or_else(|| $crate::MissingChildError::new(stringify!($context), $name))
500        }
501    };
502    (@recovered $context:ident, label_rule optional $method:ident ($sel:ident($selarg:expr), $child:ident[$index:expr])) => {
503        pub fn $method(&self) -> Option<$child<'a>> {
504            $crate::__antlr4_rust_context_accessors!(
505                @selected(__rule_children(self.__node, $index)) $sel($selarg)
506            )
507            .map(|node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
508        }
509    };
510    (@recovered $context:ident, label_rule many $method:ident (skip($skip:expr), $child:ident[$index:expr])) => {
511        pub fn $method(&self) -> impl Iterator<Item = $child<'a>> + '_ {
512            __rule_children(self.__node, $index)
513                .skip($skip)
514                .map(move |node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
515        }
516    };
517
518    // Recovery-oriented labeled token children.
519    (@recovered $context:ident, label_token required $method:ident ($sel:ident($selarg:expr), $tokens:tt, $name:literal)) => {
520        pub fn $method(&self) -> Result<TerminalNode<'a>, $crate::MissingChildError> {
521            $crate::__antlr4_rust_context_accessors!(
522                @selected($crate::__antlr4_rust_context_accessors!(
523                    @labeled_token_children(self.__node) $tokens
524                )) $sel($selarg)
525            )
526            .map(TerminalNode::new)
527            .ok_or_else(|| $crate::MissingChildError::new(stringify!($context), $name))
528        }
529    };
530    (@recovered $context:ident, label_token optional $method:ident ($sel:ident($selarg:expr), $tokens:tt)) => {
531        pub fn $method(&self) -> Option<TerminalNode<'a>> {
532            $crate::__antlr4_rust_context_accessors!(
533                @selected($crate::__antlr4_rust_context_accessors!(
534                    @labeled_token_children(self.__node) $tokens
535                )) $sel($selarg)
536            )
537            .map(TerminalNode::new)
538        }
539    };
540    (@recovered $context:ident, label_token many $method:ident (skip($skip:expr), $tokens:tt)) => {
541        pub fn $method(&self) -> impl Iterator<Item = TerminalNode<'a>> + '_ {
542            $crate::__antlr4_rust_context_accessors!(
543                @labeled_token_children(self.__node) $tokens
544            )
545            .skip($skip)
546            .map(TerminalNode::new)
547        }
548    };
549
550    // Validated rule children.
551    (@validated $context:ident, rule required $method:ident ($child:ident[$index:expr], $name:literal)) => {
552        pub fn $method(&self) -> $child<'a, ValidatedTreeContext> {
553            let Some(node) = __rule_children(self.__node, $index).next() else {
554                unreachable!(concat!(
555                    "validated ",
556                    stringify!($context),
557                    " is missing required child ",
558                    $name
559                ))
560            };
561            $child::<ValidatedTreeContext>::__from_validated_child_node(
562                node,
563                self.__invocation_states.as_deref(),
564            )
565        }
566    };
567    (@validated $context:ident, rule optional $method:ident ($child:ident[$index:expr])) => {
568        pub fn $method(&self) -> Option<$child<'a, ValidatedTreeContext>> {
569            __rule_children(self.__node, $index)
570                .next()
571                .map(|node| {
572                    $child::<ValidatedTreeContext>::__from_validated_child_node(
573                        node,
574                        self.__invocation_states.as_deref(),
575                    )
576                })
577        }
578    };
579    (@validated $context:ident, rule many $method:ident ($child:ident[$index:expr])) => {
580        pub fn $method(&self) -> impl Iterator<Item = $child<'a, ValidatedTreeContext>> + '_ {
581            __rule_children(self.__node, $index).map(move |node| {
582                $child::<ValidatedTreeContext>::__from_validated_child_node(
583                    node,
584                    self.__invocation_states.as_deref(),
585                )
586            })
587        }
588    };
589
590    // Validated token children.
591    (@validated $context:ident, token required $method:ident ($token_type:expr, $name:literal)) => {
592        pub fn $method(&self) -> TerminalNode<'a> {
593            let Some(node) = __token_children(self.__node, $token_type).next() else {
594                unreachable!(concat!(
595                    "validated ",
596                    stringify!($context),
597                    " is missing required child ",
598                    $name
599                ))
600            };
601            TerminalNode::new(node)
602        }
603    };
604    (@validated $context:ident, token optional $method:ident ($token_type:expr)) => {
605        pub fn $method(&self) -> Option<TerminalNode<'a>> {
606            __token_children(self.__node, $token_type)
607                .next()
608                .map(TerminalNode::new)
609        }
610    };
611    (@validated $context:ident, token many $method:ident ($token_type:expr)) => {
612        pub fn $method(&self) -> impl Iterator<Item = TerminalNode<'a>> + '_ {
613            __token_children(self.__node, $token_type).map(TerminalNode::new)
614        }
615    };
616
617    // Validated labeled rule children.
618    (@validated $context:ident, label_rule required $method:ident ($sel:ident($selarg:expr), $child:ident[$index:expr], $name:literal)) => {
619        pub fn $method(&self) -> $child<'a, ValidatedTreeContext> {
620            let Some(node) = $crate::__antlr4_rust_context_accessors!(
621                @selected(__rule_children(self.__node, $index)) $sel($selarg)
622            ) else {
623                unreachable!(concat!(
624                    "validated ",
625                    stringify!($context),
626                    " is missing required child ",
627                    $name
628                ))
629            };
630            $child::<ValidatedTreeContext>::__from_validated_child_node(
631                node,
632                self.__invocation_states.as_deref(),
633            )
634        }
635    };
636    (@validated $context:ident, label_rule optional $method:ident ($sel:ident($selarg:expr), $child:ident[$index:expr])) => {
637        pub fn $method(&self) -> Option<$child<'a, ValidatedTreeContext>> {
638            $crate::__antlr4_rust_context_accessors!(
639                @selected(__rule_children(self.__node, $index)) $sel($selarg)
640            )
641            .map(|node| {
642                $child::<ValidatedTreeContext>::__from_validated_child_node(
643                    node,
644                    self.__invocation_states.as_deref(),
645                )
646            })
647        }
648    };
649    (@validated $context:ident, label_rule many $method:ident (skip($skip:expr), $child:ident[$index:expr])) => {
650        pub fn $method(&self) -> impl Iterator<Item = $child<'a, ValidatedTreeContext>> + '_ {
651            __rule_children(self.__node, $index)
652                .skip($skip)
653                .map(move |node| {
654                    $child::<ValidatedTreeContext>::__from_validated_child_node(
655                        node,
656                        self.__invocation_states.as_deref(),
657                    )
658                })
659        }
660    };
661
662    // Validated labeled token children.
663    (@validated $context:ident, label_token required $method:ident ($sel:ident($selarg:expr), $tokens:tt, $name:literal)) => {
664        pub fn $method(&self) -> TerminalNode<'a> {
665            let Some(node) = $crate::__antlr4_rust_context_accessors!(
666                @selected($crate::__antlr4_rust_context_accessors!(
667                    @labeled_token_children(self.__node) $tokens
668                )) $sel($selarg)
669            ) else {
670                unreachable!(concat!(
671                    "validated ",
672                    stringify!($context),
673                    " is missing required child ",
674                    $name
675                ))
676            };
677            TerminalNode::new(node)
678        }
679    };
680    (@validated $context:ident, label_token optional $method:ident ($sel:ident($selarg:expr), $tokens:tt)) => {
681        pub fn $method(&self) -> Option<TerminalNode<'a>> {
682            $crate::__antlr4_rust_context_accessors!(
683                @selected($crate::__antlr4_rust_context_accessors!(
684                    @labeled_token_children(self.__node) $tokens
685                )) $sel($selarg)
686            )
687            .map(TerminalNode::new)
688        }
689    };
690    (@validated $context:ident, label_token many $method:ident (skip($skip:expr), $tokens:tt)) => {
691        pub fn $method(&self) -> impl Iterator<Item = TerminalNode<'a>> + '_ {
692            $crate::__antlr4_rust_context_accessors!(
693                @labeled_token_children(self.__node) $tokens
694            )
695            .skip($skip)
696            .map(TerminalNode::new)
697        }
698    };
699
700    // Label occurrence selectors.
701    (@selected($children:expr) nth($occurrence:expr)) => {
702        $children.nth($occurrence)
703    };
704    (@selected($children:expr) last_after($skip:expr)) => {
705        $children.skip($skip).last()
706    };
707
708    // Labeled token child sources: a single token type uses the scalar
709    // helper; a set uses the matching helper.
710    (@labeled_token_children($node:expr) [$token_type:expr]) => {
711        __labeled_token_children($node, $token_type)
712    };
713    (@labeled_token_children($node:expr) [$($token_type:expr),+ $(,)?]) => {
714        __labeled_token_children_matching($node, &[$($token_type),+])
715    };
716
717    // Catch-alls that name the offending declaration instead of failing with
718    // a bare `no rules expected this token` deep inside a generated module.
719    // The structured arms reconstruct the source declaration order; the
720    // trailing generic arms catch shapes that do not even parse as one.
721    (@recovered $context:ident, $kind:tt $card:tt $method:ident $payload:tt) => {
722        compile_error!(concat!(
723            "unsupported generated accessor declaration for ",
724            stringify!($context),
725            ": ",
726            stringify!($kind),
727            " ",
728            stringify!($method),
729            ": ",
730            stringify!($card),
731            stringify!($payload)
732        ));
733    };
734    (@validated $context:ident, $kind:tt $card:tt $method:ident $payload:tt) => {
735        compile_error!(concat!(
736            "unsupported generated accessor declaration for ",
737            stringify!($context),
738            ": ",
739            stringify!($kind),
740            " ",
741            stringify!($method),
742            ": ",
743            stringify!($card),
744            stringify!($payload)
745        ));
746    };
747    (@recovered $context:ident, $($declaration:tt)*) => {
748        compile_error!(concat!(
749            "unsupported generated accessor declaration for ",
750            stringify!($context),
751            ": ",
752            stringify!($($declaration)*)
753        ));
754    };
755    (@validated $context:ident, $($declaration:tt)*) => {
756        compile_error!(concat!(
757            "unsupported generated accessor declaration for ",
758            stringify!($context),
759            ": ",
760            stringify!($($declaration)*)
761        ));
762    };
763    (@selected($children:expr) $($selector:tt)*) => {
764        compile_error!(concat!(
765            "unsupported generated accessor selector: ",
766            stringify!($($selector)*)
767        ))
768    };
769    (@labeled_token_children($node:expr) $($tokens:tt)*) => {
770        compile_error!(concat!(
771            "unsupported generated accessor token set: ",
772            stringify!($($tokens)*)
773        ))
774    };
775}
776
777/// Defines the grammar-independent facade and trait delegation for one
778/// generated lexer.
779#[doc(hidden)]
780#[macro_export]
781macro_rules! __antlr4_rust_lexer_facade {
782    (
783        type: $lexer:ident<$input:ident, $hooks:ident>,
784        fields: {
785            base: $base:ident,
786            hooks: $hooks_field:ident $(,)?
787        },
788        metadata: $metadata:path,
789        next_token($this:ident, $sink:ident) $next_token:block
790        $(,)?
791    ) => {
792        impl<$input, $hooks> $lexer<$input, $hooks>
793        where
794            $input: $crate::char_stream::CharStream,
795            $hooks: $crate::parser::SemanticHooks,
796        {
797            pub fn metadata() -> &'static $crate::generated::GrammarMetadata {
798                $metadata()
799            }
800
801            /// Adds a listener for lexer diagnostics.
802            pub fn add_error_listener<T>(&mut self, listener: T)
803            where
804                T: for<'a> $crate::errors::ErrorListener<dyn $crate::recognizer::Recognizer + 'a>
805                    + ::core::marker::Send
806                    + 'static,
807            {
808                $crate::recognizer::Recognizer::add_error_listener(&mut self.$base, listener);
809            }
810
811            /// Removes every lexer error listener, including the default console listener.
812            pub fn remove_error_listeners(&mut self) {
813                $crate::recognizer::Recognizer::remove_error_listeners(&mut self.$base);
814            }
815
816            /// Routes every token through ATN interpretation instead of the compiled
817            /// lexer DFA, so the learned-DFA trace (`lexer_dfa_string`) observes each
818            /// match.
819            pub fn set_force_interpreted(&mut self, force_interpreted: bool) {
820                self.$base.set_force_interpreted(force_interpreted);
821            }
822
823            /// Resets this lexer and any caller-owned lifecycle state for reuse.
824            pub fn reset(&mut self) {
825                if <$hooks as $crate::parser::SemanticHooks>::ENABLES_LEXER_LIFECYCLE {
826                    $crate::atn::lexer::reset_with_semantic_hooks(
827                        &mut self.$base,
828                        &mut self.$hooks_field,
829                    );
830                } else {
831                    self.$base.reset();
832                }
833            }
834
835            /// Replaces the input stream and resets runtime and lifecycle state.
836            pub fn set_input_stream(&mut self, input: $input) {
837                if <$hooks as $crate::parser::SemanticHooks>::ENABLES_LEXER_LIFECYCLE {
838                    $crate::atn::lexer::set_input_stream_with_semantic_hooks(
839                        &mut self.$base,
840                        &mut self.$hooks_field,
841                        input,
842                    );
843                } else {
844                    self.$base.set_input_stream(input);
845                }
846            }
847
848            /// Clears the learned lexer DFA shared by this grammar.
849            pub fn clear_dfa(&self) {
850                self.$base.clear_dfa();
851            }
852
853            /// Returns learned lexer-DFA shape and optional action-payload storage.
854            #[must_use]
855            pub fn lexer_dfa_stats(&self) -> $crate::lexer::LexerDfaStats {
856                self.$base.lexer_dfa_stats()
857            }
858        }
859
860        impl<$input, $hooks> $crate::generated::GeneratedLexer for $lexer<$input, $hooks>
861        where
862            $input: $crate::char_stream::CharStream,
863            $hooks: $crate::parser::SemanticHooks,
864        {
865            fn metadata() -> &'static $crate::generated::GrammarMetadata {
866                $metadata()
867            }
868        }
869
870        impl<$input, $hooks> $crate::recognizer::Recognizer for $lexer<$input, $hooks>
871        where
872            $input: $crate::char_stream::CharStream,
873            $hooks: $crate::parser::SemanticHooks,
874        {
875            fn data(&self) -> &$crate::recognizer::RecognizerData {
876                $crate::recognizer::Recognizer::data(&self.$base)
877            }
878
879            fn data_mut(&mut self) -> &mut $crate::recognizer::RecognizerData {
880                $crate::recognizer::Recognizer::data_mut(&mut self.$base)
881            }
882        }
883
884        impl<$input, $hooks> $crate::lexer::Lexer for $lexer<$input, $hooks>
885        where
886            $input: $crate::char_stream::CharStream,
887            $hooks: $crate::parser::SemanticHooks,
888        {
889            fn mode(&self) -> i32 {
890                $crate::lexer::Lexer::mode(&self.$base)
891            }
892
893            fn set_mode(&mut self, mode: i32) {
894                $crate::lexer::Lexer::set_mode(&mut self.$base, mode);
895            }
896
897            fn push_mode(&mut self, mode: i32) {
898                $crate::lexer::Lexer::push_mode(&mut self.$base, mode);
899            }
900
901            fn pop_mode(&mut self) -> ::core::option::Option<i32> {
902                $crate::lexer::Lexer::pop_mode(&mut self.$base)
903            }
904        }
905
906        impl<$input, $hooks> $crate::token::TokenSource for $lexer<$input, $hooks>
907        where
908            $input: $crate::char_stream::CharStream,
909            $hooks: $crate::parser::SemanticHooks,
910        {
911            fn next_token(
912                &mut self,
913                $sink: &mut $crate::token::TokenSink<'_>,
914            ) -> ::core::result::Result<$crate::token::TokenId, $crate::token::TokenStoreError>
915            {
916                let $this = self;
917                $next_token
918            }
919
920            fn line(&self) -> usize {
921                self.$base.line()
922            }
923
924            fn column(&self) -> usize {
925                self.$base.column()
926            }
927
928            fn source_name(&self) -> &str {
929                self.$base.source_name()
930            }
931
932            fn source_text(&self) -> ::core::option::Option<::std::rc::Rc<str>> {
933                self.$base.source_text()
934            }
935
936            fn drain_errors(&mut self) -> ::std::vec::Vec<$crate::token::TokenSourceError> {
937                self.$base.drain_errors()
938            }
939
940            fn report_error(&self, source_error: &$crate::token::TokenSourceError) -> bool {
941                $crate::recognizer::Recognizer::notify_error_listeners(self, source_error.into());
942                true
943            }
944
945            fn lexer_dfa_string(&self) -> ::std::string::String {
946                self.$base.lexer_dfa_string()
947            }
948        }
949    };
950}
951
952/// Defines the grammar-independent facade and trait delegation for one
953/// generated parser.
954#[doc(hidden)]
955#[macro_export]
956macro_rules! __antlr4_rust_parser_facade {
957    (
958        type: $parser:ident<$source:ident, $hooks:ident>,
959        fields: {
960            base: $base:ident,
961            simulator: $simulator:ident,
962            generated_only: $generated_only:ident $(,)?
963        },
964        metadata: $metadata:path,
965        parser_atn: $parser_atn:path,
966        reset($this:ident) $reset:block
967        $(,)?
968    ) => {
969        impl<$source, $hooks> $parser<$source, $hooks>
970        where
971            $source: $crate::token::TokenSource,
972            $hooks: $crate::parser::SemanticHooks,
973        {
974            pub fn metadata() -> &'static $crate::generated::GrammarMetadata {
975                $metadata()
976            }
977
978            /// Adds a listener for parser diagnostics.
979            pub fn add_error_listener<T>(&mut self, listener: T)
980            where
981                T: for<'a> $crate::errors::ErrorListener<dyn $crate::recognizer::Recognizer + 'a>
982                    + ::core::marker::Send
983                    + 'static,
984            {
985                $crate::recognizer::Recognizer::add_error_listener(&mut self.$base, listener);
986            }
987
988            /// Removes every parser error listener, including the default console listener.
989            pub fn remove_error_listeners(&mut self) {
990                $crate::recognizer::Recognizer::remove_error_listeners(&mut self.$base);
991            }
992
993            /// Registers a listener for committed rule enter/exit events during
994            /// recognition (ANTLR's `addParseListener`). See
995            /// [`antlr4_runtime::ParseListener`] for the delivery contract.
996            pub fn add_parse_listener<T>(&mut self, listener: T)
997            where
998                T: $crate::parser::ParseListener + 'static,
999            {
1000                self.$base.add_parse_listener(listener);
1001            }
1002
1003            /// Removes every registered parse listener and returns them, dropping
1004            /// any sticky abort a removed listener had requested.
1005            pub fn remove_parse_listeners(
1006                &mut self,
1007            ) -> ::std::vec::Vec<::std::boxed::Box<dyn $crate::parser::ParseListener>> {
1008                self.$base.remove_parse_listeners()
1009            }
1010
1011            /// Fully resets parser-owned state and rewinds the current token stream.
1012            pub fn reset(&mut self) {
1013                self.$base.reset();
1014                if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
1015                    simulator.reset();
1016                }
1017                let $this = &mut *self;
1018                $reset
1019            }
1020
1021            /// Replaces the token stream and fully resets parser-owned state.
1022            pub fn set_token_stream(
1023                &mut self,
1024                input: $crate::token_stream::CommonTokenStream<$source>,
1025            ) {
1026                self.$base.set_token_stream(input);
1027                if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
1028                    simulator.reset();
1029                }
1030                let $this = &mut *self;
1031                $reset
1032            }
1033
1034            #[must_use]
1035            pub const fn token_stream(&self) -> &$crate::token_stream::CommonTokenStream<$source> {
1036                self.$base.token_stream()
1037            }
1038
1039            #[must_use]
1040            pub const fn token_stream_mut(
1041                &mut self,
1042            ) -> &mut $crate::token_stream::CommonTokenStream<$source> {
1043                self.$base.token_stream_mut()
1044            }
1045
1046            #[must_use]
1047            pub const fn token_store(&self) -> &$crate::token::TokenStore {
1048                self.$base.token_store()
1049            }
1050
1051            #[must_use]
1052            pub const fn parse_tree_storage(&self) -> &$crate::tree::ParseTreeStorage {
1053                self.$base.parse_tree_storage()
1054            }
1055
1056            #[must_use]
1057            pub fn prediction_context_stats(&self) -> $crate::prediction::PredictionContextStats {
1058                self.$simulator.as_ref().map_or_else(
1059                    $crate::prediction::PredictionContextStats::default,
1060                    $crate::atn::parser::ParserAtnSimulator::prediction_context_stats,
1061                )
1062            }
1063
1064            #[must_use]
1065            pub fn parser_dfa_stats(&self) -> $crate::dfa::ParserDfaStats {
1066                self.$simulator.as_ref().map_or_else(
1067                    $crate::dfa::ParserDfaStats::default,
1068                    $crate::atn::parser::ParserAtnSimulator::parser_dfa_stats,
1069                )
1070            }
1071
1072            /// Clears this grammar's learned parser decision DFAs.
1073            pub fn clear_dfa(&mut self) {
1074                if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
1075                    simulator.clear_dfa();
1076                } else {
1077                    $crate::atn::parser::ParserAtnSimulator::clear_shared_dfa($parser_atn());
1078                }
1079                let $this = &mut *self;
1080                $reset
1081            }
1082
1083            #[must_use]
1084            pub fn node(&self, id: $crate::tree::NodeId) -> $crate::tree::Node<'_> {
1085                self.$base.node(id)
1086            }
1087
1088            #[must_use]
1089            pub fn into_token_stream(self) -> $crate::token_stream::CommonTokenStream<$source> {
1090                self.$base.into_token_stream()
1091            }
1092
1093            #[must_use]
1094            pub fn into_token_store(self) -> $crate::token::TokenStore {
1095                self.$base.into_token_store()
1096            }
1097
1098            #[must_use]
1099            pub fn into_parsed_file(self, root: $crate::tree::NodeId) -> $crate::tree::ParsedFile {
1100                self.$base.into_parsed_file(root)
1101            }
1102
1103            /// Compiles a tree pattern rooted at parser rule `rule_index`.
1104            ///
1105            /// Mirrors ANTLR's `Parser.compileParseTreePattern`. Literal chunks of
1106            /// `pattern` are lexed with a fresh lexer built by `make_lexer`.
1107            pub fn compile_parse_tree_pattern<PL>(
1108                &self,
1109                pattern: &str,
1110                rule_index: usize,
1111                mut make_lexer: impl ::core::ops::FnMut($crate::char_stream::InputStream) -> PL,
1112            ) -> ::core::result::Result<
1113                $crate::tree_pattern::ParseTreePattern,
1114                $crate::tree_pattern::ParseTreePatternError,
1115            >
1116            where
1117                PL: $crate::token::TokenSource,
1118            {
1119                static PATTERN_DATA: ::std::sync::OnceLock<$crate::recognizer::RecognizerData> =
1120                    ::std::sync::OnceLock::new();
1121                static PATTERN_MATCHER: ::std::sync::OnceLock<
1122                    $crate::tree_pattern::ParseTreePatternMatcher<'static>,
1123                > = ::std::sync::OnceLock::new();
1124                let matcher = match PATTERN_MATCHER.get() {
1125                    ::core::option::Option::Some(matcher) => matcher,
1126                    ::core::option::Option::None => {
1127                        let data = PATTERN_DATA.get_or_init(|| $metadata().recognizer_data());
1128                        let matcher = $crate::tree_pattern::ParseTreePatternMatcher::new(
1129                            $parser_atn(),
1130                            data,
1131                        )?;
1132                        PATTERN_MATCHER.get_or_init(|| matcher)
1133                    }
1134                };
1135                matcher.compile(pattern, rule_index, move |text: &str| {
1136                    $crate::tree_pattern::lex_pattern_chunk(text, &mut make_lexer)
1137                })
1138            }
1139
1140            #[allow(dead_code)]
1141            fn simulator(&mut self) -> &mut $crate::atn::parser::ParserAtnSimulator<'static> {
1142                self.$simulator.get_or_insert_with(|| {
1143                    $crate::atn::parser::ParserAtnSimulator::new_shared($parser_atn())
1144                })
1145            }
1146
1147            #[allow(dead_code)]
1148            fn generated_only(&self) -> bool {
1149                self.$generated_only
1150            }
1151        }
1152
1153        impl<$source, $hooks> $crate::generated::GeneratedParser for $parser<$source, $hooks>
1154        where
1155            $source: $crate::token::TokenSource,
1156            $hooks: $crate::parser::SemanticHooks,
1157        {
1158            fn metadata() -> &'static $crate::generated::GrammarMetadata {
1159                $metadata()
1160            }
1161
1162            fn parser_atn() -> &'static $crate::atn::parser_atn::ParserAtn {
1163                $parser_atn()
1164            }
1165        }
1166
1167        impl<$source, $hooks> $crate::generated::GeneratedRuleParser for $parser<$source, $hooks>
1168        where
1169            $source: $crate::token::TokenSource,
1170            $hooks: $crate::parser::SemanticHooks,
1171        {
1172            type Source = $source;
1173            type Hooks = $hooks;
1174
1175            fn generated_rule_base(
1176                &mut self,
1177            ) -> &mut $crate::parser::BaseParser<Self::Source, Self::Hooks> {
1178                &mut self.$base
1179            }
1180        }
1181
1182        impl<$source, $hooks> $crate::recognizer::Recognizer for $parser<$source, $hooks>
1183        where
1184            $source: $crate::token::TokenSource,
1185            $hooks: $crate::parser::SemanticHooks,
1186        {
1187            fn data(&self) -> &$crate::recognizer::RecognizerData {
1188                $crate::recognizer::Recognizer::data(&self.$base)
1189            }
1190
1191            fn data_mut(&mut self) -> &mut $crate::recognizer::RecognizerData {
1192                $crate::recognizer::Recognizer::data_mut(&mut self.$base)
1193            }
1194        }
1195
1196        impl<$source, $hooks> $crate::parser::Parser for $parser<$source, $hooks>
1197        where
1198            $source: $crate::token::TokenSource,
1199            $hooks: $crate::parser::SemanticHooks,
1200        {
1201            fn build_parse_trees(&self) -> bool {
1202                $crate::parser::Parser::build_parse_trees(&self.$base)
1203            }
1204
1205            fn set_build_parse_trees(&mut self, build: bool) {
1206                $crate::parser::Parser::set_build_parse_trees(&mut self.$base, build);
1207            }
1208
1209            fn number_of_syntax_errors(&self) -> usize {
1210                $crate::parser::Parser::number_of_syntax_errors(&self.$base)
1211            }
1212
1213            fn report_diagnostic_errors(&self) -> bool {
1214                $crate::parser::Parser::report_diagnostic_errors(&self.$base)
1215            }
1216
1217            fn set_report_diagnostic_errors(&mut self, report: bool) {
1218                $crate::parser::Parser::set_report_diagnostic_errors(&mut self.$base, report);
1219            }
1220
1221            fn prediction_mode(&self) -> $crate::parser::PredictionMode {
1222                $crate::parser::Parser::prediction_mode(&self.$base)
1223            }
1224
1225            fn set_prediction_mode(&mut self, mode: $crate::parser::PredictionMode) {
1226                $crate::parser::Parser::set_prediction_mode(&mut self.$base, mode);
1227            }
1228
1229            fn max_rule_depth(&self) -> ::core::option::Option<usize> {
1230                $crate::parser::Parser::max_rule_depth(&self.$base)
1231            }
1232
1233            fn set_max_rule_depth(&mut self, depth: ::core::option::Option<usize>) {
1234                $crate::parser::Parser::set_max_rule_depth(&mut self.$base, depth);
1235            }
1236
1237            fn add_parse_listener(
1238                &mut self,
1239                listener: ::std::boxed::Box<dyn $crate::parser::ParseListener>,
1240            ) {
1241                $crate::parser::Parser::add_parse_listener(&mut self.$base, listener);
1242            }
1243
1244            fn remove_parse_listeners(
1245                &mut self,
1246            ) -> ::std::vec::Vec<::std::boxed::Box<dyn $crate::parser::ParseListener>> {
1247                $crate::parser::Parser::remove_parse_listeners(&mut self.$base)
1248            }
1249        }
1250    };
1251}
1252
1253/// Defines the grammar-independent parse-driver core for one generated
1254/// parser: entry/reset bookkeeping, generated-vs-interpreted engine routing,
1255/// sticky-abort and fail-loud semantic-error draining, and the interpreted
1256/// fallback with uniform action dispatch through the module's `run_action`.
1257///
1258/// This is an implementation detail of `antlr4-rust-gen`, not a stable
1259/// hand-written parser API. The `fallback` binder block supplied by generated
1260/// code composes the grammar's `ParserRuntimeOptions` (semantics table,
1261/// action indices, policy) and must evaluate to
1262/// `Result<(ParseTree, Vec<ParserAction>), AntlrError>`; this macro owns
1263/// everything else.
1264#[doc(hidden)]
1265#[macro_export]
1266macro_rules! __antlr4_rust_parser_driver {
1267    (
1268        type: $parser:ident<$source:ident, $hooks:ident>,
1269        fields: {
1270            base: $base:ident,
1271            simulator: $simulator:ident $(,)?
1272        },
1273        atn: $atn:path,
1274        adaptive_direct: $adaptive_direct:expr,
1275        fallback($this:ident, $rule_index:ident, $precedence:ident) $fallback:block
1276        $(,)?
1277    ) => {
1278        impl<$source, $hooks> $parser<$source, $hooks>
1279        where
1280            $source: $crate::token::TokenSource,
1281            $hooks: $crate::parser::SemanticHooks,
1282        {
1283            #[allow(dead_code)]
1284            fn parse_rule(
1285                &mut self,
1286                rule_index: usize,
1287            ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1288                self.parse_rule_precedence(rule_index, 0)
1289            }
1290
1291            #[allow(dead_code)]
1292            fn parse_rule_precedence(
1293                &mut self,
1294                rule_index: usize,
1295                precedence: i32,
1296            ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1297                self.parse_rule_precedence_inner(rule_index, precedence, true)
1298            }
1299
1300            #[allow(dead_code)]
1301            fn parse_rule_precedence_from_generated(
1302                &mut self,
1303                rule_index: usize,
1304                precedence: i32,
1305            ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1306                self.parse_rule_precedence_inner(rule_index, precedence, false)
1307            }
1308
1309            #[allow(dead_code)]
1310            fn parse_rule_precedence_inner(
1311                &mut self,
1312                rule_index: usize,
1313                precedence: i32,
1314                allow_generated_fallback: bool,
1315            ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1316                if allow_generated_fallback {
1317                    // True top-level entry: drop any fail-loud coordinates left by a
1318                    // previous parse so a reused parser starts clean. Mid-parse the hits
1319                    // are preserved so a generated parent can surface a recovered child's
1320                    // fail-loud coordinate at this boundary.
1321                    self.$base.reset_unknown_semantic_hits();
1322                    // Likewise drop stale sticky aborts (depth-cap violation,
1323                    // parse-listener abort): entry rules share one parser instance,
1324                    // and the flags must not poison the next parse when the previous
1325                    // one exited through an error path.
1326                    let _ = self.$base.take_parse_abort();
1327                }
1328                let __rule_start = $crate::int_stream::IntStream::index(self.$base.input());
1329                let __generated_only = self.generated_only();
1330                let __tree = if let ::core::option::Option::Some(result) =
1331                    self.parse_generated_rule(rule_index, precedence, allow_generated_fallback)
1332                {
1333                    match result {
1334                        ::core::result::Result::Ok(tree) => tree,
1335                        ::core::result::Result::Err(error) => {
1336                            $crate::int_stream::IntStream::seek(self.$base.input(), __rule_start);
1337                            let __report_error = ::core::matches!(
1338                                &error,
1339                                $crate::generated::GeneratedRuleError::Fatal(_)
1340                            );
1341                            // A fatal unwind retains recovery diagnostics committed
1342                            // earlier in this entry. Dispatch them before a semantic
1343                            // or parser-abort override can return, or they would leak
1344                            // into the next entry on a reused parser.
1345                            if allow_generated_fallback && __report_error {
1346                                self.$base.report_generated_parser_diagnostics();
1347                            }
1348                            if allow_generated_fallback {
1349                                // A sticky abort (depth cap, listener) wins over an
1350                                // error or semantic miss derived after recovery absorbed
1351                                // the aborted rule. Drain any masked semantic miss too,
1352                                // so neither condition poisons the next entry.
1353                                if let ::core::option::Option::Some(abort) =
1354                                    self.$base.take_parse_abort()
1355                                {
1356                                    let _ = self.$base.take_unknown_semantic_error();
1357                                    return ::core::result::Result::Err(abort);
1358                                }
1359                                // A generated predicate that consulted an unimplemented
1360                                // hook fails the alternative and surfaces here as a generic
1361                                // failed-predicate/rule error. Prefer the recorded fail-loud
1362                                // semantic error when no parser abort occurred.
1363                                if let ::core::option::Option::Some(semantic_error) =
1364                                    self.$base.take_unknown_semantic_error()
1365                                {
1366                                    return ::core::result::Result::Err(semantic_error);
1367                                }
1368                            }
1369                            let error = error.into_error();
1370                            if allow_generated_fallback && __report_error {
1371                                self.$base.report_unrecovered_parser_error(&error);
1372                            }
1373                            return ::core::result::Result::Err(error);
1374                        }
1375                    }
1376                } else if __generated_only {
1377                    return ::core::result::Result::Err($crate::errors::AntlrError::Unsupported(
1378                        ::std::format!("generated parser did not emit rule {}", rule_index),
1379                    ));
1380                } else {
1381                    self.parse_interpreted_rule_precedence(rule_index, precedence)?
1382                };
1383                if allow_generated_fallback {
1384                    self.$base.report_generated_parser_diagnostics();
1385                    // A sticky abort (depth-cap violation, listener abort) is not a
1386                    // syntax error: rule-level recovery may have produced a tree
1387                    // and semantic miss anyway, but the abort is the root cause. Drain
1388                    // both sticky conditions before returning so parser reuse is clean.
1389                    if let ::core::option::Option::Some(error) = self.$base.take_parse_abort() {
1390                        let _ = self.$base.take_unknown_semantic_error();
1391                        return ::core::result::Result::Err(error);
1392                    }
1393                    // Surface unknown predicate/action coordinates recorded under the
1394                    // Error policy only after parser aborts have been ruled out.
1395                    if let ::core::option::Option::Some(error) =
1396                        self.$base.take_unknown_semantic_error()
1397                    {
1398                        return ::core::result::Result::Err(error);
1399                    }
1400                }
1401                ::core::result::Result::Ok(__tree)
1402            }
1403
1404            #[allow(dead_code)]
1405            fn parse_interpreted_rule(
1406                &mut self,
1407                rule_index: usize,
1408            ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1409                self.parse_interpreted_rule_precedence(rule_index, 0)
1410            }
1411
1412            #[allow(dead_code)]
1413            fn parse_interpreted_rule_precedence(
1414                &mut self,
1415                rule_index: usize,
1416                precedence: i32,
1417            ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1418                if precedence == 0
1419                    && $adaptive_direct
1420                    && ::std::env::var_os("ANTLR4_RUST_ADAPTIVE_DIRECT").is_some()
1421                {
1422                    let simulator = self.$simulator.get_or_insert_with(|| {
1423                        $crate::atn::parser::ParserAtnSimulator::new_shared($atn())
1424                    });
1425                    self.$base
1426                        .parse_atn_rule_adaptive_or_fallback($atn(), simulator, rule_index)
1427                } else {
1428                    let (__tree, __actions) = {
1429                        let $this = &mut *self;
1430                        let $rule_index = rule_index;
1431                        let $precedence = precedence;
1432                        $fallback
1433                    }?;
1434                    // Uniform dispatch: grammars without action states define an
1435                    // empty `run_action` and collect no deferred actions, so this
1436                    // loop is a no-op for them.
1437                    for __action in __actions {
1438                        self.run_action(__action, __tree);
1439                    }
1440                    ::core::result::Result::Ok(__tree)
1441                }
1442            }
1443        }
1444    };
1445}
1446
1447/// Defines the grammar-independent parse entry points for one generated
1448/// parser module: the `<Grammar>ParserParseOutput` alias of
1449/// [`GeneratedParseOutput`], the validation bridge behind
1450/// [`GeneratedParseOutput::validate`], and the `parse*` / `parse_stream*`
1451/// convenience functions.
1452///
1453/// This is an implementation detail of `antlr4-rust-gen`, not a stable
1454/// hand-written parser API.
1455#[doc(hidden)]
1456#[macro_export]
1457macro_rules! __antlr4_rust_parser_entry_points {
1458    (
1459        parser: $parser:ident,
1460        output: $output:ident,
1461        validated_tree: $validated:ident,
1462        validation_error: $validation_error:ident,
1463        validate_tree: $validate_tree:path
1464        $(,)?
1465    ) => {
1466        #[doc = ::core::concat!(
1467                    "Result from [`parse_with_parser`], [`parse_with_parser_constructor`],\n",
1468                    "[`parse_stream_with_parser`], or [`parse_stream_with_parser_constructor`].\n\n",
1469                    "Keeps the generated parser available after the entry rule runs so callers\n",
1470                    "can inspect diagnostics or recover the parser-owned token stream. Alias of\n",
1471                    "the runtime's `GeneratedParseOutput` with [`",
1472                    ::core::stringify!($parser),
1473                    "`] substituted for its parser type parameter. The semantic-hooks type\n",
1474                    "defaults to `NoSemanticHooks` for the original entry points.",
1475                )]
1476        pub type $output<R, L, H = $crate::parser::NoSemanticHooks> =
1477            $crate::generated::GeneratedParseOutput<R, $parser<L, H>>;
1478
1479        impl<L, H> $crate::generated::__GeneratedParserIntoParsedFile for $parser<L, H>
1480        where
1481            L: $crate::token::TokenSource,
1482            H: $crate::parser::SemanticHooks,
1483        {
1484            fn __into_parsed_file(
1485                self,
1486                root: $crate::tree::NodeId,
1487            ) -> $crate::tree::ParsedFile {
1488                self.into_parsed_file(root)
1489            }
1490        }
1491
1492        impl<L, H> $crate::generated::__GeneratedParserValidate for $parser<L, H>
1493        where
1494            L: $crate::token::TokenSource,
1495            H: $crate::parser::SemanticHooks,
1496        {
1497            type Validated = $validated;
1498
1499            fn __validate(
1500                self,
1501                root: $crate::tree::NodeId,
1502            ) -> ::core::result::Result<$validated, $crate::validated::ValidationError> {
1503                let lexer = self.token_stream().number_of_source_errors();
1504                let parser = $crate::parser::Parser::number_of_syntax_errors(&self);
1505                if lexer != 0 || parser != 0 {
1506                    return ::core::result::Result::Err($validation_error::SyntaxErrors {
1507                        lexer,
1508                        parser,
1509                    });
1510                }
1511                let parsed = self.into_parsed_file(root);
1512                $validate_tree(&parsed)?;
1513                ::core::result::Result::Ok(<$validated>::__new(parsed))
1514            }
1515        }
1516
1517        /// Parses UTF-8 text by constructing the lexer, token stream, parser, and
1518        /// caller-selected entry rule in one call.
1519        ///
1520        #[doc = ::core::concat!(
1521                    "Pass the generated lexer constructor and a parser entry rule, for example\n",
1522                    "`parse(src, MyGrammarLexer::new, ",
1523                    ::core::stringify!($parser),
1524                    "::file)`.",
1525                )]
1526        ///
1527        /// The returned [`antlr4_runtime::ParsedFile`] owns the canonical token store,
1528        /// flat CST storage, and entry-rule root.
1529        /// Use [`parse_with_parser`] instead when the caller also needs parser
1530        /// diagnostics after the entry rule runs. Parsers that need semantic hooks
1531        /// or other constructor-time customization can use
1532        /// [`parse_with_parser_constructor`] and call
1533        /// [`antlr4_runtime::GeneratedParseOutput::into_parsed_file`] on its result.
1534        pub fn parse<L: $crate::token::TokenSource>(
1535            input: impl ::core::convert::AsRef<str>,
1536            lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1537            entry: impl ::core::ops::FnOnce(
1538                &mut $parser<L>,
1539            ) -> ::core::result::Result<
1540                $crate::tree::NodeId,
1541                $crate::errors::AntlrError,
1542            >,
1543        ) -> ::core::result::Result<$crate::tree::ParsedFile, $crate::errors::AntlrError> {
1544            parse_stream(
1545                $crate::char_stream::InputStream::new(input.as_ref()),
1546                lexer,
1547                entry,
1548            )
1549        }
1550
1551        /// Parses UTF-8 text and returns a typed tree whose required generated child
1552        /// accessors are infallible.
1553        ///
1554        /// Parsers that need semantic hooks or other constructor-time customization
1555        /// can call [`parse_with_parser_constructor`] followed by
1556        /// [`antlr4_runtime::GeneratedParseOutput::validate`].
1557        pub fn parse_validated<L: $crate::token::TokenSource>(
1558            input: impl ::core::convert::AsRef<str>,
1559            lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1560            entry: impl ::core::ops::FnOnce(
1561                &mut $parser<L>,
1562            ) -> ::core::result::Result<
1563                $crate::tree::NodeId,
1564                $crate::errors::AntlrError,
1565            >,
1566        ) -> ::core::result::Result<$validated, $validation_error> {
1567            parse_stream_validated(
1568                $crate::char_stream::InputStream::new(input.as_ref()),
1569                lexer,
1570                entry,
1571            )
1572        }
1573
1574        /// Parses UTF-8 text like [`parse`] while returning the parser after the entry
1575        /// rule has run.
1576        ///
1577        #[doc = ::core::concat!(
1578                    "This keeps the compact generated setup path available for callers that also\n",
1579                    "need `Parser::number_of_syntax_errors()` or `",
1580                    ::core::stringify!($parser),
1581                    "::into_token_stream()`.",
1582                )]
1583        ///
1584        /// Use [`parse_with_parser_constructor`] when the parser needs semantic hooks
1585        /// or other constructor-time customization.
1586        pub fn parse_with_parser<L: $crate::token::TokenSource, R>(
1587            input: impl ::core::convert::AsRef<str>,
1588            lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1589            entry: impl ::core::ops::FnOnce(
1590                &mut $parser<L>,
1591            )
1592                -> ::core::result::Result<R, $crate::errors::AntlrError>,
1593        ) -> ::core::result::Result<$output<R, L>, $crate::errors::AntlrError> {
1594            parse_stream_with_parser(
1595                $crate::char_stream::InputStream::new(input.as_ref()),
1596                lexer,
1597                entry,
1598            )
1599        }
1600
1601        /// Parses UTF-8 text using caller-provided lexer and parser constructors.
1602        ///
1603        /// This is the constructor-aware counterpart of [`parse_with_parser`].
1604        /// It keeps the concrete parser type, including its semantic hooks, in the
1605        /// returned [`antlr4_runtime::GeneratedParseOutput`]. Call
1606        /// [`antlr4_runtime::GeneratedParseOutput::into_parsed_file`] for the
1607        /// [`antlr4_runtime::ParsedFile`] result shape of [`parse`], or
1608        /// [`antlr4_runtime::GeneratedParseOutput::validate`] for the typed validated
1609        /// result shape of [`parse_validated`].
1610        ///
1611        /// A generated typed-hook parser can be installed without hand-writing the
1612        /// lexer-to-token-stream driver:
1613        ///
1614        /// ```ignore
1615        /// parse_with_parser_constructor(
1616        ///     source,
1617        ///     MyGrammarLexer::new,
1618        ///     |tokens| MyGrammarParser::with_typed_hooks(tokens, MyHooks::default()),
1619        ///     MyGrammarParser::file,
1620        /// )
1621        /// ```
1622        pub fn parse_with_parser_constructor<
1623            L: $crate::token::TokenSource,
1624            H: $crate::parser::SemanticHooks,
1625            R,
1626        >(
1627            input: impl ::core::convert::AsRef<str>,
1628            lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1629            parser_constructor: impl ::core::ops::FnOnce(
1630                $crate::token_stream::CommonTokenStream<L>,
1631            ) -> $parser<L, H>,
1632            entry: impl ::core::ops::FnOnce(
1633                &mut $parser<L, H>,
1634            )
1635                -> ::core::result::Result<R, $crate::errors::AntlrError>,
1636        ) -> ::core::result::Result<$output<R, L, H>, $crate::errors::AntlrError> {
1637            parse_stream_with_parser_constructor(
1638                $crate::char_stream::InputStream::new(input.as_ref()),
1639                lexer,
1640                parser_constructor,
1641                entry,
1642            )
1643        }
1644
1645        /// Parses a caller-provided character stream by constructing the lexer, token
1646        /// stream, parser, and caller-selected entry rule in one call.
1647        ///
1648        /// Unlike [`parse`], this accepts any [`antlr4_runtime::CharStream`], including
1649        /// a named [`antlr4_runtime::InputStream`] or a byte-oriented
1650        /// [`antlr4_runtime::ByteStream`].
1651        ///
1652        /// Parsers that need semantic hooks or other constructor-time customization
1653        /// can use [`parse_stream_with_parser_constructor`] and call
1654        /// [`antlr4_runtime::GeneratedParseOutput::into_parsed_file`] on its result.
1655        pub fn parse_stream<I: $crate::char_stream::CharStream, L: $crate::token::TokenSource>(
1656            input: I,
1657            lexer: impl ::core::ops::FnOnce(I) -> L,
1658            entry: impl ::core::ops::FnOnce(
1659                &mut $parser<L>,
1660            ) -> ::core::result::Result<
1661                $crate::tree::NodeId,
1662                $crate::errors::AntlrError,
1663            >,
1664        ) -> ::core::result::Result<$crate::tree::ParsedFile, $crate::errors::AntlrError> {
1665            let output = parse_stream_with_parser(input, lexer, entry)?;
1666            ::core::result::Result::Ok(output.into_parsed_file())
1667        }
1668
1669        /// Parses a caller-provided character stream and validates the completed tree.
1670        ///
1671        /// Parsers that need semantic hooks or other constructor-time customization
1672        /// can call [`parse_stream_with_parser_constructor`] followed by
1673        /// [`antlr4_runtime::GeneratedParseOutput::validate`].
1674        pub fn parse_stream_validated<
1675            I: $crate::char_stream::CharStream,
1676            L: $crate::token::TokenSource,
1677        >(
1678            input: I,
1679            lexer: impl ::core::ops::FnOnce(I) -> L,
1680            entry: impl ::core::ops::FnOnce(
1681                &mut $parser<L>,
1682            ) -> ::core::result::Result<
1683                $crate::tree::NodeId,
1684                $crate::errors::AntlrError,
1685            >,
1686        ) -> ::core::result::Result<$validated, $validation_error> {
1687            let output = parse_stream_with_parser(input, lexer, entry)
1688                .map_err($validation_error::Recognition)?;
1689            output.validate()
1690        }
1691
1692        /// Parses a caller-provided character stream like [`parse_stream`] while
1693        /// returning the parser after the entry rule has run.
1694        ///
1695        /// Use [`parse_stream_with_parser_constructor`] when the parser needs semantic
1696        /// hooks or other constructor-time customization.
1697        pub fn parse_stream_with_parser<
1698            I: $crate::char_stream::CharStream,
1699            L: $crate::token::TokenSource,
1700            R,
1701        >(
1702            input: I,
1703            lexer: impl ::core::ops::FnOnce(I) -> L,
1704            entry: impl ::core::ops::FnOnce(
1705                &mut $parser<L>,
1706            )
1707                -> ::core::result::Result<R, $crate::errors::AntlrError>,
1708        ) -> ::core::result::Result<$output<R, L>, $crate::errors::AntlrError> {
1709            parse_stream_with_parser_constructor(input, lexer, $parser::new, entry)
1710        }
1711
1712        /// Parses a caller-provided character stream using caller-provided lexer and
1713        /// parser constructors while returning the concrete parser after the entry
1714        /// rule has run.
1715        ///
1716        /// This is the stream-based counterpart of
1717        /// [`parse_with_parser_constructor`].
1718        pub fn parse_stream_with_parser_constructor<
1719            I: $crate::char_stream::CharStream,
1720            L: $crate::token::TokenSource,
1721            H: $crate::parser::SemanticHooks,
1722            R,
1723        >(
1724            input: I,
1725            lexer: impl ::core::ops::FnOnce(I) -> L,
1726            parser_constructor: impl ::core::ops::FnOnce(
1727                $crate::token_stream::CommonTokenStream<L>,
1728            ) -> $parser<L, H>,
1729            entry: impl ::core::ops::FnOnce(
1730                &mut $parser<L, H>,
1731            )
1732                -> ::core::result::Result<R, $crate::errors::AntlrError>,
1733        ) -> ::core::result::Result<$output<R, L, H>, $crate::errors::AntlrError> {
1734            let lexer = lexer(input);
1735            let tokens = $crate::token_stream::CommonTokenStream::new(lexer);
1736            let mut parser = parser_constructor(tokens);
1737            let result = entry(&mut parser)?;
1738            ::core::result::Result::Ok($crate::generated::GeneratedParseOutput { result, parser })
1739        }
1740    };
1741}
1742
1743#[derive(Debug)]
1744pub struct GrammarMetadata {
1745    grammar_file_name: &'static str,
1746    rule_names: &'static [&'static str],
1747    literal_names: &'static [Option<&'static str>],
1748    symbolic_names: &'static [Option<&'static str>],
1749    display_names: &'static [Option<&'static str>],
1750    channel_names: &'static [&'static str],
1751    mode_names: &'static [&'static str],
1752    serialized_atn: &'static [i32],
1753    recognizer_metadata: OnceLock<Arc<RecognizerMetadata>>,
1754}
1755
1756impl Clone for GrammarMetadata {
1757    fn clone(&self) -> Self {
1758        Self {
1759            grammar_file_name: self.grammar_file_name,
1760            rule_names: self.rule_names,
1761            literal_names: self.literal_names,
1762            symbolic_names: self.symbolic_names,
1763            display_names: self.display_names,
1764            channel_names: self.channel_names,
1765            mode_names: self.mode_names,
1766            serialized_atn: self.serialized_atn,
1767            recognizer_metadata: OnceLock::from(Arc::clone(self.cached_recognizer_metadata())),
1768        }
1769    }
1770}
1771
1772impl GrammarMetadata {
1773    /// Creates static grammar metadata emitted by the Rust target generator.
1774    #[allow(clippy::too_many_arguments)]
1775    pub const fn new(
1776        grammar_file_name: &'static str,
1777        rule_names: &'static [&'static str],
1778        literal_names: &'static [Option<&'static str>],
1779        symbolic_names: &'static [Option<&'static str>],
1780        display_names: &'static [Option<&'static str>],
1781        channel_names: &'static [&'static str],
1782        mode_names: &'static [&'static str],
1783        serialized_atn: &'static [i32],
1784    ) -> Self {
1785        Self {
1786            grammar_file_name,
1787            rule_names,
1788            literal_names,
1789            symbolic_names,
1790            display_names,
1791            channel_names,
1792            mode_names,
1793            serialized_atn,
1794            recognizer_metadata: OnceLock::new(),
1795        }
1796    }
1797
1798    pub const fn grammar_file_name(&self) -> &'static str {
1799        self.grammar_file_name
1800    }
1801
1802    pub const fn rule_names(&self) -> &'static [&'static str] {
1803        self.rule_names
1804    }
1805
1806    pub const fn channel_names(&self) -> &'static [&'static str] {
1807        self.channel_names
1808    }
1809
1810    pub const fn mode_names(&self) -> &'static [&'static str] {
1811        self.mode_names
1812    }
1813
1814    pub fn vocabulary(&self) -> Vocabulary {
1815        Vocabulary::new(
1816            self.literal_names.iter().copied(),
1817            self.symbolic_names.iter().copied(),
1818            self.display_names.iter().copied(),
1819        )
1820    }
1821
1822    /// Creates per-instance recognizer state backed by this grammar's cached
1823    /// immutable metadata.
1824    pub fn recognizer_data(&self) -> RecognizerData {
1825        RecognizerData::from_shared(Arc::clone(self.cached_recognizer_metadata()))
1826    }
1827
1828    fn cached_recognizer_metadata(&self) -> &Arc<RecognizerMetadata> {
1829        self.recognizer_metadata.get_or_init(|| {
1830            Arc::new(RecognizerMetadata::from_static(
1831                self.grammar_file_name,
1832                self.rule_names,
1833                self.channel_names,
1834                self.mode_names,
1835                self.vocabulary(),
1836            ))
1837        })
1838    }
1839
1840    /// Borrows the serialized ATN values for deserialization by the runtime
1841    /// simulators without copying generated static data.
1842    pub const fn serialized_atn(&self) -> SerializedAtn<'_> {
1843        SerializedAtn::from_i32(self.serialized_atn)
1844    }
1845}
1846
1847pub trait GeneratedLexer {
1848    fn metadata() -> &'static GrammarMetadata;
1849}
1850
1851pub trait GeneratedParser {
1852    fn metadata() -> &'static GrammarMetadata;
1853
1854    /// Borrows the validated packed ATN embedded by the matching generator.
1855    fn parser_atn() -> &'static ParserAtn;
1856}
1857
1858/// Exposes the parser base needed by the generated-rule dispatch lifecycle.
1859///
1860/// This is implemented by [`crate::__antlr4_rust_parser_facade`] for generated
1861/// parsers so [`dispatch_generated_rule`] can remain grammar-agnostic.
1862#[doc(hidden)]
1863pub trait GeneratedRuleParser {
1864    type Source: TokenSource;
1865    type Hooks: SemanticHooks;
1866
1867    fn generated_rule_base(&mut self) -> &mut BaseParser<Self::Source, Self::Hooks>;
1868}
1869
1870// ---------------------------------------------------------------------------
1871// Parse-driver and entry-point support shared by every generated parser and
1872// lexer module. The `__antlr4_rust_parser_driver!` and
1873// `__antlr4_rust_parser_entry_points!` expansions, and the generated
1874// `lex`/`lex_stream` re-exports, resolve against these items.
1875// ---------------------------------------------------------------------------
1876
1877/// Error routing for generated rule bodies.
1878///
1879/// This is an implementation detail of `antlr4-rust-gen`, not a stable
1880/// hand-written parser API. Generated dispatch code distinguishes fatal
1881/// unwinds (which report recovery diagnostics) from errors that request the
1882/// interpreted fallback, plus the internal adaptive-ATN retry signal.
1883#[doc(hidden)]
1884#[derive(Debug)]
1885pub enum GeneratedRuleError {
1886    /// Unrecoverable failure of the generated engine for this entry.
1887    Fatal(AntlrError),
1888    /// Failure that requests the interpreted fallback for this entry.
1889    Interpreted(AntlrError),
1890    /// Internal adaptive-ATN retry unwind; never escapes the routing boundary.
1891    AdaptiveRetry,
1892}
1893
1894impl GeneratedRuleError {
1895    /// Unwraps the underlying recognition error.
1896    #[must_use]
1897    pub fn into_error(self) -> AntlrError {
1898        match self {
1899            Self::Fatal(error) | Self::Interpreted(error) => error,
1900            Self::AdaptiveRetry => AntlrError::Unsupported(
1901                "internal adaptive ATN retry escaped its routing boundary".to_owned(),
1902            ),
1903        }
1904    }
1905}
1906
1907/// Uniform function-pointer shape for one generated parser rule body.
1908#[doc(hidden)]
1909pub type GeneratedRuleBody<P> =
1910    fn(&mut P, i32, bool) -> Result<crate::tree::ParseTree, GeneratedRuleError>;
1911
1912/// Applies the grammar-independent generated-rule guard around one table-selected body.
1913///
1914/// The function stays out of line so every generated parser monomorphization
1915/// carries one lifecycle shell instead of repeating it for every rule.
1916#[doc(hidden)]
1917#[inline(never)]
1918pub fn dispatch_generated_rule<P>(
1919    parser: &mut P,
1920    rule_index: usize,
1921    precedence: i32,
1922    allow_fallback: bool,
1923    body: GeneratedRuleBody<P>,
1924) -> Result<crate::tree::ParseTree, GeneratedRuleError>
1925where
1926    P: GeneratedRuleParser,
1927{
1928    if let Some(error) = parser.generated_rule_base().rule_depth_cap_violation() {
1929        return Err(GeneratedRuleError::Fatal(error));
1930    }
1931    if let Some(error) = parser
1932        .generated_rule_base()
1933        .parse_listener_enter_rule(rule_index)
1934    {
1935        return Err(GeneratedRuleError::Fatal(error));
1936    }
1937    let result = if parser
1938        .generated_rule_base()
1939        .generated_rule_stack_check_due()
1940    {
1941        grow_generated_rule_stack(|| body(parser, precedence, allow_fallback))
1942    } else {
1943        body(parser, precedence, allow_fallback)
1944    };
1945    parser
1946        .generated_rule_base()
1947        .parse_listener_exit_rule(rule_index);
1948    result
1949}
1950
1951/// Adaptive-ATN preference state for the generated rules a grammar routes
1952/// through warmed-retry dispatch.
1953///
1954/// `RULES` is the number of adaptive-ATN-preferred rules the generator
1955/// assigned retry slots to; grammars without residual adaptive routing
1956/// instantiate `AdaptiveAtnRetryState<0>`, whose [`Self::retry_pending`]
1957/// check constant-folds to `false`.
1958#[doc(hidden)]
1959#[derive(Debug)]
1960pub struct AdaptiveAtnRetryState<const RULES: usize> {
1961    /// Rules whose warmed adaptive-prediction work marked them expensive.
1962    pub preferred_rules: [bool; RULES],
1963    /// Per-slot recursion depth of in-flight adaptive dispatches.
1964    pub preference_depths: [usize; RULES],
1965    /// Adaptive-prediction work counters captured at outermost entry.
1966    pub preference_starts: [(usize, usize); RULES],
1967    /// Syntax-error counts captured at outermost entry.
1968    pub syntax_error_starts: [usize; RULES],
1969    /// Slot currently unwinding through an adaptive retry, if any.
1970    pub retry_slot: Option<usize>,
1971}
1972
1973impl<const RULES: usize> AdaptiveAtnRetryState<RULES> {
1974    /// Creates cleared preference state.
1975    #[must_use]
1976    pub const fn new() -> Self {
1977        Self {
1978            preferred_rules: [false; RULES],
1979            preference_depths: [0; RULES],
1980            preference_starts: [(0, 0); RULES],
1981            syntax_error_starts: [0; RULES],
1982            retry_slot: None,
1983        }
1984    }
1985
1986    /// Clears every learned preference and any in-flight retry.
1987    pub const fn reset(&mut self) {
1988        *self = Self::new();
1989    }
1990
1991    /// Reports whether an adaptive retry is currently unwinding.
1992    ///
1993    /// Constant-folds to `false` when the grammar has no retry slots, so the
1994    /// uniform generated retry clause costs nothing for such grammars.
1995    #[must_use]
1996    pub const fn retry_pending(&self) -> bool {
1997        RULES > 0 && self.retry_slot.is_some()
1998    }
1999}
2000
2001impl<const RULES: usize> Default for AdaptiveAtnRetryState<RULES> {
2002    fn default() -> Self {
2003        Self::new()
2004    }
2005}
2006
2007/// Result from a generated parser entry point that retains the parser.
2008///
2009/// Keeps the generated parser available after the entry rule runs so callers
2010/// can inspect diagnostics or recover the parser-owned token stream. Generated
2011/// modules alias this type as `<Grammar>ParserParseOutput<R, L, H>` with their
2012/// parser type substituted for `P` and `H` defaulting to
2013/// [`crate::NoSemanticHooks`]. [`Self::into_parsed_file`] and
2014/// [`Self::validate`] are available for those generated parser types, which
2015/// wire in their module's parsed and validated surfaces.
2016#[derive(Debug)]
2017pub struct GeneratedParseOutput<R, P> {
2018    /// Value returned by the caller-selected entry rule.
2019    pub result: R,
2020    /// The generated parser after the entry rule has run.
2021    pub parser: P,
2022}
2023
2024/// Grammar-specific parsed-file conversion behind
2025/// [`GeneratedParseOutput::into_parsed_file`].
2026///
2027/// This is an implementation detail of `antlr4-rust-gen`, not a stable
2028/// hand-written parser API: each generated module implements it for its parser
2029/// type via `__antlr4_rust_parser_entry_points!`.
2030#[doc(hidden)]
2031pub trait __GeneratedParserIntoParsedFile: Sized {
2032    /// Converts a completed parse into the parser's owned parsed-file surface.
2033    fn __into_parsed_file(self, root: NodeId) -> crate::tree::ParsedFile;
2034}
2035
2036/// Grammar-specific validation step behind [`GeneratedParseOutput::validate`].
2037///
2038/// This is an implementation detail of `antlr4-rust-gen`, not a stable
2039/// hand-written parser API: each generated module implements it for its parser
2040/// type via `__antlr4_rust_parser_entry_points!`.
2041#[doc(hidden)]
2042pub trait __GeneratedParserValidate: Sized {
2043    /// The module-branded validated-tree type.
2044    type Validated;
2045
2046    /// Validates a completed parse rooted at `root`.
2047    fn __validate(self, root: NodeId) -> Result<Self::Validated, ValidationError>;
2048}
2049
2050impl<P: __GeneratedParserIntoParsedFile> GeneratedParseOutput<NodeId, P> {
2051    /// Converts the completed parse into its owned [`crate::ParsedFile`].
2052    ///
2053    /// This consumes the retained parser, so inspect diagnostics such as
2054    /// `Parser::number_of_syntax_errors()` first. Unlike `validate()`, this
2055    /// preserves recovered parses, matching the generated `parse` entry point.
2056    #[must_use]
2057    pub fn into_parsed_file(self) -> crate::tree::ParsedFile {
2058        self.parser.__into_parsed_file(self.result)
2059    }
2060}
2061
2062impl<P: __GeneratedParserValidate> GeneratedParseOutput<NodeId, P> {
2063    /// Validates a completed parse and changes its generated context surface.
2064    ///
2065    /// Validation rejects lexer diagnostics, parser recovery, recovered error
2066    /// nodes, and missing generated required children before constructing the
2067    /// validated-tree type boundary.
2068    ///
2069    /// # Errors
2070    ///
2071    /// Returns a [`ValidationError`] when the parse recorded lexer or parser
2072    /// syntax errors or the completed tree fails structural validation.
2073    pub fn validate(self) -> Result<P::Validated, ValidationError> {
2074        self.parser.__validate(self.result)
2075    }
2076}
2077
2078/// Lexes UTF-8 text into an eagerly filled token stream without constructing
2079/// a parser.
2080///
2081/// Pass the generated lexer constructor, for example
2082/// `lex(src, MyGrammarLexer::new)`.
2083///
2084/// The stream retains every emitted token, including EOF and tokens on hidden
2085/// or custom channels. Lexer rules using `skip` do not emit tokens.
2086///
2087/// With `use antlr4_runtime::Token as _;` and the generated module's
2088/// `metadata()`, print each token's vocabulary name, numeric channel, and
2089/// text:
2090/// `let vocabulary = metadata().vocabulary(); for token in lex(src, MyGrammarLexer::new).tokens() { println!("type={} channel={} text={:?}", vocabulary.display_name(token.token_type()), token.channel(), token.text()); }`
2091///
2092/// `number_of_source_errors()` reports buffered lexer diagnostics. After
2093/// iterating `tokens()`, `drain_source_errors()` retrieves those diagnostics.
2094///
2095/// # Panics
2096///
2097/// Panics if buffering returns an [`crate::TokenStoreError`]. Construct the
2098/// lexer and call [`CommonTokenStream::try_new`] to handle that error instead.
2099pub fn lex<L: TokenSource>(
2100    input: impl AsRef<str>,
2101    lexer: impl FnOnce(InputStream) -> L,
2102) -> CommonTokenStream<L> {
2103    lex_stream(InputStream::new(input.as_ref()), lexer)
2104}
2105
2106/// Lexes a caller-provided character stream without constructing a parser.
2107///
2108/// Unlike [`lex`], this accepts any [`CharStream`], including a named
2109/// [`InputStream`] or a byte-oriented [`crate::ByteStream`].
2110///
2111/// `number_of_source_errors()` reports buffered lexer diagnostics. After
2112/// iterating `tokens()`, `drain_source_errors()` retrieves those diagnostics.
2113///
2114/// # Panics
2115///
2116/// Panics if buffering returns an [`crate::TokenStoreError`]. Call
2117/// [`CommonTokenStream::try_new`] with the constructed lexer to handle that
2118/// error instead.
2119pub fn lex_stream<I: CharStream, L: TokenSource>(
2120    input: I,
2121    lexer: impl FnOnce(I) -> L,
2122) -> CommonTokenStream<L> {
2123    CommonTokenStream::new(lexer(input))
2124}
2125
2126// ---------------------------------------------------------------------------
2127// Grammar-independent support surface imported by every generated parser
2128// module. These items back the typed context views, listener/visitor bridges,
2129// and embedded-action facades emitted by `antlr4-rust-gen`; the generated
2130// module brings them into scope by name so the `__antlr4_rust_context!` /
2131// `__antlr4_rust_context_accessors!` expansions resolve against them.
2132// ---------------------------------------------------------------------------
2133
2134/// Token-stream facade backing embedded-action `$input` translation
2135/// (`self.input().text()` / `.la(i)` / `.lt(i).text()`).
2136#[doc(hidden)]
2137pub struct __GeneratedInput<'a, L: TokenSource>(#[doc(hidden)] pub &'a mut CommonTokenStream<L>);
2138
2139impl<L: TokenSource> __GeneratedInput<'_, L> {
2140    #[must_use]
2141    #[inline]
2142    pub fn text(&self) -> String {
2143        self.0.text_all()
2144    }
2145
2146    #[inline]
2147    pub fn la(&mut self, offset: isize) -> i32 {
2148        IntStream::la(self.0, offset)
2149    }
2150
2151    #[must_use]
2152    #[inline]
2153    pub fn lt(&self, offset: isize) -> __GeneratedTokenView {
2154        __GeneratedTokenView {
2155            text: self
2156                .0
2157                .lt(offset)
2158                .map(|token| token.text_or_empty().to_owned())
2159                .unwrap_or_default(),
2160        }
2161    }
2162}
2163
2164impl<L: TokenSource> fmt::Debug for __GeneratedInput<'_, L> {
2165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2166        f.debug_struct("__GeneratedInput").finish_non_exhaustive()
2167    }
2168}
2169
2170/// Owned token view returned by [`__GeneratedInput::lt`] and the generated
2171/// contexts' `start()` accessors.
2172#[doc(hidden)]
2173#[derive(Debug)]
2174pub struct __GeneratedTokenView {
2175    #[doc(hidden)]
2176    pub text: String,
2177}
2178
2179impl __GeneratedTokenView {
2180    #[must_use]
2181    #[inline]
2182    pub fn text(&self) -> &str {
2183        &self.text
2184    }
2185}
2186
2187/// Typed terminal wrapper exposed by generated listener, visitor, and context
2188/// surfaces.
2189///
2190/// Recovery-inserted error nodes travel through the same surface; use
2191/// [`TerminalNode::is_error`] and [`TerminalNode::is_missing`] to identify
2192/// them.
2193#[derive(Clone, Debug)]
2194pub struct TerminalNode<'a> {
2195    __node: TerminalNodeView<'a>,
2196}
2197
2198impl<'a> TerminalNode<'a> {
2199    #[doc(hidden)]
2200    #[must_use]
2201    #[inline]
2202    pub const fn new(node: TerminalNodeView<'a>) -> Self {
2203        Self { __node: node }
2204    }
2205
2206    #[must_use]
2207    #[inline]
2208    pub fn symbol(&self) -> TokenView<'a> {
2209        self.__node.symbol()
2210    }
2211
2212    #[must_use]
2213    #[inline]
2214    pub fn is_error(&self) -> bool {
2215        matches!(self.__node.node().kind(), NodeKind::Error)
2216    }
2217
2218    #[must_use]
2219    #[inline]
2220    pub fn is_missing(&self) -> bool {
2221        self.symbol().is_synthetic()
2222    }
2223
2224    /// The underlying parse-tree node.
2225    #[doc(hidden)]
2226    #[must_use]
2227    #[inline]
2228    pub const fn node(&self) -> Node<'a> {
2229        self.__node.node()
2230    }
2231}
2232
2233impl fmt::Display for TerminalNode<'_> {
2234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2235        f.write_str(self.__node.text())
2236    }
2237}
2238
2239/// Typed error-node wrapper exposed by generated listener and visitor
2240/// surfaces.
2241#[derive(Clone, Debug)]
2242pub struct ErrorNode<'a> {
2243    __node: ErrorNodeView<'a>,
2244}
2245
2246impl<'a> ErrorNode<'a> {
2247    #[doc(hidden)]
2248    #[must_use]
2249    #[inline]
2250    pub const fn new(node: ErrorNodeView<'a>) -> Self {
2251        Self { __node: node }
2252    }
2253
2254    #[must_use]
2255    #[inline]
2256    pub fn symbol(&self) -> TokenView<'a> {
2257        self.__node.symbol()
2258    }
2259
2260    #[must_use]
2261    #[inline]
2262    pub fn is_missing(&self) -> bool {
2263        self.symbol().is_synthetic()
2264    }
2265
2266    /// The underlying parse-tree node.
2267    #[doc(hidden)]
2268    #[must_use]
2269    #[inline]
2270    pub const fn node(&self) -> Node<'a> {
2271        self.__node.node()
2272    }
2273}
2274
2275impl fmt::Display for ErrorNode<'_> {
2276    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2277        f.write_str(self.__node.text())
2278    }
2279}
2280
2281/// Defines a grammar-specific callback adapter for [`walk_generated`].
2282#[doc(hidden)]
2283#[macro_export]
2284macro_rules! __antlr4_rust_generated_walk_callbacks {
2285    (
2286        callbacks: $callbacks:ident,
2287        listener: $listener:ident,
2288        enter: |$enter_listener:ident, $enter_context:ident, $enter_states:ident| $enter_body:block,
2289        exit: |$exit_listener:ident, $exit_context:ident, $exit_states:ident| $exit_body:block,
2290        terminal: |$terminal_listener:ident, $terminal_node:ident| $terminal_body:block,
2291        error: |$error_listener:ident, $error_node:ident| $error_body:block $(,)?
2292    ) => {
2293        #[allow(dead_code)]
2294        struct $callbacks<'listener, T>(&'listener mut T);
2295
2296        impl<E, T: $listener<E>> $crate::generated::GeneratedWalkCallbacks<E>
2297            for $callbacks<'_, T>
2298        {
2299            #[inline(always)]
2300            fn dispatch_enter_rule(
2301                &mut self,
2302                $enter_context: $crate::RuleNodeView<'_>,
2303                $enter_states: ::core::option::Option<&[isize]>,
2304            ) -> ::core::result::Result<(), E> {
2305                let $enter_listener = &mut *self.0;
2306                $enter_body
2307            }
2308
2309            #[inline(always)]
2310            fn dispatch_exit_rule(
2311                &mut self,
2312                $exit_context: $crate::RuleNodeView<'_>,
2313                $exit_states: ::core::option::Option<&[isize]>,
2314            ) -> ::core::result::Result<(), E> {
2315                let $exit_listener = &mut *self.0;
2316                $exit_body
2317            }
2318
2319            #[inline(always)]
2320            fn visit_terminal(
2321                &mut self,
2322                $terminal_node: $crate::TerminalNodeView<'_>,
2323            ) -> ::core::result::Result<(), E> {
2324                let $terminal_listener = &mut *self.0;
2325                $terminal_body
2326            }
2327
2328            #[inline(always)]
2329            fn visit_error_node(
2330                &mut self,
2331                $error_node: $crate::ErrorNodeView<'_>,
2332            ) -> ::core::result::Result<(), E> {
2333                let $error_listener = &mut *self.0;
2334                $error_body
2335            }
2336        }
2337    };
2338}
2339
2340/// Grammar-specific callbacks used by the runtime-owned generated tree walker.
2341#[doc(hidden)]
2342pub trait GeneratedWalkCallbacks<E> {
2343    fn dispatch_enter_rule(
2344        &mut self,
2345        context: RuleNodeView<'_>,
2346        invocation_states: Option<&[isize]>,
2347    ) -> Result<(), E>;
2348
2349    fn dispatch_exit_rule(
2350        &mut self,
2351        context: RuleNodeView<'_>,
2352        invocation_states: Option<&[isize]>,
2353    ) -> Result<(), E>;
2354
2355    fn visit_terminal(&mut self, node: TerminalNodeView<'_>) -> Result<(), E>;
2356
2357    fn visit_error_node(&mut self, node: ErrorNodeView<'_>) -> Result<(), E>;
2358}
2359
2360/// Walks a generated parse tree while generated callbacks perform typed
2361/// context dispatch.
2362#[doc(hidden)]
2363#[inline(always)]
2364pub fn walk_generated<E, C>(
2365    tree: Node<'_>,
2366    mut invocation_states: Option<Vec<isize>>,
2367    callbacks: &mut C,
2368) -> Result<(), E>
2369where
2370    C: GeneratedWalkCallbacks<E>,
2371{
2372    enum Event<'tree> {
2373        Enter(Node<'tree>),
2374        Exit(RuleNodeView<'tree>),
2375    }
2376
2377    let mut stack = vec![Event::Enter(tree)];
2378    while let Some(event) = stack.pop() {
2379        match event {
2380            Event::Enter(node) => match node.kind() {
2381                NodeKind::Rule => {
2382                    let context = node.as_rule().expect("rule node kind checked");
2383                    if let Some(states) = &mut invocation_states {
2384                        states.insert(0, context.invoking_state());
2385                    }
2386                    callbacks.dispatch_enter_rule(context, invocation_states.as_deref())?;
2387                    stack.push(Event::Exit(context));
2388                    stack.extend(context.children().rev().map(Event::Enter));
2389                }
2390                NodeKind::Terminal => callbacks
2391                    .visit_terminal(node.as_terminal().expect("terminal node kind checked"))?,
2392                NodeKind::Error => {
2393                    callbacks
2394                        .visit_error_node(node.as_error().expect("error node kind checked"))?;
2395                }
2396            },
2397            Event::Exit(context) => {
2398                callbacks.dispatch_exit_rule(context, invocation_states.as_deref())?;
2399                if let Some(states) = &mut invocation_states {
2400                    states.remove(0);
2401                }
2402            }
2403        }
2404    }
2405    Ok(())
2406}
2407
2408/// Child source of one generated context view: either a stored parse-tree
2409/// node or the live parser context observed from an in-flight rule.
2410#[doc(hidden)]
2411#[derive(Clone, Copy, Debug)]
2412pub enum __GeneratedRuleContext<'a> {
2413    Stored(RuleNodeView<'a>),
2414    Active {
2415        context: &'a ParserRuleContext,
2416        storage: &'a ParseTreeStorage,
2417        tokens: &'a TokenStore,
2418    },
2419}
2420
2421/// Marker state for generated contexts borrowed from a stored parse tree.
2422#[doc(hidden)]
2423#[derive(Clone, Copy, Debug)]
2424pub struct StoredTreeContext;
2425
2426/// Marker state for generated contexts observed from an in-flight parse.
2427#[doc(hidden)]
2428#[derive(Clone, Copy, Debug)]
2429pub struct __ActiveParserContext;
2430
2431#[doc(hidden)]
2432#[inline]
2433pub fn __context_children(
2434    source: __GeneratedRuleContext<'_>,
2435) -> impl Iterator<Item = Node<'_>> + '_ {
2436    let mut stored = match source {
2437        __GeneratedRuleContext::Stored(node) => Some(node.children()),
2438        __GeneratedRuleContext::Active { .. } => None,
2439    };
2440    let mut active = match source {
2441        __GeneratedRuleContext::Stored(_) => None,
2442        __GeneratedRuleContext::Active {
2443            context,
2444            storage,
2445            tokens,
2446        } => Some(context.child_nodes(storage, tokens)),
2447    };
2448    std::iter::from_fn(move || {
2449        stored
2450            .as_mut()
2451            .and_then(Iterator::next)
2452            .or_else(|| active.as_mut().and_then(Iterator::next))
2453    })
2454}
2455
2456#[doc(hidden)]
2457#[inline]
2458pub fn __rule_children(
2459    source: __GeneratedRuleContext<'_>,
2460    rule_index: usize,
2461) -> impl Iterator<Item = RuleNodeView<'_>> + '_ {
2462    __context_children(source).filter_map(move |child| {
2463        let rule = child.as_rule()?;
2464        (rule.rule_index() == rule_index).then_some(rule)
2465    })
2466}
2467
2468#[doc(hidden)]
2469#[inline]
2470pub fn __terminal_children(
2471    source: __GeneratedRuleContext<'_>,
2472) -> impl Iterator<Item = TerminalNodeView<'_>> + '_ {
2473    __context_children(source).filter_map(Node::terminal_view)
2474}
2475
2476#[doc(hidden)]
2477#[inline]
2478pub fn __token_children(
2479    source: __GeneratedRuleContext<'_>,
2480    token_type: i32,
2481) -> impl Iterator<Item = TerminalNodeView<'_>> + '_ {
2482    __terminal_children(source).filter(move |terminal| terminal.symbol().token_type() == token_type)
2483}
2484
2485#[doc(hidden)]
2486#[inline]
2487pub fn __token_children_matching<'a>(
2488    source: __GeneratedRuleContext<'a>,
2489    token_types: &'static [i32],
2490) -> impl Iterator<Item = TerminalNodeView<'a>> + 'a {
2491    __terminal_children(source)
2492        .filter(move |terminal| token_types.contains(&terminal.symbol().token_type()))
2493}
2494
2495#[doc(hidden)]
2496#[inline]
2497pub fn __labeled_token_children(
2498    source: __GeneratedRuleContext<'_>,
2499    token_type: i32,
2500) -> impl Iterator<Item = TerminalNodeView<'_>> + '_ {
2501    __context_children(source).filter_map(move |child| {
2502        let terminal = child.labeled_terminal_view()?;
2503        (terminal.symbol().token_type() == token_type).then_some(terminal)
2504    })
2505}
2506
2507#[doc(hidden)]
2508#[inline]
2509pub fn __labeled_token_children_matching<'a>(
2510    source: __GeneratedRuleContext<'a>,
2511    token_types: &'static [i32],
2512) -> impl Iterator<Item = TerminalNodeView<'a>> + 'a {
2513    __context_children(source).filter_map(move |child| {
2514        let terminal = child.labeled_terminal_view()?;
2515        token_types
2516            .contains(&terminal.symbol().token_type())
2517            .then_some(terminal)
2518    })
2519}
2520
2521/// Constructs a generated context view over a live parser context.
2522/// Implemented by `__antlr4_rust_context!` for every generated context.
2523#[doc(hidden)]
2524pub trait __FromActiveRuleContext<'a>: Sized {
2525    fn __from_active(
2526        context: &'a ParserRuleContext,
2527        live_attrs: Option<&dyn Any>,
2528        invocation_states: Vec<isize>,
2529        storage: &'a ParseTreeStorage,
2530        tokens: &'a TokenStore,
2531    ) -> Option<Self>;
2532}
2533
2534#[doc(hidden)]
2535#[inline]
2536pub fn __active_context_view<'a, T: __FromActiveRuleContext<'a>>(
2537    context: &'a ParserRuleContext,
2538    invocation_states: Vec<isize>,
2539    storage: &'a ParseTreeStorage,
2540    tokens: &'a TokenStore,
2541) -> Option<T> {
2542    T::__from_active(context, None, invocation_states, storage, tokens)
2543}
2544
2545#[doc(hidden)]
2546#[inline]
2547pub fn __active_context_view_with_attrs<'a, T: __FromActiveRuleContext<'a>>(
2548    context: &'a ParserRuleContext,
2549    live_attrs: &dyn Any,
2550    invocation_states: Vec<isize>,
2551    storage: &'a ParseTreeStorage,
2552    tokens: &'a TokenStore,
2553) -> Option<T> {
2554    T::__from_active(
2555        context,
2556        Some(live_attrs),
2557        invocation_states,
2558        storage,
2559        tokens,
2560    )
2561}
2562
2563/// Formats an invoking-state chain the way Java's `RuleContext.toString`
2564/// renders it: `[13 6]`.
2565#[doc(hidden)]
2566pub fn __write_invocation_states(
2567    f: &mut fmt::Formatter<'_>,
2568    states: impl Iterator<Item = isize>,
2569) -> fmt::Result {
2570    f.write_str("[")?;
2571    let mut separator = "";
2572    for state in states {
2573        write!(f, "{separator}{state}")?;
2574        separator = " ";
2575    }
2576    f.write_str("]")
2577}
2578
2579/// Bound on the recovery-oriented state markers accepted by generated
2580/// context accessors.
2581///
2582/// The validated marker (`ValidatedTreeContext`) intentionally stays emitted
2583/// per generated module: the accessors macro relies on rustc proving that the
2584/// validated marker never implements this trait, and coherence only permits
2585/// that negative reasoning while the marker type is local to the generated
2586/// crate.
2587#[doc(hidden)]
2588pub trait __RecoveryContextState {}
2589
2590impl __RecoveryContextState for StoredTreeContext {}
2591impl __RecoveryContextState for __ActiveParserContext {}
2592
2593#[cfg(test)]
2594#[allow(clippy::disallowed_methods)] // insta assertion macros unwrap internal I/O.
2595mod tests {
2596    use super::*;
2597    use crate::token::{TokenId, TokenSpec};
2598    use crate::tree::ParsedFile;
2599
2600    static META: GrammarMetadata = GrammarMetadata::new(
2601        "Mini.g4",
2602        &["file"],
2603        &[None, Some("'x'")],
2604        &[None, Some("X")],
2605        &[None, None],
2606        &["DEFAULT_TOKEN_CHANNEL", "HIDDEN"],
2607        &["DEFAULT_MODE"],
2608        &[4, 1, 1, 0, 0, 0],
2609    );
2610
2611    fn test_token(store: &mut TokenStore, token_type: i32, text: &str) -> TokenId {
2612        store
2613            .push(TokenSpec::explicit(token_type, text))
2614            .expect("test token should fit")
2615    }
2616
2617    fn generated_walk_test_tree() -> ParsedFile {
2618        let mut tokens = TokenStore::new(None, "");
2619        let a = test_token(&mut tokens, 1, "a");
2620        let b = test_token(&mut tokens, 2, "b");
2621        let error = test_token(&mut tokens, 3, "!");
2622        let mut storage = ParseTreeStorage::new();
2623        let a = storage.terminal(a);
2624        let b = storage.terminal(b);
2625        let error = storage.error(error);
2626        let mut child = ParserRuleContext::new(1, 7);
2627        storage.add_child(&mut child, b);
2628        let child = storage.finish_rule(child);
2629        let mut root = ParserRuleContext::new(0, -1);
2630        storage.add_child(&mut root, a);
2631        storage.add_child(&mut root, child);
2632        storage.add_child(&mut root, error);
2633        let root = storage.finish_rule(root);
2634        ParsedFile::new(tokens, storage, root)
2635    }
2636
2637    #[derive(Default)]
2638    struct RecordingWalkCallbacks {
2639        events: Vec<String>,
2640        fail_on_terminal: Option<&'static str>,
2641    }
2642
2643    impl GeneratedWalkCallbacks<&'static str> for RecordingWalkCallbacks {
2644        fn dispatch_enter_rule(
2645            &mut self,
2646            context: RuleNodeView<'_>,
2647            invocation_states: Option<&[isize]>,
2648        ) -> Result<(), &'static str> {
2649            self.events.push(format!(
2650                "enter rule {} {invocation_states:?}",
2651                context.rule_index()
2652            ));
2653            Ok(())
2654        }
2655
2656        fn dispatch_exit_rule(
2657            &mut self,
2658            context: RuleNodeView<'_>,
2659            invocation_states: Option<&[isize]>,
2660        ) -> Result<(), &'static str> {
2661            self.events.push(format!(
2662                "exit rule {} {invocation_states:?}",
2663                context.rule_index()
2664            ));
2665            Ok(())
2666        }
2667
2668        fn visit_terminal(&mut self, node: TerminalNodeView<'_>) -> Result<(), &'static str> {
2669            self.events.push(format!("terminal {}", node.text()));
2670            if self.fail_on_terminal == Some(node.text()) {
2671                Err("terminal callback failed")
2672            } else {
2673                Ok(())
2674            }
2675        }
2676
2677        fn visit_error_node(&mut self, node: ErrorNodeView<'_>) -> Result<(), &'static str> {
2678            self.events.push(format!("error {}", node.text()));
2679            Ok(())
2680        }
2681    }
2682
2683    #[test]
2684    fn generated_walk_preserves_order_and_invocation_states() {
2685        let parsed = generated_walk_test_tree();
2686        let mut callbacks = RecordingWalkCallbacks::default();
2687
2688        walk_generated(parsed.tree(), Some(vec![99]), &mut callbacks)
2689            .expect("recording callbacks should accept every event");
2690
2691        insta::assert_debug_snapshot!(
2692            "generated_walk_order_and_invocation_states",
2693            callbacks.events
2694        );
2695    }
2696
2697    #[test]
2698    fn generated_walk_short_circuits_callback_errors() {
2699        let parsed = generated_walk_test_tree();
2700        let mut callbacks = RecordingWalkCallbacks {
2701            fail_on_terminal: Some("b"),
2702            ..RecordingWalkCallbacks::default()
2703        };
2704
2705        assert_eq!(
2706            walk_generated(parsed.tree(), None, &mut callbacks),
2707            Err("terminal callback failed")
2708        );
2709        insta::assert_debug_snapshot!("generated_walk_short_circuit", callbacks.events);
2710    }
2711
2712    // Compile-only fixture: successful expansion of both facade macros with
2713    // invocation-site prelude names shadowed is the assertion.
2714    #[allow(dead_code, unreachable_pub)]
2715    mod facade_hygiene {
2716        struct Box;
2717        struct FnMut;
2718        struct None;
2719        struct Option;
2720        struct Rc;
2721        struct Result;
2722        struct Send;
2723        struct Some;
2724        struct String;
2725        struct Vec;
2726
2727        struct HygieneLexer<I, H> {
2728            base: crate::lexer::BaseLexer<I>,
2729            hooks: H,
2730        }
2731
2732        struct HygieneParser<S, H> {
2733            base: crate::parser::BaseParser<S, H>,
2734            simulator: ::core::option::Option<crate::atn::parser::ParserAtnSimulator<'static>>,
2735            generated_only: bool,
2736        }
2737
2738        fn metadata() -> &'static crate::generated::GrammarMetadata {
2739            &super::META
2740        }
2741
2742        fn parser_atn() -> &'static crate::atn::parser_atn::ParserAtn {
2743            panic!("compile-only facade hygiene fixture")
2744        }
2745
2746        crate::__antlr4_rust_lexer_facade! {
2747            type: HygieneLexer<I, H>,
2748            fields: {
2749                base: base,
2750                hooks: hooks,
2751            },
2752            metadata: metadata,
2753            next_token(_lexer, _sink) {
2754                panic!("compile-only facade hygiene fixture")
2755            }
2756        }
2757
2758        crate::__antlr4_rust_parser_facade! {
2759            type: HygieneParser<S, H>,
2760            fields: {
2761                base: base,
2762                simulator: simulator,
2763                generated_only: generated_only,
2764            },
2765            metadata: metadata,
2766            parser_atn: parser_atn,
2767            reset(_parser) {}
2768        }
2769    }
2770
2771    #[test]
2772    fn metadata_builds_vocabulary() {
2773        assert_eq!(META.grammar_file_name(), "Mini.g4");
2774        assert_eq!(META.vocabulary().display_name(1), "'x'");
2775    }
2776
2777    #[test]
2778    fn cloned_metadata_shares_the_cache_before_explicit_initialization() {
2779        let original = GrammarMetadata::new(
2780            "Clone.g4",
2781            &["start"],
2782            &[None, Some("'x'")],
2783            &[None, Some("X")],
2784            &[None, None],
2785            &["DEFAULT_TOKEN_CHANNEL"],
2786            &["DEFAULT_MODE"],
2787            &[],
2788        );
2789        let cloned = original.clone();
2790        let first = original.recognizer_data();
2791        let second = cloned.recognizer_data();
2792
2793        assert!(std::ptr::eq(first.rule_names(), second.rule_names()));
2794        assert!(std::ptr::eq(first.vocabulary(), second.vocabulary()));
2795    }
2796}
2797
2798#[cfg(test)]
2799mod parser_driver_tests {
2800    // Anchors into the `__antlr4_rust_parser_driver!` macro body. Each search
2801    // string is declared once so a rename inside the macro is a one-line
2802    // update here, and the assertions below stay readable.
2803    const DRIVER_MACRO: &str = "macro_rules! __antlr4_rust_parser_driver";
2804    const ENTRY_POINTS_MACRO: &str = "macro_rules! __antlr4_rust_parser_entry_points";
2805    /// Unique to the top-level surfacing check: the Err-arm check binds
2806    /// `semantic_error` and the sticky-abort drains bind `_`, so anchoring on
2807    /// the `Some(error)` binder cannot accidentally match a drain.
2808    const TOP_LEVEL_SEMANTIC_SURFACE: &str =
2809        "Some(error) = self.$base.take_unknown_semantic_error()";
2810    const ERR_ARM_SEMANTIC_SURFACE: &str =
2811        "Some(semantic_error) = self.$base.take_unknown_semantic_error()";
2812    const ERR_ARM_START: &str = "::core::result::Result::Err(error) => {";
2813    const ERR_CONVERSION: &str = "let error = error.into_error();";
2814    const ERR_RETURN: &str = "return ::core::result::Result::Err(error);";
2815    const DIAGNOSTICS_DISPATCH: &str = "self.$base.report_generated_parser_diagnostics();";
2816    const ABORT_DRAIN: &str = "Some(abort) = self.$base.take_parse_abort()";
2817    const UNRECOVERED_REPORT: &str = "self.$base.report_unrecovered_parser_error(&error);";
2818    const OK_TREE: &str = "::core::result::Result::Ok(__tree)";
2819    const INTERPRETED_FALLBACK: &str =
2820        "self.parse_interpreted_rule_precedence(rule_index, precedence)?";
2821    const ACTION_DISPATCH: &str = "self.run_action(__action, __tree);";
2822
2823    /// The driver macro body with all whitespace collapsed, so anchors that
2824    /// rustfmt wraps across lines (`if let ::core::option::Option::Some(error)
2825    /// = self.$base...`) match as single strings.
2826    fn driver_macro_body() -> String {
2827        let source = include_str!("generated.rs");
2828        let driver_at = source
2829            .find(DRIVER_MACRO)
2830            .expect("driver macro is defined in this module");
2831        let entry_points_at = source
2832            .find(ENTRY_POINTS_MACRO)
2833            .expect("entry-points macro is defined in this module");
2834        source[driver_at..entry_points_at]
2835            .split_whitespace()
2836            .collect::<Vec<_>>()
2837            .join(" ")
2838    }
2839
2840    /// Pins ordering invariants of the `__antlr4_rust_parser_driver!` entry
2841    /// body that generated-parser behavior depends on. These checks lived in
2842    /// the generator's per-grammar rendered-text tests while the driver was
2843    /// emitted per module; the macro is the single copy now, so the source
2844    /// text is asserted here once. The runtime behavior itself is covered by
2845    /// `public_entry_surfaces_recorded_semantic_miss_after_clean_parse` in
2846    /// the generator's CLI suite, which parses through a generated entry and
2847    /// asserts the fail-loud error is returned.
2848    #[test]
2849    fn parser_driver_entry_ordering_invariants() {
2850        let driver = driver_macro_body();
2851
2852        // The fail-loud surfacing check runs before the entry can return Ok,
2853        // or a parse that consulted an unimplemented hook would return a
2854        // recovered Ok tree instead of AntlrError::Unsupported. The binder
2855        // anchor is unique, so this cannot be satisfied by one of the
2856        // `let _ =` drains.
2857        assert_eq!(
2858            driver.matches(TOP_LEVEL_SEMANTIC_SURFACE).count(),
2859            1,
2860            "exactly one top-level surfacing check binds `error`"
2861        );
2862        let surface_at = driver
2863            .find(TOP_LEVEL_SEMANTIC_SURFACE)
2864            .expect("entry surfaces recorded unknown-semantic coordinates");
2865        let ok_at = driver[surface_at..]
2866            .find(OK_TREE)
2867            .map(|offset| surface_at + offset)
2868            .expect("entry returns the tree after semantic checks");
2869        assert!(surface_at < ok_at);
2870
2871        // Inside the generated-rule Err arm, retained diagnostics dispatch
2872        // first, then parser aborts, then recorded semantic misses; otherwise
2873        // the documented fail-loud error would be shadowed or diagnostics
2874        // would leak into the next entry on a reused parser.
2875        let arm_start = driver
2876            .find(ERR_ARM_START)
2877            .expect("the generated-rule match has an Err arm");
2878        let conversion_at = driver[arm_start..]
2879            .find(ERR_CONVERSION)
2880            .map(|offset| arm_start + offset)
2881            .expect("Err arm converts the generic rule error");
2882        let arm = &driver[arm_start..conversion_at];
2883        let diagnostics_at = arm
2884            .find(DIAGNOSTICS_DISPATCH)
2885            .expect("the fatal Err arm drains retained diagnostics");
2886        let abort_at = arm
2887            .find(ABORT_DRAIN)
2888            .expect("the Err arm drains a recorded parser abort");
2889        let semantic_at = arm
2890            .find(ERR_ARM_SEMANTIC_SURFACE)
2891            .expect("the Err arm drains a recorded semantic error");
2892        assert!(
2893            diagnostics_at < abort_at && abort_at < semantic_at,
2894            "retained diagnostics dispatch first, then parser aborts precede semantic misses"
2895        );
2896
2897        // A fatal unwind reports the converted error through the listener
2898        // boundary before returning it.
2899        let err_return_at = driver[conversion_at..]
2900            .find(ERR_RETURN)
2901            .map(|offset| conversion_at + offset)
2902            .expect("the Err arm returns the converted error");
2903        assert!(
2904            driver[conversion_at..err_return_at].contains(UNRECOVERED_REPORT),
2905            "the Err arm reports the unrecovered error before returning it"
2906        );
2907
2908        // The interpreted fallback runs the uniform action-dispatch loop
2909        // (every generated parser defines `run_action`; grammars without
2910        // action states get the empty stub); the top-level boundary then
2911        // dispatches recovery diagnostics and never returns Ok between the
2912        // fallback and the surfacing check, so an action-hook miss recorded
2913        // by the fallback's immediate `run_action` loop cannot escape as Ok.
2914        let fallback_at = driver
2915            .find(INTERPRETED_FALLBACK)
2916            .expect("entry runs the interpreted fallback when a rule is not generated");
2917        assert!(
2918            fallback_at < surface_at,
2919            "the surfacing check follows the interpreted fallback"
2920        );
2921        assert!(
2922            driver[fallback_at..surface_at].contains(DIAGNOSTICS_DISPATCH),
2923            "the entry dispatches boundary diagnostics between the fallback and the surfacing check"
2924        );
2925        assert!(
2926            !driver[fallback_at..surface_at].contains(OK_TREE),
2927            "the entry must not return Ok between the interpreted fallback and the surfacing check"
2928        );
2929        assert!(driver.contains(ACTION_DISPATCH));
2930    }
2931}