antlr-rust-runtime 0.32.0

High performance Rust runtime and target support for ANTLR v4 generated parsers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
use std::sync::{Arc, OnceLock};

use crate::atn::parser_atn::ParserAtn;
use crate::atn::serialized::SerializedAtn;
use crate::recognizer::{RecognizerData, RecognizerMetadata};
use crate::vocabulary::Vocabulary;

/// Defines the grammar-independent storage, conversion, and accessor mechanics
/// for one generated typed parser context.
#[doc(hidden)]
#[macro_export]
macro_rules! __antlr4_rust_context {
    (
        pub struct $context:ident {
            rule_index: $rule_index:expr,
            context_kind: $kind_mode:ident $(($kind:expr))?,
            attributes: {
                $(
                    $attrs:ident {
                        $($field:ident: $field_ty:ty),+ $(,)?
                    }
                )?
            },
            methods: {
                rule_node: $rule_node_method:ident,
                child_count: $child_count_method:ident,
                direct_terminals: $direct_terminals_method:ident,
                start: $start_method:ident,
                text: $text_method:ident $(,)?
            }
        }
    ) => {
        #[allow(non_camel_case_types, dead_code)]
        #[derive(Clone)]
        pub struct $context<'a, State = StoredTreeContext> {
            __node: __GeneratedRuleContext<'a>,
            __invocation_states: Option<Vec<isize>>,
            __state: std::marker::PhantomData<State>,
            $(
                $(pub $field: $field_ty,)+
            )?
        }

        impl<'a> $crate::FromRuleNode<'a> for $context<'a> {
            fn from_rule_node(node: $crate::RuleNodeView<'a>) -> Option<Self> {
                if node.rule_index() != $rule_index
                    || $crate::__antlr4_rust_context!(
                        @stored_kind_mismatch $kind_mode $(($kind))?, node
                    )
                {
                    return None;
                }
                Some(Self::__from_node(node))
            }
        }

        impl<'a> $crate::AsRuleNode<'a> for $context<'a> {
            fn as_rule_node(&self) -> $crate::RuleNodeView<'a> {
                self.$rule_node_method()
            }
        }

        impl<'a> $context<'a> {
            pub fn $rule_node_method(&self) -> $crate::RuleNodeView<'a> {
                match self.__node {
                    __GeneratedRuleContext::Stored(node) => node,
                    __GeneratedRuleContext::Active { .. } => {
                        unreachable!("stored context type contains an active parser context")
                    }
                }
            }
        }

        impl<'a> __FromActiveRuleContext<'a> for $context<'a, __ActiveParserContext> {
            fn __from_active(
                context: &'a $crate::ParserRuleContext,
                live_attrs: Option<&dyn std::any::Any>,
                invocation_states: Vec<isize>,
                storage: &'a $crate::ParseTreeStorage,
                tokens: &'a $crate::TokenStore,
            ) -> Option<Self> {
                if context.rule_index() != $rule_index
                    || $crate::__antlr4_rust_context!(
                        @active_kind_mismatch
                        $kind_mode $(($kind))?,
                        context,
                        storage,
                        tokens
                    )
                {
                    return None;
                }
                $(
                    let __default = <$attrs>::default();
                    let __attrs = match live_attrs {
                        Some(live_attrs) => live_attrs
                            .downcast_ref::<$attrs>()
                            .expect("active context attributes match the parser rule"),
                        None => context
                            .generated_attrs::<$attrs>()
                            .unwrap_or(&__default),
                    };
                )?
                Some(Self {
                    __node: __GeneratedRuleContext::Active {
                        context,
                        storage,
                        tokens,
                    },
                    __invocation_states: Some(invocation_states),
                    __state: std::marker::PhantomData,
                    $(
                        $($field: __attrs.$field.clone(),)+
                    )?
                })
            }
        }

        impl<'a> FromValidatedRuleNode<'a> for $context<'a, ValidatedTreeContext> {
            fn from_validated_rule_node(node: ValidatedRuleNode<'a>) -> Option<Self> {
                let node = node.rule_node();
                if node.rule_index() != $rule_index
                    || $crate::__antlr4_rust_context!(
                        @stored_kind_mismatch $kind_mode $(($kind))?, node
                    )
                {
                    return None;
                }
                Some(Self::__from_validated_node(node))
            }
        }

        impl<'a> $crate::AsRuleNode<'a> for $context<'a, ValidatedTreeContext> {
            fn as_rule_node(&self) -> $crate::RuleNodeView<'a> {
                self.$rule_node_method()
            }
        }

        #[allow(dead_code, clippy::all)]
        impl<'a> $context<'a> {
            fn __from_node(node: $crate::RuleNodeView<'a>) -> Self {
                Self::__from_node_with_invocation_states(node, None)
            }

            fn __from_child_node(
                node: $crate::RuleNodeView<'a>,
                parent_invocation_states: Option<&[isize]>,
            ) -> Self {
                let invocation_states = parent_invocation_states.map(|states| {
                    let mut invocation_states = Vec::with_capacity(states.len() + 1);
                    invocation_states.push(node.invoking_state());
                    invocation_states.extend_from_slice(states);
                    invocation_states
                });
                Self::__from_node_with_invocation_states(node, invocation_states)
            }

            fn __from_listener_node(
                node: $crate::RuleNodeView<'a>,
                invocation_states: Option<&[isize]>,
            ) -> Self {
                Self::__from_node_with_invocation_states(
                    node,
                    invocation_states.map(<[isize]>::to_vec),
                )
            }

            fn __from_node_with_invocation_states(
                node: $crate::RuleNodeView<'a>,
                invocation_states: Option<Vec<isize>>,
            ) -> Self {
                $(
                    let __default = <$attrs>::default();
                    let __attrs = node.generated_attrs::<$attrs>().unwrap_or(&__default);
                )?
                Self {
                    __node: __GeneratedRuleContext::Stored(node),
                    __invocation_states: invocation_states,
                    __state: std::marker::PhantomData,
                    $(
                        $($field: __attrs.$field.clone(),)+
                    )?
                }
            }
        }

        #[allow(dead_code, clippy::all)]
        impl<'a, State> $context<'a, State> {
            pub fn $child_count_method(&self) -> usize {
                match &self.__node {
                    __GeneratedRuleContext::Stored(node) => node.child_count(),
                    __GeneratedRuleContext::Active { context, .. } => context.child_count(),
                }
            }

            /// Iterates terminals owned directly by this context without
            /// descending into nested rule contexts.
            ///
            /// Recovered trees expose inserted and deleted recovery tokens as
            /// error nodes through the same `TerminalNode` surface. Use
            /// `TerminalNode::is_error()` to identify recovery nodes and
            /// `TerminalNode::is_missing()` to identify inserted synthetic
            /// tokens.
            pub fn $direct_terminals_method(
                &self,
            ) -> impl Iterator<Item = TerminalNode<'a>> + 'a + use<'a, State> {
                __terminal_children(self.__node).map(TerminalNode::new)
            }

            pub fn $start_method(&self) -> __GeneratedTokenView {
                let token = match &self.__node {
                    __GeneratedRuleContext::Stored(node) => node.start(),
                    __GeneratedRuleContext::Active {
                        context, tokens, ..
                    } => context.start(tokens),
                };
                __GeneratedTokenView {
                    text: token
                        .map(|token| token.text_or_empty().to_owned())
                        .unwrap_or_default(),
                }
            }

            pub fn $text_method(&self) -> String {
                match &self.__node {
                    __GeneratedRuleContext::Stored(node) => node.text(),
                    __GeneratedRuleContext::Active {
                        context,
                        storage,
                        tokens,
                    } => context.text(storage, tokens),
                }
            }
        }

        #[allow(dead_code, clippy::all)]
        impl<'a> $context<'a, ValidatedTreeContext> {
            fn __from_validated_node(node: $crate::RuleNodeView<'a>) -> Self {
                Self::__from_validated_node_with_invocation_states(node, None)
            }

            fn __from_validated_child_node(
                node: $crate::RuleNodeView<'a>,
                parent_invocation_states: Option<&[isize]>,
            ) -> Self {
                let invocation_states = parent_invocation_states.map(|states| {
                    let mut invocation_states = Vec::with_capacity(states.len() + 1);
                    invocation_states.push(node.invoking_state());
                    invocation_states.extend_from_slice(states);
                    invocation_states
                });
                Self::__from_validated_node_with_invocation_states(node, invocation_states)
            }

            fn __from_validated_listener_node(
                node: $crate::RuleNodeView<'a>,
                invocation_states: Option<&[isize]>,
            ) -> Self {
                Self::__from_validated_node_with_invocation_states(
                    node,
                    invocation_states.map(<[isize]>::to_vec),
                )
            }

            fn __from_validated_node_with_invocation_states(
                node: $crate::RuleNodeView<'a>,
                invocation_states: Option<Vec<isize>>,
            ) -> Self {
                $(
                    let __default = <$attrs>::default();
                    let __attrs = node.generated_attrs::<$attrs>().unwrap_or(&__default);
                )?
                Self {
                    __node: __GeneratedRuleContext::Stored(node),
                    __invocation_states: invocation_states,
                    __state: std::marker::PhantomData,
                    $(
                        $($field: __attrs.$field.clone(),)+
                    )?
                }
            }

            pub fn $rule_node_method(&self) -> $crate::RuleNodeView<'a> {
                match self.__node {
                    __GeneratedRuleContext::Stored(node) => node,
                    __GeneratedRuleContext::Active { .. } => {
                        unreachable!("validated context contains an active parser context")
                    }
                }
            }
        }

        impl<State> std::fmt::Display for $context<'_, State> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match &self.__invocation_states {
                    Some(states) => __write_invocation_states(f, states.iter().copied()),
                    None => match self.__node {
                        __GeneratedRuleContext::Stored(node) => {
                            __write_invocation_states(f, node.invocation_states())
                        }
                        __GeneratedRuleContext::Active { .. } => {
                            unreachable!("active context is missing invocation states")
                        }
                    },
                }
            }
        }
    };
    (@stored_kind_mismatch any, $node:expr) => {
        false
    };
    (@stored_kind_mismatch exact($kind:expr), $node:expr) => {
        __context_kind($node) != $kind
    };
    (@active_kind_mismatch any, $context:expr, $storage:expr, $tokens:expr) => {
        false
    };
    (@active_kind_mismatch exact($kind:expr), $context:expr, $storage:expr, $tokens:expr) => {
        __active_context_kind($context, $storage, $tokens) != $kind
    };
}

/// Expands one declarative accessor list into both state-variant impls of a
/// generated typed parser context: the recovery-oriented impl (generic over
/// the module's `__RecoveryContextState`, returning `Result<_,
/// MissingChildError>` for required children) and the validated impl
/// (`ValidatedTreeContext`, returning required children directly).
///
/// Accessor declarations, one per generated method:
///
/// ```text
/// rule <method>: required(<ChildContext>[<child rule index>], "<child name>"),
/// rule <method>: optional(<ChildContext>[<child rule index>]),
/// rule <method>: many(<ChildContext>[<child rule index>]),
/// token <method>: required(<token type>, "<token name>"),
/// token <method>: optional(<token type>),
/// token <method>: many(<token type>),
/// label_rule <method>: required(<selector>, <ChildContext>[<child rule index>], "<label>"),
/// label_rule <method>: optional(<selector>, <ChildContext>[<child rule index>]),
/// label_rule <method>: many(skip(<n>), <ChildContext>[<child rule index>]),
/// label_token <method>: required(<selector>, [<token types>], "<label>"),
/// label_token <method>: optional(<selector>, [<token types>]),
/// label_token <method>: many(skip(<n>), [<token types>]),
/// ```
///
/// where `<selector>` is `nth(<n>)` or `last_after(<n>)`. All names, indices,
/// and token types are grammar data supplied by the generated invocation; the
/// module-local support items (`__rule_children`, `__token_children`,
/// `__labeled_token_children`, `__labeled_token_children_matching`,
/// `TerminalNode`, `ValidatedTreeContext`, `__RecoveryContextState`, plus the
/// `__from_child_node`/`__from_validated_child_node` constructors and the
/// `__node`/`__invocation_states` context fields defined by
/// `__antlr4_rust_context!`) are emitted per generated module, exactly as
/// `__antlr4_rust_context!` relies on.
#[doc(hidden)]
#[macro_export]
macro_rules! __antlr4_rust_context_accessors {
    (
        $context:ident {
            $( $kind:tt $method:ident: $card:tt $payload:tt ),* $(,)?
        }
    ) => {
        #[allow(dead_code, private_bounds, clippy::all)]
        impl<'a, State: __RecoveryContextState> $context<'a, State> {
            $(
                $crate::__antlr4_rust_context_accessors!(
                    @recovered $context, $kind $card $method $payload
                );
            )*
        }

        #[allow(dead_code, clippy::all)]
        impl<'a> $context<'a, ValidatedTreeContext> {
            $(
                $crate::__antlr4_rust_context_accessors!(
                    @validated $context, $kind $card $method $payload
                );
            )*
        }
    };

    // Recovery-oriented rule children.
    (@recovered $context:ident, rule required $method:ident ($child:ident[$index:expr], $name:literal)) => {
        pub fn $method(&self) -> Result<$child<'a>, $crate::MissingChildError> {
            __rule_children(self.__node, $index)
                .next()
                .map(|node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
                .ok_or_else(|| $crate::MissingChildError::new(stringify!($context), $name))
        }
    };
    (@recovered $context:ident, rule optional $method:ident ($child:ident[$index:expr])) => {
        pub fn $method(&self) -> Option<$child<'a>> {
            __rule_children(self.__node, $index)
                .next()
                .map(|node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
        }
    };
    (@recovered $context:ident, rule many $method:ident ($child:ident[$index:expr])) => {
        pub fn $method(&self) -> impl Iterator<Item = $child<'a>> + '_ {
            __rule_children(self.__node, $index)
                .map(move |node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
        }
    };

    // Recovery-oriented token children.
    (@recovered $context:ident, token required $method:ident ($token_type:expr, $name:literal)) => {
        pub fn $method(&self) -> Result<TerminalNode<'a>, $crate::MissingChildError> {
            __token_children(self.__node, $token_type)
                .next()
                .map(TerminalNode::new)
                .ok_or_else(|| $crate::MissingChildError::new(stringify!($context), $name))
        }
    };
    (@recovered $context:ident, token optional $method:ident ($token_type:expr)) => {
        pub fn $method(&self) -> Option<TerminalNode<'a>> {
            __token_children(self.__node, $token_type)
                .next()
                .map(TerminalNode::new)
        }
    };
    (@recovered $context:ident, token many $method:ident ($token_type:expr)) => {
        pub fn $method(&self) -> impl Iterator<Item = TerminalNode<'a>> + '_ {
            __token_children(self.__node, $token_type).map(TerminalNode::new)
        }
    };

    // Recovery-oriented labeled rule children.
    (@recovered $context:ident, label_rule required $method:ident ($sel:ident($selarg:expr), $child:ident[$index:expr], $name:literal)) => {
        pub fn $method(&self) -> Result<$child<'a>, $crate::MissingChildError> {
            $crate::__antlr4_rust_context_accessors!(
                @selected(__rule_children(self.__node, $index)) $sel($selarg)
            )
            .map(|node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
            .ok_or_else(|| $crate::MissingChildError::new(stringify!($context), $name))
        }
    };
    (@recovered $context:ident, label_rule optional $method:ident ($sel:ident($selarg:expr), $child:ident[$index:expr])) => {
        pub fn $method(&self) -> Option<$child<'a>> {
            $crate::__antlr4_rust_context_accessors!(
                @selected(__rule_children(self.__node, $index)) $sel($selarg)
            )
            .map(|node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
        }
    };
    (@recovered $context:ident, label_rule many $method:ident (skip($skip:expr), $child:ident[$index:expr])) => {
        pub fn $method(&self) -> impl Iterator<Item = $child<'a>> + '_ {
            __rule_children(self.__node, $index)
                .skip($skip)
                .map(move |node| $child::__from_child_node(node, self.__invocation_states.as_deref()))
        }
    };

    // Recovery-oriented labeled token children.
    (@recovered $context:ident, label_token required $method:ident ($sel:ident($selarg:expr), $tokens:tt, $name:literal)) => {
        pub fn $method(&self) -> Result<TerminalNode<'a>, $crate::MissingChildError> {
            $crate::__antlr4_rust_context_accessors!(
                @selected($crate::__antlr4_rust_context_accessors!(
                    @labeled_token_children(self.__node) $tokens
                )) $sel($selarg)
            )
            .map(TerminalNode::new)
            .ok_or_else(|| $crate::MissingChildError::new(stringify!($context), $name))
        }
    };
    (@recovered $context:ident, label_token optional $method:ident ($sel:ident($selarg:expr), $tokens:tt)) => {
        pub fn $method(&self) -> Option<TerminalNode<'a>> {
            $crate::__antlr4_rust_context_accessors!(
                @selected($crate::__antlr4_rust_context_accessors!(
                    @labeled_token_children(self.__node) $tokens
                )) $sel($selarg)
            )
            .map(TerminalNode::new)
        }
    };
    (@recovered $context:ident, label_token many $method:ident (skip($skip:expr), $tokens:tt)) => {
        pub fn $method(&self) -> impl Iterator<Item = TerminalNode<'a>> + '_ {
            $crate::__antlr4_rust_context_accessors!(
                @labeled_token_children(self.__node) $tokens
            )
            .skip($skip)
            .map(TerminalNode::new)
        }
    };

    // Validated rule children.
    (@validated $context:ident, rule required $method:ident ($child:ident[$index:expr], $name:literal)) => {
        pub fn $method(&self) -> $child<'a, ValidatedTreeContext> {
            let Some(node) = __rule_children(self.__node, $index).next() else {
                unreachable!(concat!(
                    "validated ",
                    stringify!($context),
                    " is missing required child ",
                    $name
                ))
            };
            $child::<ValidatedTreeContext>::__from_validated_child_node(
                node,
                self.__invocation_states.as_deref(),
            )
        }
    };
    (@validated $context:ident, rule optional $method:ident ($child:ident[$index:expr])) => {
        pub fn $method(&self) -> Option<$child<'a, ValidatedTreeContext>> {
            __rule_children(self.__node, $index)
                .next()
                .map(|node| {
                    $child::<ValidatedTreeContext>::__from_validated_child_node(
                        node,
                        self.__invocation_states.as_deref(),
                    )
                })
        }
    };
    (@validated $context:ident, rule many $method:ident ($child:ident[$index:expr])) => {
        pub fn $method(&self) -> impl Iterator<Item = $child<'a, ValidatedTreeContext>> + '_ {
            __rule_children(self.__node, $index).map(move |node| {
                $child::<ValidatedTreeContext>::__from_validated_child_node(
                    node,
                    self.__invocation_states.as_deref(),
                )
            })
        }
    };

    // Validated token children.
    (@validated $context:ident, token required $method:ident ($token_type:expr, $name:literal)) => {
        pub fn $method(&self) -> TerminalNode<'a> {
            let Some(node) = __token_children(self.__node, $token_type).next() else {
                unreachable!(concat!(
                    "validated ",
                    stringify!($context),
                    " is missing required child ",
                    $name
                ))
            };
            TerminalNode::new(node)
        }
    };
    (@validated $context:ident, token optional $method:ident ($token_type:expr)) => {
        pub fn $method(&self) -> Option<TerminalNode<'a>> {
            __token_children(self.__node, $token_type)
                .next()
                .map(TerminalNode::new)
        }
    };
    (@validated $context:ident, token many $method:ident ($token_type:expr)) => {
        pub fn $method(&self) -> impl Iterator<Item = TerminalNode<'a>> + '_ {
            __token_children(self.__node, $token_type).map(TerminalNode::new)
        }
    };

    // Validated labeled rule children.
    (@validated $context:ident, label_rule required $method:ident ($sel:ident($selarg:expr), $child:ident[$index:expr], $name:literal)) => {
        pub fn $method(&self) -> $child<'a, ValidatedTreeContext> {
            let Some(node) = $crate::__antlr4_rust_context_accessors!(
                @selected(__rule_children(self.__node, $index)) $sel($selarg)
            ) else {
                unreachable!(concat!(
                    "validated ",
                    stringify!($context),
                    " is missing required child ",
                    $name
                ))
            };
            $child::<ValidatedTreeContext>::__from_validated_child_node(
                node,
                self.__invocation_states.as_deref(),
            )
        }
    };
    (@validated $context:ident, label_rule optional $method:ident ($sel:ident($selarg:expr), $child:ident[$index:expr])) => {
        pub fn $method(&self) -> Option<$child<'a, ValidatedTreeContext>> {
            $crate::__antlr4_rust_context_accessors!(
                @selected(__rule_children(self.__node, $index)) $sel($selarg)
            )
            .map(|node| {
                $child::<ValidatedTreeContext>::__from_validated_child_node(
                    node,
                    self.__invocation_states.as_deref(),
                )
            })
        }
    };
    (@validated $context:ident, label_rule many $method:ident (skip($skip:expr), $child:ident[$index:expr])) => {
        pub fn $method(&self) -> impl Iterator<Item = $child<'a, ValidatedTreeContext>> + '_ {
            __rule_children(self.__node, $index)
                .skip($skip)
                .map(move |node| {
                    $child::<ValidatedTreeContext>::__from_validated_child_node(
                        node,
                        self.__invocation_states.as_deref(),
                    )
                })
        }
    };

    // Validated labeled token children.
    (@validated $context:ident, label_token required $method:ident ($sel:ident($selarg:expr), $tokens:tt, $name:literal)) => {
        pub fn $method(&self) -> TerminalNode<'a> {
            let Some(node) = $crate::__antlr4_rust_context_accessors!(
                @selected($crate::__antlr4_rust_context_accessors!(
                    @labeled_token_children(self.__node) $tokens
                )) $sel($selarg)
            ) else {
                unreachable!(concat!(
                    "validated ",
                    stringify!($context),
                    " is missing required child ",
                    $name
                ))
            };
            TerminalNode::new(node)
        }
    };
    (@validated $context:ident, label_token optional $method:ident ($sel:ident($selarg:expr), $tokens:tt)) => {
        pub fn $method(&self) -> Option<TerminalNode<'a>> {
            $crate::__antlr4_rust_context_accessors!(
                @selected($crate::__antlr4_rust_context_accessors!(
                    @labeled_token_children(self.__node) $tokens
                )) $sel($selarg)
            )
            .map(TerminalNode::new)
        }
    };
    (@validated $context:ident, label_token many $method:ident (skip($skip:expr), $tokens:tt)) => {
        pub fn $method(&self) -> impl Iterator<Item = TerminalNode<'a>> + '_ {
            $crate::__antlr4_rust_context_accessors!(
                @labeled_token_children(self.__node) $tokens
            )
            .skip($skip)
            .map(TerminalNode::new)
        }
    };

    // Label occurrence selectors.
    (@selected($children:expr) nth($occurrence:expr)) => {
        $children.nth($occurrence)
    };
    (@selected($children:expr) last_after($skip:expr)) => {
        $children.skip($skip).last()
    };

    // Labeled token child sources: a single token type uses the scalar
    // helper; a set uses the matching helper.
    (@labeled_token_children($node:expr) [$token_type:expr]) => {
        __labeled_token_children($node, $token_type)
    };
    (@labeled_token_children($node:expr) [$($token_type:expr),+ $(,)?]) => {
        __labeled_token_children_matching($node, &[$($token_type),+])
    };

    // Catch-alls that name the offending declaration instead of failing with
    // a bare `no rules expected this token` deep inside a generated module.
    // The structured arms reconstruct the source declaration order; the
    // trailing generic arms catch shapes that do not even parse as one.
    (@recovered $context:ident, $kind:tt $card:tt $method:ident $payload:tt) => {
        compile_error!(concat!(
            "unsupported generated accessor declaration for ",
            stringify!($context),
            ": ",
            stringify!($kind),
            " ",
            stringify!($method),
            ": ",
            stringify!($card),
            stringify!($payload)
        ));
    };
    (@validated $context:ident, $kind:tt $card:tt $method:ident $payload:tt) => {
        compile_error!(concat!(
            "unsupported generated accessor declaration for ",
            stringify!($context),
            ": ",
            stringify!($kind),
            " ",
            stringify!($method),
            ": ",
            stringify!($card),
            stringify!($payload)
        ));
    };
    (@recovered $context:ident, $($declaration:tt)*) => {
        compile_error!(concat!(
            "unsupported generated accessor declaration for ",
            stringify!($context),
            ": ",
            stringify!($($declaration)*)
        ));
    };
    (@validated $context:ident, $($declaration:tt)*) => {
        compile_error!(concat!(
            "unsupported generated accessor declaration for ",
            stringify!($context),
            ": ",
            stringify!($($declaration)*)
        ));
    };
    (@selected($children:expr) $($selector:tt)*) => {
        compile_error!(concat!(
            "unsupported generated accessor selector: ",
            stringify!($($selector)*)
        ))
    };
    (@labeled_token_children($node:expr) $($tokens:tt)*) => {
        compile_error!(concat!(
            "unsupported generated accessor token set: ",
            stringify!($($tokens)*)
        ))
    };
}

/// Defines the grammar-independent facade and trait delegation for one
/// generated lexer.
#[doc(hidden)]
#[macro_export]
macro_rules! __antlr4_rust_lexer_facade {
    (
        type: $lexer:ident<$input:ident, $hooks:ident>,
        fields: {
            base: $base:ident,
            hooks: $hooks_field:ident $(,)?
        },
        metadata: $metadata:path,
        next_token($this:ident, $sink:ident) $next_token:block
        $(,)?
    ) => {
        impl<$input, $hooks> $lexer<$input, $hooks>
        where
            $input: $crate::char_stream::CharStream,
            $hooks: $crate::parser::SemanticHooks,
        {
            pub fn metadata() -> &'static $crate::generated::GrammarMetadata {
                $metadata()
            }

            /// Adds a listener for lexer diagnostics.
            pub fn add_error_listener<T>(&mut self, listener: T)
            where
                T: for<'a> $crate::errors::ErrorListener<dyn $crate::recognizer::Recognizer + 'a>
                    + ::core::marker::Send
                    + 'static,
            {
                $crate::recognizer::Recognizer::add_error_listener(&mut self.$base, listener);
            }

            /// Removes every lexer error listener, including the default console listener.
            pub fn remove_error_listeners(&mut self) {
                $crate::recognizer::Recognizer::remove_error_listeners(&mut self.$base);
            }

            /// Routes every token through ATN interpretation instead of the compiled
            /// lexer DFA, so the learned-DFA trace (`lexer_dfa_string`) observes each
            /// match.
            pub fn set_force_interpreted(&mut self, force_interpreted: bool) {
                self.$base.set_force_interpreted(force_interpreted);
            }

            /// Resets this lexer and any caller-owned lifecycle state for reuse.
            pub fn reset(&mut self) {
                if <$hooks as $crate::parser::SemanticHooks>::ENABLES_LEXER_LIFECYCLE {
                    $crate::atn::lexer::reset_with_semantic_hooks(
                        &mut self.$base,
                        &mut self.$hooks_field,
                    );
                } else {
                    self.$base.reset();
                }
            }

            /// Replaces the input stream and resets runtime and lifecycle state.
            pub fn set_input_stream(&mut self, input: $input) {
                if <$hooks as $crate::parser::SemanticHooks>::ENABLES_LEXER_LIFECYCLE {
                    $crate::atn::lexer::set_input_stream_with_semantic_hooks(
                        &mut self.$base,
                        &mut self.$hooks_field,
                        input,
                    );
                } else {
                    self.$base.set_input_stream(input);
                }
            }

            /// Clears the learned lexer DFA shared by this grammar.
            pub fn clear_dfa(&self) {
                self.$base.clear_dfa();
            }
        }

        impl<$input, $hooks> $crate::generated::GeneratedLexer for $lexer<$input, $hooks>
        where
            $input: $crate::char_stream::CharStream,
            $hooks: $crate::parser::SemanticHooks,
        {
            fn metadata() -> &'static $crate::generated::GrammarMetadata {
                $metadata()
            }
        }

        impl<$input, $hooks> $crate::recognizer::Recognizer for $lexer<$input, $hooks>
        where
            $input: $crate::char_stream::CharStream,
            $hooks: $crate::parser::SemanticHooks,
        {
            fn data(&self) -> &$crate::recognizer::RecognizerData {
                $crate::recognizer::Recognizer::data(&self.$base)
            }

            fn data_mut(&mut self) -> &mut $crate::recognizer::RecognizerData {
                $crate::recognizer::Recognizer::data_mut(&mut self.$base)
            }
        }

        impl<$input, $hooks> $crate::lexer::Lexer for $lexer<$input, $hooks>
        where
            $input: $crate::char_stream::CharStream,
            $hooks: $crate::parser::SemanticHooks,
        {
            fn mode(&self) -> i32 {
                $crate::lexer::Lexer::mode(&self.$base)
            }

            fn set_mode(&mut self, mode: i32) {
                $crate::lexer::Lexer::set_mode(&mut self.$base, mode);
            }

            fn push_mode(&mut self, mode: i32) {
                $crate::lexer::Lexer::push_mode(&mut self.$base, mode);
            }

            fn pop_mode(&mut self) -> ::core::option::Option<i32> {
                $crate::lexer::Lexer::pop_mode(&mut self.$base)
            }
        }

        impl<$input, $hooks> $crate::token::TokenSource for $lexer<$input, $hooks>
        where
            $input: $crate::char_stream::CharStream,
            $hooks: $crate::parser::SemanticHooks,
        {
            fn next_token(
                &mut self,
                $sink: &mut $crate::token::TokenSink<'_>,
            ) -> ::core::result::Result<$crate::token::TokenId, $crate::token::TokenStoreError>
            {
                let $this = self;
                $next_token
            }

            fn line(&self) -> usize {
                self.$base.line()
            }

            fn column(&self) -> usize {
                self.$base.column()
            }

            fn source_name(&self) -> &str {
                self.$base.source_name()
            }

            fn source_text(&self) -> ::core::option::Option<::std::rc::Rc<str>> {
                self.$base.source_text()
            }

            fn drain_errors(&mut self) -> ::std::vec::Vec<$crate::token::TokenSourceError> {
                self.$base.drain_errors()
            }

            fn report_error(&self, source_error: &$crate::token::TokenSourceError) -> bool {
                $crate::recognizer::Recognizer::notify_error_listeners(self, source_error.into());
                true
            }

            fn lexer_dfa_string(&self) -> ::std::string::String {
                self.$base.lexer_dfa_string()
            }
        }
    };
}

/// Defines the grammar-independent facade and trait delegation for one
/// generated parser.
#[doc(hidden)]
#[macro_export]
macro_rules! __antlr4_rust_parser_facade {
    (
        type: $parser:ident<$source:ident, $hooks:ident>,
        fields: {
            base: $base:ident,
            simulator: $simulator:ident,
            generated_only: $generated_only:ident $(,)?
        },
        metadata: $metadata:path,
        parser_atn: $parser_atn:path,
        reset($this:ident) $reset:block
        $(,)?
    ) => {
        impl<$source, $hooks> $parser<$source, $hooks>
        where
            $source: $crate::token::TokenSource,
            $hooks: $crate::parser::SemanticHooks,
        {
            pub fn metadata() -> &'static $crate::generated::GrammarMetadata {
                $metadata()
            }

            /// Adds a listener for parser diagnostics.
            pub fn add_error_listener<T>(&mut self, listener: T)
            where
                T: for<'a> $crate::errors::ErrorListener<dyn $crate::recognizer::Recognizer + 'a>
                    + ::core::marker::Send
                    + 'static,
            {
                $crate::recognizer::Recognizer::add_error_listener(&mut self.$base, listener);
            }

            /// Removes every parser error listener, including the default console listener.
            pub fn remove_error_listeners(&mut self) {
                $crate::recognizer::Recognizer::remove_error_listeners(&mut self.$base);
            }

            /// Registers a listener for committed rule enter/exit events during
            /// recognition (ANTLR's `addParseListener`). See
            /// [`antlr4_runtime::ParseListener`] for the delivery contract.
            pub fn add_parse_listener<T>(&mut self, listener: T)
            where
                T: $crate::parser::ParseListener + 'static,
            {
                self.$base.add_parse_listener(listener);
            }

            /// Removes every registered parse listener and returns them, dropping
            /// any sticky abort a removed listener had requested.
            pub fn remove_parse_listeners(
                &mut self,
            ) -> ::std::vec::Vec<::std::boxed::Box<dyn $crate::parser::ParseListener>> {
                self.$base.remove_parse_listeners()
            }

            /// Fully resets parser-owned state and rewinds the current token stream.
            pub fn reset(&mut self) {
                self.$base.reset();
                if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
                    simulator.reset();
                }
                let $this = &mut *self;
                $reset
            }

            /// Replaces the token stream and fully resets parser-owned state.
            pub fn set_token_stream(
                &mut self,
                input: $crate::token_stream::CommonTokenStream<$source>,
            ) {
                self.$base.set_token_stream(input);
                if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
                    simulator.reset();
                }
                let $this = &mut *self;
                $reset
            }

            #[must_use]
            pub const fn token_stream(&self) -> &$crate::token_stream::CommonTokenStream<$source> {
                self.$base.token_stream()
            }

            #[must_use]
            pub const fn token_stream_mut(
                &mut self,
            ) -> &mut $crate::token_stream::CommonTokenStream<$source> {
                self.$base.token_stream_mut()
            }

            #[must_use]
            pub const fn token_store(&self) -> &$crate::token::TokenStore {
                self.$base.token_store()
            }

            #[must_use]
            pub const fn parse_tree_storage(&self) -> &$crate::tree::ParseTreeStorage {
                self.$base.parse_tree_storage()
            }

            #[must_use]
            pub fn prediction_context_stats(&self) -> $crate::prediction::PredictionContextStats {
                self.$simulator.as_ref().map_or_else(
                    $crate::prediction::PredictionContextStats::default,
                    $crate::atn::parser::ParserAtnSimulator::prediction_context_stats,
                )
            }

            #[must_use]
            pub fn parser_dfa_stats(&self) -> $crate::dfa::ParserDfaStats {
                self.$simulator.as_ref().map_or_else(
                    $crate::dfa::ParserDfaStats::default,
                    $crate::atn::parser::ParserAtnSimulator::parser_dfa_stats,
                )
            }

            /// Clears this grammar's learned parser decision DFAs.
            pub fn clear_dfa(&mut self) {
                if let ::core::option::Option::Some(simulator) = self.$simulator.as_mut() {
                    simulator.clear_dfa();
                } else {
                    $crate::atn::parser::ParserAtnSimulator::clear_shared_dfa($parser_atn());
                }
                let $this = &mut *self;
                $reset
            }

            #[must_use]
            pub fn node(&self, id: $crate::tree::NodeId) -> $crate::tree::Node<'_> {
                self.$base.node(id)
            }

            #[must_use]
            pub fn into_token_stream(self) -> $crate::token_stream::CommonTokenStream<$source> {
                self.$base.into_token_stream()
            }

            #[must_use]
            pub fn into_token_store(self) -> $crate::token::TokenStore {
                self.$base.into_token_store()
            }

            #[must_use]
            pub fn into_parsed_file(self, root: $crate::tree::NodeId) -> $crate::tree::ParsedFile {
                self.$base.into_parsed_file(root)
            }

            /// Compiles a tree pattern rooted at parser rule `rule_index`.
            ///
            /// Mirrors ANTLR's `Parser.compileParseTreePattern`. Literal chunks of
            /// `pattern` are lexed with a fresh lexer built by `make_lexer`.
            pub fn compile_parse_tree_pattern<PL>(
                &self,
                pattern: &str,
                rule_index: usize,
                mut make_lexer: impl ::core::ops::FnMut($crate::char_stream::InputStream) -> PL,
            ) -> ::core::result::Result<
                $crate::tree_pattern::ParseTreePattern,
                $crate::tree_pattern::ParseTreePatternError,
            >
            where
                PL: $crate::token::TokenSource,
            {
                static PATTERN_DATA: ::std::sync::OnceLock<$crate::recognizer::RecognizerData> =
                    ::std::sync::OnceLock::new();
                static PATTERN_MATCHER: ::std::sync::OnceLock<
                    $crate::tree_pattern::ParseTreePatternMatcher<'static>,
                > = ::std::sync::OnceLock::new();
                let matcher = match PATTERN_MATCHER.get() {
                    ::core::option::Option::Some(matcher) => matcher,
                    ::core::option::Option::None => {
                        let data = PATTERN_DATA.get_or_init(|| $metadata().recognizer_data());
                        let matcher = $crate::tree_pattern::ParseTreePatternMatcher::new(
                            $parser_atn(),
                            data,
                        )?;
                        PATTERN_MATCHER.get_or_init(|| matcher)
                    }
                };
                matcher.compile(pattern, rule_index, move |text: &str| {
                    $crate::tree_pattern::lex_pattern_chunk(text, &mut make_lexer)
                })
            }

            #[allow(dead_code)]
            fn simulator(&mut self) -> &mut $crate::atn::parser::ParserAtnSimulator<'static> {
                self.$simulator.get_or_insert_with(|| {
                    $crate::atn::parser::ParserAtnSimulator::new_shared($parser_atn())
                })
            }

            #[allow(dead_code)]
            fn generated_only(&self) -> bool {
                self.$generated_only
            }
        }

        impl<$source, $hooks> $crate::generated::GeneratedParser for $parser<$source, $hooks>
        where
            $source: $crate::token::TokenSource,
            $hooks: $crate::parser::SemanticHooks,
        {
            fn metadata() -> &'static $crate::generated::GrammarMetadata {
                $metadata()
            }

            fn parser_atn() -> &'static $crate::atn::parser_atn::ParserAtn {
                $parser_atn()
            }
        }

        impl<$source, $hooks> $crate::recognizer::Recognizer for $parser<$source, $hooks>
        where
            $source: $crate::token::TokenSource,
            $hooks: $crate::parser::SemanticHooks,
        {
            fn data(&self) -> &$crate::recognizer::RecognizerData {
                $crate::recognizer::Recognizer::data(&self.$base)
            }

            fn data_mut(&mut self) -> &mut $crate::recognizer::RecognizerData {
                $crate::recognizer::Recognizer::data_mut(&mut self.$base)
            }
        }

        impl<$source, $hooks> $crate::parser::Parser for $parser<$source, $hooks>
        where
            $source: $crate::token::TokenSource,
            $hooks: $crate::parser::SemanticHooks,
        {
            fn build_parse_trees(&self) -> bool {
                $crate::parser::Parser::build_parse_trees(&self.$base)
            }

            fn set_build_parse_trees(&mut self, build: bool) {
                $crate::parser::Parser::set_build_parse_trees(&mut self.$base, build);
            }

            fn number_of_syntax_errors(&self) -> usize {
                $crate::parser::Parser::number_of_syntax_errors(&self.$base)
            }

            fn report_diagnostic_errors(&self) -> bool {
                $crate::parser::Parser::report_diagnostic_errors(&self.$base)
            }

            fn set_report_diagnostic_errors(&mut self, report: bool) {
                $crate::parser::Parser::set_report_diagnostic_errors(&mut self.$base, report);
            }

            fn prediction_mode(&self) -> $crate::parser::PredictionMode {
                $crate::parser::Parser::prediction_mode(&self.$base)
            }

            fn set_prediction_mode(&mut self, mode: $crate::parser::PredictionMode) {
                $crate::parser::Parser::set_prediction_mode(&mut self.$base, mode);
            }

            fn max_rule_depth(&self) -> ::core::option::Option<usize> {
                $crate::parser::Parser::max_rule_depth(&self.$base)
            }

            fn set_max_rule_depth(&mut self, depth: ::core::option::Option<usize>) {
                $crate::parser::Parser::set_max_rule_depth(&mut self.$base, depth);
            }

            fn add_parse_listener(
                &mut self,
                listener: ::std::boxed::Box<dyn $crate::parser::ParseListener>,
            ) {
                $crate::parser::Parser::add_parse_listener(&mut self.$base, listener);
            }

            fn remove_parse_listeners(
                &mut self,
            ) -> ::std::vec::Vec<::std::boxed::Box<dyn $crate::parser::ParseListener>> {
                $crate::parser::Parser::remove_parse_listeners(&mut self.$base)
            }
        }
    };
}

#[derive(Debug)]
pub struct GrammarMetadata {
    grammar_file_name: &'static str,
    rule_names: &'static [&'static str],
    literal_names: &'static [Option<&'static str>],
    symbolic_names: &'static [Option<&'static str>],
    display_names: &'static [Option<&'static str>],
    channel_names: &'static [&'static str],
    mode_names: &'static [&'static str],
    serialized_atn: &'static [i32],
    recognizer_metadata: OnceLock<Arc<RecognizerMetadata>>,
}

impl Clone for GrammarMetadata {
    fn clone(&self) -> Self {
        Self {
            grammar_file_name: self.grammar_file_name,
            rule_names: self.rule_names,
            literal_names: self.literal_names,
            symbolic_names: self.symbolic_names,
            display_names: self.display_names,
            channel_names: self.channel_names,
            mode_names: self.mode_names,
            serialized_atn: self.serialized_atn,
            recognizer_metadata: OnceLock::from(Arc::clone(self.cached_recognizer_metadata())),
        }
    }
}

impl GrammarMetadata {
    /// Creates static grammar metadata emitted by the Rust target generator.
    #[allow(clippy::too_many_arguments)]
    pub const fn new(
        grammar_file_name: &'static str,
        rule_names: &'static [&'static str],
        literal_names: &'static [Option<&'static str>],
        symbolic_names: &'static [Option<&'static str>],
        display_names: &'static [Option<&'static str>],
        channel_names: &'static [&'static str],
        mode_names: &'static [&'static str],
        serialized_atn: &'static [i32],
    ) -> Self {
        Self {
            grammar_file_name,
            rule_names,
            literal_names,
            symbolic_names,
            display_names,
            channel_names,
            mode_names,
            serialized_atn,
            recognizer_metadata: OnceLock::new(),
        }
    }

    pub const fn grammar_file_name(&self) -> &'static str {
        self.grammar_file_name
    }

    pub const fn rule_names(&self) -> &'static [&'static str] {
        self.rule_names
    }

    pub const fn channel_names(&self) -> &'static [&'static str] {
        self.channel_names
    }

    pub const fn mode_names(&self) -> &'static [&'static str] {
        self.mode_names
    }

    pub fn vocabulary(&self) -> Vocabulary {
        Vocabulary::new(
            self.literal_names.iter().copied(),
            self.symbolic_names.iter().copied(),
            self.display_names.iter().copied(),
        )
    }

    /// Creates per-instance recognizer state backed by this grammar's cached
    /// immutable metadata.
    pub fn recognizer_data(&self) -> RecognizerData {
        RecognizerData::from_shared(Arc::clone(self.cached_recognizer_metadata()))
    }

    fn cached_recognizer_metadata(&self) -> &Arc<RecognizerMetadata> {
        self.recognizer_metadata.get_or_init(|| {
            Arc::new(RecognizerMetadata::from_static(
                self.grammar_file_name,
                self.rule_names,
                self.channel_names,
                self.mode_names,
                self.vocabulary(),
            ))
        })
    }

    /// Borrows the serialized ATN values for deserialization by the runtime
    /// simulators without copying generated static data.
    pub const fn serialized_atn(&self) -> SerializedAtn<'_> {
        SerializedAtn::from_i32(self.serialized_atn)
    }
}

pub trait GeneratedLexer {
    fn metadata() -> &'static GrammarMetadata;
}

pub trait GeneratedParser {
    fn metadata() -> &'static GrammarMetadata;

    /// Borrows the validated packed ATN embedded by the matching generator.
    fn parser_atn() -> &'static ParserAtn;
}

#[cfg(test)]
mod tests {
    use super::*;

    static META: GrammarMetadata = GrammarMetadata::new(
        "Mini.g4",
        &["file"],
        &[None, Some("'x'")],
        &[None, Some("X")],
        &[None, None],
        &["DEFAULT_TOKEN_CHANNEL", "HIDDEN"],
        &["DEFAULT_MODE"],
        &[4, 1, 1, 0, 0, 0],
    );

    // Compile-only fixture: successful expansion of both facade macros with
    // invocation-site prelude names shadowed is the assertion.
    #[allow(dead_code, unreachable_pub)]
    mod facade_hygiene {
        struct Box;
        struct FnMut;
        struct None;
        struct Option;
        struct Rc;
        struct Result;
        struct Send;
        struct Some;
        struct String;
        struct Vec;

        struct HygieneLexer<I, H> {
            base: crate::lexer::BaseLexer<I>,
            hooks: H,
        }

        struct HygieneParser<S, H> {
            base: crate::parser::BaseParser<S, H>,
            simulator: ::core::option::Option<crate::atn::parser::ParserAtnSimulator<'static>>,
            generated_only: bool,
        }

        fn metadata() -> &'static crate::generated::GrammarMetadata {
            &super::META
        }

        fn parser_atn() -> &'static crate::atn::parser_atn::ParserAtn {
            panic!("compile-only facade hygiene fixture")
        }

        crate::__antlr4_rust_lexer_facade! {
            type: HygieneLexer<I, H>,
            fields: {
                base: base,
                hooks: hooks,
            },
            metadata: metadata,
            next_token(_lexer, _sink) {
                panic!("compile-only facade hygiene fixture")
            }
        }

        crate::__antlr4_rust_parser_facade! {
            type: HygieneParser<S, H>,
            fields: {
                base: base,
                simulator: simulator,
                generated_only: generated_only,
            },
            metadata: metadata,
            parser_atn: parser_atn,
            reset(_parser) {}
        }
    }

    #[test]
    fn metadata_builds_vocabulary() {
        assert_eq!(META.grammar_file_name(), "Mini.g4");
        assert_eq!(META.vocabulary().display_name(1), "'x'");
    }

    #[test]
    fn cloned_metadata_shares_the_cache_before_explicit_initialization() {
        let original = GrammarMetadata::new(
            "Clone.g4",
            &["start"],
            &[None, Some("'x'")],
            &[None, Some("X")],
            &[None, None],
            &["DEFAULT_TOKEN_CHANNEL"],
            &["DEFAULT_MODE"],
            &[],
        );
        let cloned = original.clone();
        let first = original.recognizer_data();
        let second = cloned.recognizer_data();

        assert!(std::ptr::eq(first.rule_names(), second.rule_names()));
        assert!(std::ptr::eq(first.vocabulary(), second.vocabulary()));
    }
}