1use std::sync::{Arc, OnceLock};
2
3use crate::atn::parser_atn::ParserAtn;
4use crate::atn::serialized::SerializedAtn;
5use crate::recognizer::{RecognizerData, RecognizerMetadata};
6use crate::vocabulary::Vocabulary;
7
8#[doc(hidden)]
11#[macro_export]
12macro_rules! __antlr4_rust_context {
13 (
14 pub struct $context:ident {
15 rule_index: $rule_index:expr,
16 context_kind: $kind_mode:ident $(($kind:expr))?,
17 attributes: {
18 $(
19 $attrs:ident {
20 $($field:ident: $field_ty:ty),+ $(,)?
21 }
22 )?
23 },
24 methods: {
25 rule_node: $rule_node_method:ident,
26 child_count: $child_count_method:ident,
27 direct_terminals: $direct_terminals_method:ident,
28 start: $start_method:ident,
29 text: $text_method:ident $(,)?
30 }
31 }
32 ) => {
33 #[allow(non_camel_case_types, dead_code)]
34 #[derive(Clone)]
35 pub struct $context<'a, State = StoredTreeContext> {
36 __node: __GeneratedRuleContext<'a>,
37 __invocation_states: Option<Vec<isize>>,
38 __state: std::marker::PhantomData<State>,
39 $(
40 $(pub $field: $field_ty,)+
41 )?
42 }
43
44 impl<'a> $crate::FromRuleNode<'a> for $context<'a> {
45 fn from_rule_node(node: $crate::RuleNodeView<'a>) -> Option<Self> {
46 if node.rule_index() != $rule_index
47 || $crate::__antlr4_rust_context!(
48 @stored_kind_mismatch $kind_mode $(($kind))?, node
49 )
50 {
51 return None;
52 }
53 Some(Self::__from_node(node))
54 }
55 }
56
57 impl<'a> $crate::AsRuleNode<'a> for $context<'a> {
58 fn as_rule_node(&self) -> $crate::RuleNodeView<'a> {
59 self.$rule_node_method()
60 }
61 }
62
63 impl<'a> $context<'a> {
64 pub fn $rule_node_method(&self) -> $crate::RuleNodeView<'a> {
65 match self.__node {
66 __GeneratedRuleContext::Stored(node) => node,
67 __GeneratedRuleContext::Active { .. } => {
68 unreachable!("stored context type contains an active parser context")
69 }
70 }
71 }
72 }
73
74 impl<'a> __FromActiveRuleContext<'a> for $context<'a, __ActiveParserContext> {
75 fn __from_active(
76 context: &'a $crate::ParserRuleContext,
77 live_attrs: Option<&dyn std::any::Any>,
78 invocation_states: Vec<isize>,
79 storage: &'a $crate::ParseTreeStorage,
80 tokens: &'a $crate::TokenStore,
81 ) -> Option<Self> {
82 if context.rule_index() != $rule_index
83 || $crate::__antlr4_rust_context!(
84 @active_kind_mismatch
85 $kind_mode $(($kind))?,
86 context,
87 storage,
88 tokens
89 )
90 {
91 return None;
92 }
93 $(
94 let __default = <$attrs>::default();
95 let __attrs = match live_attrs {
96 Some(live_attrs) => live_attrs
97 .downcast_ref::<$attrs>()
98 .expect("active context attributes match the parser rule"),
99 None => context
100 .generated_attrs::<$attrs>()
101 .unwrap_or(&__default),
102 };
103 )?
104 Some(Self {
105 __node: __GeneratedRuleContext::Active {
106 context,
107 storage,
108 tokens,
109 },
110 __invocation_states: Some(invocation_states),
111 __state: std::marker::PhantomData,
112 $(
113 $($field: __attrs.$field.clone(),)+
114 )?
115 })
116 }
117 }
118
119 impl<'a> FromValidatedRuleNode<'a> for $context<'a, ValidatedTreeContext> {
120 fn from_validated_rule_node(node: ValidatedRuleNode<'a>) -> Option<Self> {
121 let node = node.rule_node();
122 if node.rule_index() != $rule_index
123 || $crate::__antlr4_rust_context!(
124 @stored_kind_mismatch $kind_mode $(($kind))?, node
125 )
126 {
127 return None;
128 }
129 Some(Self::__from_validated_node(node))
130 }
131 }
132
133 impl<'a> $crate::AsRuleNode<'a> for $context<'a, ValidatedTreeContext> {
134 fn as_rule_node(&self) -> $crate::RuleNodeView<'a> {
135 self.$rule_node_method()
136 }
137 }
138
139 #[allow(dead_code, clippy::all)]
140 impl<'a> $context<'a> {
141 fn __from_node(node: $crate::RuleNodeView<'a>) -> Self {
142 Self::__from_node_with_invocation_states(node, None)
143 }
144
145 fn __from_child_node(
146 node: $crate::RuleNodeView<'a>,
147 parent_invocation_states: Option<&[isize]>,
148 ) -> Self {
149 let invocation_states = parent_invocation_states.map(|states| {
150 let mut invocation_states = Vec::with_capacity(states.len() + 1);
151 invocation_states.push(node.invoking_state());
152 invocation_states.extend_from_slice(states);
153 invocation_states
154 });
155 Self::__from_node_with_invocation_states(node, invocation_states)
156 }
157
158 fn __from_listener_node(
159 node: $crate::RuleNodeView<'a>,
160 invocation_states: Option<&[isize]>,
161 ) -> Self {
162 Self::__from_node_with_invocation_states(
163 node,
164 invocation_states.map(<[isize]>::to_vec),
165 )
166 }
167
168 fn __from_node_with_invocation_states(
169 node: $crate::RuleNodeView<'a>,
170 invocation_states: Option<Vec<isize>>,
171 ) -> Self {
172 $(
173 let __default = <$attrs>::default();
174 let __attrs = node.generated_attrs::<$attrs>().unwrap_or(&__default);
175 )?
176 Self {
177 __node: __GeneratedRuleContext::Stored(node),
178 __invocation_states: invocation_states,
179 __state: std::marker::PhantomData,
180 $(
181 $($field: __attrs.$field.clone(),)+
182 )?
183 }
184 }
185 }
186
187 #[allow(dead_code, clippy::all)]
188 impl<'a, State> $context<'a, State> {
189 pub fn $child_count_method(&self) -> usize {
190 match &self.__node {
191 __GeneratedRuleContext::Stored(node) => node.child_count(),
192 __GeneratedRuleContext::Active { context, .. } => context.child_count(),
193 }
194 }
195
196 pub fn $direct_terminals_method(
205 &self,
206 ) -> impl Iterator<Item = TerminalNode<'a>> + 'a + use<'a, State> {
207 __terminal_children(self.__node).map(TerminalNode::new)
208 }
209
210 pub fn $start_method(&self) -> __GeneratedTokenView {
211 let token = match &self.__node {
212 __GeneratedRuleContext::Stored(node) => node.start(),
213 __GeneratedRuleContext::Active {
214 context, tokens, ..
215 } => context.start(tokens),
216 };
217 __GeneratedTokenView {
218 text: token
219 .map(|token| token.text_or_empty().to_owned())
220 .unwrap_or_default(),
221 }
222 }
223
224 pub fn $text_method(&self) -> String {
225 match &self.__node {
226 __GeneratedRuleContext::Stored(node) => node.text(),
227 __GeneratedRuleContext::Active {
228 context,
229 storage,
230 tokens,
231 } => context.text(storage, tokens),
232 }
233 }
234 }
235
236 #[allow(dead_code, clippy::all)]
237 impl<'a> $context<'a, ValidatedTreeContext> {
238 fn __from_validated_node(node: $crate::RuleNodeView<'a>) -> Self {
239 Self::__from_validated_node_with_invocation_states(node, None)
240 }
241
242 fn __from_validated_child_node(
243 node: $crate::RuleNodeView<'a>,
244 parent_invocation_states: Option<&[isize]>,
245 ) -> Self {
246 let invocation_states = parent_invocation_states.map(|states| {
247 let mut invocation_states = Vec::with_capacity(states.len() + 1);
248 invocation_states.push(node.invoking_state());
249 invocation_states.extend_from_slice(states);
250 invocation_states
251 });
252 Self::__from_validated_node_with_invocation_states(node, invocation_states)
253 }
254
255 fn __from_validated_listener_node(
256 node: $crate::RuleNodeView<'a>,
257 invocation_states: Option<&[isize]>,
258 ) -> Self {
259 Self::__from_validated_node_with_invocation_states(
260 node,
261 invocation_states.map(<[isize]>::to_vec),
262 )
263 }
264
265 fn __from_validated_node_with_invocation_states(
266 node: $crate::RuleNodeView<'a>,
267 invocation_states: Option<Vec<isize>>,
268 ) -> Self {
269 $(
270 let __default = <$attrs>::default();
271 let __attrs = node.generated_attrs::<$attrs>().unwrap_or(&__default);
272 )?
273 Self {
274 __node: __GeneratedRuleContext::Stored(node),
275 __invocation_states: invocation_states,
276 __state: std::marker::PhantomData,
277 $(
278 $($field: __attrs.$field.clone(),)+
279 )?
280 }
281 }
282
283 pub fn $rule_node_method(&self) -> $crate::RuleNodeView<'a> {
284 match self.__node {
285 __GeneratedRuleContext::Stored(node) => node,
286 __GeneratedRuleContext::Active { .. } => {
287 unreachable!("validated context contains an active parser context")
288 }
289 }
290 }
291 }
292
293 impl<State> std::fmt::Display for $context<'_, State> {
294 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
295 match &self.__invocation_states {
296 Some(states) => __write_invocation_states(f, states.iter().copied()),
297 None => match self.__node {
298 __GeneratedRuleContext::Stored(node) => {
299 __write_invocation_states(f, node.invocation_states())
300 }
301 __GeneratedRuleContext::Active { .. } => {
302 unreachable!("active context is missing invocation states")
303 }
304 },
305 }
306 }
307 }
308 };
309 (@stored_kind_mismatch any, $node:expr) => {
310 false
311 };
312 (@stored_kind_mismatch exact($kind:expr), $node:expr) => {
313 __context_kind($node) != $kind
314 };
315 (@active_kind_mismatch any, $context:expr, $storage:expr, $tokens:expr) => {
316 false
317 };
318 (@active_kind_mismatch exact($kind:expr), $context:expr, $storage:expr, $tokens:expr) => {
319 __active_context_kind($context, $storage, $tokens) != $kind
320 };
321}
322
323#[doc(hidden)]
356#[macro_export]
357macro_rules! __antlr4_rust_context_accessors {
358 (
359 $context:ident {
360 $( $kind:tt $method:ident: $card:tt $payload:tt ),* $(,)?
361 }
362 ) => {
363 #[allow(dead_code, private_bounds, clippy::all)]
364 impl<'a, State: __RecoveryContextState> $context<'a, State> {
365 $(
366 $crate::__antlr4_rust_context_accessors!(
367 @recovered $context, $kind $card $method $payload
368 );
369 )*
370 }
371
372 #[allow(dead_code, clippy::all)]
373 impl<'a> $context<'a, ValidatedTreeContext> {
374 $(
375 $crate::__antlr4_rust_context_accessors!(
376 @validated $context, $kind $card $method $payload
377 );
378 )*
379 }
380 };
381
382 (@recovered $context:ident, rule required $method:ident ($child:ident[$index:expr], $name:literal)) => {
384 pub fn $method(&self) -> Result<$child<'a>, $crate::MissingChildError> {
385 __rule_children(self.__node, $index)
386 .next()
387 .map(|node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
388 .ok_or_else(|| $crate::MissingChildError::new(stringify!($context), $name))
389 }
390 };
391 (@recovered $context:ident, rule optional $method:ident ($child:ident[$index:expr])) => {
392 pub fn $method(&self) -> Option<$child<'a>> {
393 __rule_children(self.__node, $index)
394 .next()
395 .map(|node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
396 }
397 };
398 (@recovered $context:ident, rule many $method:ident ($child:ident[$index:expr])) => {
399 pub fn $method(&self) -> impl Iterator<Item = $child<'a>> + '_ {
400 __rule_children(self.__node, $index)
401 .map(move |node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
402 }
403 };
404
405 (@recovered $context:ident, token required $method:ident ($token_type:expr, $name:literal)) => {
407 pub fn $method(&self) -> Result<TerminalNode<'a>, $crate::MissingChildError> {
408 __token_children(self.__node, $token_type)
409 .next()
410 .map(TerminalNode::new)
411 .ok_or_else(|| $crate::MissingChildError::new(stringify!($context), $name))
412 }
413 };
414 (@recovered $context:ident, token optional $method:ident ($token_type:expr)) => {
415 pub fn $method(&self) -> Option<TerminalNode<'a>> {
416 __token_children(self.__node, $token_type)
417 .next()
418 .map(TerminalNode::new)
419 }
420 };
421 (@recovered $context:ident, token many $method:ident ($token_type:expr)) => {
422 pub fn $method(&self) -> impl Iterator<Item = TerminalNode<'a>> + '_ {
423 __token_children(self.__node, $token_type).map(TerminalNode::new)
424 }
425 };
426
427 (@recovered $context:ident, label_rule required $method:ident ($sel:ident($selarg:expr), $child:ident[$index:expr], $name:literal)) => {
429 pub fn $method(&self) -> Result<$child<'a>, $crate::MissingChildError> {
430 $crate::__antlr4_rust_context_accessors!(
431 @selected(__rule_children(self.__node, $index)) $sel($selarg)
432 )
433 .map(|node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
434 .ok_or_else(|| $crate::MissingChildError::new(stringify!($context), $name))
435 }
436 };
437 (@recovered $context:ident, label_rule optional $method:ident ($sel:ident($selarg:expr), $child:ident[$index:expr])) => {
438 pub fn $method(&self) -> Option<$child<'a>> {
439 $crate::__antlr4_rust_context_accessors!(
440 @selected(__rule_children(self.__node, $index)) $sel($selarg)
441 )
442 .map(|node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
443 }
444 };
445 (@recovered $context:ident, label_rule many $method:ident (skip($skip:expr), $child:ident[$index:expr])) => {
446 pub fn $method(&self) -> impl Iterator<Item = $child<'a>> + '_ {
447 __rule_children(self.__node, $index)
448 .skip($skip)
449 .map(move |node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
450 }
451 };
452
453 (@recovered $context:ident, label_token required $method:ident ($sel:ident($selarg:expr), $tokens:tt, $name:literal)) => {
455 pub fn $method(&self) -> Result<TerminalNode<'a>, $crate::MissingChildError> {
456 $crate::__antlr4_rust_context_accessors!(
457 @selected($crate::__antlr4_rust_context_accessors!(
458 @labeled_token_children(self.__node) $tokens
459 )) $sel($selarg)
460 )
461 .map(TerminalNode::new)
462 .ok_or_else(|| $crate::MissingChildError::new(stringify!($context), $name))
463 }
464 };
465 (@recovered $context:ident, label_token optional $method:ident ($sel:ident($selarg:expr), $tokens:tt)) => {
466 pub fn $method(&self) -> Option<TerminalNode<'a>> {
467 $crate::__antlr4_rust_context_accessors!(
468 @selected($crate::__antlr4_rust_context_accessors!(
469 @labeled_token_children(self.__node) $tokens
470 )) $sel($selarg)
471 )
472 .map(TerminalNode::new)
473 }
474 };
475 (@recovered $context:ident, label_token many $method:ident (skip($skip:expr), $tokens:tt)) => {
476 pub fn $method(&self) -> impl Iterator<Item = TerminalNode<'a>> + '_ {
477 $crate::__antlr4_rust_context_accessors!(
478 @labeled_token_children(self.__node) $tokens
479 )
480 .skip($skip)
481 .map(TerminalNode::new)
482 }
483 };
484
485 (@validated $context:ident, rule required $method:ident ($child:ident[$index:expr], $name:literal)) => {
487 pub fn $method(&self) -> $child<'a, ValidatedTreeContext> {
488 let Some(node) = __rule_children(self.__node, $index).next() else {
489 unreachable!(concat!(
490 "validated ",
491 stringify!($context),
492 " is missing required child ",
493 $name
494 ))
495 };
496 $child::<ValidatedTreeContext>::__from_validated_child_node(
497 node,
498 self.__invocation_states.as_deref(),
499 )
500 }
501 };
502 (@validated $context:ident, rule optional $method:ident ($child:ident[$index:expr])) => {
503 pub fn $method(&self) -> Option<$child<'a, ValidatedTreeContext>> {
504 __rule_children(self.__node, $index)
505 .next()
506 .map(|node| {
507 $child::<ValidatedTreeContext>::__from_validated_child_node(
508 node,
509 self.__invocation_states.as_deref(),
510 )
511 })
512 }
513 };
514 (@validated $context:ident, rule many $method:ident ($child:ident[$index:expr])) => {
515 pub fn $method(&self) -> impl Iterator<Item = $child<'a, ValidatedTreeContext>> + '_ {
516 __rule_children(self.__node, $index).map(move |node| {
517 $child::<ValidatedTreeContext>::__from_validated_child_node(
518 node,
519 self.__invocation_states.as_deref(),
520 )
521 })
522 }
523 };
524
525 (@validated $context:ident, token required $method:ident ($token_type:expr, $name:literal)) => {
527 pub fn $method(&self) -> TerminalNode<'a> {
528 let Some(node) = __token_children(self.__node, $token_type).next() else {
529 unreachable!(concat!(
530 "validated ",
531 stringify!($context),
532 " is missing required child ",
533 $name
534 ))
535 };
536 TerminalNode::new(node)
537 }
538 };
539 (@validated $context:ident, token optional $method:ident ($token_type:expr)) => {
540 pub fn $method(&self) -> Option<TerminalNode<'a>> {
541 __token_children(self.__node, $token_type)
542 .next()
543 .map(TerminalNode::new)
544 }
545 };
546 (@validated $context:ident, token many $method:ident ($token_type:expr)) => {
547 pub fn $method(&self) -> impl Iterator<Item = TerminalNode<'a>> + '_ {
548 __token_children(self.__node, $token_type).map(TerminalNode::new)
549 }
550 };
551
552 (@validated $context:ident, label_rule required $method:ident ($sel:ident($selarg:expr), $child:ident[$index:expr], $name:literal)) => {
554 pub fn $method(&self) -> $child<'a, ValidatedTreeContext> {
555 let Some(node) = $crate::__antlr4_rust_context_accessors!(
556 @selected(__rule_children(self.__node, $index)) $sel($selarg)
557 ) else {
558 unreachable!(concat!(
559 "validated ",
560 stringify!($context),
561 " is missing required child ",
562 $name
563 ))
564 };
565 $child::<ValidatedTreeContext>::__from_validated_child_node(
566 node,
567 self.__invocation_states.as_deref(),
568 )
569 }
570 };
571 (@validated $context:ident, label_rule optional $method:ident ($sel:ident($selarg:expr), $child:ident[$index:expr])) => {
572 pub fn $method(&self) -> Option<$child<'a, ValidatedTreeContext>> {
573 $crate::__antlr4_rust_context_accessors!(
574 @selected(__rule_children(self.__node, $index)) $sel($selarg)
575 )
576 .map(|node| {
577 $child::<ValidatedTreeContext>::__from_validated_child_node(
578 node,
579 self.__invocation_states.as_deref(),
580 )
581 })
582 }
583 };
584 (@validated $context:ident, label_rule many $method:ident (skip($skip:expr), $child:ident[$index:expr])) => {
585 pub fn $method(&self) -> impl Iterator<Item = $child<'a, ValidatedTreeContext>> + '_ {
586 __rule_children(self.__node, $index)
587 .skip($skip)
588 .map(move |node| {
589 $child::<ValidatedTreeContext>::__from_validated_child_node(
590 node,
591 self.__invocation_states.as_deref(),
592 )
593 })
594 }
595 };
596
597 (@validated $context:ident, label_token required $method:ident ($sel:ident($selarg:expr), $tokens:tt, $name:literal)) => {
599 pub fn $method(&self) -> TerminalNode<'a> {
600 let Some(node) = $crate::__antlr4_rust_context_accessors!(
601 @selected($crate::__antlr4_rust_context_accessors!(
602 @labeled_token_children(self.__node) $tokens
603 )) $sel($selarg)
604 ) else {
605 unreachable!(concat!(
606 "validated ",
607 stringify!($context),
608 " is missing required child ",
609 $name
610 ))
611 };
612 TerminalNode::new(node)
613 }
614 };
615 (@validated $context:ident, label_token optional $method:ident ($sel:ident($selarg:expr), $tokens:tt)) => {
616 pub fn $method(&self) -> Option<TerminalNode<'a>> {
617 $crate::__antlr4_rust_context_accessors!(
618 @selected($crate::__antlr4_rust_context_accessors!(
619 @labeled_token_children(self.__node) $tokens
620 )) $sel($selarg)
621 )
622 .map(TerminalNode::new)
623 }
624 };
625 (@validated $context:ident, label_token many $method:ident (skip($skip:expr), $tokens:tt)) => {
626 pub fn $method(&self) -> impl Iterator<Item = TerminalNode<'a>> + '_ {
627 $crate::__antlr4_rust_context_accessors!(
628 @labeled_token_children(self.__node) $tokens
629 )
630 .skip($skip)
631 .map(TerminalNode::new)
632 }
633 };
634
635 (@selected($children:expr) nth($occurrence:expr)) => {
637 $children.nth($occurrence)
638 };
639 (@selected($children:expr) last_after($skip:expr)) => {
640 $children.skip($skip).last()
641 };
642
643 (@labeled_token_children($node:expr) [$token_type:expr]) => {
646 __labeled_token_children($node, $token_type)
647 };
648 (@labeled_token_children($node:expr) [$($token_type:expr),+ $(,)?]) => {
649 __labeled_token_children_matching($node, &[$($token_type),+])
650 };
651
652 (@recovered $context:ident, $kind:tt $card:tt $method:ident $payload:tt) => {
657 compile_error!(concat!(
658 "unsupported generated accessor declaration for ",
659 stringify!($context),
660 ": ",
661 stringify!($kind),
662 " ",
663 stringify!($method),
664 ": ",
665 stringify!($card),
666 stringify!($payload)
667 ));
668 };
669 (@validated $context:ident, $kind:tt $card:tt $method:ident $payload:tt) => {
670 compile_error!(concat!(
671 "unsupported generated accessor declaration for ",
672 stringify!($context),
673 ": ",
674 stringify!($kind),
675 " ",
676 stringify!($method),
677 ": ",
678 stringify!($card),
679 stringify!($payload)
680 ));
681 };
682 (@recovered $context:ident, $($declaration:tt)*) => {
683 compile_error!(concat!(
684 "unsupported generated accessor declaration for ",
685 stringify!($context),
686 ": ",
687 stringify!($($declaration)*)
688 ));
689 };
690 (@validated $context:ident, $($declaration:tt)*) => {
691 compile_error!(concat!(
692 "unsupported generated accessor declaration for ",
693 stringify!($context),
694 ": ",
695 stringify!($($declaration)*)
696 ));
697 };
698 (@selected($children:expr) $($selector:tt)*) => {
699 compile_error!(concat!(
700 "unsupported generated accessor selector: ",
701 stringify!($($selector)*)
702 ))
703 };
704 (@labeled_token_children($node:expr) $($tokens:tt)*) => {
705 compile_error!(concat!(
706 "unsupported generated accessor token set: ",
707 stringify!($($tokens)*)
708 ))
709 };
710}
711
712#[doc(hidden)]
715#[macro_export]
716macro_rules! __antlr4_rust_lexer_facade {
717 (
718 type: $lexer:ident<$input:ident, $hooks:ident>,
719 fields: {
720 base: $base:ident,
721 hooks: $hooks_field:ident $(,)?
722 },
723 metadata: $metadata:path,
724 next_token($this:ident, $sink:ident) $next_token:block
725 $(,)?
726 ) => {
727 impl<$input, $hooks> $lexer<$input, $hooks>
728 where
729 $input: $crate::char_stream::CharStream,
730 $hooks: $crate::parser::SemanticHooks,
731 {
732 pub fn metadata() -> &'static $crate::generated::GrammarMetadata {
733 $metadata()
734 }
735
736 pub fn add_error_listener<T>(&mut self, listener: T)
738 where
739 T: for<'a> $crate::errors::ErrorListener<dyn $crate::recognizer::Recognizer + 'a>
740 + ::core::marker::Send
741 + 'static,
742 {
743 $crate::recognizer::Recognizer::add_error_listener(&mut self.$base, listener);
744 }
745
746 pub fn remove_error_listeners(&mut self) {
748 $crate::recognizer::Recognizer::remove_error_listeners(&mut self.$base);
749 }
750
751 pub fn set_force_interpreted(&mut self, force_interpreted: bool) {
755 self.$base.set_force_interpreted(force_interpreted);
756 }
757
758 pub fn reset(&mut self) {
760 if <$hooks as $crate::parser::SemanticHooks>::ENABLES_LEXER_LIFECYCLE {
761 $crate::atn::lexer::reset_with_semantic_hooks(
762 &mut self.$base,
763 &mut self.$hooks_field,
764 );
765 } else {
766 self.$base.reset();
767 }
768 }
769
770 pub fn set_input_stream(&mut self, input: $input) {
772 if <$hooks as $crate::parser::SemanticHooks>::ENABLES_LEXER_LIFECYCLE {
773 $crate::atn::lexer::set_input_stream_with_semantic_hooks(
774 &mut self.$base,
775 &mut self.$hooks_field,
776 input,
777 );
778 } else {
779 self.$base.set_input_stream(input);
780 }
781 }
782
783 pub fn clear_dfa(&self) {
785 self.$base.clear_dfa();
786 }
787 }
788
789 impl<$input, $hooks> $crate::generated::GeneratedLexer for $lexer<$input, $hooks>
790 where
791 $input: $crate::char_stream::CharStream,
792 $hooks: $crate::parser::SemanticHooks,
793 {
794 fn metadata() -> &'static $crate::generated::GrammarMetadata {
795 $metadata()
796 }
797 }
798
799 impl<$input, $hooks> $crate::recognizer::Recognizer for $lexer<$input, $hooks>
800 where
801 $input: $crate::char_stream::CharStream,
802 $hooks: $crate::parser::SemanticHooks,
803 {
804 fn data(&self) -> &$crate::recognizer::RecognizerData {
805 $crate::recognizer::Recognizer::data(&self.$base)
806 }
807
808 fn data_mut(&mut self) -> &mut $crate::recognizer::RecognizerData {
809 $crate::recognizer::Recognizer::data_mut(&mut self.$base)
810 }
811 }
812
813 impl<$input, $hooks> $crate::lexer::Lexer for $lexer<$input, $hooks>
814 where
815 $input: $crate::char_stream::CharStream,
816 $hooks: $crate::parser::SemanticHooks,
817 {
818 fn mode(&self) -> i32 {
819 $crate::lexer::Lexer::mode(&self.$base)
820 }
821
822 fn set_mode(&mut self, mode: i32) {
823 $crate::lexer::Lexer::set_mode(&mut self.$base, mode);
824 }
825
826 fn push_mode(&mut self, mode: i32) {
827 $crate::lexer::Lexer::push_mode(&mut self.$base, mode);
828 }
829
830 fn pop_mode(&mut self) -> ::core::option::Option<i32> {
831 $crate::lexer::Lexer::pop_mode(&mut self.$base)
832 }
833 }
834
835 impl<$input, $hooks> $crate::token::TokenSource for $lexer<$input, $hooks>
836 where
837 $input: $crate::char_stream::CharStream,
838 $hooks: $crate::parser::SemanticHooks,
839 {
840 fn next_token(
841 &mut self,
842 $sink: &mut $crate::token::TokenSink<'_>,
843 ) -> ::core::result::Result<$crate::token::TokenId, $crate::token::TokenStoreError>
844 {
845 let $this = self;
846 $next_token
847 }
848
849 fn line(&self) -> usize {
850 self.$base.line()
851 }
852
853 fn column(&self) -> usize {
854 self.$base.column()
855 }
856
857 fn source_name(&self) -> &str {
858 self.$base.source_name()
859 }
860
861 fn source_text(&self) -> ::core::option::Option<::std::rc::Rc<str>> {
862 self.$base.source_text()
863 }
864
865 fn drain_errors(&mut self) -> ::std::vec::Vec<$crate::token::TokenSourceError> {
866 self.$base.drain_errors()
867 }
868
869 fn report_error(&self, source_error: &$crate::token::TokenSourceError) -> bool {
870 $crate::recognizer::Recognizer::notify_error_listeners(self, source_error.into());
871 true
872 }
873
874 fn lexer_dfa_string(&self) -> ::std::string::String {
875 self.$base.lexer_dfa_string()
876 }
877 }
878 };
879}
880
881#[doc(hidden)]
884#[macro_export]
885macro_rules! __antlr4_rust_parser_facade {
886 (
887 type: $parser:ident<$source:ident, $hooks:ident>,
888 fields: {
889 base: $base:ident,
890 simulator: $simulator:ident,
891 generated_only: $generated_only:ident $(,)?
892 },
893 metadata: $metadata:path,
894 parser_atn: $parser_atn:path,
895 reset($this:ident) $reset:block
896 $(,)?
897 ) => {
898 impl<$source, $hooks> $parser<$source, $hooks>
899 where
900 $source: $crate::token::TokenSource,
901 $hooks: $crate::parser::SemanticHooks,
902 {
903 pub fn metadata() -> &'static $crate::generated::GrammarMetadata {
904 $metadata()
905 }
906
907 pub fn add_error_listener<T>(&mut self, listener: T)
909 where
910 T: for<'a> $crate::errors::ErrorListener<dyn $crate::recognizer::Recognizer + 'a>
911 + ::core::marker::Send
912 + 'static,
913 {
914 $crate::recognizer::Recognizer::add_error_listener(&mut self.$base, listener);
915 }
916
917 pub fn remove_error_listeners(&mut self) {
919 $crate::recognizer::Recognizer::remove_error_listeners(&mut self.$base);
920 }
921
922 pub fn add_parse_listener<T>(&mut self, listener: T)
926 where
927 T: $crate::parser::ParseListener + 'static,
928 {
929 self.$base.add_parse_listener(listener);
930 }
931
932 pub fn remove_parse_listeners(
935 &mut self,
936 ) -> ::std::vec::Vec<::std::boxed::Box<dyn $crate::parser::ParseListener>> {
937 self.$base.remove_parse_listeners()
938 }
939
940 pub fn reset(&mut self) {
942 self.$base.reset();
943 if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
944 simulator.reset();
945 }
946 let $this = &mut *self;
947 $reset
948 }
949
950 pub fn set_token_stream(
952 &mut self,
953 input: $crate::token_stream::CommonTokenStream<$source>,
954 ) {
955 self.$base.set_token_stream(input);
956 if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
957 simulator.reset();
958 }
959 let $this = &mut *self;
960 $reset
961 }
962
963 #[must_use]
964 pub const fn token_stream(&self) -> &$crate::token_stream::CommonTokenStream<$source> {
965 self.$base.token_stream()
966 }
967
968 #[must_use]
969 pub const fn token_stream_mut(
970 &mut self,
971 ) -> &mut $crate::token_stream::CommonTokenStream<$source> {
972 self.$base.token_stream_mut()
973 }
974
975 #[must_use]
976 pub const fn token_store(&self) -> &$crate::token::TokenStore {
977 self.$base.token_store()
978 }
979
980 #[must_use]
981 pub const fn parse_tree_storage(&self) -> &$crate::tree::ParseTreeStorage {
982 self.$base.parse_tree_storage()
983 }
984
985 #[must_use]
986 pub fn prediction_context_stats(&self) -> $crate::prediction::PredictionContextStats {
987 self.$simulator.as_ref().map_or_else(
988 $crate::prediction::PredictionContextStats::default,
989 $crate::atn::parser::ParserAtnSimulator::prediction_context_stats,
990 )
991 }
992
993 #[must_use]
994 pub fn parser_dfa_stats(&self) -> $crate::dfa::ParserDfaStats {
995 self.$simulator.as_ref().map_or_else(
996 $crate::dfa::ParserDfaStats::default,
997 $crate::atn::parser::ParserAtnSimulator::parser_dfa_stats,
998 )
999 }
1000
1001 pub fn clear_dfa(&mut self) {
1003 if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
1004 simulator.clear_dfa();
1005 } else {
1006 $crate::atn::parser::ParserAtnSimulator::clear_shared_dfa($parser_atn());
1007 }
1008 let $this = &mut *self;
1009 $reset
1010 }
1011
1012 #[must_use]
1013 pub fn node(&self, id: $crate::tree::NodeId) -> $crate::tree::Node<'_> {
1014 self.$base.node(id)
1015 }
1016
1017 #[must_use]
1018 pub fn into_token_stream(self) -> $crate::token_stream::CommonTokenStream<$source> {
1019 self.$base.into_token_stream()
1020 }
1021
1022 #[must_use]
1023 pub fn into_token_store(self) -> $crate::token::TokenStore {
1024 self.$base.into_token_store()
1025 }
1026
1027 #[must_use]
1028 pub fn into_parsed_file(self, root: $crate::tree::NodeId) -> $crate::tree::ParsedFile {
1029 self.$base.into_parsed_file(root)
1030 }
1031
1032 pub fn compile_parse_tree_pattern<PL>(
1037 &self,
1038 pattern: &str,
1039 rule_index: usize,
1040 mut make_lexer: impl ::core::ops::FnMut($crate::char_stream::InputStream) -> PL,
1041 ) -> ::core::result::Result<
1042 $crate::tree_pattern::ParseTreePattern,
1043 $crate::tree_pattern::ParseTreePatternError,
1044 >
1045 where
1046 PL: $crate::token::TokenSource,
1047 {
1048 static PATTERN_DATA: ::std::sync::OnceLock<$crate::recognizer::RecognizerData> =
1049 ::std::sync::OnceLock::new();
1050 static PATTERN_MATCHER: ::std::sync::OnceLock<
1051 $crate::tree_pattern::ParseTreePatternMatcher<'static>,
1052 > = ::std::sync::OnceLock::new();
1053 let matcher = match PATTERN_MATCHER.get() {
1054 ::core::option::Option::Some(matcher) => matcher,
1055 ::core::option::Option::None => {
1056 let data = PATTERN_DATA.get_or_init(|| $metadata().recognizer_data());
1057 let matcher = $crate::tree_pattern::ParseTreePatternMatcher::new(
1058 $parser_atn(),
1059 data,
1060 )?;
1061 PATTERN_MATCHER.get_or_init(|| matcher)
1062 }
1063 };
1064 matcher.compile(pattern, rule_index, move |text: &str| {
1065 $crate::tree_pattern::lex_pattern_chunk(text, &mut make_lexer)
1066 })
1067 }
1068
1069 #[allow(dead_code)]
1070 fn simulator(&mut self) -> &mut $crate::atn::parser::ParserAtnSimulator<'static> {
1071 self.$simulator.get_or_insert_with(|| {
1072 $crate::atn::parser::ParserAtnSimulator::new_shared($parser_atn())
1073 })
1074 }
1075
1076 #[allow(dead_code)]
1077 fn generated_only(&self) -> bool {
1078 self.$generated_only
1079 }
1080 }
1081
1082 impl<$source, $hooks> $crate::generated::GeneratedParser for $parser<$source, $hooks>
1083 where
1084 $source: $crate::token::TokenSource,
1085 $hooks: $crate::parser::SemanticHooks,
1086 {
1087 fn metadata() -> &'static $crate::generated::GrammarMetadata {
1088 $metadata()
1089 }
1090
1091 fn parser_atn() -> &'static $crate::atn::parser_atn::ParserAtn {
1092 $parser_atn()
1093 }
1094 }
1095
1096 impl<$source, $hooks> $crate::recognizer::Recognizer for $parser<$source, $hooks>
1097 where
1098 $source: $crate::token::TokenSource,
1099 $hooks: $crate::parser::SemanticHooks,
1100 {
1101 fn data(&self) -> &$crate::recognizer::RecognizerData {
1102 $crate::recognizer::Recognizer::data(&self.$base)
1103 }
1104
1105 fn data_mut(&mut self) -> &mut $crate::recognizer::RecognizerData {
1106 $crate::recognizer::Recognizer::data_mut(&mut self.$base)
1107 }
1108 }
1109
1110 impl<$source, $hooks> $crate::parser::Parser for $parser<$source, $hooks>
1111 where
1112 $source: $crate::token::TokenSource,
1113 $hooks: $crate::parser::SemanticHooks,
1114 {
1115 fn build_parse_trees(&self) -> bool {
1116 $crate::parser::Parser::build_parse_trees(&self.$base)
1117 }
1118
1119 fn set_build_parse_trees(&mut self, build: bool) {
1120 $crate::parser::Parser::set_build_parse_trees(&mut self.$base, build);
1121 }
1122
1123 fn number_of_syntax_errors(&self) -> usize {
1124 $crate::parser::Parser::number_of_syntax_errors(&self.$base)
1125 }
1126
1127 fn report_diagnostic_errors(&self) -> bool {
1128 $crate::parser::Parser::report_diagnostic_errors(&self.$base)
1129 }
1130
1131 fn set_report_diagnostic_errors(&mut self, report: bool) {
1132 $crate::parser::Parser::set_report_diagnostic_errors(&mut self.$base, report);
1133 }
1134
1135 fn prediction_mode(&self) -> $crate::parser::PredictionMode {
1136 $crate::parser::Parser::prediction_mode(&self.$base)
1137 }
1138
1139 fn set_prediction_mode(&mut self, mode: $crate::parser::PredictionMode) {
1140 $crate::parser::Parser::set_prediction_mode(&mut self.$base, mode);
1141 }
1142
1143 fn max_rule_depth(&self) -> ::core::option::Option<usize> {
1144 $crate::parser::Parser::max_rule_depth(&self.$base)
1145 }
1146
1147 fn set_max_rule_depth(&mut self, depth: ::core::option::Option<usize>) {
1148 $crate::parser::Parser::set_max_rule_depth(&mut self.$base, depth);
1149 }
1150
1151 fn add_parse_listener(
1152 &mut self,
1153 listener: ::std::boxed::Box<dyn $crate::parser::ParseListener>,
1154 ) {
1155 $crate::parser::Parser::add_parse_listener(&mut self.$base, listener);
1156 }
1157
1158 fn remove_parse_listeners(
1159 &mut self,
1160 ) -> ::std::vec::Vec<::std::boxed::Box<dyn $crate::parser::ParseListener>> {
1161 $crate::parser::Parser::remove_parse_listeners(&mut self.$base)
1162 }
1163 }
1164 };
1165}
1166
1167#[derive(Debug)]
1168pub struct GrammarMetadata {
1169 grammar_file_name: &'static str,
1170 rule_names: &'static [&'static str],
1171 literal_names: &'static [Option<&'static str>],
1172 symbolic_names: &'static [Option<&'static str>],
1173 display_names: &'static [Option<&'static str>],
1174 channel_names: &'static [&'static str],
1175 mode_names: &'static [&'static str],
1176 serialized_atn: &'static [i32],
1177 recognizer_metadata: OnceLock<Arc<RecognizerMetadata>>,
1178}
1179
1180impl Clone for GrammarMetadata {
1181 fn clone(&self) -> Self {
1182 Self {
1183 grammar_file_name: self.grammar_file_name,
1184 rule_names: self.rule_names,
1185 literal_names: self.literal_names,
1186 symbolic_names: self.symbolic_names,
1187 display_names: self.display_names,
1188 channel_names: self.channel_names,
1189 mode_names: self.mode_names,
1190 serialized_atn: self.serialized_atn,
1191 recognizer_metadata: OnceLock::from(Arc::clone(self.cached_recognizer_metadata())),
1192 }
1193 }
1194}
1195
1196impl GrammarMetadata {
1197 #[allow(clippy::too_many_arguments)]
1199 pub const fn new(
1200 grammar_file_name: &'static str,
1201 rule_names: &'static [&'static str],
1202 literal_names: &'static [Option<&'static str>],
1203 symbolic_names: &'static [Option<&'static str>],
1204 display_names: &'static [Option<&'static str>],
1205 channel_names: &'static [&'static str],
1206 mode_names: &'static [&'static str],
1207 serialized_atn: &'static [i32],
1208 ) -> Self {
1209 Self {
1210 grammar_file_name,
1211 rule_names,
1212 literal_names,
1213 symbolic_names,
1214 display_names,
1215 channel_names,
1216 mode_names,
1217 serialized_atn,
1218 recognizer_metadata: OnceLock::new(),
1219 }
1220 }
1221
1222 pub const fn grammar_file_name(&self) -> &'static str {
1223 self.grammar_file_name
1224 }
1225
1226 pub const fn rule_names(&self) -> &'static [&'static str] {
1227 self.rule_names
1228 }
1229
1230 pub const fn channel_names(&self) -> &'static [&'static str] {
1231 self.channel_names
1232 }
1233
1234 pub const fn mode_names(&self) -> &'static [&'static str] {
1235 self.mode_names
1236 }
1237
1238 pub fn vocabulary(&self) -> Vocabulary {
1239 Vocabulary::new(
1240 self.literal_names.iter().copied(),
1241 self.symbolic_names.iter().copied(),
1242 self.display_names.iter().copied(),
1243 )
1244 }
1245
1246 pub fn recognizer_data(&self) -> RecognizerData {
1249 RecognizerData::from_shared(Arc::clone(self.cached_recognizer_metadata()))
1250 }
1251
1252 fn cached_recognizer_metadata(&self) -> &Arc<RecognizerMetadata> {
1253 self.recognizer_metadata.get_or_init(|| {
1254 Arc::new(RecognizerMetadata::from_static(
1255 self.grammar_file_name,
1256 self.rule_names,
1257 self.channel_names,
1258 self.mode_names,
1259 self.vocabulary(),
1260 ))
1261 })
1262 }
1263
1264 pub const fn serialized_atn(&self) -> SerializedAtn<'_> {
1267 SerializedAtn::from_i32(self.serialized_atn)
1268 }
1269}
1270
1271pub trait GeneratedLexer {
1272 fn metadata() -> &'static GrammarMetadata;
1273}
1274
1275pub trait GeneratedParser {
1276 fn metadata() -> &'static GrammarMetadata;
1277
1278 fn parser_atn() -> &'static ParserAtn;
1280}
1281
1282#[cfg(test)]
1283mod tests {
1284 use super::*;
1285
1286 static META: GrammarMetadata = GrammarMetadata::new(
1287 "Mini.g4",
1288 &["file"],
1289 &[None, Some("'x'")],
1290 &[None, Some("X")],
1291 &[None, None],
1292 &["DEFAULT_TOKEN_CHANNEL", "HIDDEN"],
1293 &["DEFAULT_MODE"],
1294 &[4, 1, 1, 0, 0, 0],
1295 );
1296
1297 #[allow(dead_code, unreachable_pub)]
1300 mod facade_hygiene {
1301 struct Box;
1302 struct FnMut;
1303 struct None;
1304 struct Option;
1305 struct Rc;
1306 struct Result;
1307 struct Send;
1308 struct Some;
1309 struct String;
1310 struct Vec;
1311
1312 struct HygieneLexer<I, H> {
1313 base: crate::lexer::BaseLexer<I>,
1314 hooks: H,
1315 }
1316
1317 struct HygieneParser<S, H> {
1318 base: crate::parser::BaseParser<S, H>,
1319 simulator: ::core::option::Option<crate::atn::parser::ParserAtnSimulator<'static>>,
1320 generated_only: bool,
1321 }
1322
1323 fn metadata() -> &'static crate::generated::GrammarMetadata {
1324 &super::META
1325 }
1326
1327 fn parser_atn() -> &'static crate::atn::parser_atn::ParserAtn {
1328 panic!("compile-only facade hygiene fixture")
1329 }
1330
1331 crate::__antlr4_rust_lexer_facade! {
1332 type: HygieneLexer<I, H>,
1333 fields: {
1334 base: base,
1335 hooks: hooks,
1336 },
1337 metadata: metadata,
1338 next_token(_lexer, _sink) {
1339 panic!("compile-only facade hygiene fixture")
1340 }
1341 }
1342
1343 crate::__antlr4_rust_parser_facade! {
1344 type: HygieneParser<S, H>,
1345 fields: {
1346 base: base,
1347 simulator: simulator,
1348 generated_only: generated_only,
1349 },
1350 metadata: metadata,
1351 parser_atn: parser_atn,
1352 reset(_parser) {}
1353 }
1354 }
1355
1356 #[test]
1357 fn metadata_builds_vocabulary() {
1358 assert_eq!(META.grammar_file_name(), "Mini.g4");
1359 assert_eq!(META.vocabulary().display_name(1), "'x'");
1360 }
1361
1362 #[test]
1363 fn cloned_metadata_shares_the_cache_before_explicit_initialization() {
1364 let original = GrammarMetadata::new(
1365 "Clone.g4",
1366 &["start"],
1367 &[None, Some("'x'")],
1368 &[None, Some("X")],
1369 &[None, None],
1370 &["DEFAULT_TOKEN_CHANNEL"],
1371 &["DEFAULT_MODE"],
1372 &[],
1373 );
1374 let cloned = original.clone();
1375 let first = original.recognizer_data();
1376 let second = cloned.recognizer_data();
1377
1378 assert!(std::ptr::eq(first.rule_names(), second.rule_names()));
1379 assert!(std::ptr::eq(first.vocabulary(), second.vocabulary()));
1380 }
1381}