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
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#[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 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 pub fn remove_error_listeners(&mut self) {
984 $crate::recognizer::Recognizer::remove_error_listeners(&mut self.$base);
985 }
986
987 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 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 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 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 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 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#[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 self.$base.reset_unknown_semantic_hits();
1316 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 if allow_generated_fallback && __report_error {
1340 self.$base.report_generated_parser_diagnostics();
1341 }
1342 if allow_generated_fallback {
1343 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 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 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 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 for __action in __actions {
1432 self.run_action(__action, __tree);
1433 }
1434 ::core::result::Result::Ok(__tree)
1435 }
1436 }
1437 }
1438 };
1439}
1440
1441#[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 #[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 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 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 #[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 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 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 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 #[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 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 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 fn parser_atn() -> &'static ParserAtn;
1745}
1746
1747#[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#[doc(hidden)]
1773#[derive(Debug)]
1774pub enum GeneratedRuleError {
1775 Fatal(AntlrError),
1777 Interpreted(AntlrError),
1779 AdaptiveRetry,
1781}
1782
1783impl GeneratedRuleError {
1784 #[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#[doc(hidden)]
1798pub type GeneratedRuleBody<P> =
1799 fn(&mut P, i32, bool) -> Result<crate::tree::ParseTree, GeneratedRuleError>;
1800
1801#[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#[doc(hidden)]
1848#[derive(Debug)]
1849pub struct AdaptiveAtnRetryState<const RULES: usize> {
1850 pub preferred_rules: [bool; RULES],
1852 pub preference_depths: [usize; RULES],
1854 pub preference_starts: [(usize, usize); RULES],
1856 pub syntax_error_starts: [usize; RULES],
1858 pub retry_slot: Option<usize>,
1860}
1861
1862impl<const RULES: usize> AdaptiveAtnRetryState<RULES> {
1863 #[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 pub const fn reset(&mut self) {
1877 *self = Self::new();
1878 }
1879
1880 #[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#[derive(Debug)]
1905pub struct GeneratedParseOutput<R, P> {
1906 pub result: R,
1908 pub parser: P,
1910}
1911
1912#[doc(hidden)]
1918pub trait __GeneratedParserValidate: Sized {
1919 type Validated;
1921
1922 fn __validate(self, root: NodeId) -> Result<Self::Validated, ValidationError>;
1924}
1925
1926impl<P: __GeneratedParserValidate> GeneratedParseOutput<NodeId, P> {
1927 pub fn validate(self) -> Result<P::Validated, ValidationError> {
1938 self.parser.__validate(self.result)
1939 }
1940}
1941
1942pub 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
1970pub 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#[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#[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#[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 #[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#[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 #[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#[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#[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#[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#[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#[doc(hidden)]
2287#[derive(Clone, Copy, Debug)]
2288pub struct StoredTreeContext;
2289
2290#[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#[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#[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#[doc(hidden)]
2452pub trait __RecoveryContextState {}
2453
2454impl __RecoveryContextState for StoredTreeContext {}
2455impl __RecoveryContextState for __ActiveParserContext {}
2456
2457#[cfg(test)]
2458#[allow(clippy::disallowed_methods)] mod 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 #[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 const DRIVER_MACRO: &str = "macro_rules! __antlr4_rust_parser_driver";
2668 const ENTRY_POINTS_MACRO: &str = "macro_rules! __antlr4_rust_parser_entry_points";
2669 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 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 #[test]
2713 fn parser_driver_entry_ordering_invariants() {
2714 let driver = driver_macro_body();
2715
2716 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 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 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 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}