rusty_lr_parser 4.2.0

grammar line parser for rusty_lr
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
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
use proc_macro2::Ident;
use proc_macro2::Span;
use proc_macro2::TokenStream;

use quote::format_ident;
use quote::quote;

use crate::grammar::Grammar;
use crate::terminal_info::TerminalName;
use crate::utils;

/// emit Rust code for the parser
impl Grammar {
    /// write type alias Context, Rule, Tables, Error...
    fn emit_type_alises(&self, stream: &mut TokenStream) {
        let module_prefix = &self.module_prefix;
        let start_rule_span = self
            .span_manager
            .get_span_in_location(&self.start_rule_name.location());
        let rule_typename = Ident::new(&format!("{}Rule", self.start_rule_name), start_rule_span);
        let tables_typename =
            Ident::new(&format!("{}Tables", self.start_rule_name), start_rule_span);
        let nonterm_typename = Ident::new(
            &format!("{}NonTerminals", self.start_rule_name),
            start_rule_span,
        );
        let parse_error_typename = Ident::new(
            &format!("{}ParseError", self.start_rule_name),
            start_rule_span,
        );
        let parser_struct_name =
            Ident::new(&format!("{}Parser", self.start_rule_name), start_rule_span);
        let context_struct_name =
            Ident::new(&format!("{}Context", self.start_rule_name), start_rule_span);
        let data_stack_typename = Ident::new(
            &format!("{}DataStack", self.start_rule_name),
            start_rule_span,
        );
        let termclass_typename = Ident::new(
            &format!("{}TerminalClasses", self.start_rule_name),
            start_rule_span,
        );
        let location_typename = &self.location_typename;
        let reduce_error_typename = &self.error_typename;

        let table_structname = if self.emit_dense {
            format_ident!("DenseFlatTables")
        } else {
            format_ident!("SparseFlatTables")
        };
        let token_typename = &self.token_typename;

        let state_index_typename = if self.states.len() <= u8::MAX as usize {
            quote! { u8 }
        } else if self.states.len() <= u16::MAX as usize {
            quote! { u16 }
        } else if self.states.len() <= u32::MAX as usize {
            quote! { u32 }
        } else {
            quote! { usize }
        };
        let rule_index_type = if self.builder.rules.len() <= u8::MAX as usize {
            quote! { u8 }
        } else if self.builder.rules.len() <= u16::MAX as usize {
            quote! { u16 }
        } else if self.builder.rules.len() <= u32::MAX as usize {
            quote! { u32 }
        } else {
            quote! { usize }
        };

        let max_reduce_rules = self
            .states
            .iter()
            .flat_map(|s| s.reduce_map.iter().map(|(_, rules)| rules.len()))
            .max()
            .unwrap_or(1);
        let rule_container_type = if self.glr && max_reduce_rules > 1 {
            quote! { #module_prefix::parser::table::ArrayVec<#rule_index_type, #max_reduce_rules> }
        } else {
            rule_index_type.clone()
        };

        if self.glr {
            stream.extend(
            quote! {
                    /// type alias for `Context`
                    #[allow(non_camel_case_types,dead_code)]
                    pub type #context_struct_name = #module_prefix::parser::nondeterministic::Context<#parser_struct_name, #data_stack_typename, #state_index_typename, #max_reduce_rules>;
                    /// type alias for CFG production rule
                    #[allow(non_camel_case_types,dead_code)]
                    pub type #rule_typename = #module_prefix::production::Production<#termclass_typename, #nonterm_typename>;
                    /// type alias for runtime parser tables
                    #[allow(non_camel_case_types,dead_code)]
                    pub type #tables_typename = #module_prefix::parser::table::#table_structname<#termclass_typename, #nonterm_typename, #rule_container_type, #state_index_typename>;
                    /// type alias for `InvalidTerminalError`
                    #[allow(non_camel_case_types,dead_code)]
                    pub type #parse_error_typename = #module_prefix::parser::nondeterministic::ParseError<#token_typename, #location_typename, #reduce_error_typename>;
                }
            );
        } else {
            stream.extend(
        quote! {
                /// type alias for `Context`
                #[allow(non_camel_case_types,dead_code)]
                pub type #context_struct_name = #module_prefix::parser::deterministic::Context<#parser_struct_name, #data_stack_typename, #state_index_typename>;
                /// type alias for CFG production rule
                #[allow(non_camel_case_types,dead_code)]
                pub type #rule_typename = #module_prefix::production::Production<#termclass_typename, #nonterm_typename>;
                /// type alias for runtime parser tables
                #[allow(non_camel_case_types,dead_code)]
                pub type #tables_typename = #module_prefix::parser::table::#table_structname<#termclass_typename, #nonterm_typename, #rule_container_type, #state_index_typename>;
                /// type alias for `ParseError`
                #[allow(non_camel_case_types,dead_code)]
                pub type #parse_error_typename = #module_prefix::parser::deterministic::ParseError<#token_typename, #location_typename, #reduce_error_typename>;
            }
            );
        }
    }

    fn emit_termclass_enum(&self, stream: &mut TokenStream) {
        let start_rule_span = self
            .span_manager
            .get_span_in_location(&self.start_rule_name.location());
        let termclass_typename = Ident::new(
            &format!("{}TerminalClasses", self.start_rule_name),
            start_rule_span,
        );
        let module_prefix = &self.module_prefix;
        let error_name = format_ident!("{}", utils::ERROR_NAME);
        let eof_name = format_ident!("{}", utils::EOF_NAME);
        let token_typename = &self.token_typename;

        let mut class_variants = Vec::with_capacity(self.terminal_classes.len());
        let mut as_str_match_stream = TokenStream::new();
        for (class_id, class_def) in self.terminal_classes.iter().enumerate() {
            let (variant_name, pretty_name) = if self.is_u8 || self.is_char {
                let name = format_ident!("TermClass{}", class_id);
                let pretty_name = self
                    .class_pretty_name_list(rusty_lr_core::TerminalSymbol::Terminal(class_id), 4);
                (name, pretty_name)
            } else {
                if class_def.terminals.len() == 1 {
                    let term_idx = class_def.terminals[0];
                    let term_str = self.terminals[term_idx].name.ident_str().unwrap();
                    let term = Ident::new(term_str, Span::call_site());
                    (term.clone(), term.to_string())
                } else {
                    let name = format_ident!("TermClass{}", class_id);
                    let pretty_name = self.class_pretty_name_list(
                        rusty_lr_core::TerminalSymbol::Terminal(class_id),
                        4,
                    );
                    (name, pretty_name)
                }
            };
            as_str_match_stream.extend(quote! {
                #termclass_typename::#variant_name => #pretty_name,
            });
            class_variants.push(variant_name);
        }

        let other_class_id = self.other_terminal_class_id;

        let mut from_term_match_stream = TokenStream::new();

        // building terminal-class_id map
        if self.is_char || self.is_u8 {
            // range-compressed Vec based terminal-class_id map

            // for terminal -> terminal_class_id map to_terminal_class()
            for (class_id, class_def) in self.terminal_classes.iter().enumerate() {
                if class_id == self.other_terminal_class_id {
                    continue;
                }
                let mut match_case_stream = TokenStream::new();
                for (i, &(s, e)) in class_def.ranges.iter().enumerate() {
                    let stream = if self.is_char {
                        let s = unsafe { char::from_u32_unchecked(s) };
                        let e = unsafe { char::from_u32_unchecked(e) };

                        if s == e {
                            quote! { #s }
                        } else {
                            quote! { #s..=#e }
                        }
                    } else if self.is_u8 {
                        let s = s as u8;
                        let e = e as u8;

                        if s == e {
                            quote! { #s }
                        } else {
                            quote! { #s..=#e }
                        }
                    } else {
                        unreachable!("unexpected char type")
                    };

                    if i > 0 {
                        match_case_stream.extend(quote! {|});
                    }
                    match_case_stream.extend(quote! { #stream });
                }
                let class_variant = &class_variants[class_id];
                from_term_match_stream.extend(quote! {
                    #match_case_stream => #termclass_typename::#class_variant,
                });
            }
            let other_variant = &class_variants[other_class_id];
            from_term_match_stream.extend(quote! {
                _ => #termclass_typename::#other_variant,
            });
        } else {
            // match based terminal-class_id map

            // for terminal -> terminal_class_id map to_terminal_class()
            for (class_id, class_def) in self.terminal_classes.iter().enumerate() {
                if class_id == self.other_terminal_class_id {
                    continue;
                }
                let mut match_case_stream = TokenStream::new();
                for (i, &term) in class_def.terminals.iter().enumerate() {
                    // check if this term is range-based character
                    let case_stream = match &self.terminals[term].name {
                        TerminalName::CharRange(s, l) => {
                            if self.is_char {
                                if s == l {
                                    quote! {#s}
                                } else {
                                    quote! {#s..=#l}
                                }
                            } else if self.is_u8 {
                                let s = *s as u8;
                                let l = *l as u8;
                                if s == l {
                                    quote! {#s}
                                } else {
                                    quote! {#s..=#l}
                                }
                            } else {
                                unreachable!("unexpected char type")
                            }
                        }
                        TerminalName::Ident(_) => {
                            let term_stream = &self.terminals[term].body;
                            quote! {#term_stream}
                        }
                    };

                    if i > 0 {
                        match_case_stream.extend(quote! { | });
                    }
                    match_case_stream.extend(case_stream);
                }
                let class_variant = &class_variants[class_id];
                from_term_match_stream.extend(quote! {
                    #match_case_stream => #termclass_typename::#class_variant,
                });
            }
            let other_class_variant = &class_variants[other_class_id];
            from_term_match_stream.extend(quote! {
                _ => #termclass_typename::#other_class_variant,
            });
        }

        let max_variants = self.terminal_classes.len() + 2;

        stream.extend(quote! {
            /// A enum that represents terminal classes
            #[allow(non_camel_case_types, dead_code)]
            #[derive(Clone, Copy, std::hash::Hash, std::cmp::PartialEq, std::cmp::Eq, std::cmp::PartialOrd, std::cmp::Ord)]
            // repr(usize) is used to ensure a stable memory layout compatible with integer casting and transmutes
            #[repr(usize)]
            pub enum #termclass_typename {
                #(#class_variants),*,
                #error_name,
                #eof_name,
            }

            impl #termclass_typename {
                // Decodes a terminal class from its integer index stored in the serialized parser tables.
                // This avoids verbose static enum instantiations and significantly reduces compiled binary size.
                #[inline]
                pub fn from_usize(value: usize) -> Self {
                    debug_assert!(value < #max_variants, "Terminal class index {} is out of bounds (max {})", value, #max_variants);
                    unsafe { ::std::mem::transmute(value) }
                }
            }

            impl #module_prefix::parser::terminalclass::TerminalClass for #termclass_typename {
                type Term = #token_typename;
                const ERROR:Self = Self::#error_name;
                const EOF:Self = Self::#eof_name;

                fn as_str(&self) -> &'static str {
                    match self {
                        #as_str_match_stream
                        #termclass_typename::#error_name => "error",
                        #termclass_typename::#eof_name => "eof",
                    }
                }
                fn to_usize(&self) -> usize {
                    *self as usize
                }

                fn from_term(terminal: &Self::Term) -> Self {
                    #[allow(unreachable_patterns, unused_variables)]
                    match terminal {
                        #from_term_match_stream
                    }
                }
            }

            impl std::fmt::Display for #termclass_typename {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    use #module_prefix::parser::terminalclass::TerminalClass;
                    write!(f, "{}", self.as_str())
                }
            }
            impl std::fmt::Debug for #termclass_typename {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    use #module_prefix::parser::terminalclass::TerminalClass;
                    write!(f, "{}", self.as_str())
                }
            }
        });
    }

    /// write `NonTerminal` enum
    fn emit_nonterm_enum(&self, stream: &mut TokenStream) {
        // =====================================================================
        // =====================Writing NonTerminal Enum========================
        // =====================================================================

        let start_rule_span = self
            .span_manager
            .get_span_in_location(&self.start_rule_name.location());
        let start_rule_ident = Ident::new(&self.start_rule_name, start_rule_span);
        let enum_typename = format_ident!("{}NonTerminals", start_rule_ident);
        let module_prefix = &self.module_prefix;

        let mut comma_separated_variants = TokenStream::new();
        let mut case_as_str = TokenStream::new();
        let mut nonterm_type_case = TokenStream::new();
        for nonterm in self.nonterminals.iter() {
            let name = utils::ident_from_located(
                nonterm.name.value().as_str(),
                &nonterm.name.location(),
                &self.span_manager,
            );
            // enum variants definition
            comma_separated_variants.extend(quote! {
                #name,
            });

            // impl `Display` and `Debug` for NonTerminal
            let display_str = nonterm.pretty_name.as_str();
            case_as_str.extend(quote! {
                #enum_typename::#name => #display_str,
            });

            if let Some(enum_name) = &nonterm.nonterm_type {
                let enum_name = format!("{:?}", enum_name);
                let enum_name = Ident::new(&enum_name, Span::call_site());
                nonterm_type_case.extend(quote! {
                    #enum_typename::#name => Some(#module_prefix::parser::nonterminal::NonTerminalType::#enum_name),
                });
            } else {
                nonterm_type_case.extend(quote! {
                    #enum_typename::#name => None,
                });
            }
        }

        let max_variants = self.nonterminals.len();

        stream.extend(
    quote! {
            /// An enum that represents non-terminal symbols
            #[allow(non_camel_case_types, dead_code)]
            #[derive(Clone, Copy, std::hash::Hash, std::cmp::PartialEq, std::cmp::Eq, std::cmp::PartialOrd, std::cmp::Ord)]
            // repr(usize) is used to ensure a stable memory layout compatible with integer casting and transmutes
            #[repr(usize)]
            pub enum #enum_typename {
                #comma_separated_variants
            }

            impl #enum_typename {
                // Decodes a non-terminal from its integer index stored in the serialized parser tables.
                // This avoids verbose static enum instantiations and significantly reduces compiled binary size.
                #[inline]
                pub fn from_usize(value: usize) -> Self {
                    debug_assert!(value < #max_variants, "Non-terminal index {} is out of bounds (max {})", value, #max_variants);
                    unsafe { ::std::mem::transmute(value) }
                }
            }
            impl std::fmt::Display for #enum_typename {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    use #module_prefix::parser::nonterminal::NonTerminal;
                    write!(f, "{}", self.as_str())
                }
            }
            impl std::fmt::Debug for #enum_typename {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    use #module_prefix::parser::nonterminal::NonTerminal;
                    write!(f, "{}", self.as_str())
                }
            }

            impl #module_prefix::parser::nonterminal::NonTerminal for #enum_typename{
                fn as_str(&self) -> &'static str {
                    match self {
                        #case_as_str
                    }
                }
                fn nonterm_type(&self) -> Option<#module_prefix::parser::nonterminal::NonTerminalType> {
                    match self {
                        #nonterm_type_case
                    }
                }
                fn to_usize(&self) -> usize {
                    *self as usize
                }
            }
        }
        );
    }

    fn emit_parser(&self, stream: &mut TokenStream) {
        let module_prefix = &self.module_prefix;
        let start_rule_ident = Ident::new(
            &self.start_rule_name,
            self.span_manager
                .get_span_in_location(&self.start_rule_name.location()),
        );
        let nonterminals_enum_name = format_ident!("{}NonTerminals", &start_rule_ident);
        let tables_typename = format_ident!("{}Tables", start_rule_ident);
        let parser_struct_name = format_ident!("{}Parser", start_rule_ident);
        let token_typename = &self.token_typename;
        let termclass_typename = format_ident!("{}TerminalClasses", &start_rule_ident);

        let mut class_variants = Vec::with_capacity(self.terminal_classes.len());
        for (class_id, class_def) in self.terminal_classes.iter().enumerate() {
            let variant_name = if self.is_u8 || self.is_char {
                let name = format_ident!("TermClass{}", class_id);
                name
            } else {
                if class_def.terminals.len() == 1 {
                    let term_idx = class_def.terminals[0];
                    let term_str = self.terminals[term_idx].name.ident_str().unwrap();
                    Ident::new(term_str, Span::call_site())
                } else {
                    let name = format_ident!("TermClass{}", class_id);
                    name
                }
            };
            class_variants.push(variant_name);
        }

        // ======================
        // building grammar
        // ======================
        use rusty_lr_core::TerminalSymbol;

        // do not build at runtime
        // write all parser tables and production rules directly here

        let state_index_typename = if self.states.len() <= u8::MAX as usize {
            quote! { u8 }
        } else if self.states.len() <= u16::MAX as usize {
            quote! { u16 }
        } else if self.states.len() <= u32::MAX as usize {
            quote! { u32 }
        } else {
            quote! { usize }
        };

        let rule_index_typename = if self.builder.rules.len() <= u8::MAX as usize {
            quote! { u8 }
        } else if self.builder.rules.len() <= u16::MAX as usize {
            quote! { u16 }
        } else if self.builder.rules.len() <= u32::MAX as usize {
            quote! { u32 }
        } else {
            quote! { usize }
        };
        let max_reduce_rules = self
            .states
            .iter()
            .flat_map(|s| s.reduce_map.iter().map(|(_, rules)| rules.len()))
            .max()
            .unwrap_or(1);
        let rule_container_type = if self.glr && max_reduce_rules > 1 {
            quote! { #module_prefix::parser::table::ArrayVec<#rule_index_typename, #max_reduce_rules> }
        } else {
            rule_index_typename.clone()
        };

        // ------------------
        // Rules Serialization
        // ------------------
        let mut rule_names = Vec::new();
        let mut rule_lengths = Vec::new();

        for rule in &self.builder.rules {
            assert!(
                rule.rule.lhs < 32768,
                "Non-terminal index {} exceeds 15-bit serialization limit (32768)",
                rule.rule.lhs
            );
            rule_names.push(rule.rule.lhs as u32);
            rule_lengths.push(rule.rule.rhs.len() as u32);
        }

        // ------------------
        // Table Row Serialization
        // ------------------
        let mut shift_term_data = Vec::new();
        let mut shift_term_offsets = Vec::new();
        let mut shift_nonterm_data = Vec::new();
        let mut shift_nonterm_offsets = Vec::new();
        let mut reduce_data = Vec::new();
        let mut reduce_offsets = Vec::new();
        let mut can_accept_error = Vec::new();

        shift_term_offsets.push(0);
        shift_nonterm_offsets.push(0);
        reduce_offsets.push(0);

        for state in &self.states {
            // 1. shift_goto_map_term
            for &(term, next_state) in &state.shift_goto_map_term {
                let term_idx = match term {
                    TerminalSymbol::Terminal(t) => t,
                    TerminalSymbol::Error => self.terminal_classes.len(),
                    TerminalSymbol::Eof => self.terminal_classes.len() + 1,
                };
                let state_idx = next_state.state;
                let push = next_state.push;
                assert!(
                    term_idx < 32768,
                    "Terminal class index {} exceeds 15-bit limit (32768)",
                    term_idx
                );
                assert!(
                    state_idx < 65536,
                    "State index {} exceeds 16-bit limit (65536)",
                    state_idx
                );
                let val = (term_idx as u32) | ((state_idx as u32) << 15) | ((push as u32) << 31);
                shift_term_data.push(val);
            }
            shift_term_offsets.push(shift_term_data.len() as u32);

            // 2. shift_goto_map_nonterm
            for &(nonterm, next_state) in &state.shift_goto_map_nonterm {
                let nonterm_idx = nonterm;
                let state_idx = next_state.state;
                let push = next_state.push;
                assert!(
                    nonterm_idx < 32768,
                    "Non-terminal index {} exceeds 15-bit limit (32768)",
                    nonterm_idx
                );
                assert!(
                    state_idx < 65536,
                    "State index {} exceeds 16-bit limit (65536)",
                    state_idx
                );
                let val = (nonterm_idx as u32) | ((state_idx as u32) << 15) | ((push as u32) << 31);
                shift_nonterm_data.push(val);
            }
            shift_nonterm_offsets.push(shift_nonterm_data.len() as u32);

            // 3. reduce_map: Vec<(TermClass, Vec<usize>)>
            for (term, rules) in &state.reduce_map {
                let term_idx = match term {
                    TerminalSymbol::Terminal(t) => *t,
                    TerminalSymbol::Error => self.terminal_classes.len(),
                    TerminalSymbol::Eof => self.terminal_classes.len() + 1,
                };
                assert!(
                    term_idx < 32768,
                    "Terminal class index {} exceeds 15-bit limit (32768)",
                    term_idx
                );
                reduce_data.push(term_idx as u32);
                reduce_data.push(rules.len() as u32);
                for &rule in rules {
                    assert!(
                        rule < 65536,
                        "Rule index {} exceeds 16-bit limit (65536)",
                        rule
                    );
                    reduce_data.push(rule as u32);
                }
            }
            reduce_offsets.push(reduce_data.len() as u32);

            // 5. can_accept_error: TriState
            let tri_val = match state.can_accept_error {
                rusty_lr_core::TriState::False => 0u8,
                rusty_lr_core::TriState::True => 1u8,
                rusty_lr_core::TriState::Maybe => 2u8,
            };
            can_accept_error.push(tri_val);
        }

        let num_rules = self.builder.rules.len();
        let num_states = self.states.len();
        let error_used = self.error_used;

        // to remove suffix from generated data
        let rule_names = rule_names
            .into_iter()
            .map(proc_macro2::Literal::u32_unsuffixed);

        let rule_lengths = rule_lengths
            .into_iter()
            .map(proc_macro2::Literal::u32_unsuffixed);

        let shift_term_data = shift_term_data
            .into_iter()
            .map(proc_macro2::Literal::u32_unsuffixed);
        let shift_term_offsets = shift_term_offsets
            .into_iter()
            .map(proc_macro2::Literal::u32_unsuffixed);
        let shift_nonterm_data = shift_nonterm_data
            .into_iter()
            .map(proc_macro2::Literal::u32_unsuffixed);
        let shift_nonterm_offsets = shift_nonterm_offsets
            .into_iter()
            .map(proc_macro2::Literal::u32_unsuffixed);
        let reduce_data = reduce_data
            .into_iter()
            .map(proc_macro2::Literal::u32_unsuffixed);
        let reduce_offsets = reduce_offsets
            .into_iter()
            .map(proc_macro2::Literal::u32_unsuffixed);
        let can_accept_error = can_accept_error
            .into_iter()
            .map(proc_macro2::Literal::u8_unsuffixed);

        // range-compressed Vec based terminal-class_id map
        stream.extend(quote! {
            /// A lightweight parser struct that references the static parser tables and production rules.
            ///
            /// Since this struct only holds `'static` references to shared, read-only static parser tables,
            /// it is extremely cheap to instantiate, copy, or clone, and takes very little space.
            #[allow(unused_braces, unused_parens, unused_variables, non_snake_case, unused_mut)]
            #[derive(Clone, Copy)]
            pub struct #parser_struct_name;

            unsafe impl ::std::marker::Send for #parser_struct_name {}
            unsafe impl ::std::marker::Sync for #parser_struct_name {}
            #[rustfmt::skip]
            impl #module_prefix::parser::Parser for #parser_struct_name {
                type Term = #token_typename;
                type TermClass = #termclass_typename;
                type NonTerm = #nonterminals_enum_name;
                type StateIndex = #state_index_typename;
                type ReduceRules = #rule_container_type;
                type Tables = #tables_typename;

                const ERROR_USED:bool = #error_used;


                // get_tables returns the decoded flat runtime parser tables.
                // Serialized integer arrays keep the generated source compact while Context keeps the
                // decoded table reference out of the parsing hot path.
                fn get_tables() -> &'static #tables_typename {
                    static TABLES: std::sync::OnceLock<#tables_typename> = std::sync::OnceLock::new();
                    TABLES.get_or_init(|| {
                        // Serialized rule properties:
                        // - RULE_NAMES: NonTerm enum value of the rule LHS name
                        // - RULE_LENGTHS: RHS length of each production rule
                        static RULE_NAMES: &[u32] = &[ #(#rule_names),* ];
                        static RULE_LENGTHS: &[u32] = &[ #(#rule_lengths),* ];

                        // Serialized table row properties:
                        // - SHIFT_TERM_DATA & SHIFT_NONTERM_DATA: Packed transitions (push << 31) | (state_idx << 15) | (symbol_idx)
                        // - SHIFT_TERM_OFFSETS & SHIFT_NONTERM_OFFSETS: Boundaries separating transitions for each state
                        // - REDUCE_DATA: Variable-length reduce map encoding (term_class, len, rules...)
                        // - REDUCE_OFFSETS: Boundaries separating reduce maps for each state
                        // - CAN_ACCEPT_ERROR: TriState (0 = False, 1 = True, 2 = Maybe)
                        static SHIFT_TERM_DATA: &[u32] = &[ #(#shift_term_data),* ];
                        static SHIFT_TERM_OFFSETS: &[u32] = &[ #(#shift_term_offsets),* ];
                        static SHIFT_NONTERM_DATA: &[u32] = &[ #(#shift_nonterm_data),* ];
                        static SHIFT_NONTERM_OFFSETS: &[u32] = &[ #(#shift_nonterm_offsets),* ];
                        static REDUCE_DATA: &[u32] = &[ #(#reduce_data),* ];
                        static REDUCE_OFFSETS: &[u32] = &[ #(#reduce_offsets),* ];
                        static CAN_ACCEPT_ERROR: &[u8] = &[ #(#can_accept_error),* ];

                        let num_rules = #num_rules;
                        let mut rules = Vec::with_capacity(num_rules);
                        for i in 0..num_rules {
                            let lhs = #nonterminals_enum_name::from_usize(RULE_NAMES[i] as usize);

                            rules.push(#module_prefix::parser::table::RuleInfo {
                                lhs,
                                len: RULE_LENGTHS[i] as usize,
                            });
                        }

                        let num_states = #num_states;
                        let mut state_rows = Vec::with_capacity(num_states);
                        for i in 0..num_states {
                            // Decode shift transitions for terminals (terminal class, next state index, push flag)
                            let term_start = SHIFT_TERM_OFFSETS[i] as usize;
                            let term_end = SHIFT_TERM_OFFSETS[i + 1] as usize;
                            let mut shift_goto_map_term = Vec::with_capacity(term_end - term_start);
                            for idx in term_start..term_end {
                                let val = SHIFT_TERM_DATA[idx];
                                let term_class = #termclass_typename::from_usize((val & 0x7fff) as usize);
                                let state = ((val >> 15) & 0xffff) as usize;
                                let push = (val >> 31) != 0;
                                shift_goto_map_term.push((term_class, #module_prefix::parser::table::ShiftTarget::new(state, push)));
                            }

                            // Decode shift transitions for non-terminals (non-terminal index, next state index, push flag)
                            let nonterm_start = SHIFT_NONTERM_OFFSETS[i] as usize;
                            let nonterm_end = SHIFT_NONTERM_OFFSETS[i + 1] as usize;
                            let mut shift_goto_map_nonterm = Vec::with_capacity(nonterm_end - nonterm_start);
                            for idx in nonterm_start..nonterm_end {
                                let val = SHIFT_NONTERM_DATA[idx];
                                let nonterm = #nonterminals_enum_name::from_usize((val & 0x7fff) as usize);
                                let state = ((val >> 15) & 0xffff) as usize;
                                let push = (val >> 31) != 0;
                                shift_goto_map_nonterm.push((nonterm, #module_prefix::parser::table::ShiftTarget::new(state, push)));
                            }

                            // Decode the reduce action map (variable-length encoding)
                            let reduce_start = REDUCE_OFFSETS[i] as usize;
                            let reduce_end = REDUCE_OFFSETS[i + 1] as usize;
                            let mut reduce_map = Vec::new();
                            let mut idx = reduce_start;
                            while idx < reduce_end {
                                let term_val = REDUCE_DATA[idx];
                                let term_class = #termclass_typename::from_usize(term_val as usize);
                                let len = REDUCE_DATA[idx + 1] as usize;
                                let mut rules = Vec::with_capacity(len);
                                for r_idx in 0..len {
                                    rules.push(REDUCE_DATA[idx + 2 + r_idx] as usize);
                                }
                                reduce_map.push((term_class, rules));
                                idx += 2 + len;
                            }

                            let can_accept_error = match CAN_ACCEPT_ERROR[i] {
                                0 => #module_prefix::TriState::False,
                                1 => #module_prefix::TriState::True,
                                2 => #module_prefix::TriState::Maybe,
                                _ => unreachable!(),
                            };

                            let intermediate = #module_prefix::parser::state::IntermediateState {
                                shift_goto_map_term,
                                shift_goto_map_nonterm,
                                reduce_map,
                                ruleset: Vec::new(),
                                can_accept_error,
                            };
                            state_rows.push(intermediate);
                        }

                        #module_prefix::parser::table::IntermediateTables {
                            state_rows,
                            rules,
                        }.into()
                    })
                }
            }
        });
    }

    fn emit_data_stack(&self, stream: &mut TokenStream) {
        use rusty_lr_core::Symbol;
        use rusty_lr_core::TerminalSymbol;

        let module_prefix = &self.module_prefix;
        let start_rule_ident = Ident::new(
            &self.start_rule_name,
            self.span_manager
                .get_span_in_location(&self.start_rule_name.location()),
        );
        let nonterminals_enum_name = format_ident!("{}NonTerminals", &start_rule_ident);
        let reduce_error_typename = &self.error_typename;
        let data_stack_typename = format_ident!("{}DataStack", start_rule_ident);
        let data_enum_typename = format_ident!("{}Data", &start_rule_ident);
        let token_typename = &self.token_typename;
        let user_data_parameter_name =
            Ident::new(utils::USER_DATA_PARAMETER_NAME, Span::call_site());
        let user_data_typename = &self.userdata_typename;
        let location_typename = &self.location_typename;

        // empty tag name
        let empty_variant_name = format_ident!("Empty");
        // variant name for terminal symbol
        let terminal_variant_name = format_ident!("__terminals");

        // variant name for each non-terminal
        let mut variant_names_for_nonterm = Vec::with_capacity(self.nonterminals.len());

        fn remove_whitespaces(s: String) -> String {
            s.chars().filter(|c| !c.is_whitespace()).collect()
        }

        // Map containing (<RuleType as ToString>, variant_name).
        // This maps each rule type to its enum variant name (e.g. __variant0, __variant1), merging identical types.
        let mut ruletype_variant_map: rusty_lr_core::hash::HashMap<String, Ident> =
            Default::default();

        // (variant_name, TokenStream for typename, is_boxed) sorted in insertion order
        // for consistent output
        let mut variant_names_in_order = Vec::new();

        let mut terminal_data_used = false;

        // insert variant for terminal token type
        if self.terminal_classes.iter().any(|c| c.data_used) {
            terminal_data_used = true;
            let terminal_boxed = self.is_tokentype_boxed;
            let key = format!(
                "{}_boxed:{}",
                remove_whitespaces(self.token_typename.to_string()),
                terminal_boxed
            );
            ruletype_variant_map.insert(key, terminal_variant_name.clone());
            variant_names_in_order.push((
                terminal_variant_name.clone(),
                self.token_typename.clone(),
                terminal_boxed,
            ));
        }

        // iterates through nonterminals
        for nonterm in self.nonterminals.iter() {
            if let Some(ruletype_stream) = nonterm.ruletype.as_ref().cloned() {
                let cur_len = ruletype_variant_map.len();
                let key = format!(
                    "{}_boxed:{}",
                    remove_whitespaces(ruletype_stream.to_string()),
                    nonterm.ruletype_boxed
                );
                let variant_name = ruletype_variant_map
                    .entry(key)
                    .or_insert_with(|| {
                        let new_variant_name = format_ident!("__variant{}", cur_len);
                        variant_names_in_order.push((
                            new_variant_name.clone(),
                            ruletype_stream.clone(),
                            nonterm.ruletype_boxed,
                        ));
                        new_variant_name
                    })
                    .clone();
                variant_names_for_nonterm.push(variant_name);
            } else {
                variant_names_for_nonterm.push(empty_variant_name.clone());
            }
        }

        // Maps tokens to their corresponding variant names. If the token holds no data, it maps to `Empty`.
        let token_to_variant_name = |token: Symbol<TerminalSymbol<usize>, usize>| match token {
            Symbol::Terminal(term) => match term {
                TerminalSymbol::Terminal(term) => {
                    if self.terminal_classes[term].data_used {
                        &terminal_variant_name
                    } else {
                        &empty_variant_name
                    }
                }
                TerminalSymbol::Error | TerminalSymbol::Eof => &empty_variant_name,
            },
            Symbol::NonTerminal(nonterm_idx) => &variant_names_for_nonterm[nonterm_idx],
        };

        let mut reduce_action_case_streams = quote! {};

        // TokenStream to define reduce function for each production rule
        let mut fn_reduce_for_each_rule_stream = TokenStream::new();

        for (i, action) in self.custom_reduce_actions.iter().enumerate() {
            let fn_name = format_ident!("custom_reduce_action_{}", i);

            let data_arg = action
                .input_type
                .as_ref()
                .map(|(name, ty)| {
                    let name_ident = format_ident!("{}", name);
                    quote! { mut #name_ident: #ty, }
                })
                .unwrap_or_default();

            let location_arg = action
                .input_location
                .as_ref()
                .map(|name| {
                    let name_ident = format_ident!("{}", name);
                    quote! { mut #name_ident: #location_typename, }
                })
                .unwrap_or_default();

            let body = &action.body.body;

            let output_type = if let Some(ty) = action.output_type.as_ref() {
                ty.clone()
            } else {
                quote! { () }
            };

            fn_reduce_for_each_rule_stream.extend(quote! {
                fn #fn_name(
                    #data_arg
                    #location_arg
                    #user_data_parameter_name: &mut #user_data_typename,
                    __rustylr_location0: &mut #location_typename,
                ) -> Result<#output_type, #reduce_error_typename> {
                    Ok(#body)
                }
            });
        }

        let mut rule_index: usize = 0;
        for (nonterm_idx, nonterm) in self.nonterminals.iter().enumerate() {
            for (rule_local_id, rule) in nonterm.rules.iter().enumerate() {
                let reduce_fn_ident =
                    format_ident!("reduce_{}_{}", nonterm.name.value(), rule_local_id);

                let rule_debug_str = format!(
                    "{} -> {}",
                    self.nonterm_pretty_name(nonterm_idx),
                    rule.tokens
                        .iter()
                        .map(|t| {
                            match t.symbol {
                                Symbol::Terminal(term) => self.class_pretty_name_list(term, 5),
                                Symbol::NonTerminal(nonterm) => self.nonterm_pretty_name(nonterm),
                            }
                        })
                        .collect::<Vec<_>>()
                        .join(" ")
                );

                use super::nonterminal_info::ReduceAction;

                if rule.is_used {
                    // Generate debug assertions to verify that the variants on the data stack
                    // match the expected token/non-terminal variants in the production rule.
                    let mut debug_tag_check_stream = TokenStream::new();
                    for (token_idx, token) in rule.tokens.iter().enumerate().rev() {
                        let token_index_from_end = rule.tokens.len() - 1 - token_idx;
                        let variant_name = token_to_variant_name(token.symbol);

                        if variant_name == &empty_variant_name {
                            debug_tag_check_stream.extend(quote! {
                                debug_assert!(
                                    matches!(
                                        __data_stack.__stack.get(
                                            __data_stack.__stack.len()-1-#token_index_from_end
                                        ),
                                        Some(&#data_enum_typename::Empty)
                                    )
                                );
                            });
                        } else {
                            debug_tag_check_stream.extend(quote! {
                                debug_assert!(
                                    matches!(
                                        __data_stack.__stack.get(
                                            __data_stack.__stack.len()-1-#token_index_from_end
                                        ),
                                        Some(&#data_enum_typename::#variant_name(_))
                                    )
                                );
                            });
                        }
                    }

                    // Generate code to extract values and locations from the stacks for the reduce action.
                    // Since the data stack is a single unified vector, we pop from it in reverse chronological order (right to left).
                    let mut extract_data_stream = TokenStream::new();

                    let mut location_maptos = Vec::with_capacity(rule.tokens.len());
                    let mut data_maptos = Vec::with_capacity(rule.tokens.len());

                    for (token_idx, token) in rule.tokens.iter().enumerate().rev() {
                        let variant_name = token_to_variant_name(token.symbol);

                        // Determine location_mapto
                        let location_mapto = if token.reduce_action_chains.is_empty() {
                            let location_index_varname_str =
                                format!("__rustylr_location_{}", token_idx);
                            let index_var_used =
                                rule.reduce_action_contains_ident(&location_index_varname_str);

                            if let Some(mapto) = &token.mapto {
                                let location_varname =
                                    format_ident!("__rustylr_location_{}", mapto.value());
                                let location_varname_str =
                                    format!("__rustylr_location_{}", mapto.value());
                                let mapto_used =
                                    rule.reduce_action_contains_ident(&location_varname_str);

                                if index_var_used {
                                    Some(format_ident!("__rustylr_location_{}", token_idx))
                                } else if mapto_used {
                                    Some(location_varname)
                                } else {
                                    None
                                }
                            } else {
                                if index_var_used {
                                    Some(format_ident!("__rustylr_location_{}", token_idx))
                                } else {
                                    None
                                }
                            }
                        } else {
                            if token.reduce_action_chains.iter().any(|&idx| {
                                let action = &self.custom_reduce_actions[idx];
                                action.input_location.is_some()
                            }) {
                                Some(format_ident!("__rustylr_location_{}", token_idx))
                            } else {
                                None
                            }
                        };
                        location_maptos.push(location_mapto);

                        // Determine mapto for data
                        let mapto = if variant_name != &empty_variant_name {
                            if let Some(first_chain) = token.reduce_action_chains.first() {
                                let first_chain = &self.custom_reduce_actions[*first_chain];
                                if first_chain.input_type.is_some() {
                                    Some(format_ident!("__rustylr_data_{}", token_idx))
                                } else {
                                    None
                                }
                            } else {
                                // check if index-based variable __rustylr_data_{token_idx} is used
                                let index_var_used = rule.reduce_action_contains_ident(&format!(
                                    "__rustylr_data_{}",
                                    token_idx
                                ));

                                if let Some(mapto) = &token.mapto {
                                    let mapto_used =
                                        rule.reduce_action_contains_ident(mapto.value().as_str());
                                    if index_var_used {
                                        Some(format_ident!("__rustylr_data_{}", token_idx))
                                    } else if mapto_used {
                                        Some(format_ident!("{}", mapto.value()))
                                    } else {
                                        None
                                    }
                                } else {
                                    if index_var_used {
                                        Some(format_ident!("__rustylr_data_{}", token_idx))
                                    } else {
                                        None
                                    }
                                }
                            }
                        } else {
                            None
                        };

                        if variant_name != &empty_variant_name && mapto.is_some() {
                            let is_boxed = match token.symbol {
                                Symbol::Terminal(_) => self.is_tokentype_boxed,
                                Symbol::NonTerminal(nonterm_idx) => {
                                    self.nonterminals[nonterm_idx].ruletype_boxed
                                }
                            };
                            data_maptos.push(Some((
                                variant_name.clone(),
                                mapto.unwrap(),
                                is_boxed,
                            )));
                        } else {
                            data_maptos.push(None);
                        }
                    }

                    // 1. Generate location pops/truncates
                    {
                        let mut consecutive_unneeded = 0;
                        for loc_mapto in &location_maptos {
                            if let Some(loc_mapto) = loc_mapto {
                                if consecutive_unneeded > 0 {
                                    if consecutive_unneeded == 1 {
                                        extract_data_stream.extend(quote! {
                                            __location_stack.pop();
                                        });
                                    } else {
                                        let consecutive_unneeded =
                                            syn::Index::from(consecutive_unneeded);
                                        extract_data_stream.extend(quote! {
                                            __location_stack.truncate(__location_stack.len() - #consecutive_unneeded);
                                        });
                                    }
                                    consecutive_unneeded = 0;
                                }
                                extract_data_stream.extend(quote! {
                                    let mut #loc_mapto = __location_stack.pop().unwrap();
                                });
                            } else {
                                consecutive_unneeded += 1;
                            }
                        }
                        if consecutive_unneeded > 0 {
                            if consecutive_unneeded == 1 {
                                extract_data_stream.extend(quote! {
                                    __location_stack.pop();
                                });
                            } else {
                                let consecutive_unneeded = syn::Index::from(consecutive_unneeded);
                                extract_data_stream.extend(quote! {
                                    __location_stack.truncate(__location_stack.len() - #consecutive_unneeded);
                                });
                            }
                        }
                    }

                    // 2. Generate data stack pops/truncates
                    {
                        let mut consecutive_unneeded = 0;
                        for data_info in &data_maptos {
                            if let Some((variant_name, data_mapto, is_boxed)) = data_info {
                                if consecutive_unneeded > 0 {
                                    if consecutive_unneeded == 1 {
                                        extract_data_stream.extend(quote! {
                                            __data_stack.__stack.pop();
                                        });
                                    } else {
                                        let consecutive_unneeded =
                                            syn::Index::from(consecutive_unneeded);
                                        extract_data_stream.extend(quote! {
                                            __data_stack.__stack.truncate(__data_stack.__stack.len() - #consecutive_unneeded);
                                        });
                                    }
                                    consecutive_unneeded = 0;
                                }
                                let val_extracted = if *is_boxed {
                                    quote! { *val }
                                } else {
                                    quote! { val }
                                };
                                extract_data_stream.extend(quote! {
                                    let mut #data_mapto = match __data_stack.__stack.pop().unwrap() {
                                        #data_enum_typename::#variant_name(val) => #val_extracted,
                                        _ => unreachable!(),
                                    };
                                });
                            } else {
                                consecutive_unneeded += 1;
                            }
                        }
                        if consecutive_unneeded > 0 {
                            if consecutive_unneeded == 1 {
                                extract_data_stream.extend(quote! {
                                    __data_stack.__stack.pop();
                                });
                            } else {
                                let consecutive_unneeded = syn::Index::from(consecutive_unneeded);
                                extract_data_stream.extend(quote! {
                                    __data_stack.__stack.truncate(__data_stack.__stack.len() - #consecutive_unneeded);
                                });
                            }
                        }
                    }

                    let mut alias_stream = TokenStream::new();
                    for (token_idx, token) in rule.tokens.iter().enumerate() {
                        if token.reduce_action_chains.is_empty() {
                            if let Some(mapto) = &token.mapto {
                                let mapto_used =
                                    rule.reduce_action_contains_ident(mapto.value().as_str());
                                let index_var_used = rule.reduce_action_contains_ident(&format!(
                                    "__rustylr_data_{}",
                                    token_idx
                                ));
                                if mapto_used && index_var_used {
                                    let mapto_ident = format_ident!("{}", mapto.value());
                                    let data_varname =
                                        format_ident!("__rustylr_data_{}", token_idx);
                                    alias_stream.extend(quote! {
                                        let mut #mapto_ident = #data_varname;
                                    });
                                }

                                let location_varname_str =
                                    format!("__rustylr_location_{}", mapto.value());
                                let location_mapto_used =
                                    rule.reduce_action_contains_ident(&location_varname_str);
                                let location_index_varname_str =
                                    format!("__rustylr_location_{}", token_idx);
                                let location_index_var_used =
                                    rule.reduce_action_contains_ident(&location_index_varname_str);
                                if location_mapto_used && location_index_var_used {
                                    let mapto_ident = format_ident!("{}", location_varname_str);
                                    let data_varname =
                                        format_ident!("{}", location_index_varname_str);
                                    alias_stream.extend(quote! {
                                        let mut #mapto_ident = #data_varname;
                                    });
                                }
                            }
                        }
                    }

                    let mut custom_reduce_action_stream = TokenStream::new();
                    for (token_idx, token) in rule.tokens.iter().enumerate() {
                        if token.reduce_action_chains.is_empty() {
                            continue;
                        }
                        let data_varname = format_ident!("__rustylr_data_{}", token_idx);
                        let location_varname = format_ident!("__rustylr_location_{}", token_idx);
                        let location_used_in_this_action = if let Some(mapto) = &token.mapto {
                            let location_mapto_str =
                                format!("__rustylr_location_{}", mapto.value());
                            rule.reduce_action_contains_ident(&location_mapto_str)
                        } else {
                            false
                        };

                        for (idx, &chain_idx) in token.reduce_action_chains.iter().enumerate() {
                            let action = &self.custom_reduce_actions[chain_idx];
                            let fn_name = format_ident!("custom_reduce_action_{}", chain_idx);

                            let data_arg = if action.input_type.is_some() {
                                quote! { #data_varname, }
                            } else {
                                quote! {}
                            };

                            // if location is needed for later reduce action, pass by clone
                            // else, pass by move
                            let mut location_used_later = location_used_in_this_action;
                            if !location_used_later {
                                for &chain_idx in token.reduce_action_chains[idx + 1..].iter() {
                                    let action = &self.custom_reduce_actions[chain_idx];
                                    if action.input_location.is_some() {
                                        location_used_later = true;
                                        break;
                                    }
                                }
                            }
                            let location_arg = if action.input_location.is_some() {
                                if location_used_later {
                                    quote! { #location_varname.clone(), }
                                } else {
                                    quote! { #location_varname, }
                                }
                            } else {
                                quote! {}
                            };

                            custom_reduce_action_stream.extend(quote! {
                                let #data_varname = Self::#fn_name(
                                    #data_arg
                                    #location_arg
                                    #user_data_parameter_name,
                                    __rustylr_location0,
                                )?;
                            });
                        }

                        if let Some(mapto) = &token.mapto {
                            let mapto_ident = format_ident!("{}", mapto.value());
                            if rule.reduce_action_contains_ident(mapto.value().as_str()) {
                                custom_reduce_action_stream.extend(quote! {
                                    let mut #mapto_ident = #data_varname;
                                });
                            }
                            let location_mapto_varname =
                                format_ident!("__rustylr_location_{}", mapto.value());
                            let location_mapto_str =
                                format!("__rustylr_location_{}", mapto.value());

                            if rule.reduce_action_contains_ident(&location_mapto_str) {
                                custom_reduce_action_stream.extend(quote! {
                                    let mut #location_mapto_varname = #location_varname;
                                });
                            }
                        }
                    }

                    reduce_action_case_streams.extend(quote! {
                        #rule_index => Self::#reduce_fn_ident( data_stack, location_stack, push_data, shift, lookahead, user_data, location0 ),
                    });

                    let reduce_action_body = match &rule.reduce_action {
                        Some(ReduceAction::Custom(custom)) => {
                            let body = &custom.body;
                            quote! { #body }
                        }
                        Some(ReduceAction::Identity(identity_idx)) => {
                            let ith_ident = format_ident!(
                                "{}",
                                rule.tokens[*identity_idx].mapto.as_ref().unwrap().value()
                            );
                            quote! { #ith_ident }
                        }
                        None => TokenStream::new(),
                    };
                    let variant_name = &variant_names_for_nonterm[nonterm_idx];
                    if variant_name != &empty_variant_name {
                        let res_expr = if reduce_action_body.is_empty() {
                            quote! { () }
                        } else {
                            quote! { #reduce_action_body }
                        };
                        let push_val = if nonterm.ruletype_boxed {
                            quote! { ::std::boxed::Box::new(__res) }
                        } else {
                            quote! { __res }
                        };
                        fn_reduce_for_each_rule_stream.extend(quote! {
                            #[doc = #rule_debug_str]
                            #[inline]
                            fn #reduce_fn_ident(
                                __data_stack: &mut Self,
                                __location_stack: &mut Vec<#location_typename>,
                                __push_data: bool,
                                shift: &mut bool,
                                lookahead: &#module_prefix::TerminalSymbol<#token_typename>,
                                #user_data_parameter_name: &mut #user_data_typename,
                                __rustylr_location0: &mut #location_typename,
                            ) -> Result<(), #reduce_error_typename> {
                                #[cfg(debug_assertions)]
                                {
                                    #debug_tag_check_stream
                                }

                                #extract_data_stream
                                #alias_stream
                                #custom_reduce_action_stream

                                let __res = #res_expr;
                                if __push_data {
                                    __data_stack.__stack.push(#data_enum_typename::#variant_name(#push_val));
                                } else {
                                    __data_stack.__stack.push(#data_enum_typename::Empty);
                                }

                                Ok(())
                            }
                        });
                    } else {
                        let semicolon_or_empty = if reduce_action_body.is_empty() {
                            quote! {}
                        } else {
                            quote! { ; }
                        };
                        fn_reduce_for_each_rule_stream.extend(quote! {
                            #[doc = #rule_debug_str]
                            #[inline]
                            fn #reduce_fn_ident(
                                __data_stack: &mut Self,
                                __location_stack: &mut Vec<#location_typename>,
                                __push_data: bool,
                                shift: &mut bool,
                                lookahead: &#module_prefix::TerminalSymbol<#token_typename>,
                                #user_data_parameter_name: &mut #user_data_typename,
                                __rustylr_location0: &mut #location_typename,
                            ) -> Result<(), #reduce_error_typename> {
                                #[cfg(debug_assertions)]
                                {
                                    #debug_tag_check_stream
                                }

                                #extract_data_stream
                                #alias_stream
                                #custom_reduce_action_stream

                                #reduce_action_body #semicolon_or_empty
                                __data_stack.__stack.push(#data_enum_typename::Empty);

                                Ok(())
                            }
                        });
                    }
                }
                rule_index += 1;
            }
        }

        let start_idx = *self
            .nonterminals_index
            .get(self.start_rule_name.value())
            .unwrap();
        let start_variant_name = &variant_names_for_nonterm[start_idx];
        // Generate the pop_start implementation.
        // At the time of acceptance, the stack contains the EOF token (which has no data, i.e., Empty)
        // on top of the actual start symbol's value. We pop the EOF token first, and then retrieve the start value.
        let (start_typename, pop_start) = if start_variant_name != &empty_variant_name {
            let ruletype = self.nonterminals[start_idx]
                .ruletype
                .as_ref()
                .unwrap()
                .clone();

            let is_start_boxed = self.nonterminals[start_idx].ruletype_boxed;
            let val_expr = if is_start_boxed {
                quote! { *val }
            } else {
                quote! { val }
            };

            (
                ruletype,
                quote! {
                    self.__stack.pop();
                    match self.__stack.pop() {
                        Some(#data_enum_typename::#start_variant_name(val)) => Some(#val_expr),
                        _ => None,
                    }
                },
            )
        } else {
            (
                quote! {()},
                quote! {
                    self.__stack.pop();
                    match self.__stack.pop() {
                        Some(#data_enum_typename::Empty) => Some(()),
                        _ => None,
                    }
                },
            )
        };

        let derive_clone_for_glr = if self.glr {
            quote! {#[derive(Clone)]}
        } else {
            quote! {}
        };

        let push_terminal_body_stream = if terminal_data_used {
            let push_val = if self.is_tokentype_boxed {
                quote! { ::std::boxed::Box::new(term) }
            } else {
                quote! { term }
            };
            quote! {
                self.__stack.push(#data_enum_typename::#terminal_variant_name(#push_val));
            }
        } else {
            quote! {
                self.__stack.push(#data_enum_typename::Empty);
            }
        };
        let push_empty_body_stream = quote! {
            self.__stack.push(#data_enum_typename::Empty);
        };

        let data_enum_definition = {
            let mut variants = TokenStream::new();
            for (variant_name, typename, boxed) in &variant_names_in_order {
                if *boxed {
                    variants.extend(quote! {
                        #variant_name(::std::boxed::Box<#typename>),
                    });
                } else {
                    variants.extend(quote! {
                        #variant_name(#typename),
                    });
                }
            }
            variants.extend(quote! {
                Empty,
            });
            quote! {
                /// enum for each non-terminal and terminal symbol, that actually hold data
                #[rustfmt::skip]
                #[allow(unused_braces, unused_parens, non_snake_case, non_camel_case_types)]
                #derive_clone_for_glr
                pub enum #data_enum_typename {
                    #variants
                }
            }
        };

        stream.extend(quote! {

        #data_enum_definition

        /// enum for each non-terminal and terminal symbol, that actually hold data
        #[rustfmt::skip]
        #[allow(unused_braces, unused_parens, non_snake_case, non_camel_case_types)]
        #derive_clone_for_glr
        pub struct #data_stack_typename {
            pub __stack: Vec<#data_enum_typename>,
        }

        impl Default for #data_stack_typename {
            fn default() -> Self {
                Self {
                    __stack: Vec::new(),
                }
            }
        }

        #[rustfmt::skip]
        #[allow(unused_braces, unused_parens, unused_variables, non_snake_case, unused_mut, dead_code)]
        impl #data_stack_typename {
            #fn_reduce_for_each_rule_stream
        }


        #[rustfmt::skip]
        #[allow(unused_braces, unused_parens, non_snake_case, non_camel_case_types, unused_variables)]
        impl #module_prefix::parser::data_stack::DataStack for #data_stack_typename {
            type Term = #token_typename;
            type NonTerm = #nonterminals_enum_name;
            type ReduceActionError = #reduce_error_typename;
            type UserData = #user_data_typename;
            type StartType = #start_typename;
            type Location = #location_typename;

            fn pop_start(&mut self) -> Option<Self::StartType> {
                #pop_start
            }
            fn pop(&mut self) {
                self.__stack.pop();
            }
            fn push_terminal(&mut self, term: Self::Term) {
                #push_terminal_body_stream
            }
            fn push_empty(&mut self) {
                #push_empty_body_stream
            }

            // Trait operations like clear, split_off, truncate, and append are highly simplified
            // and efficient because they only need to perform a single vector operation on the unified stack.
            fn clear(&mut self) {
                self.__stack.clear();
            }
            fn reserve(&mut self, additional: usize) {
                self.__stack.reserve(additional);
            }

            fn split_off(&mut self, at: usize) -> Self {
                Self {
                    __stack: self.__stack.split_off(at),
                }
            }
            fn truncate(&mut self, at: usize) {
                self.__stack.truncate(at);
            }
            fn append(&mut self, other: &mut Self) {
                self.__stack.append(&mut other.__stack);
            }

            fn reduce_action(
                data_stack: &mut Self,
                location_stack: &mut Vec<#location_typename>,
                push_data: bool,
                rule_index: usize,
                shift: &mut bool,
                lookahead: &#module_prefix::TerminalSymbol<Self::Term>,
                user_data: &mut Self::UserData,
                location0: &mut Self::Location,
            ) -> Result<(), Self::ReduceActionError> {
                match rule_index {
                    #reduce_action_case_streams
                    _ => {
                        unreachable!( "Invalid Rule: {}", rule_index );
                    }
                }
            }
        }

        });
    }

    pub fn emit_compiletime(&self) -> TokenStream {
        let mut stream = TokenStream::new();
        self.emit_type_alises(&mut stream);
        self.emit_termclass_enum(&mut stream);
        self.emit_nonterm_enum(&mut stream);
        self.emit_data_stack(&mut stream);
        self.emit_parser(&mut stream);

        stream
    }
}