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
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
//! A compiler from an LR(1) table to a traditional table driven parser.

use crate::collections::{Entry, Map, Set};
use crate::grammar::repr::*;
use crate::lr1::core::*;
use crate::lr1::lookahead::Token;
use crate::rust::RustWrite;
use crate::tls::Tls;
use crate::util::Sep;
use itertools::Itertools;
use std::fmt;
use std::io::{self, Write};
use std::rc::Rc;
use string_cache::DefaultAtom as Atom;

use super::base::CodeGenerator;

const DEBUG_PRINT: bool = false;

pub fn compile<'grammar, W: Write>(
    grammar: &'grammar Grammar,
    user_start_symbol: NonterminalString,
    start_symbol: NonterminalString,
    states: &[Lr1State<'grammar>],
    action_module: &str,
    out: &mut RustWrite<W>,
) -> io::Result<()> {
    let mut table_driven = CodeGenerator::new_table_driven(
        grammar,
        user_start_symbol,
        start_symbol,
        states,
        action_module,
        out,
    );
    table_driven.write()
}

enum Comment<'a, T> {
    Goto(T, usize),
    Error(T),
    Reduce(T, &'a Production),
}

impl<'a, T: fmt::Display> fmt::Display for Comment<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Comment::Goto(ref token, new_state) => {
                write!(f, " // on {}, goto {}", token, new_state)
            }
            Comment::Error(ref token) => write!(f, " // on {}, error", token),
            Comment::Reduce(ref token, production) => {
                write!(f, " // on {}, reduce `{:?}`", token, production)
            }
        }
    }
}

struct TableDriven<'grammar> {
    /// type parameters for the `Nonterminal` type
    symbol_type_params: Vec<TypeParameter>,

    symbol_where_clauses: Vec<WhereClause>,

    machine: Rc<MachineParameters>,

    /// a list of each nonterminal in some specific order
    all_nonterminals: Vec<NonterminalString>,

    reduce_indices: Map<&'grammar Production, usize>,

    state_type: &'static str,

    variant_names: Map<Symbol, String>,
    variants: Map<TypeRepr, String>,
    reduce_functions: Set<usize>,
}

impl<'ascent, 'grammar, W: Write> CodeGenerator<'ascent, 'grammar, W, TableDriven<'grammar>> {
    fn new_table_driven(
        grammar: &'grammar Grammar,
        user_start_symbol: NonterminalString,
        start_symbol: NonterminalString,
        states: &'ascent [Lr1State<'grammar>],
        action_module: &str,
        out: &'ascent mut RustWrite<W>,
    ) -> Self {
        let (symbol_type_params, symbol_where_clauses) =
            Self::filter_type_parameters_and_where_clauses(
                grammar,
                grammar
                    .types
                    .nonterminal_types()
                    .into_iter()
                    .chain(grammar.types.terminal_types()),
            );

        let machine = Rc::new(MachineParameters::new(grammar));

        // Assign each production a unique index to use as the values for reduce
        // actions in the ACTION and EOF_ACTION tables.
        let reduce_indices: Map<&'grammar Production, usize> = grammar
            .nonterminals
            .values()
            .flat_map(|nt| &nt.productions)
            .zip(0..)
            .collect();

        let state_type = {
            // `reduce_indices` are allowed to be +1 since the negative maximum of any integer type
            // is one larger than the positive maximum
            let max_value = ::std::cmp::max(states.len(), reduce_indices.len());
            if max_value <= ::std::i8::MAX as usize {
                "i8"
            } else if max_value <= ::std::i16::MAX as usize {
                "i16"
            } else {
                "i32"
            }
        };

        CodeGenerator::new(
            grammar,
            user_start_symbol,
            start_symbol,
            states,
            out,
            false,
            action_module,
            TableDriven {
                symbol_type_params,
                symbol_where_clauses,
                machine,
                all_nonterminals: grammar.nonterminals.keys().cloned().collect(),
                reduce_indices,
                state_type,
                variant_names: Map::new(),
                variants: Map::new(),
                reduce_functions: Set::new(),
            },
        )
    }

    fn write(&mut self) -> io::Result<()> {
        self.write_parse_mod(|this| {
            this.write_value_type_defn()?;
            this.write_parse_table()?;
            this.write_machine_definition()?;
            this.write_token_to_integer_fn()?;
            this.write_token_to_symbol_fn()?;
            this.write_simulate_reduce_fn()?;
            this.write_parser_fn()?;
            this.write_accepts_fn()?;
            this.emit_reduce_actions()?;
            this.emit_downcast_fns()?;
            this.emit_reduce_action_functions()?;
            Ok(())
        })
    }

    fn write_machine_definition(&mut self) -> io::Result<()> {
        let error_type = self.types.error_type();
        let token_type = self.types.terminal_token_type();
        let loc_type = self.types.terminal_loc_type();
        let start_type = self.types.nonterminal_type(&self.start_symbol);
        let state_type = self.custom.state_type;
        let symbol_type = self.symbol_type();
        let phantom_data_type = self.phantom_data_type();
        let phantom_data_expr = self.phantom_data_expr();
        let machine = self.custom.machine.clone();
        let machine_type_parameters = Sep(", ", &machine.type_parameters);
        let machine_where_clauses = Sep(", ", &machine.where_clauses);

        rust!(
            self.out,
            "pub(crate) struct {p}StateMachine<{mtp}>",
            p = self.prefix,
            mtp = machine_type_parameters,
        );
        rust!(self.out, "where {mwc}", mwc = machine_where_clauses);
        rust!(self.out, "{{");
        for param in &machine.fields {
            rust!(self.out, "{name}: {ty},", name = param.name, ty = param.ty,);
        }
        rust!(
            self.out,
            "{p}phantom: {phantom},",
            p = self.prefix,
            phantom = phantom_data_type,
        );
        rust!(self.out, "}}");

        rust!(
            self.out,
            "impl<{mtp}> {p}state_machine::ParserDefinition for {p}StateMachine<{mtp}>",
            p = self.prefix,
            mtp = machine_type_parameters,
        );
        rust!(self.out, "where {mwc}", mwc = machine_where_clauses);
        rust!(self.out, "{{");
        rust!(self.out, "type Location = {t};", t = loc_type);
        rust!(self.out, "type Error = {t};", t = error_type);
        rust!(self.out, "type Token = {t};", t = token_type);
        rust!(self.out, "type TokenIndex = usize;");
        rust!(
            self.out,
            "type Symbol = {symbol_type};",
            symbol_type = symbol_type,
        );
        rust!(self.out, "type Success = {t};", t = start_type);
        rust!(self.out, "type StateIndex = {t};", t = state_type);
        rust!(self.out, "type Action = {t};", t = state_type);
        rust!(self.out, "type ReduceIndex = {t};", t = state_type);
        rust!(self.out, "type NonterminalIndex = usize;");

        rust!(self.out, "");
        rust!(self.out, "#[inline]");
        rust!(self.out, "fn start_location(&self) -> Self::Location {{");
        rust!(self.out, "  Default::default()");
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(self.out, "#[inline]");
        rust!(self.out, "fn start_state(&self) -> Self::StateIndex {{");
        rust!(self.out, "  0");
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(self.out, "#[inline]");
        rust!(
            self.out,
            "fn token_to_index(&self, token: &Self::Token) -> Option<usize> {{"
        );
        rust!(
            self.out,
            "{p}token_to_integer(token, {phantom})",
            p = self.prefix,
            phantom = phantom_data_expr,
        );
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(self.out, "#[inline]");
        rust!(
            self.out,
            "fn action(&self, state: {state_type}, integer: usize) -> {state_type} {{",
            state_type = state_type
        );
        rust!(self.out, "{p}action(state, integer)", p = self.prefix);
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(self.out, "#[inline]");
        rust!(
            self.out,
            "fn error_action(&self, state: {state_type}) -> {state_type} {{",
            state_type = state_type,
        );
        rust!(
            self.out,
            "{p}action(state, {num_term} - 1)",
            p = self.prefix,
            num_term = self.grammar.terminals.all.len(),
        );
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(self.out, "#[inline]");
        rust!(
            self.out,
            "fn eof_action(&self, state: {state_type}) -> {state_type} {{",
            state_type = state_type,
        );
        rust!(self.out, "{p}EOF_ACTION[state as usize]", p = self.prefix,);
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(self.out, "#[inline]");
        rust!(
            self.out,
            "fn goto(&self, state: {state_type}, nt: usize) -> {state_type} {{",
            state_type = state_type,
        );
        rust!(self.out, "{}goto(state, nt)", self.prefix);
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(
            self.out,
            "fn token_to_symbol(&self, token_index: usize, token: Self::Token) -> Self::Symbol {{"
        );
        rust!(
            self.out,
            "{p}token_to_symbol(token_index, token, {phantom})",
            p = self.prefix,
            phantom = phantom_data_expr,
        );
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(
            self.out,
            "fn expected_tokens(&self, state: {state_type}) -> alloc::vec::Vec<alloc::string::String> {{",
            state_type = state_type,
        );
        rust!(self.out, "{p}expected_tokens(state)", p = self.prefix);
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(
            self.out,
            "fn expected_tokens_from_states(&self, states: &[{state_type}]) -> alloc::vec::Vec<alloc::string::String> {{",
            state_type = state_type,
        );
        rust!(
            self.out,
            "{p}expected_tokens_from_states(states, {pde})",
            p = self.prefix,
            pde = phantom_data_expr,
        );
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(self.out, "#[inline]");
        rust!(self.out, "fn uses_error_recovery(&self) -> bool {{");
        rust!(self.out, "{}", self.grammar.uses_error_recovery);
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(self.out, "#[inline]");
        rust!(self.out, "fn error_recovery_symbol(");
        rust!(self.out, "&self,");
        rust!(
            self.out,
            "recovery: {p}state_machine::ErrorRecovery<Self>,",
            p = self.prefix
        );
        rust!(self.out, ") -> Self::Symbol {{");
        if self.grammar.uses_error_recovery {
            let error_variant =
                self.variant_name_for_symbol(&Symbol::Terminal(TerminalString::Error));
            rust!(
                self.out,
                "{p}Symbol::{e}(recovery)",
                p = self.prefix,
                e = error_variant
            );
        } else {
            rust!(
                self.out,
                "panic!(\"error recovery not enabled for this grammar\")"
            )
        }
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(self.out, "fn reduce(");
        rust!(self.out, "&mut self,");
        rust!(self.out, "action: {state_type},", state_type = state_type);
        rust!(self.out, "start_location: Option<&Self::Location>,");
        rust!(
            self.out,
            "states: &mut alloc::vec::Vec<{state_type}>,",
            state_type = state_type
        );
        rust!(
            self.out,
            "symbols: &mut alloc::vec::Vec<{p}state_machine::SymbolTriple<Self>>,",
            p = self.prefix,
        );
        rust!(
            self.out,
            ") -> Option<{p}state_machine::ParseResult<Self>> {{",
            p = self.prefix,
        );
        rust!(self.out, "{p}reduce(", p = self.prefix);
        for Parameter { name, .. } in self.grammar.parameters.iter() {
            rust!(self.out, "self.{},", name);
        }
        rust!(self.out, "action,");
        rust!(self.out, "start_location,");
        rust!(self.out, "states,");
        rust!(self.out, "symbols,");
        rust!(self.out, "{},", phantom_data_expr);
        rust!(self.out, ")");
        rust!(self.out, "}}");

        rust!(self.out, "");
        rust!(
            self.out,
            "fn simulate_reduce(&self, action: {state_type}) -> {p}state_machine::SimulatedReduce<Self> {{",
            p = self.prefix,
            state_type = state_type,
        );
        rust!(
            self.out,
            "{p}simulate_reduce(action, {phantom})",
            p = self.prefix,
            phantom = phantom_data_expr,
        );
        rust!(self.out, "}}");

        rust!(self.out, "}}");

        Ok(())
    }

    fn write_value_type_defn(&mut self) -> io::Result<()> {
        // sometimes some of the variants are not used, particularly
        // if we are generating multiple parsers from the same file:
        rust!(self.out, "#[allow(dead_code)]");
        rust!(
            self.out,
            "pub(crate) enum {}Symbol<{}>",
            self.prefix,
            Sep(", ", &self.custom.symbol_type_params),
        );

        if !self.custom.symbol_where_clauses.is_empty() {
            rust!(
                self.out,
                " where {}",
                Sep(", ", &self.custom.symbol_where_clauses),
            );
        }

        rust!(self.out, " {{");

        // make one variant per terminal
        for term in &self.grammar.terminals.all {
            let ty = self.types.terminal_type(term).clone();
            let len = self.custom.variants.len();
            let name = match self.custom.variants.entry(ty.clone()) {
                Entry::Occupied(entry) => entry.into_mut(),
                Entry::Vacant(entry) => {
                    let name = format!("Variant{}", len);

                    rust!(self.out, "{}({}),", name, ty);
                    entry.insert(name)
                }
            };

            self.custom
                .variant_names
                .insert(Symbol::Terminal(term.clone()), name.clone());
        }

        // make one variant per nonterminal
        for nt in self.grammar.nonterminals.keys() {
            let ty = self.types.nonterminal_type(nt).clone();
            let len = self.custom.variants.len();
            let name = match self.custom.variants.entry(ty.clone()) {
                Entry::Occupied(entry) => entry.into_mut(),
                Entry::Vacant(entry) => {
                    let name = format!("Variant{}", len);

                    rust!(self.out, "{}({}),", name, ty);
                    entry.insert(name)
                }
            };

            self.custom
                .variant_names
                .insert(Symbol::Nonterminal(nt.clone()), name.clone());
        }

        rust!(self.out, "}}");
        Ok(())
    }

    fn write_parse_table(&mut self) -> io::Result<()> {
        let state_type = self.custom.state_type;

        // The table is a two-dimensional matrix indexed first by state
        // and then by the terminal index. The value is described above.
        rust!(
            self.out,
            "const {}ACTION: &[{}] = &[",
            self.prefix,
            state_type
        );

        for (index, state) in self.states.iter().enumerate() {
            rust!(self.out, "// State {}", index);

            if Tls::session().emit_comments {
                for item in state.items.vec.iter() {
                    rust!(self.out, "//     {:?}", item);
                }
            }

            // Write an action for each terminal (either shift, reduce, or error).
            let custom = &self.custom;
            let iterator = self.grammar.terminals.all.iter().map(|terminal| {
                if let Some(new_state) = state.shifts.get(terminal) {
                    (
                        new_state.0 as i32 + 1,
                        Comment::Goto(Token::Terminal(terminal.clone()), new_state.0),
                    )
                } else {
                    Self::write_reduction(custom, state, &Token::Terminal(terminal.clone()))
                }
            });
            self.out.write_table_row(iterator)?
        }

        rust!(self.out, "];");

        rust!(
            self.out,
            "fn {p}action(state: {state_type}, integer: usize) -> {state_type} {{",
            p = self.prefix,
            state_type = state_type,
        );

        rust!(
            self.out,
            "{p}ACTION[(state as usize) * {num_term} + integer]",
            p = self.prefix,
            num_term = self.grammar.terminals.all.len(),
        );

        rust!(self.out, "}}");

        // Actions on EOF. Indexed just by state.
        rust!(
            self.out,
            "const {}EOF_ACTION: &[{}] = &[",
            self.prefix,
            self.custom.state_type
        );
        for (index, state) in self.states.iter().enumerate() {
            rust!(self.out, "// State {}", index);
            let reduction = Self::write_reduction(&self.custom, state, &Token::Eof);
            self.out.write_table_row(Some(reduction))?;
        }
        rust!(self.out, "];");

        rust!(
            self.out,
            "fn {}goto(state: {state_type}, nt: usize) -> {state_type} {{",
            self.prefix,
            state_type = state_type,
        );

        Self::emit_goto_match(
            self.out,
            "nt",
            self.grammar.nonterminals.keys(),
            "state",
            self.states.iter(),
            |nonterminal, state| {
                if let Some(&new_state) = state.gotos.get(nonterminal) {
                    (
                        Some(new_state.0 as i32),
                        Comment::Goto(nonterminal, new_state.0),
                    )
                } else {
                    (None, Comment::Error(nonterminal))
                }
            },
        )?;

        rust!(self.out, "}}");

        self.emit_terminal_repr_list()?;
        self.emit_expected_tokens_fn()?;
        self.emit_expected_tokens_from_states_fn()?;

        Ok(())
    }

    fn emit_goto_match<'a, 'k, K: 'k, K2: 'k, T>(
        out: &mut RustWrite<W>,
        k_name: &str,
        iter: impl IntoIterator<Item = &'k K>,
        k2_name: &str,
        iter2: impl IntoIterator<Item = &'k K2> + Clone,
        mut state_lookup: impl FnMut(&'k K, &'k K2) -> (Option<i32>, Comment<'a, T>),
    ) -> io::Result<()>
    where
        T: fmt::Display,
    {
        let emit_comments = Tls::session().emit_comments;

        rust!(out, "match {} {{", k_name);

        for (k_index, k) in iter.into_iter().enumerate() {
            let iter = iter2
                .clone()
                .into_iter()
                .map(|k2| state_lookup(k, k2))
                .enumerate()
                // Group consecutive indices so we can compress then as a..=b
                .group_by(|(_, (next_state, _))| *next_state);
            let mut row = Vec::new();
            row.extend(&iter);

            // If the row was all errors we don't need to emit it
            if row.len() == 1 && row[0].0.is_none() {
                continue;
            }

            row.sort_by_key(|(next_state, _)| *next_state);

            // Since the parser will always select a non-error (non-zero) next_state we can use the
            // catch all in the match to represent the largest variant
            let mut largest_variant_index = 0;
            let mut largest_variant = 0;

            // Group by next_state
            let variants: Vec<_> = (&row
                .drain(..)
                // We always emit a catch-all for 0 error states (which will never be hit)
                .filter_map(|(opt, group)| opt.map(|next_state| (next_state, group)))
                .group_by(|(next_state, _)| *next_state))
                .into_iter()
                .enumerate()
                .map(|(i, (next_state, group_group))| {
                    let mut comment = None;
                    let vec = group_group
                        .map(|(_, mut group)| {
                            let (start, (_, c)) = group.next().unwrap();
                            comment = Some(c);
                            (start, group.last().map(|(end, _)| end))
                        })
                        .collect::<Vec<_>>();
                    if vec.len() > largest_variant {
                        largest_variant_index = i;
                        largest_variant = vec.len();
                    }
                    (next_state, vec, comment)
                })
                .collect();

            if variants.len() == 1 {
                rust!(out, "{} => {},", k_index, variants[0].0);
            } else {
                rust!(out, "{} => match {} {{", k_index, k2_name);

                for (i, (next_state, ranges, comment)) in variants.iter().enumerate() {
                    if i == largest_variant_index {
                        continue;
                    }
                    if let Some(comment) = comment {
                        if emit_comments {
                            rust!(out, "{}", comment);
                        }
                    }
                    rust!(
                        out,
                        "{} => {},",
                        ranges
                            .iter()
                            .format_with(" | ", |(start, end), f| match end {
                                None => f(&format_args!("{}", start)),
                                Some(end) => f(&format_args!("{}..={}", start, end)),
                            }),
                        next_state,
                    );
                }

                rust!(out, "_ => {},", variants[largest_variant_index].0);
                rust!(out, "}},");
            }
        }

        rust!(out, "_ => 0,"); // unreachable
        rust!(out, "}}");

        Ok(())
    }

    fn write_reduction<'s>(
        custom: &TableDriven<'grammar>,
        state: &'s Lr1State,
        token: &Token,
    ) -> (i32, Comment<'s, Token>) {
        let reduction = state
            .reductions
            .iter()
            .filter(|&(t, _)| t.contains(token))
            .map(|&(_, p)| p)
            .next();
        if let Some(production) = reduction {
            let action = custom.reduce_indices[production];
            (
                -(action as i32 + 1),
                Comment::Reduce(token.clone(), production),
            )
        } else {
            // Otherwise, this is an error. Store 0.
            (0, Comment::Error(token.clone()))
        }
    }

    fn write_parser_fn(&mut self) -> io::Result<()> {
        let phantom_data_expr = self.phantom_data_expr();

        self.start_parser_fn()?;

        self.define_tokens()?;

        rust!(
            self.out,
            "{p}state_machine::Parser::drive(",
            p = self.prefix,
        );
        rust!(self.out, "{p}StateMachine {{", p = self.prefix);
        for Parameter { name, .. } in &self.grammar.parameters {
            rust!(self.out, "{},", name);
        }
        rust!(
            self.out,
            "{p}phantom: {phantom},",
            p = self.prefix,
            phantom = phantom_data_expr,
        );
        rust!(self.out, "}},");
        rust!(self.out, "{p}tokens,", p = self.prefix);
        rust!(self.out, ")");

        self.end_parser_fn()
    }

    fn write_token_to_integer_fn(&mut self) -> io::Result<()> {
        let token_type = self.types.terminal_token_type();

        let parameters = vec![
            format!(
                "{p}token: &{token_type}",
                p = self.prefix,
                token_type = token_type,
            ),
            format!("_: {}", self.phantom_data_type()),
        ];

        self.out
            .fn_header(
                &Visibility::Priv,
                format!("{p}token_to_integer", p = self.prefix),
            )
            .with_type_parameters(&self.grammar.type_parameters)
            .with_where_clauses(&self.grammar.where_clauses)
            .with_parameters(parameters)
            .with_return_type("Option<usize>")
            .emit()?;
        rust!(self.out, "{{");

        rust!(self.out, "match *{p}token {{", p = self.prefix);

        for (terminal, index) in self.grammar.terminals.all.iter().zip(0..) {
            if *terminal == TerminalString::Error {
                continue;
            }
            let pattern = self.grammar.pattern(terminal).map(&mut |_| "_");
            rust!(
                self.out,
                "{pattern} if true => Some({index}),",
                pattern = pattern,
                index = index
            );
        }

        rust!(self.out, "_ => None,");

        rust!(self.out, "}}");
        rust!(self.out, "}}");

        Ok(())
    }

    fn write_token_to_symbol_fn(&mut self) -> io::Result<()> {
        let symbol_type = self.symbol_type();
        let token_type = self.types.terminal_token_type();

        let parameters = vec![
            format!("{p}token_index: usize", p = self.prefix,),
            format!(
                "{p}token: {token_type}",
                p = self.prefix,
                token_type = token_type,
            ),
            format!("_: {}", self.phantom_data_type()),
        ];

        self.out
            .fn_header(
                &Visibility::Priv,
                format!("{p}token_to_symbol", p = self.prefix),
            )
            .with_type_parameters(&self.grammar.type_parameters)
            .with_where_clauses(&self.grammar.where_clauses)
            .with_parameters(parameters)
            .with_return_type(symbol_type)
            .emit()?;
        rust!(self.out, "{{");

        rust!(self.out, "match {p}token_index {{", p = self.prefix,);

        let mut token_to_symbol_mapping = Vec::new();

        for (index, terminal) in self.grammar.terminals.all.iter().enumerate() {
            if *terminal == TerminalString::Error {
                continue;
            }
            let variant_name = self.variant_name_for_symbol(&Symbol::Terminal(terminal.clone()));
            let pattern = self.grammar.pattern(terminal);

            match token_to_symbol_mapping
                .iter_mut()
                .find(|(other_variant_name, _)| *other_variant_name == variant_name)
            {
                None => token_to_symbol_mapping.push((variant_name, vec![(index, pattern)])),
                Some((_, indices)) => indices.push((index, pattern)),
            }
        }

        for (variant_name, indices) in token_to_symbol_mapping {
            let mut pattern_names = vec![];
            let mut first = true;
            let patterns = indices
                .iter()
                .map(|(_, pattern)| {
                    let mut has_patterns = false;
                    let mut name_index = 0;
                    let pattern = pattern.map(&mut |_| {
                        has_patterns = true;
                        let name = format!("{}tok{}", self.prefix, name_index);
                        name_index += 1;
                        if first {
                            pattern_names.push(name.clone());
                        }
                        name
                    });
                    first = false;

                    format!("{}", pattern)
                })
                .collect::<Vec<_>>();

            if !pattern_names.is_empty() {
                rust!(
                    self.out,
                    "{} => match {}token {{",
                    indices.iter().map(|(index, _)| index).format(" | "),
                    self.prefix
                );
                rust!(
                    self.out,
                    "{patterns} if true => {p}Symbol::{variant_name}({open}{pattern_names}{close}),",
                    patterns = patterns.iter().format(" | "),
                    p = self.prefix,
                    variant_name = variant_name,
                    open = if pattern_names.len() > 1 { "(" } else { "" },
                    close = if pattern_names.len() > 1 { ")" } else { "" },
                    pattern_names = pattern_names.join(", "),
                );
                rust!(self.out, "_ => unreachable!(),");
                rust!(self.out, "}},");
            } else {
                rust!(
                    self.out,
                    "{indices} => {p}Symbol::{variant_name}({p}token),",
                    indices = indices.iter().map(|(index, _)| index).format(" | "),
                    p = self.prefix,
                    variant_name = variant_name,
                )
            }
        }

        rust!(self.out, "_ => unreachable!(),");

        rust!(self.out, "}}");
        rust!(self.out, "}}");
        Ok(())
    }

    fn emit_reduce_actions(&mut self) -> io::Result<()> {
        let success_type = self.types.nonterminal_type(&self.start_symbol);
        let parse_error_type = self.types.parse_error_type();
        let loc_type = self.types.terminal_loc_type();
        let spanned_symbol_type = self.spanned_symbol_type();

        let parameters = vec![
            format!("{}action: {}", self.prefix, self.custom.state_type),
            format!("{}lookahead_start: Option<&{}>", self.prefix, loc_type),
            format!(
                "{}states: &mut alloc::vec::Vec<{}>",
                self.prefix, self.custom.state_type,
            ),
            format!(
                "{}symbols: &mut alloc::vec::Vec<{}>",
                self.prefix, spanned_symbol_type,
            ),
            format!("_: {}", self.phantom_data_type()),
        ];

        self.out
            .fn_header(
                &Visibility::Pub(Some(Path::from_id(Atom::from("crate")))),
                format!("{}reduce", self.prefix),
            )
            .with_grammar(self.grammar)
            .with_parameters(parameters)
            .with_return_type(format!(
                "Option<Result<{},{}>>",
                success_type, parse_error_type
            ))
            .emit()?;
        rust!(self.out, "{{");

        rust!(
            self.out,
            "let ({p}pop_states, {p}nonterminal) = match {p}action {{",
            p = self.prefix
        );
        for (production, index) in self
            .grammar
            .nonterminals
            .values()
            .flat_map(|nt| &nt.productions)
            .zip(0..)
        {
            rust!(self.out, "{} => {{", index);
            // In debug builds LLVM is not very good at reusing stack space which makes this
            // reduce function take up O(number of states) space. By wrapping each reduce action in
            // an immediately called function each reduction takes place in their own function
            // context which ends up reducing the stack space used.

            // Fallible actions and the start symbol may do early returns so we avoid wrapping
            // those
            let is_fallible = self.grammar.action_is_fallible(production.action);
            let reduce_stack_space = !is_fallible && production.nonterminal != self.start_symbol;

            if reduce_stack_space {
                self.custom.reduce_functions.insert(index);
                let phantom_data_expr = self.phantom_data_expr();
                rust!(
                    self.out,
                    "{p}reduce{}({}{p}lookahead_start, {p}symbols, {})",
                    index,
                    self.grammar.user_parameter_refs(),
                    phantom_data_expr,
                    p = self.prefix
                );
            } else {
                self.emit_reduce_action(production)?;
            }

            rust!(self.out, "}}");
        }
        rust!(
            self.out,
            "_ => panic!(\"invalid action code {{}}\", {}action)",
            self.prefix
        );
        rust!(self.out, "}};");

        // pop the consumed states from the stack
        rust!(
            self.out,
            "let {p}states_len = {p}states.len();",
            p = self.prefix
        );
        rust!(
            self.out,
            "{p}states.truncate({p}states_len - {p}pop_states);",
            p = self.prefix
        );

        rust!(
            self.out,
            "let {p}state = *{p}states.last().unwrap();",
            p = self.prefix,
        );

        rust!(
            self.out,
            "let {p}next_state = {p}goto({p}state, {p}nonterminal);",
            p = self.prefix
        );
        if DEBUG_PRINT {
            rust!(
                self.out,
                "println!(\"goto state {{}} from {{}} due to nonterminal {{}}\", {p}next_state, \
                 {p}state, {p}nonterminal);",
                p = self.prefix,
            );
        }
        rust!(self.out, "{p}states.push({p}next_state);", p = self.prefix,);
        rust!(self.out, "None");
        rust!(self.out, "}}");
        Ok(())
    }

    fn emit_reduce_action_functions(&mut self) -> io::Result<()> {
        for (production, index) in self
            .grammar
            .nonterminals
            .values()
            .flat_map(|nt| &nt.productions)
            .zip(0..)
        {
            if self.custom.reduce_functions.contains(&index) {
                self.emit_reduce_alternative_fn_header(index)?;
                self.emit_reduce_action(production)?;
                rust!(self.out, "}}");
            }
        }
        Ok(())
    }

    fn emit_reduce_alternative_fn_header(&mut self, index: usize) -> io::Result<()> {
        let loc_type = self.types.terminal_loc_type();
        let spanned_symbol_type = self.spanned_symbol_type();

        let parameters = vec![
            format!("{}lookahead_start: Option<&{}>", self.prefix, loc_type),
            format!(
                "{}symbols: &mut alloc::vec::Vec<{}>",
                self.prefix, spanned_symbol_type,
            ),
            format!("_: {}", self.phantom_data_type()),
        ];

        self.out
            .fn_header(
                &Visibility::Pub(Some(Path::from_id(Atom::from("crate")))),
                format!("{}reduce{}", self.prefix, index),
            )
            .with_grammar(self.grammar)
            .with_parameters(parameters)
            .with_return_type("(usize, usize)")
            .emit()?;
        rust!(self.out, "{{");
        Ok(())
    }

    fn emit_reduce_action(&mut self, production: &Production) -> io::Result<()> {
        rust!(self.out, "// {:?}", production);

        // Pop each of the symbols and their associated states.
        if production.symbols.len() > 1 {
            // By asserting that there are enough elements to pop before popping multiple elements
            // we may help LLVM to optimize better since it does not need to generate panic
            // branches for each unwrap
            rust!(
                self.out,
                "assert!({}symbols.len() >= {});",
                self.prefix,
                production.symbols.len()
            );
        }
        for (index, symbol) in production.symbols.iter().enumerate().rev() {
            let name = self.variant_name_for_symbol(symbol);
            rust!(
                self.out,
                "let {}sym{} = {}pop_{}({}symbols);",
                self.prefix,
                index,
                self.prefix,
                name,
                self.prefix
            );
        }
        let transfer_syms: Vec<_> = (0..production.symbols.len())
            .map(|i| format!("{}sym{}", self.prefix, i))
            .collect();

        // Execute the action fn
        // identify the "start" and "end" location for this production; this
        // is typically the start of the first symbol and end of the last symbol we are
        // reducing; but in the case of an empty production, it will come from the
        // lookahead
        if let (Some(first_sym), Some(last_sym)) = (transfer_syms.first(), transfer_syms.last()) {
            rust!(self.out, "let {}start = {}.0;", self.prefix, first_sym);
            rust!(self.out, "let {}end = {}.2;", self.prefix, last_sym);
        } else {
            // we pop no symbols, so grab from the top of the stack
            // (unless we are in the start state, in which case the
            // stack will be empty)
            rust!(
                self.out,
                "let {p}start = {p}lookahead_start.cloned().or_else(|| {p}symbols.last().map(|s| s.2.clone())).unwrap_or_default();",
                p = self.prefix,
            );
            rust!(self.out, "let {p}end = {p}start.clone();", p = self.prefix,);
        }

        let transferred_syms = transfer_syms.len();

        let mut args = transfer_syms;
        if transferred_syms == 0 {
            args.push(format!("&{}start", self.prefix));
            args.push(format!("&{}end", self.prefix));
        }

        // invoke the action code
        let is_fallible = self.grammar.action_is_fallible(production.action);
        if is_fallible {
            rust!(
                self.out,
                "let {}nt = match {}::{}action{}::<{}>({}{}) {{",
                self.prefix,
                self.action_module,
                self.prefix,
                production.action.index(),
                Sep(", ", &self.grammar.non_lifetime_type_parameters()),
                self.grammar.user_parameter_refs(),
                Sep(", ", &args)
            );
            rust!(self.out, "Ok(v) => v,");
            rust!(self.out, "Err(e) => return Some(Err(e)),");
            rust!(self.out, "}};");
        } else {
            rust!(
                self.out,
                "let {}nt = {}::{}action{}::<{}>({}{});",
                self.prefix,
                self.action_module,
                self.prefix,
                production.action.index(),
                Sep(", ", &self.grammar.non_lifetime_type_parameters()),
                self.grammar.user_parameter_refs(),
                Sep(", ", &args)
            );
        }

        // if this is the final state, return it
        if production.nonterminal == self.start_symbol {
            rust!(self.out, "return Some(Ok({}nt));", self.prefix);
            return Ok(());
        }

        // push the produced value on the stack
        let name =
            self.variant_name_for_symbol(&Symbol::Nonterminal(production.nonterminal.clone()));
        rust!(
            self.out,
            "{p}symbols.push(({p}start, {p}Symbol::{}({p}nt), {p}end));",
            name,
            p = self.prefix
        );

        // produce the index that we will use to extract the next state
        // from GOTO array
        let index = self
            .custom
            .all_nonterminals
            .iter()
            .position(|x| *x == production.nonterminal)
            .unwrap();
        rust!(
            self.out,
            "({len}, {index})",
            len = production.symbols.len(),
            index = index,
        );

        Ok(())
    }

    fn variant_name_for_symbol(&self, s: &Symbol) -> String {
        self.custom.variant_names[s].clone()
    }

    fn emit_downcast_fns(&mut self) -> io::Result<()> {
        rust!(self.out, "#[inline(never)]");
        rust!(self.out, "fn {}symbol_type_mismatch() -> ! {{", self.prefix);
        rust!(self.out, "panic!(\"symbol type mismatch\")");
        rust!(self.out, "}}");

        for (ty, name) in self.custom.variants.clone() {
            self.emit_downcast_fn(&name, ty)?;
        }

        Ok(())
    }

    fn emit_downcast_fn(&mut self, variant_name: &str, variant_ty: TypeRepr) -> io::Result<()> {
        let spanned_symbol_type = self.spanned_symbol_type();

        rust!(self.out, "fn {}pop_{}<", self.prefix, variant_name);
        for type_parameter in &self.custom.symbol_type_params {
            rust!(self.out, "  {},", type_parameter);
        }
        rust!(self.out, ">(");
        rust!(
            self.out,
            "{}symbols: &mut alloc::vec::Vec<{}>",
            self.prefix,
            spanned_symbol_type,
        );
        rust!(self.out, ") -> {}", self.types.spanned_type(variant_ty));

        if !self.custom.symbol_where_clauses.is_empty() {
            rust!(
                self.out,
                " where {}",
                Sep(", ", &self.custom.symbol_where_clauses)
            );
        }

        rust!(self.out, " {{");

        if DEBUG_PRINT {
            rust!(self.out, "println!(\"pop_{}\");", variant_name);
        }
        rust!(self.out, "match {}symbols.pop() {{", self.prefix);
        rust!(
            self.out,
            "Some(({}l, {}Symbol::{}({}v), {}r)) => ({}l, {}v, {}r),",
            self.prefix,
            self.prefix,
            variant_name,
            self.prefix,
            self.prefix,
            self.prefix,
            self.prefix,
            self.prefix
        );
        rust!(self.out, "_ => {}symbol_type_mismatch()", self.prefix);
        rust!(self.out, "}}");

        rust!(self.out, "}}");

        Ok(())
    }

    fn write_simulate_reduce_fn(&mut self) -> io::Result<()> {
        let state_type = self.custom.state_type;

        let parameters = vec![
            format!(
                "{p}reduce_index: {state_type}",
                p = self.prefix,
                state_type = state_type,
            ),
            format!("_: {}", self.phantom_data_type()),
        ];

        self.out
            .fn_header(
                &Visibility::Priv,
                format!("{p}simulate_reduce", p = self.prefix),
            )
            .with_type_parameters(&self.custom.machine.type_parameters)
            .with_where_clauses(&self.custom.machine.where_clauses)
            .with_parameters(parameters)
            .with_return_type(format!(
                "{p}state_machine::SimulatedReduce<{p}StateMachine<{mtp}>>",
                p = self.prefix,
                mtp = Sep(", ", &self.custom.machine.type_parameters),
            ))
            .emit()?;
        rust!(self.out, "{{");

        rust!(self.out, "match {p}reduce_index {{", p = self.prefix,);
        for (production, index) in self
            .grammar
            .nonterminals
            .values()
            .flat_map(|nt| &nt.productions)
            .zip(0..)
        {
            if Tls::session().emit_comments {
                rust!(self.out, "// simulate {:?}", production);
            }

            // if we just reduced the start symbol, that is also an accept criteria
            if production.nonterminal == self.start_symbol {
                rust!(
                    self.out,
                    "{index} => {p}state_machine::SimulatedReduce::Accept,",
                    index = index,
                    p = self.prefix,
                );
            } else {
                let num_symbols = production.symbols.len();
                let nt = self
                    .custom
                    .all_nonterminals
                    .iter()
                    .position(|x| *x == production.nonterminal)
                    .unwrap();
                rust!(self.out, "{} => {{", index);
                if DEBUG_PRINT {
                    rust!(
                        self.out,
                        "println!(r##\"accepts: simulating {:?}\"##);",
                        production
                    );
                }
                rust!(
                    self.out,
                    "{p}state_machine::SimulatedReduce::Reduce {{",
                    p = self.prefix,
                );
                rust!(
                    self.out,
                    "states_to_pop: {num_symbols},",
                    num_symbols = num_symbols,
                );
                rust!(self.out, "nonterminal_produced: {nt},", nt = nt);
                rust!(self.out, "}}");
                rust!(self.out, "}}");
            }
        }
        rust!(
            self.out,
            "_ => panic!(\"invalid reduction index {{}}\", {}reduce_index)",
            self.prefix,
        );
        rust!(self.out, "}}"); // end match

        rust!(self.out, "}}");
        Ok(())
    }

    /// The `accepts` function
    ///
    /// ```ignore
    /// fn __accepts() {
    ///     error_state: Option<i32>,
    ///     states: &Vec<i32>,
    ///     opt_integer: Option<usize>,
    /// ) -> bool {
    ///     ...
    /// }
    /// ```
    ///
    /// has the job of figuring out whether the given state stack (with the
    /// optional error state appended) would "accept" the given lookahead. We
    /// basically trace through the LR automaton looking for one of two
    /// outcomes:
    ///
    /// - the lookahead is eventually shifted
    /// - we reduce to the end state successfully (in the case of EOF).
    ///
    /// If we used the pure LR(1) algorithm, we wouldn't need this
    /// function, because we would be guaranteed to error immediately
    /// (and not after some number of reductions). But with an LALR
    /// (or Lane Table) generated automaton, it is possible to reduce
    /// some number of times before encountering an error. Failing to
    /// take this into account can lead error recovery into an
    /// infinite loop (see the `error_recovery_lalr_loop` test) or
    /// produce crappy results (see `error_recovery_lock_in`).
    fn write_accepts_fn(&mut self) -> io::Result<()> {
        let phantom_data_expr = self.phantom_data_expr();
        let parameters = vec![
            format!(
                "{p}error_state: Option<{typ}>",
                p = self.prefix,
                typ = self.custom.state_type
            ),
            format!(
                "{p}states: &[{typ}]",
                p = self.prefix,
                typ = self.custom.state_type
            ),
            format!("{p}opt_integer: Option<usize>", p = self.prefix),
            format!("_: {}", self.phantom_data_type()),
        ];

        self.out
            .fn_header(&Visibility::Priv, format!("{}accepts", self.prefix))
            .with_type_parameters(&self.custom.machine.type_parameters)
            .with_where_clauses(&self.custom.machine.where_clauses)
            .with_parameters(parameters)
            .with_return_type("bool")
            .emit()?;
        rust!(self.out, "{{");

        if DEBUG_PRINT {
            rust!(
                self.out,
                "println!(\"Testing whether state {{}} accepts token {{:?}}\", \
                 {p}error_state, {p}opt_integer);",
                p = self.prefix
            );
        }

        // Create our own copy of the state stack to play with.
        rust!(
            self.out,
            "let mut {p}states = {p}states.to_vec();",
            p = self.prefix
        );
        rust!(
            self.out,
            "{p}states.extend({p}error_state);",
            p = self.prefix
        );

        rust!(self.out, "loop {{",);

        rust!(
            self.out,
            "let mut {}states_len = {}states.len();",
            self.prefix,
            self.prefix
        );

        rust!(
            self.out,
            "let {p}top = {p}states[{p}states_len - 1];",
            p = self.prefix
        );

        if DEBUG_PRINT {
            rust!(
                self.out,
                "println!(\"accepts: top-state={{}} num-states={{}}\", {p}top, {p}states_len);",
                p = self.prefix
            );
        }

        rust!(
            self.out,
            "let {p}action = match {p}opt_integer {{",
            p = self.prefix
        );
        rust!(
            self.out,
            "None => {p}EOF_ACTION[{p}top as usize],",
            p = self.prefix
        );
        rust!(
            self.out,
            "Some({p}integer) => {p}action({p}top, {p}integer),",
            p = self.prefix,
        );
        rust!(self.out, "}};"); // end `match`

        // If we encounter an error action, we do **not** accept.
        rust!(
            self.out,
            "if {p}action == 0 {{ return false; }}",
            p = self.prefix
        );

        // If we encounter a shift action, we DO accept.
        rust!(
            self.out,
            "if {p}action > 0 {{ return true; }}",
            p = self.prefix
        );

        // If we encounter a reduce action, we need to simulate its
        // effect on the state stack.
        rust!(
            self.out,
            "let ({p}to_pop, {p}nt) = match {p}simulate_reduce(-({p}action + 1), {pde}) {{",
            p = self.prefix,
            pde = phantom_data_expr,
        );
        rust!(
            self.out,
            "{p}state_machine::SimulatedReduce::Reduce {{",
            p = self.prefix,
        );
        rust!(self.out, "states_to_pop, nonterminal_produced",);
        rust!(self.out, "}} => (states_to_pop, nonterminal_produced),",);
        rust!(
            self.out,
            "{p}state_machine::SimulatedReduce::Accept => return true,",
            p = self.prefix,
        );
        rust!(self.out, "}};");

        rust!(self.out, "{p}states_len -= {p}to_pop;", p = self.prefix);
        rust!(
            self.out,
            "{p}states.truncate({p}states_len);",
            p = self.prefix
        );
        rust!(
            self.out,
            "let {p}top = {p}states[{p}states_len - 1];",
            p = self.prefix
        );

        if DEBUG_PRINT {
            rust!(
                self.out,
                "println!(\"accepts: popped {{}} symbols, new top is {{}}, nt is {{}}\", \
                 {p}to_pop, \
                 {p}top, \
                 {p}nt, \
                 );",
                p = self.prefix
            );
        }

        rust!(
            self.out,
            "let {p}next_state = {p}goto({p}top, {p}nt);",
            p = self.prefix,
        );

        rust!(self.out, "{p}states.push({p}next_state);", p = self.prefix);

        rust!(self.out, "}}"); // end loop
        rust!(self.out, "}}"); // end fn

        Ok(())
    }

    fn symbol_type(&self) -> String {
        format!(
            "{p}Symbol<{stp}>",
            p = self.prefix,
            stp = Sep(", ", &self.custom.symbol_type_params),
        )
    }

    fn spanned_symbol_type(&self) -> String {
        let loc_type = self.types.terminal_loc_type();
        format!("({},{},{})", loc_type, self.symbol_type(), loc_type)
    }

    /// Emit the array of terminal tokens for use in generating error output
    fn emit_terminal_repr_list(&mut self) -> io::Result<()> {
        rust!(self.out, "const {}TERMINAL: &[&str] = &[", self.prefix);
        let all_terminals = if self.grammar.uses_error_recovery {
            // Subtract one to exclude the error terminal
            &self.grammar.terminals.all[..self.grammar.terminals.all.len() - 1]
        } else {
            &self.grammar.terminals.all
        };
        for terminal in all_terminals {
            // Three # should hopefully be enough to prevent any
            // reasonable terminal from escaping the literal
            rust!(self.out, "r###\"{}\"###,", terminal);
        }
        rust!(self.out, "];");
        Ok(())
    }

    fn emit_expected_tokens_fn(&mut self) -> io::Result<()> {
        rust!(
            self.out,
            "fn {p}expected_tokens({p}state: {}) -> alloc::vec::Vec<alloc::string::String> {{",
            self.custom.state_type,
            p = self.prefix,
        );

        // Grab any terminals in the current state which could have resulted in a successful parse
        rust!(
            self.out,
            "{}TERMINAL.iter().enumerate().filter_map(|(index, terminal)| {{",
            self.prefix,
        );
        rust!(
            self.out,
            "let next_state = {p}action({p}state, index);",
            p = self.prefix
        );
        rust!(self.out, "if next_state == 0 {{");
        rust!(self.out, "None");
        rust!(self.out, "}} else {{");
        rust!(
            self.out,
            "Some(alloc::string::ToString::to_string(terminal))"
        );
        rust!(self.out, "}}");
        rust!(self.out, "}}).collect()");
        rust!(self.out, "}}");

        Ok(())
    }

    fn emit_expected_tokens_from_states_fn(&mut self) -> io::Result<()> {
        let parameters = vec![
            format!(
                "{p}states: &[{typ}]",
                p = self.prefix,
                typ = self.custom.state_type
            ),
            format!("_: {}", self.phantom_data_type()),
        ];

        self.out
            .fn_header(
                &Visibility::Priv,
                format!("{}expected_tokens_from_states", self.prefix),
            )
            .with_type_parameters(&self.custom.machine.type_parameters)
            .with_where_clauses(&self.custom.machine.where_clauses)
            .with_parameters(parameters)
            .with_return_type("alloc::vec::Vec<alloc::string::String>")
            .emit()?;

        rust!(self.out, "{{");

        // Grab any terminals in the current state which would have resulted in a successful parse,
        // as verified using accepts()
        rust!(
            self.out,
            "{}TERMINAL.iter().enumerate().filter_map(|(index, terminal)| {{",
            self.prefix,
        );
        rust!(
            self.out,
            "if {p}accepts(None, {p}states, Some(index), {pde}) {{",
            p = self.prefix,
            pde = self.phantom_data_expr(),
        );
        rust!(
            self.out,
            "Some(alloc::string::ToString::to_string(terminal))"
        );
        rust!(self.out, "}} else {{");
        rust!(self.out, "None");
        rust!(self.out, "}}");
        rust!(self.out, "}}).collect()");
        rust!(self.out, "}}");
        Ok(())
    }
}

struct MachineParameters {
    type_parameters: Vec<TypeParameter>,
    fields: Vec<Parameter>,
    where_clauses: Vec<WhereClause>,
}

impl MachineParameters {
    fn new(grammar: &Grammar) -> Self {
        let mut type_parameters = grammar.type_parameters.clone();
        let mut where_clauses = grammar.where_clauses.clone();

        let fields: Vec<_> = grammar
            .parameters
            .iter()
            .map(|Parameter { name, ty }| {
                let named_ty = ty.name_anonymous_lifetimes_and_compute_implied_outlives(
                    &grammar.prefix,
                    &mut type_parameters,
                    &mut where_clauses,
                );
                Parameter {
                    name: name.clone(),
                    ty: named_ty,
                }
            })
            .collect();

        // Put lifetimes first (this is stable, mind, so order remains
        // largely unperturbed):
        type_parameters.sort_by_key(|tp| match tp {
            TypeParameter::Lifetime(_) => 0,
            TypeParameter::Id(_) => 1,
        });

        Self {
            type_parameters,
            fields,
            where_clauses,
        }
    }
}