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
854        impl<$input, $hooks> $crate::generated::GeneratedLexer for $lexer<$input, $hooks>
855        where
856            $input: $crate::char_stream::CharStream,
857            $hooks: $crate::parser::SemanticHooks,
858        {
859            fn metadata() -> &'static $crate::generated::GrammarMetadata {
860                $metadata()
861            }
862        }
863
864        impl<$input, $hooks> $crate::recognizer::Recognizer for $lexer<$input, $hooks>
865        where
866            $input: $crate::char_stream::CharStream,
867            $hooks: $crate::parser::SemanticHooks,
868        {
869            fn data(&self) -> &$crate::recognizer::RecognizerData {
870                $crate::recognizer::Recognizer::data(&self.$base)
871            }
872
873            fn data_mut(&mut self) -> &mut $crate::recognizer::RecognizerData {
874                $crate::recognizer::Recognizer::data_mut(&mut self.$base)
875            }
876        }
877
878        impl<$input, $hooks> $crate::lexer::Lexer for $lexer<$input, $hooks>
879        where
880            $input: $crate::char_stream::CharStream,
881            $hooks: $crate::parser::SemanticHooks,
882        {
883            fn mode(&self) -> i32 {
884                $crate::lexer::Lexer::mode(&self.$base)
885            }
886
887            fn set_mode(&mut self, mode: i32) {
888                $crate::lexer::Lexer::set_mode(&mut self.$base, mode);
889            }
890
891            fn push_mode(&mut self, mode: i32) {
892                $crate::lexer::Lexer::push_mode(&mut self.$base, mode);
893            }
894
895            fn pop_mode(&mut self) -> ::core::option::Option<i32> {
896                $crate::lexer::Lexer::pop_mode(&mut self.$base)
897            }
898        }
899
900        impl<$input, $hooks> $crate::token::TokenSource for $lexer<$input, $hooks>
901        where
902            $input: $crate::char_stream::CharStream,
903            $hooks: $crate::parser::SemanticHooks,
904        {
905            fn next_token(
906                &mut self,
907                $sink: &mut $crate::token::TokenSink<'_>,
908            ) -> ::core::result::Result<$crate::token::TokenId, $crate::token::TokenStoreError>
909            {
910                let $this = self;
911                $next_token
912            }
913
914            fn line(&self) -> usize {
915                self.$base.line()
916            }
917
918            fn column(&self) -> usize {
919                self.$base.column()
920            }
921
922            fn source_name(&self) -> &str {
923                self.$base.source_name()
924            }
925
926            fn source_text(&self) -> ::core::option::Option<::std::rc::Rc<str>> {
927                self.$base.source_text()
928            }
929
930            fn drain_errors(&mut self) -> ::std::vec::Vec<$crate::token::TokenSourceError> {
931                self.$base.drain_errors()
932            }
933
934            fn report_error(&self, source_error: &$crate::token::TokenSourceError) -> bool {
935                $crate::recognizer::Recognizer::notify_error_listeners(self, source_error.into());
936                true
937            }
938
939            fn lexer_dfa_string(&self) -> ::std::string::String {
940                self.$base.lexer_dfa_string()
941            }
942        }
943    };
944}
945
946/// Defines the grammar-independent facade and trait delegation for one
947/// generated parser.
948#[doc(hidden)]
949#[macro_export]
950macro_rules! __antlr4_rust_parser_facade {
951    (
952        type: $parser:ident<$source:ident, $hooks:ident>,
953        fields: {
954            base: $base:ident,
955            simulator: $simulator:ident,
956            generated_only: $generated_only:ident $(,)?
957        },
958        metadata: $metadata:path,
959        parser_atn: $parser_atn:path,
960        reset($this:ident) $reset:block
961        $(,)?
962    ) => {
963        impl<$source, $hooks> $parser<$source, $hooks>
964        where
965            $source: $crate::token::TokenSource,
966            $hooks: $crate::parser::SemanticHooks,
967        {
968            pub fn metadata() -> &'static $crate::generated::GrammarMetadata {
969                $metadata()
970            }
971
972            /// Adds a listener for parser diagnostics.
973            pub fn add_error_listener<T>(&mut self, listener: T)
974            where
975                T: for<'a> $crate::errors::ErrorListener<dyn $crate::recognizer::Recognizer + 'a>
976                    + ::core::marker::Send
977                    + 'static,
978            {
979                $crate::recognizer::Recognizer::add_error_listener(&mut self.$base, listener);
980            }
981
982            /// Removes every parser error listener, including the default console listener.
983            pub fn remove_error_listeners(&mut self) {
984                $crate::recognizer::Recognizer::remove_error_listeners(&mut self.$base);
985            }
986
987            /// Registers a listener for committed rule enter/exit events during
988            /// recognition (ANTLR's `addParseListener`). See
989            /// [`antlr4_runtime::ParseListener`] for the delivery contract.
990            pub fn add_parse_listener<T>(&mut self, listener: T)
991            where
992                T: $crate::parser::ParseListener + 'static,
993            {
994                self.$base.add_parse_listener(listener);
995            }
996
997            /// Removes every registered parse listener and returns them, dropping
998            /// any sticky abort a removed listener had requested.
999            pub fn remove_parse_listeners(
1000                &mut self,
1001            ) -> ::std::vec::Vec<::std::boxed::Box<dyn $crate::parser::ParseListener>> {
1002                self.$base.remove_parse_listeners()
1003            }
1004
1005            /// Fully resets parser-owned state and rewinds the current token stream.
1006            pub fn reset(&mut self) {
1007                self.$base.reset();
1008                if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
1009                    simulator.reset();
1010                }
1011                let $this = &mut *self;
1012                $reset
1013            }
1014
1015            /// Replaces the token stream and fully resets parser-owned state.
1016            pub fn set_token_stream(
1017                &mut self,
1018                input: $crate::token_stream::CommonTokenStream<$source>,
1019            ) {
1020                self.$base.set_token_stream(input);
1021                if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
1022                    simulator.reset();
1023                }
1024                let $this = &mut *self;
1025                $reset
1026            }
1027
1028            #[must_use]
1029            pub const fn token_stream(&self) -> &$crate::token_stream::CommonTokenStream<$source> {
1030                self.$base.token_stream()
1031            }
1032
1033            #[must_use]
1034            pub const fn token_stream_mut(
1035                &mut self,
1036            ) -> &mut $crate::token_stream::CommonTokenStream<$source> {
1037                self.$base.token_stream_mut()
1038            }
1039
1040            #[must_use]
1041            pub const fn token_store(&self) -> &$crate::token::TokenStore {
1042                self.$base.token_store()
1043            }
1044
1045            #[must_use]
1046            pub const fn parse_tree_storage(&self) -> &$crate::tree::ParseTreeStorage {
1047                self.$base.parse_tree_storage()
1048            }
1049
1050            #[must_use]
1051            pub fn prediction_context_stats(&self) -> $crate::prediction::PredictionContextStats {
1052                self.$simulator.as_ref().map_or_else(
1053                    $crate::prediction::PredictionContextStats::default,
1054                    $crate::atn::parser::ParserAtnSimulator::prediction_context_stats,
1055                )
1056            }
1057
1058            #[must_use]
1059            pub fn parser_dfa_stats(&self) -> $crate::dfa::ParserDfaStats {
1060                self.$simulator.as_ref().map_or_else(
1061                    $crate::dfa::ParserDfaStats::default,
1062                    $crate::atn::parser::ParserAtnSimulator::parser_dfa_stats,
1063                )
1064            }
1065
1066            /// Clears this grammar's learned parser decision DFAs.
1067            pub fn clear_dfa(&mut self) {
1068                if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
1069                    simulator.clear_dfa();
1070                } else {
1071                    $crate::atn::parser::ParserAtnSimulator::clear_shared_dfa($parser_atn());
1072                }
1073                let $this = &mut *self;
1074                $reset
1075            }
1076
1077            #[must_use]
1078            pub fn node(&self, id: $crate::tree::NodeId) -> $crate::tree::Node<'_> {
1079                self.$base.node(id)
1080            }
1081
1082            #[must_use]
1083            pub fn into_token_stream(self) -> $crate::token_stream::CommonTokenStream<$source> {
1084                self.$base.into_token_stream()
1085            }
1086
1087            #[must_use]
1088            pub fn into_token_store(self) -> $crate::token::TokenStore {
1089                self.$base.into_token_store()
1090            }
1091
1092            #[must_use]
1093            pub fn into_parsed_file(self, root: $crate::tree::NodeId) -> $crate::tree::ParsedFile {
1094                self.$base.into_parsed_file(root)
1095            }
1096
1097            /// Compiles a tree pattern rooted at parser rule `rule_index`.
1098            ///
1099            /// Mirrors ANTLR's `Parser.compileParseTreePattern`. Literal chunks of
1100            /// `pattern` are lexed with a fresh lexer built by `make_lexer`.
1101            pub fn compile_parse_tree_pattern<PL>(
1102                &self,
1103                pattern: &str,
1104                rule_index: usize,
1105                mut make_lexer: impl ::core::ops::FnMut($crate::char_stream::InputStream) -> PL,
1106            ) -> ::core::result::Result<
1107                $crate::tree_pattern::ParseTreePattern,
1108                $crate::tree_pattern::ParseTreePatternError,
1109            >
1110            where
1111                PL: $crate::token::TokenSource,
1112            {
1113                static PATTERN_DATA: ::std::sync::OnceLock<$crate::recognizer::RecognizerData> =
1114                    ::std::sync::OnceLock::new();
1115                static PATTERN_MATCHER: ::std::sync::OnceLock<
1116                    $crate::tree_pattern::ParseTreePatternMatcher<'static>,
1117                > = ::std::sync::OnceLock::new();
1118                let matcher = match PATTERN_MATCHER.get() {
1119                    ::core::option::Option::Some(matcher) => matcher,
1120                    ::core::option::Option::None => {
1121                        let data = PATTERN_DATA.get_or_init(|| $metadata().recognizer_data());
1122                        let matcher = $crate::tree_pattern::ParseTreePatternMatcher::new(
1123                            $parser_atn(),
1124                            data,
1125                        )?;
1126                        PATTERN_MATCHER.get_or_init(|| matcher)
1127                    }
1128                };
1129                matcher.compile(pattern, rule_index, move |text: &str| {
1130                    $crate::tree_pattern::lex_pattern_chunk(text, &mut make_lexer)
1131                })
1132            }
1133
1134            #[allow(dead_code)]
1135            fn simulator(&mut self) -> &mut $crate::atn::parser::ParserAtnSimulator<'static> {
1136                self.$simulator.get_or_insert_with(|| {
1137                    $crate::atn::parser::ParserAtnSimulator::new_shared($parser_atn())
1138                })
1139            }
1140
1141            #[allow(dead_code)]
1142            fn generated_only(&self) -> bool {
1143                self.$generated_only
1144            }
1145        }
1146
1147        impl<$source, $hooks> $crate::generated::GeneratedParser for $parser<$source, $hooks>
1148        where
1149            $source: $crate::token::TokenSource,
1150            $hooks: $crate::parser::SemanticHooks,
1151        {
1152            fn metadata() -> &'static $crate::generated::GrammarMetadata {
1153                $metadata()
1154            }
1155
1156            fn parser_atn() -> &'static $crate::atn::parser_atn::ParserAtn {
1157                $parser_atn()
1158            }
1159        }
1160
1161        impl<$source, $hooks> $crate::generated::GeneratedRuleParser for $parser<$source, $hooks>
1162        where
1163            $source: $crate::token::TokenSource,
1164            $hooks: $crate::parser::SemanticHooks,
1165        {
1166            type Source = $source;
1167            type Hooks = $hooks;
1168
1169            fn generated_rule_base(
1170                &mut self,
1171            ) -> &mut $crate::parser::BaseParser<Self::Source, Self::Hooks> {
1172                &mut self.$base
1173            }
1174        }
1175
1176        impl<$source, $hooks> $crate::recognizer::Recognizer for $parser<$source, $hooks>
1177        where
1178            $source: $crate::token::TokenSource,
1179            $hooks: $crate::parser::SemanticHooks,
1180        {
1181            fn data(&self) -> &$crate::recognizer::RecognizerData {
1182                $crate::recognizer::Recognizer::data(&self.$base)
1183            }
1184
1185            fn data_mut(&mut self) -> &mut $crate::recognizer::RecognizerData {
1186                $crate::recognizer::Recognizer::data_mut(&mut self.$base)
1187            }
1188        }
1189
1190        impl<$source, $hooks> $crate::parser::Parser for $parser<$source, $hooks>
1191        where
1192            $source: $crate::token::TokenSource,
1193            $hooks: $crate::parser::SemanticHooks,
1194        {
1195            fn build_parse_trees(&self) -> bool {
1196                $crate::parser::Parser::build_parse_trees(&self.$base)
1197            }
1198
1199            fn set_build_parse_trees(&mut self, build: bool) {
1200                $crate::parser::Parser::set_build_parse_trees(&mut self.$base, build);
1201            }
1202
1203            fn number_of_syntax_errors(&self) -> usize {
1204                $crate::parser::Parser::number_of_syntax_errors(&self.$base)
1205            }
1206
1207            fn report_diagnostic_errors(&self) -> bool {
1208                $crate::parser::Parser::report_diagnostic_errors(&self.$base)
1209            }
1210
1211            fn set_report_diagnostic_errors(&mut self, report: bool) {
1212                $crate::parser::Parser::set_report_diagnostic_errors(&mut self.$base, report);
1213            }
1214
1215            fn prediction_mode(&self) -> $crate::parser::PredictionMode {
1216                $crate::parser::Parser::prediction_mode(&self.$base)
1217            }
1218
1219            fn set_prediction_mode(&mut self, mode: $crate::parser::PredictionMode) {
1220                $crate::parser::Parser::set_prediction_mode(&mut self.$base, mode);
1221            }
1222
1223            fn max_rule_depth(&self) -> ::core::option::Option<usize> {
1224                $crate::parser::Parser::max_rule_depth(&self.$base)
1225            }
1226
1227            fn set_max_rule_depth(&mut self, depth: ::core::option::Option<usize>) {
1228                $crate::parser::Parser::set_max_rule_depth(&mut self.$base, depth);
1229            }
1230
1231            fn add_parse_listener(
1232                &mut self,
1233                listener: ::std::boxed::Box<dyn $crate::parser::ParseListener>,
1234            ) {
1235                $crate::parser::Parser::add_parse_listener(&mut self.$base, listener);
1236            }
1237
1238            fn remove_parse_listeners(
1239                &mut self,
1240            ) -> ::std::vec::Vec<::std::boxed::Box<dyn $crate::parser::ParseListener>> {
1241                $crate::parser::Parser::remove_parse_listeners(&mut self.$base)
1242            }
1243        }
1244    };
1245}
1246
1247/// Defines the grammar-independent parse-driver core for one generated
1248/// parser: entry/reset bookkeeping, generated-vs-interpreted engine routing,
1249/// sticky-abort and fail-loud semantic-error draining, and the interpreted
1250/// fallback with uniform action dispatch through the module's `run_action`.
1251///
1252/// This is an implementation detail of `antlr4-rust-gen`, not a stable
1253/// hand-written parser API. The `fallback` binder block supplied by generated
1254/// code composes the grammar's `ParserRuntimeOptions` (semantics table,
1255/// action indices, policy) and must evaluate to
1256/// `Result<(ParseTree, Vec<ParserAction>), AntlrError>`; this macro owns
1257/// everything else.
1258#[doc(hidden)]
1259#[macro_export]
1260macro_rules! __antlr4_rust_parser_driver {
1261    (
1262        type: $parser:ident<$source:ident, $hooks:ident>,
1263        fields: {
1264            base: $base:ident,
1265            simulator: $simulator:ident $(,)?
1266        },
1267        atn: $atn:path,
1268        adaptive_direct: $adaptive_direct:expr,
1269        fallback($this:ident, $rule_index:ident, $precedence:ident) $fallback:block
1270        $(,)?
1271    ) => {
1272        impl<$source, $hooks> $parser<$source, $hooks>
1273        where
1274            $source: $crate::token::TokenSource,
1275            $hooks: $crate::parser::SemanticHooks,
1276        {
1277            #[allow(dead_code)]
1278            fn parse_rule(
1279                &mut self,
1280                rule_index: usize,
1281            ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1282                self.parse_rule_precedence(rule_index, 0)
1283            }
1284
1285            #[allow(dead_code)]
1286            fn parse_rule_precedence(
1287                &mut self,
1288                rule_index: usize,
1289                precedence: i32,
1290            ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1291                self.parse_rule_precedence_inner(rule_index, precedence, true)
1292            }
1293
1294            #[allow(dead_code)]
1295            fn parse_rule_precedence_from_generated(
1296                &mut self,
1297                rule_index: usize,
1298                precedence: i32,
1299            ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1300                self.parse_rule_precedence_inner(rule_index, precedence, false)
1301            }
1302
1303            #[allow(dead_code)]
1304            fn parse_rule_precedence_inner(
1305                &mut self,
1306                rule_index: usize,
1307                precedence: i32,
1308                allow_generated_fallback: bool,
1309            ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1310                if allow_generated_fallback {
1311                    // True top-level entry: drop any fail-loud coordinates left by a
1312                    // previous parse so a reused parser starts clean. Mid-parse the hits
1313                    // are preserved so a generated parent can surface a recovered child's
1314                    // fail-loud coordinate at this boundary.
1315                    self.$base.reset_unknown_semantic_hits();
1316                    // Likewise drop stale sticky aborts (depth-cap violation,
1317                    // parse-listener abort): entry rules share one parser instance,
1318                    // and the flags must not poison the next parse when the previous
1319                    // one exited through an error path.
1320                    let _ = self.$base.take_parse_abort();
1321                }
1322                let __rule_start = $crate::int_stream::IntStream::index(self.$base.input());
1323                let __generated_only = self.generated_only();
1324                let __tree = if let ::core::option::Option::Some(result) =
1325                    self.parse_generated_rule(rule_index, precedence, allow_generated_fallback)
1326                {
1327                    match result {
1328                        ::core::result::Result::Ok(tree) => tree,
1329                        ::core::result::Result::Err(error) => {
1330                            $crate::int_stream::IntStream::seek(self.$base.input(), __rule_start);
1331                            let __report_error = ::core::matches!(
1332                                &error,
1333                                $crate::generated::GeneratedRuleError::Fatal(_)
1334                            );
1335                            // A fatal unwind retains recovery diagnostics committed
1336                            // earlier in this entry. Dispatch them before a semantic
1337                            // or parser-abort override can return, or they would leak
1338                            // into the next entry on a reused parser.
1339                            if allow_generated_fallback && __report_error {
1340                                self.$base.report_generated_parser_diagnostics();
1341                            }
1342                            if allow_generated_fallback {
1343                                // A sticky abort (depth cap, listener) wins over an
1344                                // error or semantic miss derived after recovery absorbed
1345                                // the aborted rule. Drain any masked semantic miss too,
1346                                // so neither condition poisons the next entry.
1347                                if let ::core::option::Option::Some(abort) =
1348                                    self.$base.take_parse_abort()
1349                                {
1350                                    let _ = self.$base.take_unknown_semantic_error();
1351                                    return ::core::result::Result::Err(abort);
1352                                }
1353                                // A generated predicate that consulted an unimplemented
1354                                // hook fails the alternative and surfaces here as a generic
1355                                // failed-predicate/rule error. Prefer the recorded fail-loud
1356                                // semantic error when no parser abort occurred.
1357                                if let ::core::option::Option::Some(semantic_error) =
1358                                    self.$base.take_unknown_semantic_error()
1359                                {
1360                                    return ::core::result::Result::Err(semantic_error);
1361                                }
1362                            }
1363                            let error = error.into_error();
1364                            if allow_generated_fallback && __report_error {
1365                                self.$base.report_unrecovered_parser_error(&error);
1366                            }
1367                            return ::core::result::Result::Err(error);
1368                        }
1369                    }
1370                } else if __generated_only {
1371                    return ::core::result::Result::Err($crate::errors::AntlrError::Unsupported(
1372                        ::std::format!("generated parser did not emit rule {}", rule_index),
1373                    ));
1374                } else {
1375                    self.parse_interpreted_rule_precedence(rule_index, precedence)?
1376                };
1377                if allow_generated_fallback {
1378                    self.$base.report_generated_parser_diagnostics();
1379                    // A sticky abort (depth-cap violation, listener abort) is not a
1380                    // syntax error: rule-level recovery may have produced a tree
1381                    // and semantic miss anyway, but the abort is the root cause. Drain
1382                    // both sticky conditions before returning so parser reuse is clean.
1383                    if let ::core::option::Option::Some(error) = self.$base.take_parse_abort() {
1384                        let _ = self.$base.take_unknown_semantic_error();
1385                        return ::core::result::Result::Err(error);
1386                    }
1387                    // Surface unknown predicate/action coordinates recorded under the
1388                    // Error policy only after parser aborts have been ruled out.
1389                    if let ::core::option::Option::Some(error) =
1390                        self.$base.take_unknown_semantic_error()
1391                    {
1392                        return ::core::result::Result::Err(error);
1393                    }
1394                }
1395                ::core::result::Result::Ok(__tree)
1396            }
1397
1398            #[allow(dead_code)]
1399            fn parse_interpreted_rule(
1400                &mut self,
1401                rule_index: usize,
1402            ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1403                self.parse_interpreted_rule_precedence(rule_index, 0)
1404            }
1405
1406            #[allow(dead_code)]
1407            fn parse_interpreted_rule_precedence(
1408                &mut self,
1409                rule_index: usize,
1410                precedence: i32,
1411            ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1412                if precedence == 0
1413                    && $adaptive_direct
1414                    && ::std::env::var_os("ANTLR4_RUST_ADAPTIVE_DIRECT").is_some()
1415                {
1416                    let simulator = self.$simulator.get_or_insert_with(|| {
1417                        $crate::atn::parser::ParserAtnSimulator::new_shared($atn())
1418                    });
1419                    self.$base
1420                        .parse_atn_rule_adaptive_or_fallback($atn(), simulator, rule_index)
1421                } else {
1422                    let (__tree, __actions) = {
1423                        let $this = &mut *self;
1424                        let $rule_index = rule_index;
1425                        let $precedence = precedence;
1426                        $fallback
1427                    }?;
1428                    // Uniform dispatch: grammars without action states define an
1429                    // empty `run_action` and collect no deferred actions, so this
1430                    // loop is a no-op for them.
1431                    for __action in __actions {
1432                        self.run_action(__action, __tree);
1433                    }
1434                    ::core::result::Result::Ok(__tree)
1435                }
1436            }
1437        }
1438    };
1439}
1440
1441/// Defines the grammar-independent parse entry points for one generated
1442/// parser module: the `<Grammar>ParserParseOutput` alias of
1443/// [`GeneratedParseOutput`], the validation bridge behind
1444/// [`GeneratedParseOutput::validate`], and the `parse*` / `parse_stream*`
1445/// convenience functions.
1446///
1447/// This is an implementation detail of `antlr4-rust-gen`, not a stable
1448/// hand-written parser API.
1449#[doc(hidden)]
1450#[macro_export]
1451macro_rules! __antlr4_rust_parser_entry_points {
1452    (
1453        parser: $parser:ident,
1454        output: $output:ident,
1455        validated_tree: $validated:ident,
1456        validation_error: $validation_error:ident,
1457        validate_tree: $validate_tree:path
1458        $(,)?
1459    ) => {
1460        #[doc = ::core::concat!(
1461                    "Result from [`parse_with_parser`] or [`parse_stream_with_parser`].\n\n",
1462                    "Keeps the generated parser available after the entry rule runs so callers\n",
1463                    "can inspect diagnostics or recover the parser-owned token stream. Alias of\n",
1464                    "the runtime's `GeneratedParseOutput` with [`",
1465                    ::core::stringify!($parser),
1466                    "`] substituted for its parser type parameter.",
1467                )]
1468        pub type $output<R, L> = $crate::generated::GeneratedParseOutput<R, $parser<L>>;
1469
1470        impl<L, H> $crate::generated::__GeneratedParserValidate for $parser<L, H>
1471        where
1472            L: $crate::token::TokenSource,
1473            H: $crate::parser::SemanticHooks,
1474        {
1475            type Validated = $validated;
1476
1477            fn __validate(
1478                self,
1479                root: $crate::tree::NodeId,
1480            ) -> ::core::result::Result<$validated, $crate::validated::ValidationError> {
1481                let lexer = self.token_stream().number_of_source_errors();
1482                let parser = $crate::parser::Parser::number_of_syntax_errors(&self);
1483                if lexer != 0 || parser != 0 {
1484                    return ::core::result::Result::Err($validation_error::SyntaxErrors {
1485                        lexer,
1486                        parser,
1487                    });
1488                }
1489                let parsed = self.into_parsed_file(root);
1490                $validate_tree(&parsed)?;
1491                ::core::result::Result::Ok(<$validated>::__new(parsed))
1492            }
1493        }
1494
1495        /// Parses UTF-8 text by constructing the lexer, token stream, parser, and
1496        /// caller-selected entry rule in one call.
1497        ///
1498        #[doc = ::core::concat!(
1499                    "Pass the generated lexer constructor and a parser entry rule, for example\n",
1500                    "`parse(src, MyGrammarLexer::new, ",
1501                    ::core::stringify!($parser),
1502                    "::file)`.",
1503                )]
1504        ///
1505        /// The returned [`antlr4_runtime::ParsedFile`] owns the canonical token store,
1506        /// flat CST storage, and entry-rule root.
1507        /// Use [`parse_with_parser`] instead when the caller also needs parser
1508        /// diagnostics after the entry rule runs.
1509        pub fn parse<L: $crate::token::TokenSource>(
1510            input: impl ::core::convert::AsRef<str>,
1511            lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1512            entry: impl ::core::ops::FnOnce(
1513                &mut $parser<L>,
1514            ) -> ::core::result::Result<
1515                $crate::tree::NodeId,
1516                $crate::errors::AntlrError,
1517            >,
1518        ) -> ::core::result::Result<$crate::tree::ParsedFile, $crate::errors::AntlrError> {
1519            parse_stream(
1520                $crate::char_stream::InputStream::new(input.as_ref()),
1521                lexer,
1522                entry,
1523            )
1524        }
1525
1526        /// Parses UTF-8 text and returns a typed tree whose required generated child
1527        /// accessors are infallible.
1528        pub fn parse_validated<L: $crate::token::TokenSource>(
1529            input: impl ::core::convert::AsRef<str>,
1530            lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1531            entry: impl ::core::ops::FnOnce(
1532                &mut $parser<L>,
1533            ) -> ::core::result::Result<
1534                $crate::tree::NodeId,
1535                $crate::errors::AntlrError,
1536            >,
1537        ) -> ::core::result::Result<$validated, $validation_error> {
1538            parse_stream_validated(
1539                $crate::char_stream::InputStream::new(input.as_ref()),
1540                lexer,
1541                entry,
1542            )
1543        }
1544
1545        /// Parses UTF-8 text like [`parse`] while returning the parser after the entry
1546        /// rule has run.
1547        ///
1548        #[doc = ::core::concat!(
1549                    "This keeps the compact generated setup path available for callers that also\n",
1550                    "need `Parser::number_of_syntax_errors()` or `",
1551                    ::core::stringify!($parser),
1552                    "::into_token_stream()`.",
1553                )]
1554        pub fn parse_with_parser<L: $crate::token::TokenSource, R>(
1555            input: impl ::core::convert::AsRef<str>,
1556            lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1557            entry: impl ::core::ops::FnOnce(
1558                &mut $parser<L>,
1559            )
1560                -> ::core::result::Result<R, $crate::errors::AntlrError>,
1561        ) -> ::core::result::Result<$output<R, L>, $crate::errors::AntlrError> {
1562            parse_stream_with_parser(
1563                $crate::char_stream::InputStream::new(input.as_ref()),
1564                lexer,
1565                entry,
1566            )
1567        }
1568
1569        /// Parses a caller-provided character stream by constructing the lexer, token
1570        /// stream, parser, and caller-selected entry rule in one call.
1571        ///
1572        /// Unlike [`parse`], this accepts any [`antlr4_runtime::CharStream`], including
1573        /// a named [`antlr4_runtime::InputStream`] or a byte-oriented
1574        /// [`antlr4_runtime::ByteStream`].
1575        pub fn parse_stream<I: $crate::char_stream::CharStream, L: $crate::token::TokenSource>(
1576            input: I,
1577            lexer: impl ::core::ops::FnOnce(I) -> L,
1578            entry: impl ::core::ops::FnOnce(
1579                &mut $parser<L>,
1580            ) -> ::core::result::Result<
1581                $crate::tree::NodeId,
1582                $crate::errors::AntlrError,
1583            >,
1584        ) -> ::core::result::Result<$crate::tree::ParsedFile, $crate::errors::AntlrError> {
1585            let $crate::generated::GeneratedParseOutput { result, parser } =
1586                parse_stream_with_parser(input, lexer, entry)?;
1587            ::core::result::Result::Ok(parser.into_parsed_file(result))
1588        }
1589
1590        /// Parses a caller-provided character stream and validates the completed tree.
1591        pub fn parse_stream_validated<
1592            I: $crate::char_stream::CharStream,
1593            L: $crate::token::TokenSource,
1594        >(
1595            input: I,
1596            lexer: impl ::core::ops::FnOnce(I) -> L,
1597            entry: impl ::core::ops::FnOnce(
1598                &mut $parser<L>,
1599            ) -> ::core::result::Result<
1600                $crate::tree::NodeId,
1601                $crate::errors::AntlrError,
1602            >,
1603        ) -> ::core::result::Result<$validated, $validation_error> {
1604            let output = parse_stream_with_parser(input, lexer, entry)
1605                .map_err($validation_error::Recognition)?;
1606            output.validate()
1607        }
1608
1609        /// Parses a caller-provided character stream like [`parse_stream`] while
1610        /// returning the parser after the entry rule has run.
1611        pub fn parse_stream_with_parser<
1612            I: $crate::char_stream::CharStream,
1613            L: $crate::token::TokenSource,
1614            R,
1615        >(
1616            input: I,
1617            lexer: impl ::core::ops::FnOnce(I) -> L,
1618            entry: impl ::core::ops::FnOnce(
1619                &mut $parser<L>,
1620            )
1621                -> ::core::result::Result<R, $crate::errors::AntlrError>,
1622        ) -> ::core::result::Result<$output<R, L>, $crate::errors::AntlrError> {
1623            let lexer = lexer(input);
1624            let tokens = $crate::token_stream::CommonTokenStream::new(lexer);
1625            let mut parser = $parser::new(tokens);
1626            let result = entry(&mut parser)?;
1627            ::core::result::Result::Ok($crate::generated::GeneratedParseOutput { result, parser })
1628        }
1629    };
1630}
1631
1632#[derive(Debug)]
1633pub struct GrammarMetadata {
1634    grammar_file_name: &'static str,
1635    rule_names: &'static [&'static str],
1636    literal_names: &'static [Option<&'static str>],
1637    symbolic_names: &'static [Option<&'static str>],
1638    display_names: &'static [Option<&'static str>],
1639    channel_names: &'static [&'static str],
1640    mode_names: &'static [&'static str],
1641    serialized_atn: &'static [i32],
1642    recognizer_metadata: OnceLock<Arc<RecognizerMetadata>>,
1643}
1644
1645impl Clone for GrammarMetadata {
1646    fn clone(&self) -> Self {
1647        Self {
1648            grammar_file_name: self.grammar_file_name,
1649            rule_names: self.rule_names,
1650            literal_names: self.literal_names,
1651            symbolic_names: self.symbolic_names,
1652            display_names: self.display_names,
1653            channel_names: self.channel_names,
1654            mode_names: self.mode_names,
1655            serialized_atn: self.serialized_atn,
1656            recognizer_metadata: OnceLock::from(Arc::clone(self.cached_recognizer_metadata())),
1657        }
1658    }
1659}
1660
1661impl GrammarMetadata {
1662    /// Creates static grammar metadata emitted by the Rust target generator.
1663    #[allow(clippy::too_many_arguments)]
1664    pub const fn new(
1665        grammar_file_name: &'static str,
1666        rule_names: &'static [&'static str],
1667        literal_names: &'static [Option<&'static str>],
1668        symbolic_names: &'static [Option<&'static str>],
1669        display_names: &'static [Option<&'static str>],
1670        channel_names: &'static [&'static str],
1671        mode_names: &'static [&'static str],
1672        serialized_atn: &'static [i32],
1673    ) -> Self {
1674        Self {
1675            grammar_file_name,
1676            rule_names,
1677            literal_names,
1678            symbolic_names,
1679            display_names,
1680            channel_names,
1681            mode_names,
1682            serialized_atn,
1683            recognizer_metadata: OnceLock::new(),
1684        }
1685    }
1686
1687    pub const fn grammar_file_name(&self) -> &'static str {
1688        self.grammar_file_name
1689    }
1690
1691    pub const fn rule_names(&self) -> &'static [&'static str] {
1692        self.rule_names
1693    }
1694
1695    pub const fn channel_names(&self) -> &'static [&'static str] {
1696        self.channel_names
1697    }
1698
1699    pub const fn mode_names(&self) -> &'static [&'static str] {
1700        self.mode_names
1701    }
1702
1703    pub fn vocabulary(&self) -> Vocabulary {
1704        Vocabulary::new(
1705            self.literal_names.iter().copied(),
1706            self.symbolic_names.iter().copied(),
1707            self.display_names.iter().copied(),
1708        )
1709    }
1710
1711    /// Creates per-instance recognizer state backed by this grammar's cached
1712    /// immutable metadata.
1713    pub fn recognizer_data(&self) -> RecognizerData {
1714        RecognizerData::from_shared(Arc::clone(self.cached_recognizer_metadata()))
1715    }
1716
1717    fn cached_recognizer_metadata(&self) -> &Arc<RecognizerMetadata> {
1718        self.recognizer_metadata.get_or_init(|| {
1719            Arc::new(RecognizerMetadata::from_static(
1720                self.grammar_file_name,
1721                self.rule_names,
1722                self.channel_names,
1723                self.mode_names,
1724                self.vocabulary(),
1725            ))
1726        })
1727    }
1728
1729    /// Borrows the serialized ATN values for deserialization by the runtime
1730    /// simulators without copying generated static data.
1731    pub const fn serialized_atn(&self) -> SerializedAtn<'_> {
1732        SerializedAtn::from_i32(self.serialized_atn)
1733    }
1734}
1735
1736pub trait GeneratedLexer {
1737    fn metadata() -> &'static GrammarMetadata;
1738}
1739
1740pub trait GeneratedParser {
1741    fn metadata() -> &'static GrammarMetadata;
1742
1743    /// Borrows the validated packed ATN embedded by the matching generator.
1744    fn parser_atn() -> &'static ParserAtn;
1745}
1746
1747/// Exposes the parser base needed by the generated-rule dispatch lifecycle.
1748///
1749/// This is implemented by [`crate::__antlr4_rust_parser_facade`] for generated
1750/// parsers so [`dispatch_generated_rule`] can remain grammar-agnostic.
1751#[doc(hidden)]
1752pub trait GeneratedRuleParser {
1753    type Source: TokenSource;
1754    type Hooks: SemanticHooks;
1755
1756    fn generated_rule_base(&mut self) -> &mut BaseParser<Self::Source, Self::Hooks>;
1757}
1758
1759// ---------------------------------------------------------------------------
1760// Parse-driver and entry-point support shared by every generated parser and
1761// lexer module. The `__antlr4_rust_parser_driver!` and
1762// `__antlr4_rust_parser_entry_points!` expansions, and the generated
1763// `lex`/`lex_stream` re-exports, resolve against these items.
1764// ---------------------------------------------------------------------------
1765
1766/// Error routing for generated rule bodies.
1767///
1768/// This is an implementation detail of `antlr4-rust-gen`, not a stable
1769/// hand-written parser API. Generated dispatch code distinguishes fatal
1770/// unwinds (which report recovery diagnostics) from errors that request the
1771/// interpreted fallback, plus the internal adaptive-ATN retry signal.
1772#[doc(hidden)]
1773#[derive(Debug)]
1774pub enum GeneratedRuleError {
1775    /// Unrecoverable failure of the generated engine for this entry.
1776    Fatal(AntlrError),
1777    /// Failure that requests the interpreted fallback for this entry.
1778    Interpreted(AntlrError),
1779    /// Internal adaptive-ATN retry unwind; never escapes the routing boundary.
1780    AdaptiveRetry,
1781}
1782
1783impl GeneratedRuleError {
1784    /// Unwraps the underlying recognition error.
1785    #[must_use]
1786    pub fn into_error(self) -> AntlrError {
1787        match self {
1788            Self::Fatal(error) | Self::Interpreted(error) => error,
1789            Self::AdaptiveRetry => AntlrError::Unsupported(
1790                "internal adaptive ATN retry escaped its routing boundary".to_owned(),
1791            ),
1792        }
1793    }
1794}
1795
1796/// Uniform function-pointer shape for one generated parser rule body.
1797#[doc(hidden)]
1798pub type GeneratedRuleBody<P> =
1799    fn(&mut P, i32, bool) -> Result<crate::tree::ParseTree, GeneratedRuleError>;
1800
1801/// Applies the grammar-independent generated-rule guard around one table-selected body.
1802///
1803/// The function stays out of line so every generated parser monomorphization
1804/// carries one lifecycle shell instead of repeating it for every rule.
1805#[doc(hidden)]
1806#[inline(never)]
1807pub fn dispatch_generated_rule<P>(
1808    parser: &mut P,
1809    rule_index: usize,
1810    precedence: i32,
1811    allow_fallback: bool,
1812    body: GeneratedRuleBody<P>,
1813) -> Result<crate::tree::ParseTree, GeneratedRuleError>
1814where
1815    P: GeneratedRuleParser,
1816{
1817    if let Some(error) = parser.generated_rule_base().rule_depth_cap_violation() {
1818        return Err(GeneratedRuleError::Fatal(error));
1819    }
1820    if let Some(error) = parser
1821        .generated_rule_base()
1822        .parse_listener_enter_rule(rule_index)
1823    {
1824        return Err(GeneratedRuleError::Fatal(error));
1825    }
1826    let result = if parser
1827        .generated_rule_base()
1828        .generated_rule_stack_check_due()
1829    {
1830        grow_generated_rule_stack(|| body(parser, precedence, allow_fallback))
1831    } else {
1832        body(parser, precedence, allow_fallback)
1833    };
1834    parser
1835        .generated_rule_base()
1836        .parse_listener_exit_rule(rule_index);
1837    result
1838}
1839
1840/// Adaptive-ATN preference state for the generated rules a grammar routes
1841/// through warmed-retry dispatch.
1842///
1843/// `RULES` is the number of adaptive-ATN-preferred rules the generator
1844/// assigned retry slots to; grammars without residual adaptive routing
1845/// instantiate `AdaptiveAtnRetryState<0>`, whose [`Self::retry_pending`]
1846/// check constant-folds to `false`.
1847#[doc(hidden)]
1848#[derive(Debug)]
1849pub struct AdaptiveAtnRetryState<const RULES: usize> {
1850    /// Rules whose warmed adaptive-prediction work marked them expensive.
1851    pub preferred_rules: [bool; RULES],
1852    /// Per-slot recursion depth of in-flight adaptive dispatches.
1853    pub preference_depths: [usize; RULES],
1854    /// Adaptive-prediction work counters captured at outermost entry.
1855    pub preference_starts: [(usize, usize); RULES],
1856    /// Syntax-error counts captured at outermost entry.
1857    pub syntax_error_starts: [usize; RULES],
1858    /// Slot currently unwinding through an adaptive retry, if any.
1859    pub retry_slot: Option<usize>,
1860}
1861
1862impl<const RULES: usize> AdaptiveAtnRetryState<RULES> {
1863    /// Creates cleared preference state.
1864    #[must_use]
1865    pub const fn new() -> Self {
1866        Self {
1867            preferred_rules: [false; RULES],
1868            preference_depths: [0; RULES],
1869            preference_starts: [(0, 0); RULES],
1870            syntax_error_starts: [0; RULES],
1871            retry_slot: None,
1872        }
1873    }
1874
1875    /// Clears every learned preference and any in-flight retry.
1876    pub const fn reset(&mut self) {
1877        *self = Self::new();
1878    }
1879
1880    /// Reports whether an adaptive retry is currently unwinding.
1881    ///
1882    /// Constant-folds to `false` when the grammar has no retry slots, so the
1883    /// uniform generated retry clause costs nothing for such grammars.
1884    #[must_use]
1885    pub const fn retry_pending(&self) -> bool {
1886        RULES > 0 && self.retry_slot.is_some()
1887    }
1888}
1889
1890impl<const RULES: usize> Default for AdaptiveAtnRetryState<RULES> {
1891    fn default() -> Self {
1892        Self::new()
1893    }
1894}
1895
1896/// Result from a generated `parse_with_parser` or `parse_stream_with_parser`
1897/// call.
1898///
1899/// Keeps the generated parser available after the entry rule runs so callers
1900/// can inspect diagnostics or recover the parser-owned token stream. Generated
1901/// modules alias this type as `<Grammar>ParserParseOutput<R, L>` with their
1902/// parser type substituted for `P`; [`Self::validate`] is available for those
1903/// generated parser types, which wire in their module's validated surface.
1904#[derive(Debug)]
1905pub struct GeneratedParseOutput<R, P> {
1906    /// Value returned by the caller-selected entry rule.
1907    pub result: R,
1908    /// The generated parser after the entry rule has run.
1909    pub parser: P,
1910}
1911
1912/// Grammar-specific validation step behind [`GeneratedParseOutput::validate`].
1913///
1914/// This is an implementation detail of `antlr4-rust-gen`, not a stable
1915/// hand-written parser API: each generated module implements it for its parser
1916/// type via `__antlr4_rust_parser_entry_points!`.
1917#[doc(hidden)]
1918pub trait __GeneratedParserValidate: Sized {
1919    /// The module-branded validated-tree type.
1920    type Validated;
1921
1922    /// Validates a completed parse rooted at `root`.
1923    fn __validate(self, root: NodeId) -> Result<Self::Validated, ValidationError>;
1924}
1925
1926impl<P: __GeneratedParserValidate> GeneratedParseOutput<NodeId, P> {
1927    /// Validates a completed parse and changes its generated context surface.
1928    ///
1929    /// Validation rejects lexer diagnostics, parser recovery, recovered error
1930    /// nodes, and missing generated required children before constructing the
1931    /// validated-tree type boundary.
1932    ///
1933    /// # Errors
1934    ///
1935    /// Returns a [`ValidationError`] when the parse recorded lexer or parser
1936    /// syntax errors or the completed tree fails structural validation.
1937    pub fn validate(self) -> Result<P::Validated, ValidationError> {
1938        self.parser.__validate(self.result)
1939    }
1940}
1941
1942/// Lexes UTF-8 text into an eagerly filled token stream without constructing
1943/// a parser.
1944///
1945/// Pass the generated lexer constructor, for example
1946/// `lex(src, MyGrammarLexer::new)`.
1947///
1948/// The stream retains every emitted token, including EOF and tokens on hidden
1949/// or custom channels. Lexer rules using `skip` do not emit tokens.
1950///
1951/// With `use antlr4_runtime::Token as _;` and the generated module's
1952/// `metadata()`, print each token's vocabulary name, numeric channel, and
1953/// text:
1954/// `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()); }`
1955///
1956/// `number_of_source_errors()` reports buffered lexer diagnostics. After
1957/// iterating `tokens()`, `drain_source_errors()` retrieves those diagnostics.
1958///
1959/// # Panics
1960///
1961/// Panics if buffering returns an [`crate::TokenStoreError`]. Construct the
1962/// lexer and call [`CommonTokenStream::try_new`] to handle that error instead.
1963pub fn lex<L: TokenSource>(
1964    input: impl AsRef<str>,
1965    lexer: impl FnOnce(InputStream) -> L,
1966) -> CommonTokenStream<L> {
1967    lex_stream(InputStream::new(input.as_ref()), lexer)
1968}
1969
1970/// Lexes a caller-provided character stream without constructing a parser.
1971///
1972/// Unlike [`lex`], this accepts any [`CharStream`], including a named
1973/// [`InputStream`] or a byte-oriented [`crate::ByteStream`].
1974///
1975/// `number_of_source_errors()` reports buffered lexer diagnostics. After
1976/// iterating `tokens()`, `drain_source_errors()` retrieves those diagnostics.
1977///
1978/// # Panics
1979///
1980/// Panics if buffering returns an [`crate::TokenStoreError`]. Call
1981/// [`CommonTokenStream::try_new`] with the constructed lexer to handle that
1982/// error instead.
1983pub fn lex_stream<I: CharStream, L: TokenSource>(
1984    input: I,
1985    lexer: impl FnOnce(I) -> L,
1986) -> CommonTokenStream<L> {
1987    CommonTokenStream::new(lexer(input))
1988}
1989
1990// ---------------------------------------------------------------------------
1991// Grammar-independent support surface imported by every generated parser
1992// module. These items back the typed context views, listener/visitor bridges,
1993// and embedded-action facades emitted by `antlr4-rust-gen`; the generated
1994// module brings them into scope by name so the `__antlr4_rust_context!` /
1995// `__antlr4_rust_context_accessors!` expansions resolve against them.
1996// ---------------------------------------------------------------------------
1997
1998/// Token-stream facade backing embedded-action `$input` translation
1999/// (`self.input().text()` / `.la(i)` / `.lt(i).text()`).
2000#[doc(hidden)]
2001pub struct __GeneratedInput<'a, L: TokenSource>(#[doc(hidden)] pub &'a mut CommonTokenStream<L>);
2002
2003impl<L: TokenSource> __GeneratedInput<'_, L> {
2004    #[must_use]
2005    #[inline]
2006    pub fn text(&self) -> String {
2007        self.0.text_all()
2008    }
2009
2010    #[inline]
2011    pub fn la(&mut self, offset: isize) -> i32 {
2012        IntStream::la(self.0, offset)
2013    }
2014
2015    #[must_use]
2016    #[inline]
2017    pub fn lt(&self, offset: isize) -> __GeneratedTokenView {
2018        __GeneratedTokenView {
2019            text: self
2020                .0
2021                .lt(offset)
2022                .map(|token| token.text_or_empty().to_owned())
2023                .unwrap_or_default(),
2024        }
2025    }
2026}
2027
2028impl<L: TokenSource> fmt::Debug for __GeneratedInput<'_, L> {
2029    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2030        f.debug_struct("__GeneratedInput").finish_non_exhaustive()
2031    }
2032}
2033
2034/// Owned token view returned by [`__GeneratedInput::lt`] and the generated
2035/// contexts' `start()` accessors.
2036#[doc(hidden)]
2037#[derive(Debug)]
2038pub struct __GeneratedTokenView {
2039    #[doc(hidden)]
2040    pub text: String,
2041}
2042
2043impl __GeneratedTokenView {
2044    #[must_use]
2045    #[inline]
2046    pub fn text(&self) -> &str {
2047        &self.text
2048    }
2049}
2050
2051/// Typed terminal wrapper exposed by generated listener, visitor, and context
2052/// surfaces.
2053///
2054/// Recovery-inserted error nodes travel through the same surface; use
2055/// [`TerminalNode::is_error`] and [`TerminalNode::is_missing`] to identify
2056/// them.
2057#[derive(Clone, Debug)]
2058pub struct TerminalNode<'a> {
2059    __node: TerminalNodeView<'a>,
2060}
2061
2062impl<'a> TerminalNode<'a> {
2063    #[doc(hidden)]
2064    #[must_use]
2065    #[inline]
2066    pub const fn new(node: TerminalNodeView<'a>) -> Self {
2067        Self { __node: node }
2068    }
2069
2070    #[must_use]
2071    #[inline]
2072    pub fn symbol(&self) -> TokenView<'a> {
2073        self.__node.symbol()
2074    }
2075
2076    #[must_use]
2077    #[inline]
2078    pub fn is_error(&self) -> bool {
2079        matches!(self.__node.node().kind(), NodeKind::Error)
2080    }
2081
2082    #[must_use]
2083    #[inline]
2084    pub fn is_missing(&self) -> bool {
2085        self.symbol().is_synthetic()
2086    }
2087
2088    /// The underlying parse-tree node.
2089    #[doc(hidden)]
2090    #[must_use]
2091    #[inline]
2092    pub const fn node(&self) -> Node<'a> {
2093        self.__node.node()
2094    }
2095}
2096
2097impl fmt::Display for TerminalNode<'_> {
2098    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2099        f.write_str(self.__node.text())
2100    }
2101}
2102
2103/// Typed error-node wrapper exposed by generated listener and visitor
2104/// surfaces.
2105#[derive(Clone, Debug)]
2106pub struct ErrorNode<'a> {
2107    __node: ErrorNodeView<'a>,
2108}
2109
2110impl<'a> ErrorNode<'a> {
2111    #[doc(hidden)]
2112    #[must_use]
2113    #[inline]
2114    pub const fn new(node: ErrorNodeView<'a>) -> Self {
2115        Self { __node: node }
2116    }
2117
2118    #[must_use]
2119    #[inline]
2120    pub fn symbol(&self) -> TokenView<'a> {
2121        self.__node.symbol()
2122    }
2123
2124    #[must_use]
2125    #[inline]
2126    pub fn is_missing(&self) -> bool {
2127        self.symbol().is_synthetic()
2128    }
2129
2130    /// The underlying parse-tree node.
2131    #[doc(hidden)]
2132    #[must_use]
2133    #[inline]
2134    pub const fn node(&self) -> Node<'a> {
2135        self.__node.node()
2136    }
2137}
2138
2139impl fmt::Display for ErrorNode<'_> {
2140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2141        f.write_str(self.__node.text())
2142    }
2143}
2144
2145/// Defines a grammar-specific callback adapter for [`walk_generated`].
2146#[doc(hidden)]
2147#[macro_export]
2148macro_rules! __antlr4_rust_generated_walk_callbacks {
2149    (
2150        callbacks: $callbacks:ident,
2151        listener: $listener:ident,
2152        enter: |$enter_listener:ident, $enter_context:ident, $enter_states:ident| $enter_body:block,
2153        exit: |$exit_listener:ident, $exit_context:ident, $exit_states:ident| $exit_body:block,
2154        terminal: |$terminal_listener:ident, $terminal_node:ident| $terminal_body:block,
2155        error: |$error_listener:ident, $error_node:ident| $error_body:block $(,)?
2156    ) => {
2157        #[allow(dead_code)]
2158        struct $callbacks<'listener, T>(&'listener mut T);
2159
2160        impl<E, T: $listener<E>> $crate::generated::GeneratedWalkCallbacks<E>
2161            for $callbacks<'_, T>
2162        {
2163            #[inline(always)]
2164            fn dispatch_enter_rule(
2165                &mut self,
2166                $enter_context: $crate::RuleNodeView<'_>,
2167                $enter_states: ::core::option::Option<&[isize]>,
2168            ) -> ::core::result::Result<(), E> {
2169                let $enter_listener = &mut *self.0;
2170                $enter_body
2171            }
2172
2173            #[inline(always)]
2174            fn dispatch_exit_rule(
2175                &mut self,
2176                $exit_context: $crate::RuleNodeView<'_>,
2177                $exit_states: ::core::option::Option<&[isize]>,
2178            ) -> ::core::result::Result<(), E> {
2179                let $exit_listener = &mut *self.0;
2180                $exit_body
2181            }
2182
2183            #[inline(always)]
2184            fn visit_terminal(
2185                &mut self,
2186                $terminal_node: $crate::TerminalNodeView<'_>,
2187            ) -> ::core::result::Result<(), E> {
2188                let $terminal_listener = &mut *self.0;
2189                $terminal_body
2190            }
2191
2192            #[inline(always)]
2193            fn visit_error_node(
2194                &mut self,
2195                $error_node: $crate::ErrorNodeView<'_>,
2196            ) -> ::core::result::Result<(), E> {
2197                let $error_listener = &mut *self.0;
2198                $error_body
2199            }
2200        }
2201    };
2202}
2203
2204/// Grammar-specific callbacks used by the runtime-owned generated tree walker.
2205#[doc(hidden)]
2206pub trait GeneratedWalkCallbacks<E> {
2207    fn dispatch_enter_rule(
2208        &mut self,
2209        context: RuleNodeView<'_>,
2210        invocation_states: Option<&[isize]>,
2211    ) -> Result<(), E>;
2212
2213    fn dispatch_exit_rule(
2214        &mut self,
2215        context: RuleNodeView<'_>,
2216        invocation_states: Option<&[isize]>,
2217    ) -> Result<(), E>;
2218
2219    fn visit_terminal(&mut self, node: TerminalNodeView<'_>) -> Result<(), E>;
2220
2221    fn visit_error_node(&mut self, node: ErrorNodeView<'_>) -> Result<(), E>;
2222}
2223
2224/// Walks a generated parse tree while generated callbacks perform typed
2225/// context dispatch.
2226#[doc(hidden)]
2227#[inline(always)]
2228pub fn walk_generated<E, C>(
2229    tree: Node<'_>,
2230    mut invocation_states: Option<Vec<isize>>,
2231    callbacks: &mut C,
2232) -> Result<(), E>
2233where
2234    C: GeneratedWalkCallbacks<E>,
2235{
2236    enum Event<'tree> {
2237        Enter(Node<'tree>),
2238        Exit(RuleNodeView<'tree>),
2239    }
2240
2241    let mut stack = vec![Event::Enter(tree)];
2242    while let Some(event) = stack.pop() {
2243        match event {
2244            Event::Enter(node) => match node.kind() {
2245                NodeKind::Rule => {
2246                    let context = node.as_rule().expect("rule node kind checked");
2247                    if let Some(states) = &mut invocation_states {
2248                        states.insert(0, context.invoking_state());
2249                    }
2250                    callbacks.dispatch_enter_rule(context, invocation_states.as_deref())?;
2251                    stack.push(Event::Exit(context));
2252                    stack.extend(context.children().rev().map(Event::Enter));
2253                }
2254                NodeKind::Terminal => callbacks
2255                    .visit_terminal(node.as_terminal().expect("terminal node kind checked"))?,
2256                NodeKind::Error => {
2257                    callbacks
2258                        .visit_error_node(node.as_error().expect("error node kind checked"))?;
2259                }
2260            },
2261            Event::Exit(context) => {
2262                callbacks.dispatch_exit_rule(context, invocation_states.as_deref())?;
2263                if let Some(states) = &mut invocation_states {
2264                    states.remove(0);
2265                }
2266            }
2267        }
2268    }
2269    Ok(())
2270}
2271
2272/// Child source of one generated context view: either a stored parse-tree
2273/// node or the live parser context observed from an in-flight rule.
2274#[doc(hidden)]
2275#[derive(Clone, Copy, Debug)]
2276pub enum __GeneratedRuleContext<'a> {
2277    Stored(RuleNodeView<'a>),
2278    Active {
2279        context: &'a ParserRuleContext,
2280        storage: &'a ParseTreeStorage,
2281        tokens: &'a TokenStore,
2282    },
2283}
2284
2285/// Marker state for generated contexts borrowed from a stored parse tree.
2286#[doc(hidden)]
2287#[derive(Clone, Copy, Debug)]
2288pub struct StoredTreeContext;
2289
2290/// Marker state for generated contexts observed from an in-flight parse.
2291#[doc(hidden)]
2292#[derive(Clone, Copy, Debug)]
2293pub struct __ActiveParserContext;
2294
2295#[doc(hidden)]
2296#[inline]
2297pub fn __context_children(
2298    source: __GeneratedRuleContext<'_>,
2299) -> impl Iterator<Item = Node<'_>> + '_ {
2300    let mut stored = match source {
2301        __GeneratedRuleContext::Stored(node) => Some(node.children()),
2302        __GeneratedRuleContext::Active { .. } => None,
2303    };
2304    let mut active = match source {
2305        __GeneratedRuleContext::Stored(_) => None,
2306        __GeneratedRuleContext::Active {
2307            context,
2308            storage,
2309            tokens,
2310        } => Some(context.child_nodes(storage, tokens)),
2311    };
2312    std::iter::from_fn(move || {
2313        stored
2314            .as_mut()
2315            .and_then(Iterator::next)
2316            .or_else(|| active.as_mut().and_then(Iterator::next))
2317    })
2318}
2319
2320#[doc(hidden)]
2321#[inline]
2322pub fn __rule_children(
2323    source: __GeneratedRuleContext<'_>,
2324    rule_index: usize,
2325) -> impl Iterator<Item = RuleNodeView<'_>> + '_ {
2326    __context_children(source).filter_map(move |child| {
2327        let rule = child.as_rule()?;
2328        (rule.rule_index() == rule_index).then_some(rule)
2329    })
2330}
2331
2332#[doc(hidden)]
2333#[inline]
2334pub fn __terminal_children(
2335    source: __GeneratedRuleContext<'_>,
2336) -> impl Iterator<Item = TerminalNodeView<'_>> + '_ {
2337    __context_children(source).filter_map(Node::terminal_view)
2338}
2339
2340#[doc(hidden)]
2341#[inline]
2342pub fn __token_children(
2343    source: __GeneratedRuleContext<'_>,
2344    token_type: i32,
2345) -> impl Iterator<Item = TerminalNodeView<'_>> + '_ {
2346    __terminal_children(source).filter(move |terminal| terminal.symbol().token_type() == token_type)
2347}
2348
2349#[doc(hidden)]
2350#[inline]
2351pub fn __token_children_matching<'a>(
2352    source: __GeneratedRuleContext<'a>,
2353    token_types: &'static [i32],
2354) -> impl Iterator<Item = TerminalNodeView<'a>> + 'a {
2355    __terminal_children(source)
2356        .filter(move |terminal| token_types.contains(&terminal.symbol().token_type()))
2357}
2358
2359#[doc(hidden)]
2360#[inline]
2361pub fn __labeled_token_children(
2362    source: __GeneratedRuleContext<'_>,
2363    token_type: i32,
2364) -> impl Iterator<Item = TerminalNodeView<'_>> + '_ {
2365    __context_children(source).filter_map(move |child| {
2366        let terminal = child.labeled_terminal_view()?;
2367        (terminal.symbol().token_type() == token_type).then_some(terminal)
2368    })
2369}
2370
2371#[doc(hidden)]
2372#[inline]
2373pub fn __labeled_token_children_matching<'a>(
2374    source: __GeneratedRuleContext<'a>,
2375    token_types: &'static [i32],
2376) -> impl Iterator<Item = TerminalNodeView<'a>> + 'a {
2377    __context_children(source).filter_map(move |child| {
2378        let terminal = child.labeled_terminal_view()?;
2379        token_types
2380            .contains(&terminal.symbol().token_type())
2381            .then_some(terminal)
2382    })
2383}
2384
2385/// Constructs a generated context view over a live parser context.
2386/// Implemented by `__antlr4_rust_context!` for every generated context.
2387#[doc(hidden)]
2388pub trait __FromActiveRuleContext<'a>: Sized {
2389    fn __from_active(
2390        context: &'a ParserRuleContext,
2391        live_attrs: Option<&dyn Any>,
2392        invocation_states: Vec<isize>,
2393        storage: &'a ParseTreeStorage,
2394        tokens: &'a TokenStore,
2395    ) -> Option<Self>;
2396}
2397
2398#[doc(hidden)]
2399#[inline]
2400pub fn __active_context_view<'a, T: __FromActiveRuleContext<'a>>(
2401    context: &'a ParserRuleContext,
2402    invocation_states: Vec<isize>,
2403    storage: &'a ParseTreeStorage,
2404    tokens: &'a TokenStore,
2405) -> Option<T> {
2406    T::__from_active(context, None, invocation_states, storage, tokens)
2407}
2408
2409#[doc(hidden)]
2410#[inline]
2411pub fn __active_context_view_with_attrs<'a, T: __FromActiveRuleContext<'a>>(
2412    context: &'a ParserRuleContext,
2413    live_attrs: &dyn Any,
2414    invocation_states: Vec<isize>,
2415    storage: &'a ParseTreeStorage,
2416    tokens: &'a TokenStore,
2417) -> Option<T> {
2418    T::__from_active(
2419        context,
2420        Some(live_attrs),
2421        invocation_states,
2422        storage,
2423        tokens,
2424    )
2425}
2426
2427/// Formats an invoking-state chain the way Java's `RuleContext.toString`
2428/// renders it: `[13 6]`.
2429#[doc(hidden)]
2430pub fn __write_invocation_states(
2431    f: &mut fmt::Formatter<'_>,
2432    states: impl Iterator<Item = isize>,
2433) -> fmt::Result {
2434    f.write_str("[")?;
2435    let mut separator = "";
2436    for state in states {
2437        write!(f, "{separator}{state}")?;
2438        separator = " ";
2439    }
2440    f.write_str("]")
2441}
2442
2443/// Bound on the recovery-oriented state markers accepted by generated
2444/// context accessors.
2445///
2446/// The validated marker (`ValidatedTreeContext`) intentionally stays emitted
2447/// per generated module: the accessors macro relies on rustc proving that the
2448/// validated marker never implements this trait, and coherence only permits
2449/// that negative reasoning while the marker type is local to the generated
2450/// crate.
2451#[doc(hidden)]
2452pub trait __RecoveryContextState {}
2453
2454impl __RecoveryContextState for StoredTreeContext {}
2455impl __RecoveryContextState for __ActiveParserContext {}
2456
2457#[cfg(test)]
2458#[allow(clippy::disallowed_methods)] // insta assertion macros unwrap internal I/O.
2459mod tests {
2460    use super::*;
2461    use crate::token::{TokenId, TokenSpec};
2462    use crate::tree::ParsedFile;
2463
2464    static META: GrammarMetadata = GrammarMetadata::new(
2465        "Mini.g4",
2466        &["file"],
2467        &[None, Some("'x'")],
2468        &[None, Some("X")],
2469        &[None, None],
2470        &["DEFAULT_TOKEN_CHANNEL", "HIDDEN"],
2471        &["DEFAULT_MODE"],
2472        &[4, 1, 1, 0, 0, 0],
2473    );
2474
2475    fn test_token(store: &mut TokenStore, token_type: i32, text: &str) -> TokenId {
2476        store
2477            .push(TokenSpec::explicit(token_type, text))
2478            .expect("test token should fit")
2479    }
2480
2481    fn generated_walk_test_tree() -> ParsedFile {
2482        let mut tokens = TokenStore::new(None, "");
2483        let a = test_token(&mut tokens, 1, "a");
2484        let b = test_token(&mut tokens, 2, "b");
2485        let error = test_token(&mut tokens, 3, "!");
2486        let mut storage = ParseTreeStorage::new();
2487        let a = storage.terminal(a);
2488        let b = storage.terminal(b);
2489        let error = storage.error(error);
2490        let mut child = ParserRuleContext::new(1, 7);
2491        storage.add_child(&mut child, b);
2492        let child = storage.finish_rule(child);
2493        let mut root = ParserRuleContext::new(0, -1);
2494        storage.add_child(&mut root, a);
2495        storage.add_child(&mut root, child);
2496        storage.add_child(&mut root, error);
2497        let root = storage.finish_rule(root);
2498        ParsedFile::new(tokens, storage, root)
2499    }
2500
2501    #[derive(Default)]
2502    struct RecordingWalkCallbacks {
2503        events: Vec<String>,
2504        fail_on_terminal: Option<&'static str>,
2505    }
2506
2507    impl GeneratedWalkCallbacks<&'static str> for RecordingWalkCallbacks {
2508        fn dispatch_enter_rule(
2509            &mut self,
2510            context: RuleNodeView<'_>,
2511            invocation_states: Option<&[isize]>,
2512        ) -> Result<(), &'static str> {
2513            self.events.push(format!(
2514                "enter rule {} {invocation_states:?}",
2515                context.rule_index()
2516            ));
2517            Ok(())
2518        }
2519
2520        fn dispatch_exit_rule(
2521            &mut self,
2522            context: RuleNodeView<'_>,
2523            invocation_states: Option<&[isize]>,
2524        ) -> Result<(), &'static str> {
2525            self.events.push(format!(
2526                "exit rule {} {invocation_states:?}",
2527                context.rule_index()
2528            ));
2529            Ok(())
2530        }
2531
2532        fn visit_terminal(&mut self, node: TerminalNodeView<'_>) -> Result<(), &'static str> {
2533            self.events.push(format!("terminal {}", node.text()));
2534            if self.fail_on_terminal == Some(node.text()) {
2535                Err("terminal callback failed")
2536            } else {
2537                Ok(())
2538            }
2539        }
2540
2541        fn visit_error_node(&mut self, node: ErrorNodeView<'_>) -> Result<(), &'static str> {
2542            self.events.push(format!("error {}", node.text()));
2543            Ok(())
2544        }
2545    }
2546
2547    #[test]
2548    fn generated_walk_preserves_order_and_invocation_states() {
2549        let parsed = generated_walk_test_tree();
2550        let mut callbacks = RecordingWalkCallbacks::default();
2551
2552        walk_generated(parsed.tree(), Some(vec![99]), &mut callbacks)
2553            .expect("recording callbacks should accept every event");
2554
2555        insta::assert_debug_snapshot!(
2556            "generated_walk_order_and_invocation_states",
2557            callbacks.events
2558        );
2559    }
2560
2561    #[test]
2562    fn generated_walk_short_circuits_callback_errors() {
2563        let parsed = generated_walk_test_tree();
2564        let mut callbacks = RecordingWalkCallbacks {
2565            fail_on_terminal: Some("b"),
2566            ..RecordingWalkCallbacks::default()
2567        };
2568
2569        assert_eq!(
2570            walk_generated(parsed.tree(), None, &mut callbacks),
2571            Err("terminal callback failed")
2572        );
2573        insta::assert_debug_snapshot!("generated_walk_short_circuit", callbacks.events);
2574    }
2575
2576    // Compile-only fixture: successful expansion of both facade macros with
2577    // invocation-site prelude names shadowed is the assertion.
2578    #[allow(dead_code, unreachable_pub)]
2579    mod facade_hygiene {
2580        struct Box;
2581        struct FnMut;
2582        struct None;
2583        struct Option;
2584        struct Rc;
2585        struct Result;
2586        struct Send;
2587        struct Some;
2588        struct String;
2589        struct Vec;
2590
2591        struct HygieneLexer<I, H> {
2592            base: crate::lexer::BaseLexer<I>,
2593            hooks: H,
2594        }
2595
2596        struct HygieneParser<S, H> {
2597            base: crate::parser::BaseParser<S, H>,
2598            simulator: ::core::option::Option<crate::atn::parser::ParserAtnSimulator<'static>>,
2599            generated_only: bool,
2600        }
2601
2602        fn metadata() -> &'static crate::generated::GrammarMetadata {
2603            &super::META
2604        }
2605
2606        fn parser_atn() -> &'static crate::atn::parser_atn::ParserAtn {
2607            panic!("compile-only facade hygiene fixture")
2608        }
2609
2610        crate::__antlr4_rust_lexer_facade! {
2611            type: HygieneLexer<I, H>,
2612            fields: {
2613                base: base,
2614                hooks: hooks,
2615            },
2616            metadata: metadata,
2617            next_token(_lexer, _sink) {
2618                panic!("compile-only facade hygiene fixture")
2619            }
2620        }
2621
2622        crate::__antlr4_rust_parser_facade! {
2623            type: HygieneParser<S, H>,
2624            fields: {
2625                base: base,
2626                simulator: simulator,
2627                generated_only: generated_only,
2628            },
2629            metadata: metadata,
2630            parser_atn: parser_atn,
2631            reset(_parser) {}
2632        }
2633    }
2634
2635    #[test]
2636    fn metadata_builds_vocabulary() {
2637        assert_eq!(META.grammar_file_name(), "Mini.g4");
2638        assert_eq!(META.vocabulary().display_name(1), "'x'");
2639    }
2640
2641    #[test]
2642    fn cloned_metadata_shares_the_cache_before_explicit_initialization() {
2643        let original = GrammarMetadata::new(
2644            "Clone.g4",
2645            &["start"],
2646            &[None, Some("'x'")],
2647            &[None, Some("X")],
2648            &[None, None],
2649            &["DEFAULT_TOKEN_CHANNEL"],
2650            &["DEFAULT_MODE"],
2651            &[],
2652        );
2653        let cloned = original.clone();
2654        let first = original.recognizer_data();
2655        let second = cloned.recognizer_data();
2656
2657        assert!(std::ptr::eq(first.rule_names(), second.rule_names()));
2658        assert!(std::ptr::eq(first.vocabulary(), second.vocabulary()));
2659    }
2660}
2661
2662#[cfg(test)]
2663mod parser_driver_tests {
2664    // Anchors into the `__antlr4_rust_parser_driver!` macro body. Each search
2665    // string is declared once so a rename inside the macro is a one-line
2666    // update here, and the assertions below stay readable.
2667    const DRIVER_MACRO: &str = "macro_rules! __antlr4_rust_parser_driver";
2668    const ENTRY_POINTS_MACRO: &str = "macro_rules! __antlr4_rust_parser_entry_points";
2669    /// Unique to the top-level surfacing check: the Err-arm check binds
2670    /// `semantic_error` and the sticky-abort drains bind `_`, so anchoring on
2671    /// the `Some(error)` binder cannot accidentally match a drain.
2672    const TOP_LEVEL_SEMANTIC_SURFACE: &str =
2673        "Some(error) = self.$base.take_unknown_semantic_error()";
2674    const ERR_ARM_SEMANTIC_SURFACE: &str =
2675        "Some(semantic_error) = self.$base.take_unknown_semantic_error()";
2676    const ERR_ARM_START: &str = "::core::result::Result::Err(error) => {";
2677    const ERR_CONVERSION: &str = "let error = error.into_error();";
2678    const ERR_RETURN: &str = "return ::core::result::Result::Err(error);";
2679    const DIAGNOSTICS_DISPATCH: &str = "self.$base.report_generated_parser_diagnostics();";
2680    const ABORT_DRAIN: &str = "Some(abort) = self.$base.take_parse_abort()";
2681    const UNRECOVERED_REPORT: &str = "self.$base.report_unrecovered_parser_error(&error);";
2682    const OK_TREE: &str = "::core::result::Result::Ok(__tree)";
2683    const INTERPRETED_FALLBACK: &str =
2684        "self.parse_interpreted_rule_precedence(rule_index, precedence)?";
2685    const ACTION_DISPATCH: &str = "self.run_action(__action, __tree);";
2686
2687    /// The driver macro body with all whitespace collapsed, so anchors that
2688    /// rustfmt wraps across lines (`if let ::core::option::Option::Some(error)
2689    /// = self.$base...`) match as single strings.
2690    fn driver_macro_body() -> String {
2691        let source = include_str!("generated.rs");
2692        let driver_at = source
2693            .find(DRIVER_MACRO)
2694            .expect("driver macro is defined in this module");
2695        let entry_points_at = source
2696            .find(ENTRY_POINTS_MACRO)
2697            .expect("entry-points macro is defined in this module");
2698        source[driver_at..entry_points_at]
2699            .split_whitespace()
2700            .collect::<Vec<_>>()
2701            .join(" ")
2702    }
2703
2704    /// Pins ordering invariants of the `__antlr4_rust_parser_driver!` entry
2705    /// body that generated-parser behavior depends on. These checks lived in
2706    /// the generator's per-grammar rendered-text tests while the driver was
2707    /// emitted per module; the macro is the single copy now, so the source
2708    /// text is asserted here once. The runtime behavior itself is covered by
2709    /// `public_entry_surfaces_recorded_semantic_miss_after_clean_parse` in
2710    /// the generator's CLI suite, which parses through a generated entry and
2711    /// asserts the fail-loud error is returned.
2712    #[test]
2713    fn parser_driver_entry_ordering_invariants() {
2714        let driver = driver_macro_body();
2715
2716        // The fail-loud surfacing check runs before the entry can return Ok,
2717        // or a parse that consulted an unimplemented hook would return a
2718        // recovered Ok tree instead of AntlrError::Unsupported. The binder
2719        // anchor is unique, so this cannot be satisfied by one of the
2720        // `let _ =` drains.
2721        assert_eq!(
2722            driver.matches(TOP_LEVEL_SEMANTIC_SURFACE).count(),
2723            1,
2724            "exactly one top-level surfacing check binds `error`"
2725        );
2726        let surface_at = driver
2727            .find(TOP_LEVEL_SEMANTIC_SURFACE)
2728            .expect("entry surfaces recorded unknown-semantic coordinates");
2729        let ok_at = driver[surface_at..]
2730            .find(OK_TREE)
2731            .map(|offset| surface_at + offset)
2732            .expect("entry returns the tree after semantic checks");
2733        assert!(surface_at < ok_at);
2734
2735        // Inside the generated-rule Err arm, retained diagnostics dispatch
2736        // first, then parser aborts, then recorded semantic misses; otherwise
2737        // the documented fail-loud error would be shadowed or diagnostics
2738        // would leak into the next entry on a reused parser.
2739        let arm_start = driver
2740            .find(ERR_ARM_START)
2741            .expect("the generated-rule match has an Err arm");
2742        let conversion_at = driver[arm_start..]
2743            .find(ERR_CONVERSION)
2744            .map(|offset| arm_start + offset)
2745            .expect("Err arm converts the generic rule error");
2746        let arm = &driver[arm_start..conversion_at];
2747        let diagnostics_at = arm
2748            .find(DIAGNOSTICS_DISPATCH)
2749            .expect("the fatal Err arm drains retained diagnostics");
2750        let abort_at = arm
2751            .find(ABORT_DRAIN)
2752            .expect("the Err arm drains a recorded parser abort");
2753        let semantic_at = arm
2754            .find(ERR_ARM_SEMANTIC_SURFACE)
2755            .expect("the Err arm drains a recorded semantic error");
2756        assert!(
2757            diagnostics_at < abort_at && abort_at < semantic_at,
2758            "retained diagnostics dispatch first, then parser aborts precede semantic misses"
2759        );
2760
2761        // A fatal unwind reports the converted error through the listener
2762        // boundary before returning it.
2763        let err_return_at = driver[conversion_at..]
2764            .find(ERR_RETURN)
2765            .map(|offset| conversion_at + offset)
2766            .expect("the Err arm returns the converted error");
2767        assert!(
2768            driver[conversion_at..err_return_at].contains(UNRECOVERED_REPORT),
2769            "the Err arm reports the unrecovered error before returning it"
2770        );
2771
2772        // The interpreted fallback runs the uniform action-dispatch loop
2773        // (every generated parser defines `run_action`; grammars without
2774        // action states get the empty stub); the top-level boundary then
2775        // dispatches recovery diagnostics and never returns Ok between the
2776        // fallback and the surfacing check, so an action-hook miss recorded
2777        // by the fallback's immediate `run_action` loop cannot escape as Ok.
2778        let fallback_at = driver
2779            .find(INTERPRETED_FALLBACK)
2780            .expect("entry runs the interpreted fallback when a rule is not generated");
2781        assert!(
2782            fallback_at < surface_at,
2783            "the surfacing check follows the interpreted fallback"
2784        );
2785        assert!(
2786            driver[fallback_at..surface_at].contains(DIAGNOSTICS_DISPATCH),
2787            "the entry dispatches boundary diagnostics between the fallback and the surfacing check"
2788        );
2789        assert!(
2790            !driver[fallback_at..surface_at].contains(OK_TREE),
2791            "the entry must not return Ok between the interpreted fallback and the surfacing check"
2792        );
2793        assert!(driver.contains(ACTION_DISPATCH));
2794    }
2795}