1use 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#[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 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 (@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 (@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#[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 (@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 (@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 (@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 (@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 $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 $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 $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 $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 (@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_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 (@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#[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 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 pub fn remove_error_listeners(&mut self) {
813 $crate::recognizer::Recognizer::remove_error_listeners(&mut self.$base);
814 }
815
816 pub fn set_force_interpreted(&mut self, force_interpreted: bool) {
820 self.$base.set_force_interpreted(force_interpreted);
821 }
822
823 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 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 pub fn clear_dfa(&self) {
850 self.$base.clear_dfa();
851 }
852
853 #[must_use]
855 pub fn lexer_dfa_stats(&self) -> $crate::lexer::LexerDfaStats {
856 self.$base.lexer_dfa_stats()
857 }
858 }
859
860 impl<$input, $hooks> $crate::generated::GeneratedLexer for $lexer<$input, $hooks>
861 where
862 $input: $crate::char_stream::CharStream,
863 $hooks: $crate::parser::SemanticHooks,
864 {
865 fn metadata() -> &'static $crate::generated::GrammarMetadata {
866 $metadata()
867 }
868 }
869
870 impl<$input, $hooks> $crate::recognizer::Recognizer for $lexer<$input, $hooks>
871 where
872 $input: $crate::char_stream::CharStream,
873 $hooks: $crate::parser::SemanticHooks,
874 {
875 fn data(&self) -> &$crate::recognizer::RecognizerData {
876 $crate::recognizer::Recognizer::data(&self.$base)
877 }
878
879 fn data_mut(&mut self) -> &mut $crate::recognizer::RecognizerData {
880 $crate::recognizer::Recognizer::data_mut(&mut self.$base)
881 }
882 }
883
884 impl<$input, $hooks> $crate::lexer::Lexer for $lexer<$input, $hooks>
885 where
886 $input: $crate::char_stream::CharStream,
887 $hooks: $crate::parser::SemanticHooks,
888 {
889 fn mode(&self) -> i32 {
890 $crate::lexer::Lexer::mode(&self.$base)
891 }
892
893 fn set_mode(&mut self, mode: i32) {
894 $crate::lexer::Lexer::set_mode(&mut self.$base, mode);
895 }
896
897 fn push_mode(&mut self, mode: i32) {
898 $crate::lexer::Lexer::push_mode(&mut self.$base, mode);
899 }
900
901 fn pop_mode(&mut self) -> ::core::option::Option<i32> {
902 $crate::lexer::Lexer::pop_mode(&mut self.$base)
903 }
904 }
905
906 impl<$input, $hooks> $crate::token::TokenSource for $lexer<$input, $hooks>
907 where
908 $input: $crate::char_stream::CharStream,
909 $hooks: $crate::parser::SemanticHooks,
910 {
911 fn next_token(
912 &mut self,
913 $sink: &mut $crate::token::TokenSink<'_>,
914 ) -> ::core::result::Result<$crate::token::TokenId, $crate::token::TokenStoreError>
915 {
916 let $this = self;
917 $next_token
918 }
919
920 fn line(&self) -> usize {
921 self.$base.line()
922 }
923
924 fn column(&self) -> usize {
925 self.$base.column()
926 }
927
928 fn source_name(&self) -> &str {
929 self.$base.source_name()
930 }
931
932 fn source_text(&self) -> ::core::option::Option<::std::rc::Rc<str>> {
933 self.$base.source_text()
934 }
935
936 fn drain_errors(&mut self) -> ::std::vec::Vec<$crate::token::TokenSourceError> {
937 self.$base.drain_errors()
938 }
939
940 fn report_error(&self, source_error: &$crate::token::TokenSourceError) -> bool {
941 $crate::recognizer::Recognizer::notify_error_listeners(self, source_error.into());
942 true
943 }
944
945 fn lexer_dfa_string(&self) -> ::std::string::String {
946 self.$base.lexer_dfa_string()
947 }
948 }
949 };
950}
951
952#[doc(hidden)]
955#[macro_export]
956macro_rules! __antlr4_rust_parser_facade {
957 (
958 type: $parser:ident<$source:ident, $hooks:ident>,
959 fields: {
960 base: $base:ident,
961 simulator: $simulator:ident,
962 generated_only: $generated_only:ident $(,)?
963 },
964 metadata: $metadata:path,
965 parser_atn: $parser_atn:path,
966 reset($this:ident) $reset:block
967 $(,)?
968 ) => {
969 impl<$source, $hooks> $parser<$source, $hooks>
970 where
971 $source: $crate::token::TokenSource,
972 $hooks: $crate::parser::SemanticHooks,
973 {
974 pub fn metadata() -> &'static $crate::generated::GrammarMetadata {
975 $metadata()
976 }
977
978 pub fn add_error_listener<T>(&mut self, listener: T)
980 where
981 T: for<'a> $crate::errors::ErrorListener<dyn $crate::recognizer::Recognizer + 'a>
982 + ::core::marker::Send
983 + 'static,
984 {
985 $crate::recognizer::Recognizer::add_error_listener(&mut self.$base, listener);
986 }
987
988 pub fn remove_error_listeners(&mut self) {
990 $crate::recognizer::Recognizer::remove_error_listeners(&mut self.$base);
991 }
992
993 pub fn add_parse_listener<T>(&mut self, listener: T)
997 where
998 T: $crate::parser::ParseListener + 'static,
999 {
1000 self.$base.add_parse_listener(listener);
1001 }
1002
1003 pub fn remove_parse_listeners(
1006 &mut self,
1007 ) -> ::std::vec::Vec<::std::boxed::Box<dyn $crate::parser::ParseListener>> {
1008 self.$base.remove_parse_listeners()
1009 }
1010
1011 pub fn reset(&mut self) {
1013 self.$base.reset();
1014 if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
1015 simulator.reset();
1016 }
1017 let $this = &mut *self;
1018 $reset
1019 }
1020
1021 pub fn set_token_stream(
1023 &mut self,
1024 input: $crate::token_stream::CommonTokenStream<$source>,
1025 ) {
1026 self.$base.set_token_stream(input);
1027 if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
1028 simulator.reset();
1029 }
1030 let $this = &mut *self;
1031 $reset
1032 }
1033
1034 #[must_use]
1035 pub const fn token_stream(&self) -> &$crate::token_stream::CommonTokenStream<$source> {
1036 self.$base.token_stream()
1037 }
1038
1039 #[must_use]
1040 pub const fn token_stream_mut(
1041 &mut self,
1042 ) -> &mut $crate::token_stream::CommonTokenStream<$source> {
1043 self.$base.token_stream_mut()
1044 }
1045
1046 #[must_use]
1047 pub const fn token_store(&self) -> &$crate::token::TokenStore {
1048 self.$base.token_store()
1049 }
1050
1051 #[must_use]
1052 pub const fn parse_tree_storage(&self) -> &$crate::tree::ParseTreeStorage {
1053 self.$base.parse_tree_storage()
1054 }
1055
1056 #[must_use]
1057 pub fn prediction_context_stats(&self) -> $crate::prediction::PredictionContextStats {
1058 self.$simulator.as_ref().map_or_else(
1059 $crate::prediction::PredictionContextStats::default,
1060 $crate::atn::parser::ParserAtnSimulator::prediction_context_stats,
1061 )
1062 }
1063
1064 #[must_use]
1065 pub fn parser_dfa_stats(&self) -> $crate::dfa::ParserDfaStats {
1066 self.$simulator.as_ref().map_or_else(
1067 $crate::dfa::ParserDfaStats::default,
1068 $crate::atn::parser::ParserAtnSimulator::parser_dfa_stats,
1069 )
1070 }
1071
1072 pub fn clear_dfa(&mut self) {
1074 if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
1075 simulator.clear_dfa();
1076 } else {
1077 $crate::atn::parser::ParserAtnSimulator::clear_shared_dfa($parser_atn());
1078 }
1079 let $this = &mut *self;
1080 $reset
1081 }
1082
1083 #[must_use]
1084 pub fn node(&self, id: $crate::tree::NodeId) -> $crate::tree::Node<'_> {
1085 self.$base.node(id)
1086 }
1087
1088 #[must_use]
1089 pub fn into_token_stream(self) -> $crate::token_stream::CommonTokenStream<$source> {
1090 self.$base.into_token_stream()
1091 }
1092
1093 #[must_use]
1094 pub fn into_token_store(self) -> $crate::token::TokenStore {
1095 self.$base.into_token_store()
1096 }
1097
1098 #[must_use]
1099 pub fn into_parsed_file(self, root: $crate::tree::NodeId) -> $crate::tree::ParsedFile {
1100 self.$base.into_parsed_file(root)
1101 }
1102
1103 pub fn compile_parse_tree_pattern<PL>(
1108 &self,
1109 pattern: &str,
1110 rule_index: usize,
1111 mut make_lexer: impl ::core::ops::FnMut($crate::char_stream::InputStream) -> PL,
1112 ) -> ::core::result::Result<
1113 $crate::tree_pattern::ParseTreePattern,
1114 $crate::tree_pattern::ParseTreePatternError,
1115 >
1116 where
1117 PL: $crate::token::TokenSource,
1118 {
1119 static PATTERN_DATA: ::std::sync::OnceLock<$crate::recognizer::RecognizerData> =
1120 ::std::sync::OnceLock::new();
1121 static PATTERN_MATCHER: ::std::sync::OnceLock<
1122 $crate::tree_pattern::ParseTreePatternMatcher<'static>,
1123 > = ::std::sync::OnceLock::new();
1124 let matcher = match PATTERN_MATCHER.get() {
1125 ::core::option::Option::Some(matcher) => matcher,
1126 ::core::option::Option::None => {
1127 let data = PATTERN_DATA.get_or_init(|| $metadata().recognizer_data());
1128 let matcher = $crate::tree_pattern::ParseTreePatternMatcher::new(
1129 $parser_atn(),
1130 data,
1131 )?;
1132 PATTERN_MATCHER.get_or_init(|| matcher)
1133 }
1134 };
1135 matcher.compile(pattern, rule_index, move |text: &str| {
1136 $crate::tree_pattern::lex_pattern_chunk(text, &mut make_lexer)
1137 })
1138 }
1139
1140 #[allow(dead_code)]
1141 fn simulator(&mut self) -> &mut $crate::atn::parser::ParserAtnSimulator<'static> {
1142 self.$simulator.get_or_insert_with(|| {
1143 $crate::atn::parser::ParserAtnSimulator::new_shared($parser_atn())
1144 })
1145 }
1146
1147 #[allow(dead_code)]
1148 fn generated_only(&self) -> bool {
1149 self.$generated_only
1150 }
1151 }
1152
1153 impl<$source, $hooks> $crate::generated::GeneratedParser for $parser<$source, $hooks>
1154 where
1155 $source: $crate::token::TokenSource,
1156 $hooks: $crate::parser::SemanticHooks,
1157 {
1158 fn metadata() -> &'static $crate::generated::GrammarMetadata {
1159 $metadata()
1160 }
1161
1162 fn parser_atn() -> &'static $crate::atn::parser_atn::ParserAtn {
1163 $parser_atn()
1164 }
1165 }
1166
1167 impl<$source, $hooks> $crate::generated::GeneratedRuleParser for $parser<$source, $hooks>
1168 where
1169 $source: $crate::token::TokenSource,
1170 $hooks: $crate::parser::SemanticHooks,
1171 {
1172 type Source = $source;
1173 type Hooks = $hooks;
1174
1175 fn generated_rule_base(
1176 &mut self,
1177 ) -> &mut $crate::parser::BaseParser<Self::Source, Self::Hooks> {
1178 &mut self.$base
1179 }
1180 }
1181
1182 impl<$source, $hooks> $crate::recognizer::Recognizer for $parser<$source, $hooks>
1183 where
1184 $source: $crate::token::TokenSource,
1185 $hooks: $crate::parser::SemanticHooks,
1186 {
1187 fn data(&self) -> &$crate::recognizer::RecognizerData {
1188 $crate::recognizer::Recognizer::data(&self.$base)
1189 }
1190
1191 fn data_mut(&mut self) -> &mut $crate::recognizer::RecognizerData {
1192 $crate::recognizer::Recognizer::data_mut(&mut self.$base)
1193 }
1194 }
1195
1196 impl<$source, $hooks> $crate::parser::Parser for $parser<$source, $hooks>
1197 where
1198 $source: $crate::token::TokenSource,
1199 $hooks: $crate::parser::SemanticHooks,
1200 {
1201 fn build_parse_trees(&self) -> bool {
1202 $crate::parser::Parser::build_parse_trees(&self.$base)
1203 }
1204
1205 fn set_build_parse_trees(&mut self, build: bool) {
1206 $crate::parser::Parser::set_build_parse_trees(&mut self.$base, build);
1207 }
1208
1209 fn number_of_syntax_errors(&self) -> usize {
1210 $crate::parser::Parser::number_of_syntax_errors(&self.$base)
1211 }
1212
1213 fn report_diagnostic_errors(&self) -> bool {
1214 $crate::parser::Parser::report_diagnostic_errors(&self.$base)
1215 }
1216
1217 fn set_report_diagnostic_errors(&mut self, report: bool) {
1218 $crate::parser::Parser::set_report_diagnostic_errors(&mut self.$base, report);
1219 }
1220
1221 fn prediction_mode(&self) -> $crate::parser::PredictionMode {
1222 $crate::parser::Parser::prediction_mode(&self.$base)
1223 }
1224
1225 fn set_prediction_mode(&mut self, mode: $crate::parser::PredictionMode) {
1226 $crate::parser::Parser::set_prediction_mode(&mut self.$base, mode);
1227 }
1228
1229 fn max_rule_depth(&self) -> ::core::option::Option<usize> {
1230 $crate::parser::Parser::max_rule_depth(&self.$base)
1231 }
1232
1233 fn set_max_rule_depth(&mut self, depth: ::core::option::Option<usize>) {
1234 $crate::parser::Parser::set_max_rule_depth(&mut self.$base, depth);
1235 }
1236
1237 fn add_parse_listener(
1238 &mut self,
1239 listener: ::std::boxed::Box<dyn $crate::parser::ParseListener>,
1240 ) {
1241 $crate::parser::Parser::add_parse_listener(&mut self.$base, listener);
1242 }
1243
1244 fn remove_parse_listeners(
1245 &mut self,
1246 ) -> ::std::vec::Vec<::std::boxed::Box<dyn $crate::parser::ParseListener>> {
1247 $crate::parser::Parser::remove_parse_listeners(&mut self.$base)
1248 }
1249 }
1250 };
1251}
1252
1253#[doc(hidden)]
1265#[macro_export]
1266macro_rules! __antlr4_rust_parser_driver {
1267 (
1268 type: $parser:ident<$source:ident, $hooks:ident>,
1269 fields: {
1270 base: $base:ident,
1271 simulator: $simulator:ident $(,)?
1272 },
1273 atn: $atn:path,
1274 adaptive_direct: $adaptive_direct:expr,
1275 fallback($this:ident, $rule_index:ident, $precedence:ident) $fallback:block
1276 $(,)?
1277 ) => {
1278 impl<$source, $hooks> $parser<$source, $hooks>
1279 where
1280 $source: $crate::token::TokenSource,
1281 $hooks: $crate::parser::SemanticHooks,
1282 {
1283 #[allow(dead_code)]
1284 fn parse_rule(
1285 &mut self,
1286 rule_index: usize,
1287 ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1288 self.parse_rule_precedence(rule_index, 0)
1289 }
1290
1291 #[allow(dead_code)]
1292 fn parse_rule_precedence(
1293 &mut self,
1294 rule_index: usize,
1295 precedence: i32,
1296 ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1297 self.parse_rule_precedence_inner(rule_index, precedence, true)
1298 }
1299
1300 #[allow(dead_code)]
1301 fn parse_rule_precedence_from_generated(
1302 &mut self,
1303 rule_index: usize,
1304 precedence: i32,
1305 ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1306 self.parse_rule_precedence_inner(rule_index, precedence, false)
1307 }
1308
1309 #[allow(dead_code)]
1310 fn parse_rule_precedence_inner(
1311 &mut self,
1312 rule_index: usize,
1313 precedence: i32,
1314 allow_generated_fallback: bool,
1315 ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1316 if allow_generated_fallback {
1317 self.$base.reset_unknown_semantic_hits();
1322 let _ = self.$base.take_parse_abort();
1327 }
1328 let __rule_start = $crate::int_stream::IntStream::index(self.$base.input());
1329 let __generated_only = self.generated_only();
1330 let __tree = if let ::core::option::Option::Some(result) =
1331 self.parse_generated_rule(rule_index, precedence, allow_generated_fallback)
1332 {
1333 match result {
1334 ::core::result::Result::Ok(tree) => tree,
1335 ::core::result::Result::Err(error) => {
1336 $crate::int_stream::IntStream::seek(self.$base.input(), __rule_start);
1337 let __report_error = ::core::matches!(
1338 &error,
1339 $crate::generated::GeneratedRuleError::Fatal(_)
1340 );
1341 if allow_generated_fallback && __report_error {
1346 self.$base.report_generated_parser_diagnostics();
1347 }
1348 if allow_generated_fallback {
1349 if let ::core::option::Option::Some(abort) =
1354 self.$base.take_parse_abort()
1355 {
1356 let _ = self.$base.take_unknown_semantic_error();
1357 return ::core::result::Result::Err(abort);
1358 }
1359 if let ::core::option::Option::Some(semantic_error) =
1364 self.$base.take_unknown_semantic_error()
1365 {
1366 return ::core::result::Result::Err(semantic_error);
1367 }
1368 }
1369 let error = error.into_error();
1370 if allow_generated_fallback && __report_error {
1371 self.$base.report_unrecovered_parser_error(&error);
1372 }
1373 return ::core::result::Result::Err(error);
1374 }
1375 }
1376 } else if __generated_only {
1377 return ::core::result::Result::Err($crate::errors::AntlrError::Unsupported(
1378 ::std::format!("generated parser did not emit rule {}", rule_index),
1379 ));
1380 } else {
1381 self.parse_interpreted_rule_precedence(rule_index, precedence)?
1382 };
1383 if allow_generated_fallback {
1384 self.$base.report_generated_parser_diagnostics();
1385 if let ::core::option::Option::Some(error) = self.$base.take_parse_abort() {
1390 let _ = self.$base.take_unknown_semantic_error();
1391 return ::core::result::Result::Err(error);
1392 }
1393 if let ::core::option::Option::Some(error) =
1396 self.$base.take_unknown_semantic_error()
1397 {
1398 return ::core::result::Result::Err(error);
1399 }
1400 }
1401 ::core::result::Result::Ok(__tree)
1402 }
1403
1404 #[allow(dead_code)]
1405 fn parse_interpreted_rule(
1406 &mut self,
1407 rule_index: usize,
1408 ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1409 self.parse_interpreted_rule_precedence(rule_index, 0)
1410 }
1411
1412 #[allow(dead_code)]
1413 fn parse_interpreted_rule_precedence(
1414 &mut self,
1415 rule_index: usize,
1416 precedence: i32,
1417 ) -> ::core::result::Result<$crate::tree::ParseTree, $crate::errors::AntlrError> {
1418 if precedence == 0
1419 && $adaptive_direct
1420 && ::std::env::var_os("ANTLR4_RUST_ADAPTIVE_DIRECT").is_some()
1421 {
1422 let simulator = self.$simulator.get_or_insert_with(|| {
1423 $crate::atn::parser::ParserAtnSimulator::new_shared($atn())
1424 });
1425 self.$base
1426 .parse_atn_rule_adaptive_or_fallback($atn(), simulator, rule_index)
1427 } else {
1428 let (__tree, __actions) = {
1429 let $this = &mut *self;
1430 let $rule_index = rule_index;
1431 let $precedence = precedence;
1432 $fallback
1433 }?;
1434 for __action in __actions {
1438 self.run_action(__action, __tree);
1439 }
1440 ::core::result::Result::Ok(__tree)
1441 }
1442 }
1443 }
1444 };
1445}
1446
1447#[doc(hidden)]
1456#[macro_export]
1457macro_rules! __antlr4_rust_parser_entry_points {
1458 (
1459 parser: $parser:ident,
1460 output: $output:ident,
1461 validated_tree: $validated:ident,
1462 validation_error: $validation_error:ident,
1463 validate_tree: $validate_tree:path
1464 $(,)?
1465 ) => {
1466 #[doc = ::core::concat!(
1467 "Result from [`parse_with_parser`] or [`parse_stream_with_parser`].\n\n",
1468 "Keeps the generated parser available after the entry rule runs so callers\n",
1469 "can inspect diagnostics or recover the parser-owned token stream. Alias of\n",
1470 "the runtime's `GeneratedParseOutput` with [`",
1471 ::core::stringify!($parser),
1472 "`] substituted for its parser type parameter.",
1473 )]
1474 pub type $output<R, L> = $crate::generated::GeneratedParseOutput<R, $parser<L>>;
1475
1476 impl<L, H> $crate::generated::__GeneratedParserValidate for $parser<L, H>
1477 where
1478 L: $crate::token::TokenSource,
1479 H: $crate::parser::SemanticHooks,
1480 {
1481 type Validated = $validated;
1482
1483 fn __validate(
1484 self,
1485 root: $crate::tree::NodeId,
1486 ) -> ::core::result::Result<$validated, $crate::validated::ValidationError> {
1487 let lexer = self.token_stream().number_of_source_errors();
1488 let parser = $crate::parser::Parser::number_of_syntax_errors(&self);
1489 if lexer != 0 || parser != 0 {
1490 return ::core::result::Result::Err($validation_error::SyntaxErrors {
1491 lexer,
1492 parser,
1493 });
1494 }
1495 let parsed = self.into_parsed_file(root);
1496 $validate_tree(&parsed)?;
1497 ::core::result::Result::Ok(<$validated>::__new(parsed))
1498 }
1499 }
1500
1501 #[doc = ::core::concat!(
1505 "Pass the generated lexer constructor and a parser entry rule, for example\n",
1506 "`parse(src, MyGrammarLexer::new, ",
1507 ::core::stringify!($parser),
1508 "::file)`.",
1509 )]
1510 pub fn parse<L: $crate::token::TokenSource>(
1516 input: impl ::core::convert::AsRef<str>,
1517 lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1518 entry: impl ::core::ops::FnOnce(
1519 &mut $parser<L>,
1520 ) -> ::core::result::Result<
1521 $crate::tree::NodeId,
1522 $crate::errors::AntlrError,
1523 >,
1524 ) -> ::core::result::Result<$crate::tree::ParsedFile, $crate::errors::AntlrError> {
1525 parse_stream(
1526 $crate::char_stream::InputStream::new(input.as_ref()),
1527 lexer,
1528 entry,
1529 )
1530 }
1531
1532 pub fn parse_validated<L: $crate::token::TokenSource>(
1535 input: impl ::core::convert::AsRef<str>,
1536 lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1537 entry: impl ::core::ops::FnOnce(
1538 &mut $parser<L>,
1539 ) -> ::core::result::Result<
1540 $crate::tree::NodeId,
1541 $crate::errors::AntlrError,
1542 >,
1543 ) -> ::core::result::Result<$validated, $validation_error> {
1544 parse_stream_validated(
1545 $crate::char_stream::InputStream::new(input.as_ref()),
1546 lexer,
1547 entry,
1548 )
1549 }
1550
1551 #[doc = ::core::concat!(
1555 "This keeps the compact generated setup path available for callers that also\n",
1556 "need `Parser::number_of_syntax_errors()` or `",
1557 ::core::stringify!($parser),
1558 "::into_token_stream()`.",
1559 )]
1560 pub fn parse_with_parser<L: $crate::token::TokenSource, R>(
1561 input: impl ::core::convert::AsRef<str>,
1562 lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1563 entry: impl ::core::ops::FnOnce(
1564 &mut $parser<L>,
1565 )
1566 -> ::core::result::Result<R, $crate::errors::AntlrError>,
1567 ) -> ::core::result::Result<$output<R, L>, $crate::errors::AntlrError> {
1568 parse_stream_with_parser(
1569 $crate::char_stream::InputStream::new(input.as_ref()),
1570 lexer,
1571 entry,
1572 )
1573 }
1574
1575 pub fn parse_stream<I: $crate::char_stream::CharStream, L: $crate::token::TokenSource>(
1582 input: I,
1583 lexer: impl ::core::ops::FnOnce(I) -> L,
1584 entry: impl ::core::ops::FnOnce(
1585 &mut $parser<L>,
1586 ) -> ::core::result::Result<
1587 $crate::tree::NodeId,
1588 $crate::errors::AntlrError,
1589 >,
1590 ) -> ::core::result::Result<$crate::tree::ParsedFile, $crate::errors::AntlrError> {
1591 let $crate::generated::GeneratedParseOutput { result, parser } =
1592 parse_stream_with_parser(input, lexer, entry)?;
1593 ::core::result::Result::Ok(parser.into_parsed_file(result))
1594 }
1595
1596 pub fn parse_stream_validated<
1598 I: $crate::char_stream::CharStream,
1599 L: $crate::token::TokenSource,
1600 >(
1601 input: I,
1602 lexer: impl ::core::ops::FnOnce(I) -> L,
1603 entry: impl ::core::ops::FnOnce(
1604 &mut $parser<L>,
1605 ) -> ::core::result::Result<
1606 $crate::tree::NodeId,
1607 $crate::errors::AntlrError,
1608 >,
1609 ) -> ::core::result::Result<$validated, $validation_error> {
1610 let output = parse_stream_with_parser(input, lexer, entry)
1611 .map_err($validation_error::Recognition)?;
1612 output.validate()
1613 }
1614
1615 pub fn parse_stream_with_parser<
1618 I: $crate::char_stream::CharStream,
1619 L: $crate::token::TokenSource,
1620 R,
1621 >(
1622 input: I,
1623 lexer: impl ::core::ops::FnOnce(I) -> L,
1624 entry: impl ::core::ops::FnOnce(
1625 &mut $parser<L>,
1626 )
1627 -> ::core::result::Result<R, $crate::errors::AntlrError>,
1628 ) -> ::core::result::Result<$output<R, L>, $crate::errors::AntlrError> {
1629 let lexer = lexer(input);
1630 let tokens = $crate::token_stream::CommonTokenStream::new(lexer);
1631 let mut parser = $parser::new(tokens);
1632 let result = entry(&mut parser)?;
1633 ::core::result::Result::Ok($crate::generated::GeneratedParseOutput { result, parser })
1634 }
1635 };
1636}
1637
1638#[derive(Debug)]
1639pub struct GrammarMetadata {
1640 grammar_file_name: &'static str,
1641 rule_names: &'static [&'static str],
1642 literal_names: &'static [Option<&'static str>],
1643 symbolic_names: &'static [Option<&'static str>],
1644 display_names: &'static [Option<&'static str>],
1645 channel_names: &'static [&'static str],
1646 mode_names: &'static [&'static str],
1647 serialized_atn: &'static [i32],
1648 recognizer_metadata: OnceLock<Arc<RecognizerMetadata>>,
1649}
1650
1651impl Clone for GrammarMetadata {
1652 fn clone(&self) -> Self {
1653 Self {
1654 grammar_file_name: self.grammar_file_name,
1655 rule_names: self.rule_names,
1656 literal_names: self.literal_names,
1657 symbolic_names: self.symbolic_names,
1658 display_names: self.display_names,
1659 channel_names: self.channel_names,
1660 mode_names: self.mode_names,
1661 serialized_atn: self.serialized_atn,
1662 recognizer_metadata: OnceLock::from(Arc::clone(self.cached_recognizer_metadata())),
1663 }
1664 }
1665}
1666
1667impl GrammarMetadata {
1668 #[allow(clippy::too_many_arguments)]
1670 pub const fn new(
1671 grammar_file_name: &'static str,
1672 rule_names: &'static [&'static str],
1673 literal_names: &'static [Option<&'static str>],
1674 symbolic_names: &'static [Option<&'static str>],
1675 display_names: &'static [Option<&'static str>],
1676 channel_names: &'static [&'static str],
1677 mode_names: &'static [&'static str],
1678 serialized_atn: &'static [i32],
1679 ) -> Self {
1680 Self {
1681 grammar_file_name,
1682 rule_names,
1683 literal_names,
1684 symbolic_names,
1685 display_names,
1686 channel_names,
1687 mode_names,
1688 serialized_atn,
1689 recognizer_metadata: OnceLock::new(),
1690 }
1691 }
1692
1693 pub const fn grammar_file_name(&self) -> &'static str {
1694 self.grammar_file_name
1695 }
1696
1697 pub const fn rule_names(&self) -> &'static [&'static str] {
1698 self.rule_names
1699 }
1700
1701 pub const fn channel_names(&self) -> &'static [&'static str] {
1702 self.channel_names
1703 }
1704
1705 pub const fn mode_names(&self) -> &'static [&'static str] {
1706 self.mode_names
1707 }
1708
1709 pub fn vocabulary(&self) -> Vocabulary {
1710 Vocabulary::new(
1711 self.literal_names.iter().copied(),
1712 self.symbolic_names.iter().copied(),
1713 self.display_names.iter().copied(),
1714 )
1715 }
1716
1717 pub fn recognizer_data(&self) -> RecognizerData {
1720 RecognizerData::from_shared(Arc::clone(self.cached_recognizer_metadata()))
1721 }
1722
1723 fn cached_recognizer_metadata(&self) -> &Arc<RecognizerMetadata> {
1724 self.recognizer_metadata.get_or_init(|| {
1725 Arc::new(RecognizerMetadata::from_static(
1726 self.grammar_file_name,
1727 self.rule_names,
1728 self.channel_names,
1729 self.mode_names,
1730 self.vocabulary(),
1731 ))
1732 })
1733 }
1734
1735 pub const fn serialized_atn(&self) -> SerializedAtn<'_> {
1738 SerializedAtn::from_i32(self.serialized_atn)
1739 }
1740}
1741
1742pub trait GeneratedLexer {
1743 fn metadata() -> &'static GrammarMetadata;
1744}
1745
1746pub trait GeneratedParser {
1747 fn metadata() -> &'static GrammarMetadata;
1748
1749 fn parser_atn() -> &'static ParserAtn;
1751}
1752
1753#[doc(hidden)]
1758pub trait GeneratedRuleParser {
1759 type Source: TokenSource;
1760 type Hooks: SemanticHooks;
1761
1762 fn generated_rule_base(&mut self) -> &mut BaseParser<Self::Source, Self::Hooks>;
1763}
1764
1765#[doc(hidden)]
1779#[derive(Debug)]
1780pub enum GeneratedRuleError {
1781 Fatal(AntlrError),
1783 Interpreted(AntlrError),
1785 AdaptiveRetry,
1787}
1788
1789impl GeneratedRuleError {
1790 #[must_use]
1792 pub fn into_error(self) -> AntlrError {
1793 match self {
1794 Self::Fatal(error) | Self::Interpreted(error) => error,
1795 Self::AdaptiveRetry => AntlrError::Unsupported(
1796 "internal adaptive ATN retry escaped its routing boundary".to_owned(),
1797 ),
1798 }
1799 }
1800}
1801
1802#[doc(hidden)]
1804pub type GeneratedRuleBody<P> =
1805 fn(&mut P, i32, bool) -> Result<crate::tree::ParseTree, GeneratedRuleError>;
1806
1807#[doc(hidden)]
1812#[inline(never)]
1813pub fn dispatch_generated_rule<P>(
1814 parser: &mut P,
1815 rule_index: usize,
1816 precedence: i32,
1817 allow_fallback: bool,
1818 body: GeneratedRuleBody<P>,
1819) -> Result<crate::tree::ParseTree, GeneratedRuleError>
1820where
1821 P: GeneratedRuleParser,
1822{
1823 if let Some(error) = parser.generated_rule_base().rule_depth_cap_violation() {
1824 return Err(GeneratedRuleError::Fatal(error));
1825 }
1826 if let Some(error) = parser
1827 .generated_rule_base()
1828 .parse_listener_enter_rule(rule_index)
1829 {
1830 return Err(GeneratedRuleError::Fatal(error));
1831 }
1832 let result = if parser
1833 .generated_rule_base()
1834 .generated_rule_stack_check_due()
1835 {
1836 grow_generated_rule_stack(|| body(parser, precedence, allow_fallback))
1837 } else {
1838 body(parser, precedence, allow_fallback)
1839 };
1840 parser
1841 .generated_rule_base()
1842 .parse_listener_exit_rule(rule_index);
1843 result
1844}
1845
1846#[doc(hidden)]
1854#[derive(Debug)]
1855pub struct AdaptiveAtnRetryState<const RULES: usize> {
1856 pub preferred_rules: [bool; RULES],
1858 pub preference_depths: [usize; RULES],
1860 pub preference_starts: [(usize, usize); RULES],
1862 pub syntax_error_starts: [usize; RULES],
1864 pub retry_slot: Option<usize>,
1866}
1867
1868impl<const RULES: usize> AdaptiveAtnRetryState<RULES> {
1869 #[must_use]
1871 pub const fn new() -> Self {
1872 Self {
1873 preferred_rules: [false; RULES],
1874 preference_depths: [0; RULES],
1875 preference_starts: [(0, 0); RULES],
1876 syntax_error_starts: [0; RULES],
1877 retry_slot: None,
1878 }
1879 }
1880
1881 pub const fn reset(&mut self) {
1883 *self = Self::new();
1884 }
1885
1886 #[must_use]
1891 pub const fn retry_pending(&self) -> bool {
1892 RULES > 0 && self.retry_slot.is_some()
1893 }
1894}
1895
1896impl<const RULES: usize> Default for AdaptiveAtnRetryState<RULES> {
1897 fn default() -> Self {
1898 Self::new()
1899 }
1900}
1901
1902#[derive(Debug)]
1911pub struct GeneratedParseOutput<R, P> {
1912 pub result: R,
1914 pub parser: P,
1916}
1917
1918#[doc(hidden)]
1924pub trait __GeneratedParserValidate: Sized {
1925 type Validated;
1927
1928 fn __validate(self, root: NodeId) -> Result<Self::Validated, ValidationError>;
1930}
1931
1932impl<P: __GeneratedParserValidate> GeneratedParseOutput<NodeId, P> {
1933 pub fn validate(self) -> Result<P::Validated, ValidationError> {
1944 self.parser.__validate(self.result)
1945 }
1946}
1947
1948pub fn lex<L: TokenSource>(
1970 input: impl AsRef<str>,
1971 lexer: impl FnOnce(InputStream) -> L,
1972) -> CommonTokenStream<L> {
1973 lex_stream(InputStream::new(input.as_ref()), lexer)
1974}
1975
1976pub fn lex_stream<I: CharStream, L: TokenSource>(
1990 input: I,
1991 lexer: impl FnOnce(I) -> L,
1992) -> CommonTokenStream<L> {
1993 CommonTokenStream::new(lexer(input))
1994}
1995
1996#[doc(hidden)]
2007pub struct __GeneratedInput<'a, L: TokenSource>(#[doc(hidden)] pub &'a mut CommonTokenStream<L>);
2008
2009impl<L: TokenSource> __GeneratedInput<'_, L> {
2010 #[must_use]
2011 #[inline]
2012 pub fn text(&self) -> String {
2013 self.0.text_all()
2014 }
2015
2016 #[inline]
2017 pub fn la(&mut self, offset: isize) -> i32 {
2018 IntStream::la(self.0, offset)
2019 }
2020
2021 #[must_use]
2022 #[inline]
2023 pub fn lt(&self, offset: isize) -> __GeneratedTokenView {
2024 __GeneratedTokenView {
2025 text: self
2026 .0
2027 .lt(offset)
2028 .map(|token| token.text_or_empty().to_owned())
2029 .unwrap_or_default(),
2030 }
2031 }
2032}
2033
2034impl<L: TokenSource> fmt::Debug for __GeneratedInput<'_, L> {
2035 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2036 f.debug_struct("__GeneratedInput").finish_non_exhaustive()
2037 }
2038}
2039
2040#[doc(hidden)]
2043#[derive(Debug)]
2044pub struct __GeneratedTokenView {
2045 #[doc(hidden)]
2046 pub text: String,
2047}
2048
2049impl __GeneratedTokenView {
2050 #[must_use]
2051 #[inline]
2052 pub fn text(&self) -> &str {
2053 &self.text
2054 }
2055}
2056
2057#[derive(Clone, Debug)]
2064pub struct TerminalNode<'a> {
2065 __node: TerminalNodeView<'a>,
2066}
2067
2068impl<'a> TerminalNode<'a> {
2069 #[doc(hidden)]
2070 #[must_use]
2071 #[inline]
2072 pub const fn new(node: TerminalNodeView<'a>) -> Self {
2073 Self { __node: node }
2074 }
2075
2076 #[must_use]
2077 #[inline]
2078 pub fn symbol(&self) -> TokenView<'a> {
2079 self.__node.symbol()
2080 }
2081
2082 #[must_use]
2083 #[inline]
2084 pub fn is_error(&self) -> bool {
2085 matches!(self.__node.node().kind(), NodeKind::Error)
2086 }
2087
2088 #[must_use]
2089 #[inline]
2090 pub fn is_missing(&self) -> bool {
2091 self.symbol().is_synthetic()
2092 }
2093
2094 #[doc(hidden)]
2096 #[must_use]
2097 #[inline]
2098 pub const fn node(&self) -> Node<'a> {
2099 self.__node.node()
2100 }
2101}
2102
2103impl fmt::Display for TerminalNode<'_> {
2104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2105 f.write_str(self.__node.text())
2106 }
2107}
2108
2109#[derive(Clone, Debug)]
2112pub struct ErrorNode<'a> {
2113 __node: ErrorNodeView<'a>,
2114}
2115
2116impl<'a> ErrorNode<'a> {
2117 #[doc(hidden)]
2118 #[must_use]
2119 #[inline]
2120 pub const fn new(node: ErrorNodeView<'a>) -> Self {
2121 Self { __node: node }
2122 }
2123
2124 #[must_use]
2125 #[inline]
2126 pub fn symbol(&self) -> TokenView<'a> {
2127 self.__node.symbol()
2128 }
2129
2130 #[must_use]
2131 #[inline]
2132 pub fn is_missing(&self) -> bool {
2133 self.symbol().is_synthetic()
2134 }
2135
2136 #[doc(hidden)]
2138 #[must_use]
2139 #[inline]
2140 pub const fn node(&self) -> Node<'a> {
2141 self.__node.node()
2142 }
2143}
2144
2145impl fmt::Display for ErrorNode<'_> {
2146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2147 f.write_str(self.__node.text())
2148 }
2149}
2150
2151#[doc(hidden)]
2153#[macro_export]
2154macro_rules! __antlr4_rust_generated_walk_callbacks {
2155 (
2156 callbacks: $callbacks:ident,
2157 listener: $listener:ident,
2158 enter: |$enter_listener:ident, $enter_context:ident, $enter_states:ident| $enter_body:block,
2159 exit: |$exit_listener:ident, $exit_context:ident, $exit_states:ident| $exit_body:block,
2160 terminal: |$terminal_listener:ident, $terminal_node:ident| $terminal_body:block,
2161 error: |$error_listener:ident, $error_node:ident| $error_body:block $(,)?
2162 ) => {
2163 #[allow(dead_code)]
2164 struct $callbacks<'listener, T>(&'listener mut T);
2165
2166 impl<E, T: $listener<E>> $crate::generated::GeneratedWalkCallbacks<E>
2167 for $callbacks<'_, T>
2168 {
2169 #[inline(always)]
2170 fn dispatch_enter_rule(
2171 &mut self,
2172 $enter_context: $crate::RuleNodeView<'_>,
2173 $enter_states: ::core::option::Option<&[isize]>,
2174 ) -> ::core::result::Result<(), E> {
2175 let $enter_listener = &mut *self.0;
2176 $enter_body
2177 }
2178
2179 #[inline(always)]
2180 fn dispatch_exit_rule(
2181 &mut self,
2182 $exit_context: $crate::RuleNodeView<'_>,
2183 $exit_states: ::core::option::Option<&[isize]>,
2184 ) -> ::core::result::Result<(), E> {
2185 let $exit_listener = &mut *self.0;
2186 $exit_body
2187 }
2188
2189 #[inline(always)]
2190 fn visit_terminal(
2191 &mut self,
2192 $terminal_node: $crate::TerminalNodeView<'_>,
2193 ) -> ::core::result::Result<(), E> {
2194 let $terminal_listener = &mut *self.0;
2195 $terminal_body
2196 }
2197
2198 #[inline(always)]
2199 fn visit_error_node(
2200 &mut self,
2201 $error_node: $crate::ErrorNodeView<'_>,
2202 ) -> ::core::result::Result<(), E> {
2203 let $error_listener = &mut *self.0;
2204 $error_body
2205 }
2206 }
2207 };
2208}
2209
2210#[doc(hidden)]
2212pub trait GeneratedWalkCallbacks<E> {
2213 fn dispatch_enter_rule(
2214 &mut self,
2215 context: RuleNodeView<'_>,
2216 invocation_states: Option<&[isize]>,
2217 ) -> Result<(), E>;
2218
2219 fn dispatch_exit_rule(
2220 &mut self,
2221 context: RuleNodeView<'_>,
2222 invocation_states: Option<&[isize]>,
2223 ) -> Result<(), E>;
2224
2225 fn visit_terminal(&mut self, node: TerminalNodeView<'_>) -> Result<(), E>;
2226
2227 fn visit_error_node(&mut self, node: ErrorNodeView<'_>) -> Result<(), E>;
2228}
2229
2230#[doc(hidden)]
2233#[inline(always)]
2234pub fn walk_generated<E, C>(
2235 tree: Node<'_>,
2236 mut invocation_states: Option<Vec<isize>>,
2237 callbacks: &mut C,
2238) -> Result<(), E>
2239where
2240 C: GeneratedWalkCallbacks<E>,
2241{
2242 enum Event<'tree> {
2243 Enter(Node<'tree>),
2244 Exit(RuleNodeView<'tree>),
2245 }
2246
2247 let mut stack = vec![Event::Enter(tree)];
2248 while let Some(event) = stack.pop() {
2249 match event {
2250 Event::Enter(node) => match node.kind() {
2251 NodeKind::Rule => {
2252 let context = node.as_rule().expect("rule node kind checked");
2253 if let Some(states) = &mut invocation_states {
2254 states.insert(0, context.invoking_state());
2255 }
2256 callbacks.dispatch_enter_rule(context, invocation_states.as_deref())?;
2257 stack.push(Event::Exit(context));
2258 stack.extend(context.children().rev().map(Event::Enter));
2259 }
2260 NodeKind::Terminal => callbacks
2261 .visit_terminal(node.as_terminal().expect("terminal node kind checked"))?,
2262 NodeKind::Error => {
2263 callbacks
2264 .visit_error_node(node.as_error().expect("error node kind checked"))?;
2265 }
2266 },
2267 Event::Exit(context) => {
2268 callbacks.dispatch_exit_rule(context, invocation_states.as_deref())?;
2269 if let Some(states) = &mut invocation_states {
2270 states.remove(0);
2271 }
2272 }
2273 }
2274 }
2275 Ok(())
2276}
2277
2278#[doc(hidden)]
2281#[derive(Clone, Copy, Debug)]
2282pub enum __GeneratedRuleContext<'a> {
2283 Stored(RuleNodeView<'a>),
2284 Active {
2285 context: &'a ParserRuleContext,
2286 storage: &'a ParseTreeStorage,
2287 tokens: &'a TokenStore,
2288 },
2289}
2290
2291#[doc(hidden)]
2293#[derive(Clone, Copy, Debug)]
2294pub struct StoredTreeContext;
2295
2296#[doc(hidden)]
2298#[derive(Clone, Copy, Debug)]
2299pub struct __ActiveParserContext;
2300
2301#[doc(hidden)]
2302#[inline]
2303pub fn __context_children(
2304 source: __GeneratedRuleContext<'_>,
2305) -> impl Iterator<Item = Node<'_>> + '_ {
2306 let mut stored = match source {
2307 __GeneratedRuleContext::Stored(node) => Some(node.children()),
2308 __GeneratedRuleContext::Active { .. } => None,
2309 };
2310 let mut active = match source {
2311 __GeneratedRuleContext::Stored(_) => None,
2312 __GeneratedRuleContext::Active {
2313 context,
2314 storage,
2315 tokens,
2316 } => Some(context.child_nodes(storage, tokens)),
2317 };
2318 std::iter::from_fn(move || {
2319 stored
2320 .as_mut()
2321 .and_then(Iterator::next)
2322 .or_else(|| active.as_mut().and_then(Iterator::next))
2323 })
2324}
2325
2326#[doc(hidden)]
2327#[inline]
2328pub fn __rule_children(
2329 source: __GeneratedRuleContext<'_>,
2330 rule_index: usize,
2331) -> impl Iterator<Item = RuleNodeView<'_>> + '_ {
2332 __context_children(source).filter_map(move |child| {
2333 let rule = child.as_rule()?;
2334 (rule.rule_index() == rule_index).then_some(rule)
2335 })
2336}
2337
2338#[doc(hidden)]
2339#[inline]
2340pub fn __terminal_children(
2341 source: __GeneratedRuleContext<'_>,
2342) -> impl Iterator<Item = TerminalNodeView<'_>> + '_ {
2343 __context_children(source).filter_map(Node::terminal_view)
2344}
2345
2346#[doc(hidden)]
2347#[inline]
2348pub fn __token_children(
2349 source: __GeneratedRuleContext<'_>,
2350 token_type: i32,
2351) -> impl Iterator<Item = TerminalNodeView<'_>> + '_ {
2352 __terminal_children(source).filter(move |terminal| terminal.symbol().token_type() == token_type)
2353}
2354
2355#[doc(hidden)]
2356#[inline]
2357pub fn __token_children_matching<'a>(
2358 source: __GeneratedRuleContext<'a>,
2359 token_types: &'static [i32],
2360) -> impl Iterator<Item = TerminalNodeView<'a>> + 'a {
2361 __terminal_children(source)
2362 .filter(move |terminal| token_types.contains(&terminal.symbol().token_type()))
2363}
2364
2365#[doc(hidden)]
2366#[inline]
2367pub fn __labeled_token_children(
2368 source: __GeneratedRuleContext<'_>,
2369 token_type: i32,
2370) -> impl Iterator<Item = TerminalNodeView<'_>> + '_ {
2371 __context_children(source).filter_map(move |child| {
2372 let terminal = child.labeled_terminal_view()?;
2373 (terminal.symbol().token_type() == token_type).then_some(terminal)
2374 })
2375}
2376
2377#[doc(hidden)]
2378#[inline]
2379pub fn __labeled_token_children_matching<'a>(
2380 source: __GeneratedRuleContext<'a>,
2381 token_types: &'static [i32],
2382) -> impl Iterator<Item = TerminalNodeView<'a>> + 'a {
2383 __context_children(source).filter_map(move |child| {
2384 let terminal = child.labeled_terminal_view()?;
2385 token_types
2386 .contains(&terminal.symbol().token_type())
2387 .then_some(terminal)
2388 })
2389}
2390
2391#[doc(hidden)]
2394pub trait __FromActiveRuleContext<'a>: Sized {
2395 fn __from_active(
2396 context: &'a ParserRuleContext,
2397 live_attrs: Option<&dyn Any>,
2398 invocation_states: Vec<isize>,
2399 storage: &'a ParseTreeStorage,
2400 tokens: &'a TokenStore,
2401 ) -> Option<Self>;
2402}
2403
2404#[doc(hidden)]
2405#[inline]
2406pub fn __active_context_view<'a, T: __FromActiveRuleContext<'a>>(
2407 context: &'a ParserRuleContext,
2408 invocation_states: Vec<isize>,
2409 storage: &'a ParseTreeStorage,
2410 tokens: &'a TokenStore,
2411) -> Option<T> {
2412 T::__from_active(context, None, invocation_states, storage, tokens)
2413}
2414
2415#[doc(hidden)]
2416#[inline]
2417pub fn __active_context_view_with_attrs<'a, T: __FromActiveRuleContext<'a>>(
2418 context: &'a ParserRuleContext,
2419 live_attrs: &dyn Any,
2420 invocation_states: Vec<isize>,
2421 storage: &'a ParseTreeStorage,
2422 tokens: &'a TokenStore,
2423) -> Option<T> {
2424 T::__from_active(
2425 context,
2426 Some(live_attrs),
2427 invocation_states,
2428 storage,
2429 tokens,
2430 )
2431}
2432
2433#[doc(hidden)]
2436pub fn __write_invocation_states(
2437 f: &mut fmt::Formatter<'_>,
2438 states: impl Iterator<Item = isize>,
2439) -> fmt::Result {
2440 f.write_str("[")?;
2441 let mut separator = "";
2442 for state in states {
2443 write!(f, "{separator}{state}")?;
2444 separator = " ";
2445 }
2446 f.write_str("]")
2447}
2448
2449#[doc(hidden)]
2458pub trait __RecoveryContextState {}
2459
2460impl __RecoveryContextState for StoredTreeContext {}
2461impl __RecoveryContextState for __ActiveParserContext {}
2462
2463#[cfg(test)]
2464#[allow(clippy::disallowed_methods)] mod tests {
2466 use super::*;
2467 use crate::token::{TokenId, TokenSpec};
2468 use crate::tree::ParsedFile;
2469
2470 static META: GrammarMetadata = GrammarMetadata::new(
2471 "Mini.g4",
2472 &["file"],
2473 &[None, Some("'x'")],
2474 &[None, Some("X")],
2475 &[None, None],
2476 &["DEFAULT_TOKEN_CHANNEL", "HIDDEN"],
2477 &["DEFAULT_MODE"],
2478 &[4, 1, 1, 0, 0, 0],
2479 );
2480
2481 fn test_token(store: &mut TokenStore, token_type: i32, text: &str) -> TokenId {
2482 store
2483 .push(TokenSpec::explicit(token_type, text))
2484 .expect("test token should fit")
2485 }
2486
2487 fn generated_walk_test_tree() -> ParsedFile {
2488 let mut tokens = TokenStore::new(None, "");
2489 let a = test_token(&mut tokens, 1, "a");
2490 let b = test_token(&mut tokens, 2, "b");
2491 let error = test_token(&mut tokens, 3, "!");
2492 let mut storage = ParseTreeStorage::new();
2493 let a = storage.terminal(a);
2494 let b = storage.terminal(b);
2495 let error = storage.error(error);
2496 let mut child = ParserRuleContext::new(1, 7);
2497 storage.add_child(&mut child, b);
2498 let child = storage.finish_rule(child);
2499 let mut root = ParserRuleContext::new(0, -1);
2500 storage.add_child(&mut root, a);
2501 storage.add_child(&mut root, child);
2502 storage.add_child(&mut root, error);
2503 let root = storage.finish_rule(root);
2504 ParsedFile::new(tokens, storage, root)
2505 }
2506
2507 #[derive(Default)]
2508 struct RecordingWalkCallbacks {
2509 events: Vec<String>,
2510 fail_on_terminal: Option<&'static str>,
2511 }
2512
2513 impl GeneratedWalkCallbacks<&'static str> for RecordingWalkCallbacks {
2514 fn dispatch_enter_rule(
2515 &mut self,
2516 context: RuleNodeView<'_>,
2517 invocation_states: Option<&[isize]>,
2518 ) -> Result<(), &'static str> {
2519 self.events.push(format!(
2520 "enter rule {} {invocation_states:?}",
2521 context.rule_index()
2522 ));
2523 Ok(())
2524 }
2525
2526 fn dispatch_exit_rule(
2527 &mut self,
2528 context: RuleNodeView<'_>,
2529 invocation_states: Option<&[isize]>,
2530 ) -> Result<(), &'static str> {
2531 self.events.push(format!(
2532 "exit rule {} {invocation_states:?}",
2533 context.rule_index()
2534 ));
2535 Ok(())
2536 }
2537
2538 fn visit_terminal(&mut self, node: TerminalNodeView<'_>) -> Result<(), &'static str> {
2539 self.events.push(format!("terminal {}", node.text()));
2540 if self.fail_on_terminal == Some(node.text()) {
2541 Err("terminal callback failed")
2542 } else {
2543 Ok(())
2544 }
2545 }
2546
2547 fn visit_error_node(&mut self, node: ErrorNodeView<'_>) -> Result<(), &'static str> {
2548 self.events.push(format!("error {}", node.text()));
2549 Ok(())
2550 }
2551 }
2552
2553 #[test]
2554 fn generated_walk_preserves_order_and_invocation_states() {
2555 let parsed = generated_walk_test_tree();
2556 let mut callbacks = RecordingWalkCallbacks::default();
2557
2558 walk_generated(parsed.tree(), Some(vec![99]), &mut callbacks)
2559 .expect("recording callbacks should accept every event");
2560
2561 insta::assert_debug_snapshot!(
2562 "generated_walk_order_and_invocation_states",
2563 callbacks.events
2564 );
2565 }
2566
2567 #[test]
2568 fn generated_walk_short_circuits_callback_errors() {
2569 let parsed = generated_walk_test_tree();
2570 let mut callbacks = RecordingWalkCallbacks {
2571 fail_on_terminal: Some("b"),
2572 ..RecordingWalkCallbacks::default()
2573 };
2574
2575 assert_eq!(
2576 walk_generated(parsed.tree(), None, &mut callbacks),
2577 Err("terminal callback failed")
2578 );
2579 insta::assert_debug_snapshot!("generated_walk_short_circuit", callbacks.events);
2580 }
2581
2582 #[allow(dead_code, unreachable_pub)]
2585 mod facade_hygiene {
2586 struct Box;
2587 struct FnMut;
2588 struct None;
2589 struct Option;
2590 struct Rc;
2591 struct Result;
2592 struct Send;
2593 struct Some;
2594 struct String;
2595 struct Vec;
2596
2597 struct HygieneLexer<I, H> {
2598 base: crate::lexer::BaseLexer<I>,
2599 hooks: H,
2600 }
2601
2602 struct HygieneParser<S, H> {
2603 base: crate::parser::BaseParser<S, H>,
2604 simulator: ::core::option::Option<crate::atn::parser::ParserAtnSimulator<'static>>,
2605 generated_only: bool,
2606 }
2607
2608 fn metadata() -> &'static crate::generated::GrammarMetadata {
2609 &super::META
2610 }
2611
2612 fn parser_atn() -> &'static crate::atn::parser_atn::ParserAtn {
2613 panic!("compile-only facade hygiene fixture")
2614 }
2615
2616 crate::__antlr4_rust_lexer_facade! {
2617 type: HygieneLexer<I, H>,
2618 fields: {
2619 base: base,
2620 hooks: hooks,
2621 },
2622 metadata: metadata,
2623 next_token(_lexer, _sink) {
2624 panic!("compile-only facade hygiene fixture")
2625 }
2626 }
2627
2628 crate::__antlr4_rust_parser_facade! {
2629 type: HygieneParser<S, H>,
2630 fields: {
2631 base: base,
2632 simulator: simulator,
2633 generated_only: generated_only,
2634 },
2635 metadata: metadata,
2636 parser_atn: parser_atn,
2637 reset(_parser) {}
2638 }
2639 }
2640
2641 #[test]
2642 fn metadata_builds_vocabulary() {
2643 assert_eq!(META.grammar_file_name(), "Mini.g4");
2644 assert_eq!(META.vocabulary().display_name(1), "'x'");
2645 }
2646
2647 #[test]
2648 fn cloned_metadata_shares_the_cache_before_explicit_initialization() {
2649 let original = GrammarMetadata::new(
2650 "Clone.g4",
2651 &["start"],
2652 &[None, Some("'x'")],
2653 &[None, Some("X")],
2654 &[None, None],
2655 &["DEFAULT_TOKEN_CHANNEL"],
2656 &["DEFAULT_MODE"],
2657 &[],
2658 );
2659 let cloned = original.clone();
2660 let first = original.recognizer_data();
2661 let second = cloned.recognizer_data();
2662
2663 assert!(std::ptr::eq(first.rule_names(), second.rule_names()));
2664 assert!(std::ptr::eq(first.vocabulary(), second.vocabulary()));
2665 }
2666}
2667
2668#[cfg(test)]
2669mod parser_driver_tests {
2670 const DRIVER_MACRO: &str = "macro_rules! __antlr4_rust_parser_driver";
2674 const ENTRY_POINTS_MACRO: &str = "macro_rules! __antlr4_rust_parser_entry_points";
2675 const TOP_LEVEL_SEMANTIC_SURFACE: &str =
2679 "Some(error) = self.$base.take_unknown_semantic_error()";
2680 const ERR_ARM_SEMANTIC_SURFACE: &str =
2681 "Some(semantic_error) = self.$base.take_unknown_semantic_error()";
2682 const ERR_ARM_START: &str = "::core::result::Result::Err(error) => {";
2683 const ERR_CONVERSION: &str = "let error = error.into_error();";
2684 const ERR_RETURN: &str = "return ::core::result::Result::Err(error);";
2685 const DIAGNOSTICS_DISPATCH: &str = "self.$base.report_generated_parser_diagnostics();";
2686 const ABORT_DRAIN: &str = "Some(abort) = self.$base.take_parse_abort()";
2687 const UNRECOVERED_REPORT: &str = "self.$base.report_unrecovered_parser_error(&error);";
2688 const OK_TREE: &str = "::core::result::Result::Ok(__tree)";
2689 const INTERPRETED_FALLBACK: &str =
2690 "self.parse_interpreted_rule_precedence(rule_index, precedence)?";
2691 const ACTION_DISPATCH: &str = "self.run_action(__action, __tree);";
2692
2693 fn driver_macro_body() -> String {
2697 let source = include_str!("generated.rs");
2698 let driver_at = source
2699 .find(DRIVER_MACRO)
2700 .expect("driver macro is defined in this module");
2701 let entry_points_at = source
2702 .find(ENTRY_POINTS_MACRO)
2703 .expect("entry-points macro is defined in this module");
2704 source[driver_at..entry_points_at]
2705 .split_whitespace()
2706 .collect::<Vec<_>>()
2707 .join(" ")
2708 }
2709
2710 #[test]
2719 fn parser_driver_entry_ordering_invariants() {
2720 let driver = driver_macro_body();
2721
2722 assert_eq!(
2728 driver.matches(TOP_LEVEL_SEMANTIC_SURFACE).count(),
2729 1,
2730 "exactly one top-level surfacing check binds `error`"
2731 );
2732 let surface_at = driver
2733 .find(TOP_LEVEL_SEMANTIC_SURFACE)
2734 .expect("entry surfaces recorded unknown-semantic coordinates");
2735 let ok_at = driver[surface_at..]
2736 .find(OK_TREE)
2737 .map(|offset| surface_at + offset)
2738 .expect("entry returns the tree after semantic checks");
2739 assert!(surface_at < ok_at);
2740
2741 let arm_start = driver
2746 .find(ERR_ARM_START)
2747 .expect("the generated-rule match has an Err arm");
2748 let conversion_at = driver[arm_start..]
2749 .find(ERR_CONVERSION)
2750 .map(|offset| arm_start + offset)
2751 .expect("Err arm converts the generic rule error");
2752 let arm = &driver[arm_start..conversion_at];
2753 let diagnostics_at = arm
2754 .find(DIAGNOSTICS_DISPATCH)
2755 .expect("the fatal Err arm drains retained diagnostics");
2756 let abort_at = arm
2757 .find(ABORT_DRAIN)
2758 .expect("the Err arm drains a recorded parser abort");
2759 let semantic_at = arm
2760 .find(ERR_ARM_SEMANTIC_SURFACE)
2761 .expect("the Err arm drains a recorded semantic error");
2762 assert!(
2763 diagnostics_at < abort_at && abort_at < semantic_at,
2764 "retained diagnostics dispatch first, then parser aborts precede semantic misses"
2765 );
2766
2767 let err_return_at = driver[conversion_at..]
2770 .find(ERR_RETURN)
2771 .map(|offset| conversion_at + offset)
2772 .expect("the Err arm returns the converted error");
2773 assert!(
2774 driver[conversion_at..err_return_at].contains(UNRECOVERED_REPORT),
2775 "the Err arm reports the unrecovered error before returning it"
2776 );
2777
2778 let fallback_at = driver
2785 .find(INTERPRETED_FALLBACK)
2786 .expect("entry runs the interpreted fallback when a rule is not generated");
2787 assert!(
2788 fallback_at < surface_at,
2789 "the surfacing check follows the interpreted fallback"
2790 );
2791 assert!(
2792 driver[fallback_at..surface_at].contains(DIAGNOSTICS_DISPATCH),
2793 "the entry dispatches boundary diagnostics between the fallback and the surfacing check"
2794 );
2795 assert!(
2796 !driver[fallback_at..surface_at].contains(OK_TREE),
2797 "the entry must not return Ok between the interpreted fallback and the surfacing check"
2798 );
2799 assert!(driver.contains(ACTION_DISPATCH));
2800 }
2801}