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`], [`parse_with_parser_constructor`],\n",
1468 "[`parse_stream_with_parser`], or [`parse_stream_with_parser_constructor`].\n\n",
1469 "Keeps the generated parser available after the entry rule runs so callers\n",
1470 "can inspect diagnostics or recover the parser-owned token stream. Alias of\n",
1471 "the runtime's `GeneratedParseOutput` with [`",
1472 ::core::stringify!($parser),
1473 "`] substituted for its parser type parameter. The semantic-hooks type\n",
1474 "defaults to `NoSemanticHooks` for the original entry points.",
1475 )]
1476 pub type $output<R, L, H = $crate::parser::NoSemanticHooks> =
1477 $crate::generated::GeneratedParseOutput<R, $parser<L, H>>;
1478
1479 impl<L, H> $crate::generated::__GeneratedParserIntoParsedFile for $parser<L, H>
1480 where
1481 L: $crate::token::TokenSource,
1482 H: $crate::parser::SemanticHooks,
1483 {
1484 fn __into_parsed_file(
1485 self,
1486 root: $crate::tree::NodeId,
1487 ) -> $crate::tree::ParsedFile {
1488 self.into_parsed_file(root)
1489 }
1490 }
1491
1492 impl<L, H> $crate::generated::__GeneratedParserValidate for $parser<L, H>
1493 where
1494 L: $crate::token::TokenSource,
1495 H: $crate::parser::SemanticHooks,
1496 {
1497 type Validated = $validated;
1498
1499 fn __validate(
1500 self,
1501 root: $crate::tree::NodeId,
1502 ) -> ::core::result::Result<$validated, $crate::validated::ValidationError> {
1503 let lexer = self.token_stream().number_of_source_errors();
1504 let parser = $crate::parser::Parser::number_of_syntax_errors(&self);
1505 if lexer != 0 || parser != 0 {
1506 return ::core::result::Result::Err($validation_error::SyntaxErrors {
1507 lexer,
1508 parser,
1509 });
1510 }
1511 let parsed = self.into_parsed_file(root);
1512 $validate_tree(&parsed)?;
1513 ::core::result::Result::Ok(<$validated>::__new(parsed))
1514 }
1515 }
1516
1517 #[doc = ::core::concat!(
1521 "Pass the generated lexer constructor and a parser entry rule, for example\n",
1522 "`parse(src, MyGrammarLexer::new, ",
1523 ::core::stringify!($parser),
1524 "::file)`.",
1525 )]
1526 pub fn parse<L: $crate::token::TokenSource>(
1535 input: impl ::core::convert::AsRef<str>,
1536 lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1537 entry: impl ::core::ops::FnOnce(
1538 &mut $parser<L>,
1539 ) -> ::core::result::Result<
1540 $crate::tree::NodeId,
1541 $crate::errors::AntlrError,
1542 >,
1543 ) -> ::core::result::Result<$crate::tree::ParsedFile, $crate::errors::AntlrError> {
1544 parse_stream(
1545 $crate::char_stream::InputStream::new(input.as_ref()),
1546 lexer,
1547 entry,
1548 )
1549 }
1550
1551 pub fn parse_validated<L: $crate::token::TokenSource>(
1558 input: impl ::core::convert::AsRef<str>,
1559 lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1560 entry: impl ::core::ops::FnOnce(
1561 &mut $parser<L>,
1562 ) -> ::core::result::Result<
1563 $crate::tree::NodeId,
1564 $crate::errors::AntlrError,
1565 >,
1566 ) -> ::core::result::Result<$validated, $validation_error> {
1567 parse_stream_validated(
1568 $crate::char_stream::InputStream::new(input.as_ref()),
1569 lexer,
1570 entry,
1571 )
1572 }
1573
1574 #[doc = ::core::concat!(
1578 "This keeps the compact generated setup path available for callers that also\n",
1579 "need `Parser::number_of_syntax_errors()` or `",
1580 ::core::stringify!($parser),
1581 "::into_token_stream()`.",
1582 )]
1583 pub fn parse_with_parser<L: $crate::token::TokenSource, R>(
1587 input: impl ::core::convert::AsRef<str>,
1588 lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1589 entry: impl ::core::ops::FnOnce(
1590 &mut $parser<L>,
1591 )
1592 -> ::core::result::Result<R, $crate::errors::AntlrError>,
1593 ) -> ::core::result::Result<$output<R, L>, $crate::errors::AntlrError> {
1594 parse_stream_with_parser(
1595 $crate::char_stream::InputStream::new(input.as_ref()),
1596 lexer,
1597 entry,
1598 )
1599 }
1600
1601 pub fn parse_with_parser_constructor<
1623 L: $crate::token::TokenSource,
1624 H: $crate::parser::SemanticHooks,
1625 R,
1626 >(
1627 input: impl ::core::convert::AsRef<str>,
1628 lexer: impl ::core::ops::FnOnce($crate::char_stream::InputStream) -> L,
1629 parser_constructor: impl ::core::ops::FnOnce(
1630 $crate::token_stream::CommonTokenStream<L>,
1631 ) -> $parser<L, H>,
1632 entry: impl ::core::ops::FnOnce(
1633 &mut $parser<L, H>,
1634 )
1635 -> ::core::result::Result<R, $crate::errors::AntlrError>,
1636 ) -> ::core::result::Result<$output<R, L, H>, $crate::errors::AntlrError> {
1637 parse_stream_with_parser_constructor(
1638 $crate::char_stream::InputStream::new(input.as_ref()),
1639 lexer,
1640 parser_constructor,
1641 entry,
1642 )
1643 }
1644
1645 pub fn parse_stream<I: $crate::char_stream::CharStream, L: $crate::token::TokenSource>(
1656 input: I,
1657 lexer: impl ::core::ops::FnOnce(I) -> L,
1658 entry: impl ::core::ops::FnOnce(
1659 &mut $parser<L>,
1660 ) -> ::core::result::Result<
1661 $crate::tree::NodeId,
1662 $crate::errors::AntlrError,
1663 >,
1664 ) -> ::core::result::Result<$crate::tree::ParsedFile, $crate::errors::AntlrError> {
1665 let output = parse_stream_with_parser(input, lexer, entry)?;
1666 ::core::result::Result::Ok(output.into_parsed_file())
1667 }
1668
1669 pub fn parse_stream_validated<
1675 I: $crate::char_stream::CharStream,
1676 L: $crate::token::TokenSource,
1677 >(
1678 input: I,
1679 lexer: impl ::core::ops::FnOnce(I) -> L,
1680 entry: impl ::core::ops::FnOnce(
1681 &mut $parser<L>,
1682 ) -> ::core::result::Result<
1683 $crate::tree::NodeId,
1684 $crate::errors::AntlrError,
1685 >,
1686 ) -> ::core::result::Result<$validated, $validation_error> {
1687 let output = parse_stream_with_parser(input, lexer, entry)
1688 .map_err($validation_error::Recognition)?;
1689 output.validate()
1690 }
1691
1692 pub fn parse_stream_with_parser<
1698 I: $crate::char_stream::CharStream,
1699 L: $crate::token::TokenSource,
1700 R,
1701 >(
1702 input: I,
1703 lexer: impl ::core::ops::FnOnce(I) -> L,
1704 entry: impl ::core::ops::FnOnce(
1705 &mut $parser<L>,
1706 )
1707 -> ::core::result::Result<R, $crate::errors::AntlrError>,
1708 ) -> ::core::result::Result<$output<R, L>, $crate::errors::AntlrError> {
1709 parse_stream_with_parser_constructor(input, lexer, $parser::new, entry)
1710 }
1711
1712 pub fn parse_stream_with_parser_constructor<
1719 I: $crate::char_stream::CharStream,
1720 L: $crate::token::TokenSource,
1721 H: $crate::parser::SemanticHooks,
1722 R,
1723 >(
1724 input: I,
1725 lexer: impl ::core::ops::FnOnce(I) -> L,
1726 parser_constructor: impl ::core::ops::FnOnce(
1727 $crate::token_stream::CommonTokenStream<L>,
1728 ) -> $parser<L, H>,
1729 entry: impl ::core::ops::FnOnce(
1730 &mut $parser<L, H>,
1731 )
1732 -> ::core::result::Result<R, $crate::errors::AntlrError>,
1733 ) -> ::core::result::Result<$output<R, L, H>, $crate::errors::AntlrError> {
1734 let lexer = lexer(input);
1735 let tokens = $crate::token_stream::CommonTokenStream::new(lexer);
1736 let mut parser = parser_constructor(tokens);
1737 let result = entry(&mut parser)?;
1738 ::core::result::Result::Ok($crate::generated::GeneratedParseOutput { result, parser })
1739 }
1740 };
1741}
1742
1743#[derive(Debug)]
1744pub struct GrammarMetadata {
1745 grammar_file_name: &'static str,
1746 rule_names: &'static [&'static str],
1747 literal_names: &'static [Option<&'static str>],
1748 symbolic_names: &'static [Option<&'static str>],
1749 display_names: &'static [Option<&'static str>],
1750 channel_names: &'static [&'static str],
1751 mode_names: &'static [&'static str],
1752 serialized_atn: &'static [i32],
1753 recognizer_metadata: OnceLock<Arc<RecognizerMetadata>>,
1754}
1755
1756impl Clone for GrammarMetadata {
1757 fn clone(&self) -> Self {
1758 Self {
1759 grammar_file_name: self.grammar_file_name,
1760 rule_names: self.rule_names,
1761 literal_names: self.literal_names,
1762 symbolic_names: self.symbolic_names,
1763 display_names: self.display_names,
1764 channel_names: self.channel_names,
1765 mode_names: self.mode_names,
1766 serialized_atn: self.serialized_atn,
1767 recognizer_metadata: OnceLock::from(Arc::clone(self.cached_recognizer_metadata())),
1768 }
1769 }
1770}
1771
1772impl GrammarMetadata {
1773 #[allow(clippy::too_many_arguments)]
1775 pub const fn new(
1776 grammar_file_name: &'static str,
1777 rule_names: &'static [&'static str],
1778 literal_names: &'static [Option<&'static str>],
1779 symbolic_names: &'static [Option<&'static str>],
1780 display_names: &'static [Option<&'static str>],
1781 channel_names: &'static [&'static str],
1782 mode_names: &'static [&'static str],
1783 serialized_atn: &'static [i32],
1784 ) -> Self {
1785 Self {
1786 grammar_file_name,
1787 rule_names,
1788 literal_names,
1789 symbolic_names,
1790 display_names,
1791 channel_names,
1792 mode_names,
1793 serialized_atn,
1794 recognizer_metadata: OnceLock::new(),
1795 }
1796 }
1797
1798 pub const fn grammar_file_name(&self) -> &'static str {
1799 self.grammar_file_name
1800 }
1801
1802 pub const fn rule_names(&self) -> &'static [&'static str] {
1803 self.rule_names
1804 }
1805
1806 pub const fn channel_names(&self) -> &'static [&'static str] {
1807 self.channel_names
1808 }
1809
1810 pub const fn mode_names(&self) -> &'static [&'static str] {
1811 self.mode_names
1812 }
1813
1814 pub fn vocabulary(&self) -> Vocabulary {
1815 Vocabulary::new(
1816 self.literal_names.iter().copied(),
1817 self.symbolic_names.iter().copied(),
1818 self.display_names.iter().copied(),
1819 )
1820 }
1821
1822 pub fn recognizer_data(&self) -> RecognizerData {
1825 RecognizerData::from_shared(Arc::clone(self.cached_recognizer_metadata()))
1826 }
1827
1828 fn cached_recognizer_metadata(&self) -> &Arc<RecognizerMetadata> {
1829 self.recognizer_metadata.get_or_init(|| {
1830 Arc::new(RecognizerMetadata::from_static(
1831 self.grammar_file_name,
1832 self.rule_names,
1833 self.channel_names,
1834 self.mode_names,
1835 self.vocabulary(),
1836 ))
1837 })
1838 }
1839
1840 pub const fn serialized_atn(&self) -> SerializedAtn<'_> {
1843 SerializedAtn::from_i32(self.serialized_atn)
1844 }
1845}
1846
1847pub trait GeneratedLexer {
1848 fn metadata() -> &'static GrammarMetadata;
1849}
1850
1851pub trait GeneratedParser {
1852 fn metadata() -> &'static GrammarMetadata;
1853
1854 fn parser_atn() -> &'static ParserAtn;
1856}
1857
1858#[doc(hidden)]
1863pub trait GeneratedRuleParser {
1864 type Source: TokenSource;
1865 type Hooks: SemanticHooks;
1866
1867 fn generated_rule_base(&mut self) -> &mut BaseParser<Self::Source, Self::Hooks>;
1868}
1869
1870#[doc(hidden)]
1884#[derive(Debug)]
1885pub enum GeneratedRuleError {
1886 Fatal(AntlrError),
1888 Interpreted(AntlrError),
1890 AdaptiveRetry,
1892}
1893
1894impl GeneratedRuleError {
1895 #[must_use]
1897 pub fn into_error(self) -> AntlrError {
1898 match self {
1899 Self::Fatal(error) | Self::Interpreted(error) => error,
1900 Self::AdaptiveRetry => AntlrError::Unsupported(
1901 "internal adaptive ATN retry escaped its routing boundary".to_owned(),
1902 ),
1903 }
1904 }
1905}
1906
1907#[doc(hidden)]
1909pub type GeneratedRuleBody<P> =
1910 fn(&mut P, i32, bool) -> Result<crate::tree::ParseTree, GeneratedRuleError>;
1911
1912#[doc(hidden)]
1917#[inline(never)]
1918pub fn dispatch_generated_rule<P>(
1919 parser: &mut P,
1920 rule_index: usize,
1921 precedence: i32,
1922 allow_fallback: bool,
1923 body: GeneratedRuleBody<P>,
1924) -> Result<crate::tree::ParseTree, GeneratedRuleError>
1925where
1926 P: GeneratedRuleParser,
1927{
1928 if let Some(error) = parser.generated_rule_base().rule_depth_cap_violation() {
1929 return Err(GeneratedRuleError::Fatal(error));
1930 }
1931 if let Some(error) = parser
1932 .generated_rule_base()
1933 .parse_listener_enter_rule(rule_index)
1934 {
1935 return Err(GeneratedRuleError::Fatal(error));
1936 }
1937 let result = if parser
1938 .generated_rule_base()
1939 .generated_rule_stack_check_due()
1940 {
1941 grow_generated_rule_stack(|| body(parser, precedence, allow_fallback))
1942 } else {
1943 body(parser, precedence, allow_fallback)
1944 };
1945 parser
1946 .generated_rule_base()
1947 .parse_listener_exit_rule(rule_index);
1948 result
1949}
1950
1951#[doc(hidden)]
1959#[derive(Debug)]
1960pub struct AdaptiveAtnRetryState<const RULES: usize> {
1961 pub preferred_rules: [bool; RULES],
1963 pub preference_depths: [usize; RULES],
1965 pub preference_starts: [(usize, usize); RULES],
1967 pub syntax_error_starts: [usize; RULES],
1969 pub retry_slot: Option<usize>,
1971}
1972
1973impl<const RULES: usize> AdaptiveAtnRetryState<RULES> {
1974 #[must_use]
1976 pub const fn new() -> Self {
1977 Self {
1978 preferred_rules: [false; RULES],
1979 preference_depths: [0; RULES],
1980 preference_starts: [(0, 0); RULES],
1981 syntax_error_starts: [0; RULES],
1982 retry_slot: None,
1983 }
1984 }
1985
1986 pub const fn reset(&mut self) {
1988 *self = Self::new();
1989 }
1990
1991 #[must_use]
1996 pub const fn retry_pending(&self) -> bool {
1997 RULES > 0 && self.retry_slot.is_some()
1998 }
1999}
2000
2001impl<const RULES: usize> Default for AdaptiveAtnRetryState<RULES> {
2002 fn default() -> Self {
2003 Self::new()
2004 }
2005}
2006
2007#[derive(Debug)]
2017pub struct GeneratedParseOutput<R, P> {
2018 pub result: R,
2020 pub parser: P,
2022}
2023
2024#[doc(hidden)]
2031pub trait __GeneratedParserIntoParsedFile: Sized {
2032 fn __into_parsed_file(self, root: NodeId) -> crate::tree::ParsedFile;
2034}
2035
2036#[doc(hidden)]
2042pub trait __GeneratedParserValidate: Sized {
2043 type Validated;
2045
2046 fn __validate(self, root: NodeId) -> Result<Self::Validated, ValidationError>;
2048}
2049
2050impl<P: __GeneratedParserIntoParsedFile> GeneratedParseOutput<NodeId, P> {
2051 #[must_use]
2057 pub fn into_parsed_file(self) -> crate::tree::ParsedFile {
2058 self.parser.__into_parsed_file(self.result)
2059 }
2060}
2061
2062impl<P: __GeneratedParserValidate> GeneratedParseOutput<NodeId, P> {
2063 pub fn validate(self) -> Result<P::Validated, ValidationError> {
2074 self.parser.__validate(self.result)
2075 }
2076}
2077
2078pub fn lex<L: TokenSource>(
2100 input: impl AsRef<str>,
2101 lexer: impl FnOnce(InputStream) -> L,
2102) -> CommonTokenStream<L> {
2103 lex_stream(InputStream::new(input.as_ref()), lexer)
2104}
2105
2106pub fn lex_stream<I: CharStream, L: TokenSource>(
2120 input: I,
2121 lexer: impl FnOnce(I) -> L,
2122) -> CommonTokenStream<L> {
2123 CommonTokenStream::new(lexer(input))
2124}
2125
2126#[doc(hidden)]
2137pub struct __GeneratedInput<'a, L: TokenSource>(#[doc(hidden)] pub &'a mut CommonTokenStream<L>);
2138
2139impl<L: TokenSource> __GeneratedInput<'_, L> {
2140 #[must_use]
2141 #[inline]
2142 pub fn text(&self) -> String {
2143 self.0.text_all()
2144 }
2145
2146 #[inline]
2147 pub fn la(&mut self, offset: isize) -> i32 {
2148 IntStream::la(self.0, offset)
2149 }
2150
2151 #[must_use]
2152 #[inline]
2153 pub fn lt(&self, offset: isize) -> __GeneratedTokenView {
2154 __GeneratedTokenView {
2155 text: self
2156 .0
2157 .lt(offset)
2158 .map(|token| token.text_or_empty().to_owned())
2159 .unwrap_or_default(),
2160 }
2161 }
2162}
2163
2164impl<L: TokenSource> fmt::Debug for __GeneratedInput<'_, L> {
2165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2166 f.debug_struct("__GeneratedInput").finish_non_exhaustive()
2167 }
2168}
2169
2170#[doc(hidden)]
2173#[derive(Debug)]
2174pub struct __GeneratedTokenView {
2175 #[doc(hidden)]
2176 pub text: String,
2177}
2178
2179impl __GeneratedTokenView {
2180 #[must_use]
2181 #[inline]
2182 pub fn text(&self) -> &str {
2183 &self.text
2184 }
2185}
2186
2187#[derive(Clone, Debug)]
2194pub struct TerminalNode<'a> {
2195 __node: TerminalNodeView<'a>,
2196}
2197
2198impl<'a> TerminalNode<'a> {
2199 #[doc(hidden)]
2200 #[must_use]
2201 #[inline]
2202 pub const fn new(node: TerminalNodeView<'a>) -> Self {
2203 Self { __node: node }
2204 }
2205
2206 #[must_use]
2207 #[inline]
2208 pub fn symbol(&self) -> TokenView<'a> {
2209 self.__node.symbol()
2210 }
2211
2212 #[must_use]
2213 #[inline]
2214 pub fn is_error(&self) -> bool {
2215 matches!(self.__node.node().kind(), NodeKind::Error)
2216 }
2217
2218 #[must_use]
2219 #[inline]
2220 pub fn is_missing(&self) -> bool {
2221 self.symbol().is_synthetic()
2222 }
2223
2224 #[doc(hidden)]
2226 #[must_use]
2227 #[inline]
2228 pub const fn node(&self) -> Node<'a> {
2229 self.__node.node()
2230 }
2231}
2232
2233impl fmt::Display for TerminalNode<'_> {
2234 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2235 f.write_str(self.__node.text())
2236 }
2237}
2238
2239#[derive(Clone, Debug)]
2242pub struct ErrorNode<'a> {
2243 __node: ErrorNodeView<'a>,
2244}
2245
2246impl<'a> ErrorNode<'a> {
2247 #[doc(hidden)]
2248 #[must_use]
2249 #[inline]
2250 pub const fn new(node: ErrorNodeView<'a>) -> Self {
2251 Self { __node: node }
2252 }
2253
2254 #[must_use]
2255 #[inline]
2256 pub fn symbol(&self) -> TokenView<'a> {
2257 self.__node.symbol()
2258 }
2259
2260 #[must_use]
2261 #[inline]
2262 pub fn is_missing(&self) -> bool {
2263 self.symbol().is_synthetic()
2264 }
2265
2266 #[doc(hidden)]
2268 #[must_use]
2269 #[inline]
2270 pub const fn node(&self) -> Node<'a> {
2271 self.__node.node()
2272 }
2273}
2274
2275impl fmt::Display for ErrorNode<'_> {
2276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2277 f.write_str(self.__node.text())
2278 }
2279}
2280
2281#[doc(hidden)]
2283#[macro_export]
2284macro_rules! __antlr4_rust_generated_walk_callbacks {
2285 (
2286 callbacks: $callbacks:ident,
2287 listener: $listener:ident,
2288 enter: |$enter_listener:ident, $enter_context:ident, $enter_states:ident| $enter_body:block,
2289 exit: |$exit_listener:ident, $exit_context:ident, $exit_states:ident| $exit_body:block,
2290 terminal: |$terminal_listener:ident, $terminal_node:ident| $terminal_body:block,
2291 error: |$error_listener:ident, $error_node:ident| $error_body:block $(,)?
2292 ) => {
2293 #[allow(dead_code)]
2294 struct $callbacks<'listener, T>(&'listener mut T);
2295
2296 impl<E, T: $listener<E>> $crate::generated::GeneratedWalkCallbacks<E>
2297 for $callbacks<'_, T>
2298 {
2299 #[inline(always)]
2300 fn dispatch_enter_rule(
2301 &mut self,
2302 $enter_context: $crate::RuleNodeView<'_>,
2303 $enter_states: ::core::option::Option<&[isize]>,
2304 ) -> ::core::result::Result<(), E> {
2305 let $enter_listener = &mut *self.0;
2306 $enter_body
2307 }
2308
2309 #[inline(always)]
2310 fn dispatch_exit_rule(
2311 &mut self,
2312 $exit_context: $crate::RuleNodeView<'_>,
2313 $exit_states: ::core::option::Option<&[isize]>,
2314 ) -> ::core::result::Result<(), E> {
2315 let $exit_listener = &mut *self.0;
2316 $exit_body
2317 }
2318
2319 #[inline(always)]
2320 fn visit_terminal(
2321 &mut self,
2322 $terminal_node: $crate::TerminalNodeView<'_>,
2323 ) -> ::core::result::Result<(), E> {
2324 let $terminal_listener = &mut *self.0;
2325 $terminal_body
2326 }
2327
2328 #[inline(always)]
2329 fn visit_error_node(
2330 &mut self,
2331 $error_node: $crate::ErrorNodeView<'_>,
2332 ) -> ::core::result::Result<(), E> {
2333 let $error_listener = &mut *self.0;
2334 $error_body
2335 }
2336 }
2337 };
2338}
2339
2340#[doc(hidden)]
2342pub trait GeneratedWalkCallbacks<E> {
2343 fn dispatch_enter_rule(
2344 &mut self,
2345 context: RuleNodeView<'_>,
2346 invocation_states: Option<&[isize]>,
2347 ) -> Result<(), E>;
2348
2349 fn dispatch_exit_rule(
2350 &mut self,
2351 context: RuleNodeView<'_>,
2352 invocation_states: Option<&[isize]>,
2353 ) -> Result<(), E>;
2354
2355 fn visit_terminal(&mut self, node: TerminalNodeView<'_>) -> Result<(), E>;
2356
2357 fn visit_error_node(&mut self, node: ErrorNodeView<'_>) -> Result<(), E>;
2358}
2359
2360#[doc(hidden)]
2363#[inline(always)]
2364pub fn walk_generated<E, C>(
2365 tree: Node<'_>,
2366 mut invocation_states: Option<Vec<isize>>,
2367 callbacks: &mut C,
2368) -> Result<(), E>
2369where
2370 C: GeneratedWalkCallbacks<E>,
2371{
2372 enum Event<'tree> {
2373 Enter(Node<'tree>),
2374 Exit(RuleNodeView<'tree>),
2375 }
2376
2377 let mut stack = vec![Event::Enter(tree)];
2378 while let Some(event) = stack.pop() {
2379 match event {
2380 Event::Enter(node) => match node.kind() {
2381 NodeKind::Rule => {
2382 let context = node.as_rule().expect("rule node kind checked");
2383 if let Some(states) = &mut invocation_states {
2384 states.insert(0, context.invoking_state());
2385 }
2386 callbacks.dispatch_enter_rule(context, invocation_states.as_deref())?;
2387 stack.push(Event::Exit(context));
2388 stack.extend(context.children().rev().map(Event::Enter));
2389 }
2390 NodeKind::Terminal => callbacks
2391 .visit_terminal(node.as_terminal().expect("terminal node kind checked"))?,
2392 NodeKind::Error => {
2393 callbacks
2394 .visit_error_node(node.as_error().expect("error node kind checked"))?;
2395 }
2396 },
2397 Event::Exit(context) => {
2398 callbacks.dispatch_exit_rule(context, invocation_states.as_deref())?;
2399 if let Some(states) = &mut invocation_states {
2400 states.remove(0);
2401 }
2402 }
2403 }
2404 }
2405 Ok(())
2406}
2407
2408#[doc(hidden)]
2411#[derive(Clone, Copy, Debug)]
2412pub enum __GeneratedRuleContext<'a> {
2413 Stored(RuleNodeView<'a>),
2414 Active {
2415 context: &'a ParserRuleContext,
2416 storage: &'a ParseTreeStorage,
2417 tokens: &'a TokenStore,
2418 },
2419}
2420
2421#[doc(hidden)]
2423#[derive(Clone, Copy, Debug)]
2424pub struct StoredTreeContext;
2425
2426#[doc(hidden)]
2428#[derive(Clone, Copy, Debug)]
2429pub struct __ActiveParserContext;
2430
2431#[doc(hidden)]
2432#[inline]
2433pub fn __context_children(
2434 source: __GeneratedRuleContext<'_>,
2435) -> impl Iterator<Item = Node<'_>> + '_ {
2436 let mut stored = match source {
2437 __GeneratedRuleContext::Stored(node) => Some(node.children()),
2438 __GeneratedRuleContext::Active { .. } => None,
2439 };
2440 let mut active = match source {
2441 __GeneratedRuleContext::Stored(_) => None,
2442 __GeneratedRuleContext::Active {
2443 context,
2444 storage,
2445 tokens,
2446 } => Some(context.child_nodes(storage, tokens)),
2447 };
2448 std::iter::from_fn(move || {
2449 stored
2450 .as_mut()
2451 .and_then(Iterator::next)
2452 .or_else(|| active.as_mut().and_then(Iterator::next))
2453 })
2454}
2455
2456#[doc(hidden)]
2457#[inline]
2458pub fn __rule_children(
2459 source: __GeneratedRuleContext<'_>,
2460 rule_index: usize,
2461) -> impl Iterator<Item = RuleNodeView<'_>> + '_ {
2462 __context_children(source).filter_map(move |child| {
2463 let rule = child.as_rule()?;
2464 (rule.rule_index() == rule_index).then_some(rule)
2465 })
2466}
2467
2468#[doc(hidden)]
2469#[inline]
2470pub fn __terminal_children(
2471 source: __GeneratedRuleContext<'_>,
2472) -> impl Iterator<Item = TerminalNodeView<'_>> + '_ {
2473 __context_children(source).filter_map(Node::terminal_view)
2474}
2475
2476#[doc(hidden)]
2477#[inline]
2478pub fn __token_children(
2479 source: __GeneratedRuleContext<'_>,
2480 token_type: i32,
2481) -> impl Iterator<Item = TerminalNodeView<'_>> + '_ {
2482 __terminal_children(source).filter(move |terminal| terminal.symbol().token_type() == token_type)
2483}
2484
2485#[doc(hidden)]
2486#[inline]
2487pub fn __token_children_matching<'a>(
2488 source: __GeneratedRuleContext<'a>,
2489 token_types: &'static [i32],
2490) -> impl Iterator<Item = TerminalNodeView<'a>> + 'a {
2491 __terminal_children(source)
2492 .filter(move |terminal| token_types.contains(&terminal.symbol().token_type()))
2493}
2494
2495#[doc(hidden)]
2496#[inline]
2497pub fn __labeled_token_children(
2498 source: __GeneratedRuleContext<'_>,
2499 token_type: i32,
2500) -> impl Iterator<Item = TerminalNodeView<'_>> + '_ {
2501 __context_children(source).filter_map(move |child| {
2502 let terminal = child.labeled_terminal_view()?;
2503 (terminal.symbol().token_type() == token_type).then_some(terminal)
2504 })
2505}
2506
2507#[doc(hidden)]
2508#[inline]
2509pub fn __labeled_token_children_matching<'a>(
2510 source: __GeneratedRuleContext<'a>,
2511 token_types: &'static [i32],
2512) -> impl Iterator<Item = TerminalNodeView<'a>> + 'a {
2513 __context_children(source).filter_map(move |child| {
2514 let terminal = child.labeled_terminal_view()?;
2515 token_types
2516 .contains(&terminal.symbol().token_type())
2517 .then_some(terminal)
2518 })
2519}
2520
2521#[doc(hidden)]
2524pub trait __FromActiveRuleContext<'a>: Sized {
2525 fn __from_active(
2526 context: &'a ParserRuleContext,
2527 live_attrs: Option<&dyn Any>,
2528 invocation_states: Vec<isize>,
2529 storage: &'a ParseTreeStorage,
2530 tokens: &'a TokenStore,
2531 ) -> Option<Self>;
2532}
2533
2534#[doc(hidden)]
2535#[inline]
2536pub fn __active_context_view<'a, T: __FromActiveRuleContext<'a>>(
2537 context: &'a ParserRuleContext,
2538 invocation_states: Vec<isize>,
2539 storage: &'a ParseTreeStorage,
2540 tokens: &'a TokenStore,
2541) -> Option<T> {
2542 T::__from_active(context, None, invocation_states, storage, tokens)
2543}
2544
2545#[doc(hidden)]
2546#[inline]
2547pub fn __active_context_view_with_attrs<'a, T: __FromActiveRuleContext<'a>>(
2548 context: &'a ParserRuleContext,
2549 live_attrs: &dyn Any,
2550 invocation_states: Vec<isize>,
2551 storage: &'a ParseTreeStorage,
2552 tokens: &'a TokenStore,
2553) -> Option<T> {
2554 T::__from_active(
2555 context,
2556 Some(live_attrs),
2557 invocation_states,
2558 storage,
2559 tokens,
2560 )
2561}
2562
2563#[doc(hidden)]
2566pub fn __write_invocation_states(
2567 f: &mut fmt::Formatter<'_>,
2568 states: impl Iterator<Item = isize>,
2569) -> fmt::Result {
2570 f.write_str("[")?;
2571 let mut separator = "";
2572 for state in states {
2573 write!(f, "{separator}{state}")?;
2574 separator = " ";
2575 }
2576 f.write_str("]")
2577}
2578
2579#[doc(hidden)]
2588pub trait __RecoveryContextState {}
2589
2590impl __RecoveryContextState for StoredTreeContext {}
2591impl __RecoveryContextState for __ActiveParserContext {}
2592
2593#[cfg(test)]
2594#[allow(clippy::disallowed_methods)] mod tests {
2596 use super::*;
2597 use crate::token::{TokenId, TokenSpec};
2598 use crate::tree::ParsedFile;
2599
2600 static META: GrammarMetadata = GrammarMetadata::new(
2601 "Mini.g4",
2602 &["file"],
2603 &[None, Some("'x'")],
2604 &[None, Some("X")],
2605 &[None, None],
2606 &["DEFAULT_TOKEN_CHANNEL", "HIDDEN"],
2607 &["DEFAULT_MODE"],
2608 &[4, 1, 1, 0, 0, 0],
2609 );
2610
2611 fn test_token(store: &mut TokenStore, token_type: i32, text: &str) -> TokenId {
2612 store
2613 .push(TokenSpec::explicit(token_type, text))
2614 .expect("test token should fit")
2615 }
2616
2617 fn generated_walk_test_tree() -> ParsedFile {
2618 let mut tokens = TokenStore::new(None, "");
2619 let a = test_token(&mut tokens, 1, "a");
2620 let b = test_token(&mut tokens, 2, "b");
2621 let error = test_token(&mut tokens, 3, "!");
2622 let mut storage = ParseTreeStorage::new();
2623 let a = storage.terminal(a);
2624 let b = storage.terminal(b);
2625 let error = storage.error(error);
2626 let mut child = ParserRuleContext::new(1, 7);
2627 storage.add_child(&mut child, b);
2628 let child = storage.finish_rule(child);
2629 let mut root = ParserRuleContext::new(0, -1);
2630 storage.add_child(&mut root, a);
2631 storage.add_child(&mut root, child);
2632 storage.add_child(&mut root, error);
2633 let root = storage.finish_rule(root);
2634 ParsedFile::new(tokens, storage, root)
2635 }
2636
2637 #[derive(Default)]
2638 struct RecordingWalkCallbacks {
2639 events: Vec<String>,
2640 fail_on_terminal: Option<&'static str>,
2641 }
2642
2643 impl GeneratedWalkCallbacks<&'static str> for RecordingWalkCallbacks {
2644 fn dispatch_enter_rule(
2645 &mut self,
2646 context: RuleNodeView<'_>,
2647 invocation_states: Option<&[isize]>,
2648 ) -> Result<(), &'static str> {
2649 self.events.push(format!(
2650 "enter rule {} {invocation_states:?}",
2651 context.rule_index()
2652 ));
2653 Ok(())
2654 }
2655
2656 fn dispatch_exit_rule(
2657 &mut self,
2658 context: RuleNodeView<'_>,
2659 invocation_states: Option<&[isize]>,
2660 ) -> Result<(), &'static str> {
2661 self.events.push(format!(
2662 "exit rule {} {invocation_states:?}",
2663 context.rule_index()
2664 ));
2665 Ok(())
2666 }
2667
2668 fn visit_terminal(&mut self, node: TerminalNodeView<'_>) -> Result<(), &'static str> {
2669 self.events.push(format!("terminal {}", node.text()));
2670 if self.fail_on_terminal == Some(node.text()) {
2671 Err("terminal callback failed")
2672 } else {
2673 Ok(())
2674 }
2675 }
2676
2677 fn visit_error_node(&mut self, node: ErrorNodeView<'_>) -> Result<(), &'static str> {
2678 self.events.push(format!("error {}", node.text()));
2679 Ok(())
2680 }
2681 }
2682
2683 #[test]
2684 fn generated_walk_preserves_order_and_invocation_states() {
2685 let parsed = generated_walk_test_tree();
2686 let mut callbacks = RecordingWalkCallbacks::default();
2687
2688 walk_generated(parsed.tree(), Some(vec![99]), &mut callbacks)
2689 .expect("recording callbacks should accept every event");
2690
2691 insta::assert_debug_snapshot!(
2692 "generated_walk_order_and_invocation_states",
2693 callbacks.events
2694 );
2695 }
2696
2697 #[test]
2698 fn generated_walk_short_circuits_callback_errors() {
2699 let parsed = generated_walk_test_tree();
2700 let mut callbacks = RecordingWalkCallbacks {
2701 fail_on_terminal: Some("b"),
2702 ..RecordingWalkCallbacks::default()
2703 };
2704
2705 assert_eq!(
2706 walk_generated(parsed.tree(), None, &mut callbacks),
2707 Err("terminal callback failed")
2708 );
2709 insta::assert_debug_snapshot!("generated_walk_short_circuit", callbacks.events);
2710 }
2711
2712 #[allow(dead_code, unreachable_pub)]
2715 mod facade_hygiene {
2716 struct Box;
2717 struct FnMut;
2718 struct None;
2719 struct Option;
2720 struct Rc;
2721 struct Result;
2722 struct Send;
2723 struct Some;
2724 struct String;
2725 struct Vec;
2726
2727 struct HygieneLexer<I, H> {
2728 base: crate::lexer::BaseLexer<I>,
2729 hooks: H,
2730 }
2731
2732 struct HygieneParser<S, H> {
2733 base: crate::parser::BaseParser<S, H>,
2734 simulator: ::core::option::Option<crate::atn::parser::ParserAtnSimulator<'static>>,
2735 generated_only: bool,
2736 }
2737
2738 fn metadata() -> &'static crate::generated::GrammarMetadata {
2739 &super::META
2740 }
2741
2742 fn parser_atn() -> &'static crate::atn::parser_atn::ParserAtn {
2743 panic!("compile-only facade hygiene fixture")
2744 }
2745
2746 crate::__antlr4_rust_lexer_facade! {
2747 type: HygieneLexer<I, H>,
2748 fields: {
2749 base: base,
2750 hooks: hooks,
2751 },
2752 metadata: metadata,
2753 next_token(_lexer, _sink) {
2754 panic!("compile-only facade hygiene fixture")
2755 }
2756 }
2757
2758 crate::__antlr4_rust_parser_facade! {
2759 type: HygieneParser<S, H>,
2760 fields: {
2761 base: base,
2762 simulator: simulator,
2763 generated_only: generated_only,
2764 },
2765 metadata: metadata,
2766 parser_atn: parser_atn,
2767 reset(_parser) {}
2768 }
2769 }
2770
2771 #[test]
2772 fn metadata_builds_vocabulary() {
2773 assert_eq!(META.grammar_file_name(), "Mini.g4");
2774 assert_eq!(META.vocabulary().display_name(1), "'x'");
2775 }
2776
2777 #[test]
2778 fn cloned_metadata_shares_the_cache_before_explicit_initialization() {
2779 let original = GrammarMetadata::new(
2780 "Clone.g4",
2781 &["start"],
2782 &[None, Some("'x'")],
2783 &[None, Some("X")],
2784 &[None, None],
2785 &["DEFAULT_TOKEN_CHANNEL"],
2786 &["DEFAULT_MODE"],
2787 &[],
2788 );
2789 let cloned = original.clone();
2790 let first = original.recognizer_data();
2791 let second = cloned.recognizer_data();
2792
2793 assert!(std::ptr::eq(first.rule_names(), second.rule_names()));
2794 assert!(std::ptr::eq(first.vocabulary(), second.vocabulary()));
2795 }
2796}
2797
2798#[cfg(test)]
2799mod parser_driver_tests {
2800 const DRIVER_MACRO: &str = "macro_rules! __antlr4_rust_parser_driver";
2804 const ENTRY_POINTS_MACRO: &str = "macro_rules! __antlr4_rust_parser_entry_points";
2805 const TOP_LEVEL_SEMANTIC_SURFACE: &str =
2809 "Some(error) = self.$base.take_unknown_semantic_error()";
2810 const ERR_ARM_SEMANTIC_SURFACE: &str =
2811 "Some(semantic_error) = self.$base.take_unknown_semantic_error()";
2812 const ERR_ARM_START: &str = "::core::result::Result::Err(error) => {";
2813 const ERR_CONVERSION: &str = "let error = error.into_error();";
2814 const ERR_RETURN: &str = "return ::core::result::Result::Err(error);";
2815 const DIAGNOSTICS_DISPATCH: &str = "self.$base.report_generated_parser_diagnostics();";
2816 const ABORT_DRAIN: &str = "Some(abort) = self.$base.take_parse_abort()";
2817 const UNRECOVERED_REPORT: &str = "self.$base.report_unrecovered_parser_error(&error);";
2818 const OK_TREE: &str = "::core::result::Result::Ok(__tree)";
2819 const INTERPRETED_FALLBACK: &str =
2820 "self.parse_interpreted_rule_precedence(rule_index, precedence)?";
2821 const ACTION_DISPATCH: &str = "self.run_action(__action, __tree);";
2822
2823 fn driver_macro_body() -> String {
2827 let source = include_str!("generated.rs");
2828 let driver_at = source
2829 .find(DRIVER_MACRO)
2830 .expect("driver macro is defined in this module");
2831 let entry_points_at = source
2832 .find(ENTRY_POINTS_MACRO)
2833 .expect("entry-points macro is defined in this module");
2834 source[driver_at..entry_points_at]
2835 .split_whitespace()
2836 .collect::<Vec<_>>()
2837 .join(" ")
2838 }
2839
2840 #[test]
2849 fn parser_driver_entry_ordering_invariants() {
2850 let driver = driver_macro_body();
2851
2852 assert_eq!(
2858 driver.matches(TOP_LEVEL_SEMANTIC_SURFACE).count(),
2859 1,
2860 "exactly one top-level surfacing check binds `error`"
2861 );
2862 let surface_at = driver
2863 .find(TOP_LEVEL_SEMANTIC_SURFACE)
2864 .expect("entry surfaces recorded unknown-semantic coordinates");
2865 let ok_at = driver[surface_at..]
2866 .find(OK_TREE)
2867 .map(|offset| surface_at + offset)
2868 .expect("entry returns the tree after semantic checks");
2869 assert!(surface_at < ok_at);
2870
2871 let arm_start = driver
2876 .find(ERR_ARM_START)
2877 .expect("the generated-rule match has an Err arm");
2878 let conversion_at = driver[arm_start..]
2879 .find(ERR_CONVERSION)
2880 .map(|offset| arm_start + offset)
2881 .expect("Err arm converts the generic rule error");
2882 let arm = &driver[arm_start..conversion_at];
2883 let diagnostics_at = arm
2884 .find(DIAGNOSTICS_DISPATCH)
2885 .expect("the fatal Err arm drains retained diagnostics");
2886 let abort_at = arm
2887 .find(ABORT_DRAIN)
2888 .expect("the Err arm drains a recorded parser abort");
2889 let semantic_at = arm
2890 .find(ERR_ARM_SEMANTIC_SURFACE)
2891 .expect("the Err arm drains a recorded semantic error");
2892 assert!(
2893 diagnostics_at < abort_at && abort_at < semantic_at,
2894 "retained diagnostics dispatch first, then parser aborts precede semantic misses"
2895 );
2896
2897 let err_return_at = driver[conversion_at..]
2900 .find(ERR_RETURN)
2901 .map(|offset| conversion_at + offset)
2902 .expect("the Err arm returns the converted error");
2903 assert!(
2904 driver[conversion_at..err_return_at].contains(UNRECOVERED_REPORT),
2905 "the Err arm reports the unrecovered error before returning it"
2906 );
2907
2908 let fallback_at = driver
2915 .find(INTERPRETED_FALLBACK)
2916 .expect("entry runs the interpreted fallback when a rule is not generated");
2917 assert!(
2918 fallback_at < surface_at,
2919 "the surfacing check follows the interpreted fallback"
2920 );
2921 assert!(
2922 driver[fallback_at..surface_at].contains(DIAGNOSTICS_DISPATCH),
2923 "the entry dispatches boundary diagnostics between the fallback and the surfacing check"
2924 );
2925 assert!(
2926 !driver[fallback_at..surface_at].contains(OK_TREE),
2927 "the entry must not return Ok between the interpreted fallback and the surfacing check"
2928 );
2929 assert!(driver.contains(ACTION_DISPATCH));
2930 }
2931}