kasm 2.0.2

The Kerbal Compiler Collection assembler for kOS
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
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
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
#![allow(clippy::result_unit_err)]

use std::{collections::hash_map::DefaultHasher, hash::Hasher, num::NonZeroU8};

use kerbalobjects::Opcode;

type PResult<T> = Result<T, ()>;

// Only used in the parsing of a number, but it is useful nonetheless
type NumPResult<'a> = Result<(Span, i32), (DiagnosticBuilder<'a>, Option<(String, Token)>)>;

use crate::{
    errors::{DiagnosticBuilder, Span},
    lexer::{Token, TokenKind},
    preprocessor::past::{BenignTokens, IfStatement, MLMacroDef, SLMacroDef},
    session::Session,
};

use super::past::{
    Ident, IfClause, IfClauseBegin, IfCondition, IfDefCondition, IfExpCondition, Include,
    IncludePath, MLMacroArgs, MLMacroDefDefaults, MLMacroUndef, MacroInvok, MacroInvokArg,
    MacroInvokArgs, PASTNode, Repeat, RepeatNumber, SLMacroDefArgs, SLMacroDefContents,
    SLMacroUndef, SLMacroUndefArgs,
};

/// The parser for the preprocessor, which turns tokenized source code into preprocessable PASTNodes
pub struct Parser<'a> {
    tokens: Vec<Token>,
    token_cursor: usize,
    session: &'a Session,
    last_token: Option<Token>,
}

impl<'a> Parser<'a> {
    pub fn new(tokens: Vec<Token>, session: &'a Session) -> Self {
        let first_token = tokens.get(0).copied();

        Self {
            tokens,
            token_cursor: 0,
            session,
            last_token: first_token,
        }
    }

    pub fn parse(mut self) -> PResult<Vec<PASTNode>> {
        let mut nodes = Vec::new();

        while self.peek_next().is_some() {
            // Parse only one for now
            let node = self.parse_bit()?;
            nodes.push(node);
        }

        Ok(nodes)
    }

    // This usually parses a line, but in the case of any multi-line construct, this parses more
    // than that
    //
    // This assumes that there is a next token to parse, so keep that in mind
    //
    fn parse_bit(&mut self) -> PResult<PASTNode> {
        let next = *self.peek_next().unwrap();

        match next.kind {
            TokenKind::DirectiveDefine => self.parse_sl_macro_def(),
            TokenKind::DirectiveMacro => self.parse_ml_macro_def(),
            TokenKind::DirectiveUndef => self.parse_sl_macro_undef(),
            TokenKind::DirectiveUnmacro => self.parse_ml_macro_undef(),
            TokenKind::DirectiveRepeat => self.parse_repeat(),
            TokenKind::DirectiveInclude => self.parse_include(),
            TokenKind::DirectiveIf
            | TokenKind::DirectiveIfNot
            | TokenKind::DirectiveIfDef
            | TokenKind::DirectiveIfNotDef => self.parse_if_statement(next, true, true),
            TokenKind::DirectiveElseIf
            | TokenKind::DirectiveElse
            | TokenKind::DirectiveElseIfDef
            | TokenKind::DirectiveElseIfNot
            | TokenKind::DirectiveElseIfNotDef
            | TokenKind::DirectiveEndIf => {
                self.session
                    .struct_span_error(
                        next.as_span(),
                        "if directive with no previous .if".to_string(),
                    )
                    .emit();

                Err(())
            }
            TokenKind::Identifier => {
                let snippet = self.session.span_to_snippet(&next.as_span());
                let ident_str = snippet.as_slice();
                self.consume_next();

                // Tests if this is an instruction or not
                if Opcode::from(ident_str) != Opcode::Bogus {
                    // If it is, we parse it as such
                    self.parse_benign_tokens(next)
                } else {
                    // If it isn't, it is going to be parsed as a macro invokation
                    let macro_invok = self.parse_macro_invok(next.as_span(), ident_str)?;

                    // If we have captured any tokens before this
                    // Update this just in case it is the last part of the contents
                    Ok(PASTNode::MacroInvok(macro_invok))
                }
            }
            _ => {
                self.consume_next();
                self.parse_benign_tokens(next)
            }
        }
    }

    // Parses an if statement directive
    //
    // See the IfStatement grammar
    //
    // The consume_first flag determines if this function should consume the next token or not as
    // the beginning directive.
    //
    // The allow_preprocessor flag determines if preprocessor directives will be allowed or not
    //
    fn parse_if_statement(
        &mut self,
        mut token: Token,
        consume_first: bool,
        allow_preprocessor: bool,
    ) -> PResult<PASTNode> {
        if consume_first {
            // Consume the .if*
            token = *self.consume_next().unwrap();
        }

        let mut clauses = Vec::new();
        let mut else_encountered = false;

        let (first_clause, end_kind) = self.parse_if_clause(token, allow_preprocessor)?;
        clauses.push(first_clause);

        if end_kind != TokenKind::DirectiveEndIf {
            if end_kind == TokenKind::DirectiveElse {
                else_encountered = true;
            }

            token = *self.consume_next().unwrap();

            loop {
                // Parse the clause
                let (if_clause, end_kind) = self.parse_if_clause(token, allow_preprocessor)?;

                if else_encountered && !matches!(if_clause.condition, IfCondition::Else) {
                    self.session
                        .struct_span_error(
                            if_clause.begin.span,
                            ".endif expected after .else clause".to_string(),
                        )
                        .emit();

                    return Err(());
                }

                // Add it
                clauses.push(if_clause);

                // If it isn't the end, set the next token
                if end_kind != TokenKind::DirectiveEndIf {
                    if end_kind == TokenKind::DirectiveElse {
                        else_encountered = true;
                    }

                    token = *self.consume_next().unwrap();
                } else {
                    break;
                }
            }
        }

        // Consume the .endif
        self.assert_next(TokenKind::DirectiveEndIf)?;

        Ok(PASTNode::IfStatement(IfStatement::from_vec(clauses)))
    }

    // Parses 0 or more "benign tokens" from the token stream
    //
    // "Benign tokens" are tokens that are non-preprocessor, things like normal identifiers,
    // integer literals, etc.
    //
    fn parse_benign_tokens(&mut self, start: Token) -> PResult<PASTNode> {
        let mut tokens = vec![start];

        while let Some(&next) = self.peek_next() {
            match next.kind {
                TokenKind::DirectiveDefine
                | TokenKind::DirectiveUndef
                | TokenKind::DirectiveMacro
                | TokenKind::DirectiveEndmacro
                | TokenKind::DirectiveUnmacro
                | TokenKind::DirectiveRepeat
                | TokenKind::DirectiveEndRepeat
                | TokenKind::DirectiveInclude
                | TokenKind::DirectiveIf
                | TokenKind::DirectiveIfDef
                | TokenKind::DirectiveIfNot
                | TokenKind::DirectiveIfNotDef
                | TokenKind::DirectiveElse
                | TokenKind::DirectiveElseIf
                | TokenKind::DirectiveElseIfDef
                | TokenKind::DirectiveElseIfNot
                | TokenKind::DirectiveElseIfNotDef
                | TokenKind::DirectiveEndIf => {
                    break;
                }
                TokenKind::Identifier => {
                    let snippet = self.session.span_to_snippet(&next.as_span());
                    let ident_str = snippet.as_slice();

                    // Tests if this is an instruction or not
                    if Opcode::from(ident_str) != Opcode::Bogus {
                        // It is, which is "benign"
                        tokens.push(next);

                        self.consume_next();
                    } else {
                        break;
                    }
                }
                _ => {
                    tokens.push(next);
                    self.consume_next();
                }
            }
        }

        Ok(PASTNode::BenignTokens(BenignTokens::from_vec(tokens)))
    }

    // Parses an if statement clause
    //
    // See the IfClause grammar
    //
    // The if_token is passed in to parse the if clause type and condition
    //
    // The allow_preprocessor flag determines if preprocessor directives will be allowed or not
    //
    fn parse_if_clause(
        &mut self,
        if_token: Token,
        allow_preprocessor: bool,
    ) -> PResult<(IfClause, TokenKind)> {
        let mut span = Span::new(0, 0, 0);
        let begin = self.parse_if_clause_begin(if_token)?;
        let condition = self.parse_if_condition(if_token)?;
        let mut contents = Vec::new();
        let mut end_kind = TokenKind::Error;

        span.start = begin.span.start;
        span.file = begin.span.file;

        // Two different loops is pretty bad, but it avoids checking the allow_preprocessor flag
        // every loop
        if allow_preprocessor {
            while let Some(&next) = self.peek_next() {
                let node = match next.kind {
                    TokenKind::DirectiveDefine => self.parse_sl_macro_def(),
                    TokenKind::DirectiveMacro => self.parse_ml_macro_def(),
                    TokenKind::DirectiveUndef => self.parse_sl_macro_undef(),
                    TokenKind::DirectiveUnmacro => self.parse_ml_macro_undef(),
                    TokenKind::DirectiveRepeat => self.parse_repeat(),
                    TokenKind::DirectiveInclude => self.parse_include(),
                    TokenKind::DirectiveIf
                    | TokenKind::DirectiveIfNot
                    | TokenKind::DirectiveIfDef
                    | TokenKind::DirectiveIfNotDef => self.parse_if_statement(next, true, true),
                    TokenKind::DirectiveEndIf
                    | TokenKind::DirectiveElse
                    | TokenKind::DirectiveElseIf
                    | TokenKind::DirectiveElseIfDef
                    | TokenKind::DirectiveElseIfNot
                    | TokenKind::DirectiveElseIfNotDef => {
                        end_kind = next.kind;
                        break;
                    }
                    TokenKind::Identifier => {
                        let snippet = self.session.span_to_snippet(&next.as_span());
                        let ident_str = snippet.as_slice();
                        self.consume_next();

                        // Tests if this is an instruction or not
                        if Opcode::from(ident_str) != Opcode::Bogus {
                            // If it is, we parse it as such
                            self.parse_benign_tokens(next)
                        } else {
                            // If it isn't, it is going to be parsed as a macro invokation
                            let macro_invok = self.parse_macro_invok(next.as_span(), ident_str)?;

                            // If we have captured any tokens before this
                            // Update this just in case it is the last part of the contents
                            Ok(PASTNode::MacroInvok(macro_invok))
                        }
                    }
                    _ => {
                        self.consume_next();
                        self.parse_benign_tokens(next)
                    }
                }?;

                span.end = node.span_end();

                contents.push(node);
            }
        } else {
            while let Some(&next) = self.peek_next() {
                let node = match next.kind {
                    TokenKind::DirectiveDefine
                    | TokenKind::DirectiveMacro
                    | TokenKind::DirectiveEndmacro
                    | TokenKind::DirectiveUndef
                    | TokenKind::DirectiveUnmacro
                    | TokenKind::DirectiveRepeat
                    | TokenKind::DirectiveEndRepeat
                    | TokenKind::DirectiveInclude => {
                        self.session
                            .struct_span_error(
                                next.as_span(),
                                "preprocessor directives not allowed here".to_string(),
                            )
                            .emit();

                        return Err(());
                    }
                    TokenKind::DirectiveIf
                    | TokenKind::DirectiveIfNot
                    | TokenKind::DirectiveIfDef
                    | TokenKind::DirectiveIfNotDef => self.parse_if_statement(next, true, true),
                    TokenKind::DirectiveEndIf
                    | TokenKind::DirectiveElse
                    | TokenKind::DirectiveElseIf
                    | TokenKind::DirectiveElseIfDef
                    | TokenKind::DirectiveElseIfNot
                    | TokenKind::DirectiveElseIfNotDef => {
                        end_kind = next.kind;
                        break;
                    }
                    TokenKind::Identifier => {
                        let snippet = self.session.span_to_snippet(&next.as_span());
                        let ident_str = snippet.as_slice();

                        self.consume_next();

                        // Tests if this is an instruction or not
                        if Opcode::from(ident_str) != Opcode::Bogus {
                            // If it is, we parse it as such
                            self.parse_benign_tokens(next)
                        } else {
                            // If it isn't, it is going to be parsed as a macro invokation
                            let macro_invok = self.parse_macro_invok(next.as_span(), ident_str)?;

                            // If we have captured any tokens before this
                            // Update this just in case it is the last part of the contents
                            Ok(PASTNode::MacroInvok(macro_invok))
                        }
                    }
                    _ => {
                        self.consume_next();
                        self.parse_benign_tokens(next)
                    }
                }?;

                span.end = node.span_end();

                contents.push(node);
            }
        }

        // If we have ended by running out of tokens, but the last token isn't an endif
        if self.peek_next().is_none() && end_kind != TokenKind::DirectiveEndIf {
            // Error
            self.session
                .struct_error("if clause has no .endif".to_string())
                .span_label(if_token.as_span(), "this clause".to_string())
                .span_label(
                    self.last_token.unwrap().as_span(),
                    "file ended unexpectedly".to_string(),
                )
                .emit();

            return Err(());
        }

        Ok((IfClause::new(span, begin, condition, contents), end_kind))
    }

    fn parse_if_clause_begin(&mut self, if_token: Token) -> PResult<IfClauseBegin> {
        let inverse = !matches!(
            if_token.kind,
            TokenKind::DirectiveIf
                | TokenKind::DirectiveIfDef
                | TokenKind::DirectiveElseIf
                | TokenKind::DirectiveElseIfDef
                | TokenKind::DirectiveElse
        );

        let span = if_token.as_span();

        Ok(IfClauseBegin::new(span, inverse))
    }

    fn parse_if_condition(&mut self, if_token: Token) -> PResult<IfCondition> {
        Ok(match if_token.kind {
            TokenKind::DirectiveIfDef
            | TokenKind::DirectiveIfNotDef
            | TokenKind::DirectiveElseIfDef
            | TokenKind::DirectiveElseIfNotDef => IfCondition::Def(self.parse_if_def_condition()?),
            TokenKind::DirectiveElse => {
                self.parse_if_else_condition()?;
                IfCondition::Else
            }
            _ => IfCondition::Exp(self.parse_if_exp_condition(if_token)?),
        })
    }

    fn parse_if_else_condition(&mut self) -> PResult<()> {
        self.skip_whitespace();

        if let Some(&next) = self.consume_next() {
            if next.kind != TokenKind::Newline {
                self.session
                    .struct_span_error(next.as_span(), "unexpected token".to_string())
                    .emit();

                return Err(());
            }
        }

        Ok(())
    }

    fn parse_if_def_condition(&mut self) -> PResult<IfDefCondition> {
        let mut span = Span::new(0, 0, 0);

        self.skip_whitespace();

        // We need an identifier, that is the entire idea of an .ifdef
        let identifier = self.parse_ident()?;

        // A number of arguments is optional though
        let args = self.parse_ml_macro_args()?;

        span.start = identifier.span.start;
        span.file = identifier.span.file;

        if let Some(args) = &args {
            span.end = args.span.end;
        } else {
            span.end = identifier.span.end;
        }

        Ok(IfDefCondition::new(span, identifier, args))
    }

    fn parse_if_exp_condition(&mut self, if_token: Token) -> PResult<IfExpCondition> {
        let mut span = Span::new(0, 0, 0);

        let mut expression = Vec::new();

        let mut benign_tokens = Vec::new();

        let mut ended = false;

        // Skip any whitespace
        self.skip_whitespace();

        while let Some(&token) = self.consume_next() {
            match token.kind {
                TokenKind::Newline => {
                    ended = true;
                    break;
                }
                TokenKind::DirectiveDefine
                | TokenKind::DirectiveUndef
                | TokenKind::DirectiveMacro
                | TokenKind::DirectiveEndmacro
                | TokenKind::DirectiveUnmacro
                | TokenKind::DirectiveRepeat
                | TokenKind::DirectiveEndRepeat
                | TokenKind::DirectiveInclude
                | TokenKind::DirectiveIf
                | TokenKind::DirectiveIfDef
                | TokenKind::DirectiveIfNot
                | TokenKind::DirectiveIfNotDef
                | TokenKind::DirectiveElse
                | TokenKind::DirectiveElseIf
                | TokenKind::DirectiveElseIfDef
                | TokenKind::DirectiveElseIfNot
                | TokenKind::DirectiveElseIfNotDef
                | TokenKind::DirectiveEndIf => {
                    self.session
                        .struct_span_error(token.as_span(), "Expected condition".to_string())
                        .emit();

                    return Err(());
                }
                TokenKind::Identifier => {
                    let snippet = self.session.span_to_snippet(&token.as_span());
                    let ident_str = snippet.as_slice();

                    // Tests if this is an instruction or not
                    if Opcode::from(ident_str) != Opcode::Bogus {
                        // If it is
                        // Just push it
                        benign_tokens.push(token);

                        span.end = token.as_span().end;
                    } else {
                        // If it isn't, it is going to be parsed as a macro invokation
                        let macro_invok = self.parse_macro_invok(token.as_span(), ident_str)?;

                        // If we have captured any tokens before this
                        if !benign_tokens.is_empty() {
                            let benign_tokens_node = BenignTokens::from_vec(benign_tokens);
                            expression.push(PASTNode::BenignTokens(benign_tokens_node));

                            benign_tokens = Vec::new();
                        }

                        // Update this just in case it is the last part of the contents
                        span.end = macro_invok.span.end;

                        expression.push(PASTNode::MacroInvok(macro_invok));
                    }
                }
                _ => {
                    // Just push this, it is allowed and not special
                    benign_tokens.push(token);

                    // Just in case this is the last one
                    span.end = token.as_span().end;
                }
            }
        }

        // Check if benign_tokens didn't end empty
        if !benign_tokens.is_empty() {
            expression.push(PASTNode::BenignTokens(BenignTokens::from_vec(
                benign_tokens,
            )));
        }

        // If our expression is completely empty
        if expression.is_empty() {
            // Emit an error
            self.session
                .struct_span_error(if_token.as_span(), "expected expression".to_string())
                .emit();

            return Err(());
        }

        // We didn't end with a newline, we ended with an EOF
        if !ended {
            // At this point due to the upper check, we are guaranteed to have a valid span
            self.session
                .struct_span_error(span, "expected newline after expression".to_string())
                .emit();

            return Err(());
        }

        Ok(IfExpCondition::new(span, expression))
    }

    // Parses a macro directive
    //
    // See the MLMacroDef grammar
    //
    fn parse_ml_macro_def(&mut self) -> PResult<PASTNode> {
        let mut span = Span::new(0, 0, 0);

        // Consume the .macro
        let macro_span = self.assert_next(TokenKind::DirectiveMacro)?;

        // Copy the span values
        span.start = macro_span.start;
        span.file = macro_span.file;

        // Skip whitespace
        self.skip_whitespace();

        let identifier = self.parse_ident()?;

        // Capture the macro arguments
        let args = self.parse_ml_macro_args()?;

        let defaults = if let Some(args) = &args {
            // Update this to be passed in
            span.end = args.span.end;

            if let Some(maximum) = args.maximum {
                let num_required_defaults = maximum.get() - args.required;

                let defaults = self.parse_ml_macro_defaults(span, num_required_defaults)?;

                span.end = defaults.span.end;

                Some(defaults)
            } else {
                None
            }
        } else {
            None
        };

        // Now we parse the actual contents
        let contents = self.parse_ml_macro_contents(macro_span)?;

        Ok(PASTNode::MLMacroDef(MLMacroDef::new(
            span, identifier, args, defaults, contents,
        )))
    }

    // Parse a multi line macro's contents
    fn parse_ml_macro_contents(&mut self, macro_span: Span) -> PResult<Vec<PASTNode>> {
        let mut contents = Vec::new();
        let mut benign_tokens = Vec::new();
        let mut span = Span::new(0, 0, 0);
        let mut found_end = false;

        // Parse the first token. We will allow this to immediately be an .endmacro
        if let Some(&token) = self.consume_next() {
            if token.kind == TokenKind::DirectiveEndmacro {
                found_end = true;
            } else {
                span.start = token.as_span().start;
                span.file = token.as_span().file;

                benign_tokens.push(token);
            }
        } else {
            self.session
                .struct_span_error(macro_span, "missing accompanying `.endmacro`".to_string())
                .emit();

            return Err(());
        }

        if !found_end {
            while let Some(&token) = self.consume_next() {
                match token.kind {
                    TokenKind::DirectiveDefine
                    | TokenKind::DirectiveMacro
                    | TokenKind::DirectiveRepeat
                    | TokenKind::DirectiveEndRepeat
                    | TokenKind::DirectiveInclude
                    | TokenKind::DirectiveUndef
                    | TokenKind::DirectiveElseIf
                    | TokenKind::DirectiveElseIfNot
                    | TokenKind::DirectiveElseIfDef
                    | TokenKind::DirectiveElseIfNotDef
                    | TokenKind::DirectiveElse
                    | TokenKind::DirectiveEndIf
                    | TokenKind::DirectiveUnmacro => {
                        self.session
                            .struct_span_error(
                                token.as_span(),
                                "not allowed within .macro block".to_string(),
                            )
                            .span_label(macro_span, "in macro".to_string())
                            .emit();

                        return Err(());
                    }
                    TokenKind::DirectiveIf
                    | TokenKind::DirectiveIfNot
                    | TokenKind::DirectiveIfDef
                    | TokenKind::DirectiveIfNotDef => {
                        let if_statement = match self.parse_if_statement(token, false, false)? {
                            PASTNode::IfStatement(statement) => statement,
                            _ => unreachable!(),
                        };

                        // If we have captured any tokens before this
                        if !benign_tokens.is_empty() {
                            let benign_tokens_node = BenignTokens::from_vec(benign_tokens);
                            contents.push(PASTNode::BenignTokens(benign_tokens_node));

                            benign_tokens = Vec::new();
                        }

                        // Update this just in case it is the last part of the contents
                        span.end = if_statement.span.end;

                        contents.push(PASTNode::IfStatement(if_statement));
                    }
                    TokenKind::DirectiveEndmacro => {
                        found_end = true;
                        break;
                    }
                    TokenKind::Identifier => {
                        let snippet = self.session.span_to_snippet(&token.as_span());
                        let ident_str = snippet.as_slice();

                        // Tests if this is an instruction or not
                        if Opcode::from(ident_str) != Opcode::Bogus {
                            // If it is
                            // Just push it
                            benign_tokens.push(token);

                            span.end = token.as_span().end;
                        } else {
                            // If it isn't, it is going to be parsed as a macro invokation
                            let macro_invok = self.parse_macro_invok(token.as_span(), ident_str)?;

                            // If we have captured any tokens before this
                            if !benign_tokens.is_empty() {
                                let benign_tokens_node = BenignTokens::from_vec(benign_tokens);
                                contents.push(PASTNode::BenignTokens(benign_tokens_node));

                                benign_tokens = Vec::new();
                            }

                            // Update this just in case it is the last part of the contents
                            span.end = macro_invok.span.end;

                            contents.push(PASTNode::MacroInvok(macro_invok));
                        }
                    }
                    TokenKind::SymbolAnd => {
                        benign_tokens.push(token);

                        // We expect an integer literal after this
                        if let Some(&hopefully_num) = self.consume_next() {
                            // If there is anything at all
                            if hopefully_num.kind != TokenKind::LiteralInteger {
                                if hopefully_num.kind != TokenKind::Newline {
                                    self.session
                                        .struct_span_error(
                                            hopefully_num.as_span(),
                                            "expected argument number".to_string(),
                                        )
                                        .emit();
                                } else {
                                    self.session
                                        .struct_span_error(
                                            token.as_span(),
                                            "expected argument number after `&`".to_string(),
                                        )
                                        .emit();
                                }

                                return Err(());
                            } else {
                                benign_tokens.push(hopefully_num);
                            }
                        }
                    }
                    _ => {
                        // Just push this, it is allowed and not special
                        benign_tokens.push(token);

                        // Just in case this is the last one
                        span.end = token.as_span().end;
                    }
                }
            }
        }

        // If we ended because we ran out of tokens that is bad, so check the flag
        if !found_end {
            self.struct_err_expected_eof(self.last_token.unwrap().as_span(), ".endrep")
                .emit();
        }

        // Check if benign_tokens didn't end empty
        if !benign_tokens.is_empty() {
            contents.push(PASTNode::BenignTokens(BenignTokens::from_vec(
                benign_tokens,
            )));
        }

        Ok(contents)
    }

    // Parse a multi line macro argument defaults
    //
    // See the MLMacroDefDefaults grammar
    //
    fn parse_ml_macro_defaults(
        &mut self,
        err_span: Span,
        number: u8,
    ) -> PResult<MLMacroDefDefaults> {
        let mut defaults = Vec::new();

        // Collect as many as we can
        while let (Some(default), end) = self.parse_ml_macro_default()? {
            defaults.push(default);

            if end {
                break;
            }
        }

        let defaults = MLMacroDefDefaults::from_vec(defaults);

        // Check if it is how many we need
        if defaults.values.len() != number as usize {
            if !defaults.values.is_empty() {
                self.session
                    .struct_error(format!("expected {} arguments", number))
                    .span_label(defaults.span, format!("found {}", defaults.values.len()))
                    .emit();
            } else {
                self.session
                    .struct_error(format!("expected {} arguments", number))
                    .span_label(err_span, "found none".to_string())
                    .emit();
            }

            Err(())
        } else {
            Ok(defaults)
        }
    }

    // Parse a single multi line macro argument default
    //
    // Only "benign" tokens are allowed. No macro invokations or preprocessor directives
    //
    // Returns a tuple of an Option<BenignTokens> that represents if there was a default to parse
    //
    fn parse_ml_macro_default(&mut self) -> PResult<(Option<BenignTokens>, bool)> {
        // Skip whitespace
        self.skip_whitespace();

        let mut tokens = Vec::new();
        let mut comma_span = None;
        let mut end = false;

        while let Some(&token) = self.consume_next() {
            if token.kind == TokenKind::SymbolComma {
                comma_span = Some(token.as_span());
                break;
            } else if token.kind == TokenKind::Newline {
                end = true;
                break;
            } else if token.kind == TokenKind::Identifier {
                let ident_snippet = self.session.span_to_snippet(&token.as_span());
                let ident_str = ident_snippet.as_slice();

                // If this isn't an instruction
                if Opcode::from(ident_str) == Opcode::Bogus {
                    self.session
                        .struct_span_error(
                            token.as_span(),
                            "macro invokations are not allowed as defaults".to_string(),
                        )
                        .help("maybe you misspelled an instruction mnemonic?".to_string())
                        .emit();

                    return Err(());
                }
            }

            tokens.push(token);
        }

        if tokens.is_empty() {
            if let Some(comma_span) = comma_span {
                self.session
                    .struct_span_error(
                        comma_span,
                        "expected argument default before `,`".to_string(),
                    )
                    .emit();

                Err(())
            } else {
                Ok((None, end))
            }
        } else {
            Ok((Some(BenignTokens::from_vec(tokens)), end))
        }
    }

    // Parse an include directive
    //
    // See the Include grammar
    //
    fn parse_include(&mut self) -> PResult<PASTNode> {
        let mut span = Span::new(0, 0, 0);

        // Consume the .include
        let include_span = self.assert_next(TokenKind::DirectiveInclude)?;

        // Copy the span values
        span.start = include_span.start;
        span.file = include_span.file;

        // Skip any whitespace
        self.skip_whitespace();

        // We now require the actual include path
        if let Some((path_span, expression)) = self.parse_non_preprocessor(&[])? {
            span.end = path_span.end;

            // We got one
            let path = IncludePath::new(path_span, expression);

            Ok(PASTNode::Include(Include::new(span, path)))
        } else {
            // This is required
            self.session
                .struct_span_error(include_span, ".include with no path".to_string())
                .emit();

            Err(())
        }
    }

    // Parse a repeat directive
    //
    // See the Repeat grammar
    //
    fn parse_repeat(&mut self) -> PResult<PASTNode> {
        let mut span = Span::new(0, 0, 0);

        // Consume the .rep
        let rep_span = self.assert_next(TokenKind::DirectiveRepeat)?;

        // Copy the span values
        span.start = rep_span.start;
        span.file = rep_span.file;

        // Skip any whitespace
        self.skip_whitespace();

        // As per the grammar, the next tokens must not contain preprocessor directives
        let number = self.parse_repeat_number(rep_span)?;

        let contents = self.parse_repeat_contents(rep_span)?;

        Ok(PASTNode::Repeat(Repeat::new(span, number, contents)))
    }

    // Parses a repeat preprocessor directive's contents.
    //
    // See the Repeat grammar
    //
    fn parse_repeat_contents(&mut self, rep_span: Span) -> PResult<Vec<PASTNode>> {
        let mut contents = Vec::new();
        let mut benign_tokens = Vec::new();
        let mut span = Span::new(0, 0, 0);
        let mut found_end = false;

        // Parse the first token. We will allow this to immediately be an .endrep
        if let Some(&token) = self.consume_next() {
            if token.kind == TokenKind::DirectiveEndRepeat {
                found_end = true;
            } else {
                span.start = token.as_span().start;
                span.file = token.as_span().file;

                benign_tokens.push(token);
            }
        } else {
            self.session
                .struct_span_error(rep_span, "missing accompanying `.endrep`".to_string())
                .emit();

            return Err(());
        }

        if !found_end {
            while let Some(&token) = self.consume_next() {
                match token.kind {
                    TokenKind::DirectiveDefine
                    | TokenKind::DirectiveMacro
                    | TokenKind::DirectiveEndmacro
                    | TokenKind::DirectiveRepeat
                    | TokenKind::DirectiveInclude
                    | TokenKind::DirectiveUndef
                    | TokenKind::DirectiveUnmacro
                    | TokenKind::DirectiveIf
                    | TokenKind::DirectiveIfNot
                    | TokenKind::DirectiveIfDef
                    | TokenKind::DirectiveIfNotDef
                    | TokenKind::DirectiveElseIf
                    | TokenKind::DirectiveElseIfNot
                    | TokenKind::DirectiveElseIfDef
                    | TokenKind::DirectiveElseIfNotDef
                    | TokenKind::DirectiveElse
                    | TokenKind::DirectiveEndIf => {
                        self.session
                            .struct_span_error(
                                token.as_span(),
                                "not allowed within .rep block".to_string(),
                            )
                            .emit();

                        return Err(());
                    }
                    TokenKind::DirectiveEndRepeat => {
                        found_end = true;
                        break;
                    }
                    TokenKind::Identifier => {
                        let snippet = self.session.span_to_snippet(&token.as_span());
                        let ident_str = snippet.as_slice();

                        // Tests if this is an instruction or not
                        if Opcode::from(ident_str) != Opcode::Bogus {
                            // If it is
                            // Just push it
                            benign_tokens.push(token);

                            span.end = token.as_span().end;
                        } else {
                            // If it isn't, it is going to be parsed as a macro invokation
                            let macro_invok = self.parse_macro_invok(token.as_span(), ident_str)?;

                            // If we have captured any tokens before this
                            if !benign_tokens.is_empty() {
                                let benign_tokens_node = BenignTokens::from_vec(benign_tokens);
                                contents.push(PASTNode::BenignTokens(benign_tokens_node));

                                benign_tokens = Vec::new();
                            }

                            // Update this just in case it is the last part of the contents
                            span.end = macro_invok.span.end;

                            contents.push(PASTNode::MacroInvok(macro_invok));
                        }
                    }
                    _ => {
                        // Just push this, it is allowed and not special
                        benign_tokens.push(token);

                        // Just in case this is the last one
                        span.end = token.as_span().end;
                    }
                }
            }
        }

        // If we ended because we ran out of tokens that is bad, so check the flag
        if !found_end {
            self.struct_err_expected_eof(self.last_token.unwrap().as_span(), ".endrep")
                .emit();
        }

        // Check if benign_tokens didn't end empty
        if !benign_tokens.is_empty() {
            contents.push(PASTNode::BenignTokens(BenignTokens::from_vec(
                benign_tokens,
            )));
        }

        Ok(contents)
    }

    // Parses a repeat directive number of repetitions, which can be an expression
    fn parse_repeat_number(&mut self, directive_span: Span) -> PResult<RepeatNumber> {
        let expression = self.parse_non_preprocessor(&[])?;

        if let Some((span, expression)) = expression {
            Ok(RepeatNumber::new(span, expression))
        } else {
            self.session
                .struct_span_error(
                    directive_span,
                    ".rep requires a number of repetitions".to_string(),
                )
                .emit();

            Err(())
        }
    }

    // Parse a multi line macro undefinition
    //
    // See the MLMacroUndef grammar
    //
    fn parse_ml_macro_undef(&mut self) -> PResult<PASTNode> {
        let mut span = Span::new(0, 0, 0);

        // Consume the .unmacro
        let unmacro_span = self.assert_next(TokenKind::DirectiveUnmacro)?;

        // Copy the span values
        span.start = unmacro_span.start;
        span.file = unmacro_span.file;

        // Skip any whitespace
        self.skip_whitespace();

        // As per the grammar, the next token MUST be an identifier
        let identifier = self.parse_ident()?;

        // Now parse the optional arguments/range
        let args = match self.parse_ml_macro_args()? {
            Some(args) => args,
            None => MLMacroArgs::new(identifier.span, 0, None),
        };

        // Adjust the span
        span.end = args.span.end;

        Ok(PASTNode::MLMacroUndef(MLMacroUndef::new(
            span, identifier, args,
        )))
    }

    // Parse a multi line macro's number of arguments
    fn parse_ml_macro_args(&mut self) -> PResult<Option<MLMacroArgs>> {
        // Skip any whitespace
        self.skip_whitespace();

        // If we have any tokens at all
        let required = if let Some(&next) = self.peek_next() {
            // If it is not a newline, then it _should_ be the number of arguments
            if next.kind == TokenKind::Newline {
                self.assert_next(TokenKind::Newline)?;

                // No number of arguments
                None
            } else {
                // Parse the number
                Some(self.parse_num_arguments()?)
            }
        } else {
            None
        };

        if let Some((required_span, required_num)) = required {
            // If we had the first number, there might be `-` and then another.
            let maximum = if let Some(&next) = self.peek_next() {
                // First test for a newline
                if next.kind == TokenKind::Newline {
                    self.assert_next(TokenKind::Newline)?;

                    None
                }
                // If it isn't a `-`
                else if next.kind != TokenKind::OperatorMinus {
                    // This is an error. With only the number of required arguments specified, we don't
                    // have any default arguments to take in, so there should be nothing there
                    self.struct_err_expected_found(next.as_span(), "`-` or a newline")
                        .emit();

                    return Err(());
                } else {
                    // We have a `-`
                    self.assert_next(TokenKind::OperatorMinus)?;

                    // Now parse the next number then
                    let (span, num) = self.parse_num_arguments()?;

                    // This has the additional bound that it must be > # of required arguments
                    if num <= required_num {
                        self.session
                            .struct_span_error(
                                span,
                                format!(
                                    "maximum must be greater than number of required ({})",
                                    required_num
                                ),
                            )
                            .emit();

                        return Err(());
                    }

                    // SAFETY: We just checked if this was greater the number of required
                    // arguments, which has to be at least 0, so this has to be >= 1
                    Some((span, unsafe { NonZeroU8::new_unchecked(num) }))
                }
            } else {
                None
            };

            let mut span = Span::new(required_span.start, 0, required_span.file);

            if let Some((max_span, max_num)) = maximum {
                span.end = max_span.end;

                Ok(Some(MLMacroArgs::new(span, required_num, Some(max_num))))
            } else {
                Ok(Some(MLMacroArgs::new(span, required_num, None)))
            }
        }
        // If we didn't get a number of arguments at all, give the default of 0
        else {
            Ok(Some(MLMacroArgs::new(
                self.last_token.unwrap().as_span(),
                0,
                None,
            )))
        }
    }

    // Parse a single line macro undefinition
    //
    // See the SLMacroUndef grammar
    //
    fn parse_sl_macro_undef(&mut self) -> PResult<PASTNode> {
        let mut span = Span::new(0, 0, 0);

        // Consume the .undef
        let undef_span = self.assert_next(TokenKind::DirectiveUndef)?;

        // Copy the span values
        span.start = undef_span.start;
        span.file = undef_span.file;

        // Skip any whitespace
        self.skip_whitespace();

        // As per the grammar, the next token MUST be an identifier
        let identifier = self.parse_ident()?;

        // Now parse the optional number of arguments
        let args = match self.parse_sl_macro_undef_args()? {
            Some(args) => args,
            None => SLMacroUndefArgs::new(identifier.span, 0),
        };

        // Adjust the span
        span.end = args.span.end;

        Ok(PASTNode::SLMacroUndef(SLMacroUndef::new(
            span, identifier, args,
        )))
    }

    // Parses the number of arguments in a single line macro undefinition
    fn parse_sl_macro_undef_args(&mut self) -> PResult<Option<SLMacroUndefArgs>> {
        // Skip any whitespace
        self.skip_whitespace();

        // If we have any tokens at all
        if let Some(&next) = self.peek_next() {
            // If it is not a newline, then it _should_ be the number of arguments
            if next.kind == TokenKind::Newline {
                self.assert_next(TokenKind::Newline)?;

                // No number of arguments
                Ok(None)
            } else {
                // Parse the number
                let (span, num) = self.parse_num_arguments()?;

                Ok(Some(SLMacroUndefArgs::new(span, num)))
            }
        } else {
            Ok(None)
        }
    }

    // Parses a number of arguments, which is basically just a number that has the additional
    // requirement of being less than 255. This will also emit a special diagnostic that says that
    // macro expansions are not allowed in this place.
    fn parse_num_arguments(&mut self) -> PResult<(Span, u8)> {
        let (span, num) = match self.parse_number() {
            Ok(data) => Ok(data),
            Err((mut db, data)) => {
                if let Some((string, token)) = data {
                    // If we actually got an identifier
                    if token.kind == TokenKind::Identifier {
                        // If it isn't an instruction
                        if Opcode::from(string.as_str()) == Opcode::Bogus {
                            db.help("macros expansions are not allowed here".to_string());
                        }
                    }
                }

                db.emit();

                Err(())
            }
        }?;

        if num > u8::MAX as i32 {
            self.session
                .struct_span_error(
                    span,
                    "number greater than the maximum number of arguments (255)".to_string(),
                )
                .emit();

            Err(())
        } else {
            Ok((span, num as u8))
        }
    }

    // Parses a number from the source. This could be a hexadecimal, binary, or decimal number
    //
    // i32 is the return type because that is the maximum value that any kOS value can have, and it
    // works for our purposes as well
    //
    fn parse_number(&mut self) -> NumPResult {
        if let Some(&token) = self.consume_next() {
            let span = token.as_span();
            let snippet = self.session.span_to_snippet(&span);
            let string = snippet.as_slice().to_string();

            match token.kind {
                TokenKind::LiteralInteger => {
                    if let Ok(num) = parse_integer_literal(&string) {
                        Ok((span, num))
                    } else {
                        Err((
                            self.session.struct_span_error(
                                span,
                                format!("number too large to be stored {}", string),
                            ),
                            Some((string, token)),
                        ))
                    }
                }
                TokenKind::LiteralHex => {
                    if let Ok(num) = parse_hexadecimal_literal(&string) {
                        Ok((span, num))
                    } else {
                        Err((
                            self.session.struct_span_error(
                                span,
                                format!("number too large to be stored {}", string),
                            ),
                            Some((string, token)),
                        ))
                    }
                }
                TokenKind::LiteralBinary => {
                    if let Ok(num) = parse_binary_literal(&string) {
                        Ok((span, num))
                    } else {
                        Err((
                            self.session.struct_span_error(
                                span,
                                format!("number too large to be stored {}", string),
                            ),
                            Some((string, token)),
                        ))
                    }
                }
                _ => Err((
                    self.struct_err_expected_found(token.as_span(), "number"),
                    Some((string, token)),
                )),
            }
        } else {
            Err((
                self.struct_err_expected_eof(self.last_token.unwrap().as_span(), "number"),
                None,
            ))
        }
    }

    // Parse a single line macro definition
    //
    // See the SLMacroDef grammar
    //
    fn parse_sl_macro_def(&mut self) -> PResult<PASTNode> {
        let mut span = Span::new(0, 0, 0);
        // Consume the .define
        let define_span = self.assert_next(TokenKind::DirectiveDefine)?;

        // Copy the span values
        span.start = define_span.start;
        span.file = define_span.file;

        // Skip any whitespace
        self.skip_whitespace();

        // As per the grammar, the next token MUST be an identifier
        let identifier = self.parse_ident()?;

        // Now we parse the optional arguments
        let args = self.parse_sl_macro_def_args()?;

        let not_macros: &[Ident] = match &args {
            Some(def_args) => &def_args.args,
            None => &[],
        };

        // Then the optional contents
        let contents = self.parse_sl_macro_def_contents(not_macros)?;

        // Adjust this SLMacroDef's span
        if let Some(contents) = &contents {
            span.end = contents.span.end;
        } else if let Some(args) = &args {
            // This means we have arguments, but no tokens to expand
            // This is valid, but we should emit a warning

            self.session
                .struct_span_warn(args.span, "macro arguments but no expansion".to_string())
                .emit();

            span.end = args.span.end;
        } else {
            span.end = identifier.span.end;
        }

        Ok(PASTNode::SLMacroDef(SLMacroDef::new(
            span, identifier, args, contents,
        )))
    }

    // Parse a single line macro definition arguments
    fn parse_sl_macro_def_args(&mut self) -> PResult<Option<SLMacroDefArgs>> {
        if let Some(&token) = self.peek_next() {
            // ( is required
            if token.kind != TokenKind::SymbolLeftParen {
                // No (, no args
                Ok(None)
            } else {
                let mut arguments = Vec::new();
                let mut span = Span::new(0, 0, 0);

                // Consume the (
                let paren_span = self.assert_next(TokenKind::SymbolLeftParen)?;

                span.start = paren_span.start;
                span.file = paren_span.file;

                // We have (
                // Now we parse until we reach a )
                while let Some(&token) = self.peek_next() {
                    // Check if it is a )
                    if token.kind == TokenKind::SymbolRightParen {
                        break;
                    }

                    // We could have whitespace before this which shouldn't matter
                    self.skip_whitespace();

                    // It should now be an identifier
                    let ident = self.parse_ident()?;
                    arguments.push(ident);

                    // We could also have whitespace after it
                    self.skip_whitespace();

                    // Now we should check if it is a comma, or a ). Anything else is not allowed
                    if let Some(&next) = self.peek_next() {
                        if next.kind == TokenKind::SymbolComma {
                            self.assert_next(TokenKind::SymbolComma)?;
                        } else if next.kind == TokenKind::SymbolRightParen {
                            continue;
                        } else {
                            // Emit an error, it wasn't either of them
                            self.session
                                .struct_span_error(next.as_span(), "`,` or `)`".to_string())
                                .emit();

                            return Err(());
                        }
                    }
                }

                // We need to check if this ended because we ran out of tokens, which isn't okay
                if self.peek_next().is_none() {
                    // Emit an error
                    self.struct_err_expected_eof(self.last_token.unwrap().as_span(), ")")
                        .emit();

                    Err(())
                } else {
                    // Consume the ) that caused us to stop
                    let right_span = self.assert_next(TokenKind::SymbolRightParen)?;

                    span.end = right_span.end;

                    Ok(Some(SLMacroDefArgs::new(span, arguments)))
                }
            }
        } else {
            Ok(None)
        }
    }
    // Parse a single line macro definition contents
    fn parse_sl_macro_def_contents(
        &mut self,
        not_macros: &[Ident],
    ) -> PResult<Option<SLMacroDefContents>> {
        if let Some((span, contents)) = self.parse_non_preprocessor(not_macros)? {
            Ok(Some(SLMacroDefContents::new(span, contents)))
        } else {
            Ok(None)
        }
    }

    // Parse a sequence of tokens ended by a newline or EOF that are "benign tokens" or macro
    // expansions. This just means that preprocessor directives are not allowed. Macro invokations, expressions, etc, are
    // all allowed.
    fn parse_non_preprocessor(
        &mut self,
        not_macros: &[Ident],
    ) -> PResult<Option<(Span, Vec<PASTNode>)>> {
        // Skip any whitespace
        self.skip_whitespace();

        // We basically let anything in except for preprocessor directives
        // We do let in:
        //  Macro invokations
        //  Other directives

        // We will tell if an identifier is an instruction or a macro invokation by checking it
        // against the names of instructions

        // If we do have any token
        if let Some(&next) = self.peek_next() {
            // If it is a newline, this doesn't count as contents
            if next.kind == TokenKind::Newline {
                self.assert_next(TokenKind::Newline)?;
                return Ok(None);
            }

            let mut span = Span::new(0, 0, 0);
            let first_span = next.as_span();
            span.file = first_span.file;
            span.start = first_span.start;

            let mut nodes = Vec::new();
            let mut benign_tokens = Vec::new();

            // Now that we know there is other stuff, loop until a newline/EOF
            while let Some(&next) = self.consume_next() {
                match next.kind {
                    TokenKind::DirectiveIf
                    | TokenKind::DirectiveIfNot
                    | TokenKind::DirectiveIfDef
                    | TokenKind::DirectiveIfNotDef
                    | TokenKind::DirectiveEndIf
                    | TokenKind::DirectiveElse
                    | TokenKind::DirectiveElseIf
                    | TokenKind::DirectiveElseIfNot
                    | TokenKind::DirectiveElseIfDef
                    | TokenKind::DirectiveElseIfNotDef
                    | TokenKind::DirectiveMacro
                    | TokenKind::DirectiveEndmacro
                    | TokenKind::DirectiveRepeat
                    | TokenKind::DirectiveEndRepeat
                    | TokenKind::DirectiveDefine
                    | TokenKind::DirectiveUndef
                    | TokenKind::DirectiveUnmacro
                    | TokenKind::DirectiveInclude => {
                        self.session
                            .struct_span_error(
                                next.as_span(),
                                "preprocessor directives not allowed here".to_string(),
                            )
                            .emit();

                        return Err(());
                    }
                    TokenKind::Newline => break,
                    TokenKind::Identifier => {
                        let snippet = self.session.span_to_snippet(&next.as_span());
                        let ident_str = snippet.as_slice();

                        // Tests if this is an instruction or not
                        if Opcode::from(ident_str) != Opcode::Bogus {
                            // If it is
                            // Just push it
                            benign_tokens.push(next);

                            span.end = next.as_span().end;
                        } else {
                            let mut hasher = DefaultHasher::new();
                            hasher.write(ident_str.as_bytes());
                            let ident_hash = hasher.finish();

                            // Now check if it is actually the identifier representing an argument
                            // of this macro
                            if not_macros.iter().any(|ident| ident.hash == ident_hash) {
                                // Just add it to the benign tokens
                                benign_tokens.push(next);

                                // Just in case this is the last one
                                span.end = next.as_span().end;
                            } else {
                                // If it isn't, it is going to be parsed as a macro invokation
                                let macro_invok =
                                    self.parse_macro_invok(next.as_span(), ident_str)?;

                                // If we have captured any tokens before this
                                if !benign_tokens.is_empty() {
                                    let benign_tokens_node = BenignTokens::from_vec(benign_tokens);
                                    nodes.push(PASTNode::BenignTokens(benign_tokens_node));

                                    benign_tokens = Vec::new();
                                }

                                // Update this just in case it is the last part of the contents
                                span.end = macro_invok.span.end;

                                nodes.push(PASTNode::MacroInvok(macro_invok));
                            }
                        }
                    }
                    _ => {
                        // Just push this, it is allowed and not special
                        benign_tokens.push(next);

                        // Just in case this is the last one
                        span.end = next.as_span().end;
                    }
                }
            }

            // Check if benign_tokens didn't end empty
            if !benign_tokens.is_empty() {
                nodes.push(PASTNode::BenignTokens(BenignTokens::from_vec(
                    benign_tokens,
                )));
            }
            Ok(Some((span, nodes)))
        } else {
            Ok(None)
        }
    }

    // Parses a macro invokation
    fn parse_macro_invok(&mut self, ident_span: Span, ident_str: &str) -> PResult<MacroInvok> {
        let mut hasher = DefaultHasher::new();
        hasher.write(ident_str.as_bytes());
        let hash = hasher.finish();
        let mut span = Span::new(ident_span.start, 0, ident_span.file);

        let identifier = Ident::new(ident_span, hash);

        // After the identifier, there could be arguments, or not
        if let Some(&token) = self.peek_next() {
            if token.kind == TokenKind::SymbolLeftParen {
                self.assert_next(TokenKind::SymbolLeftParen)?;

                let args = self.parse_macro_invok_args(token.as_span())?;

                span.end = args.span.end;

                Ok(MacroInvok::new(span, identifier, Some(args)))
            } else {
                span.end = identifier.span.end;

                Ok(MacroInvok::new(span, identifier, None))
            }
        } else {
            span.end = identifier.span.end;

            Ok(MacroInvok::new(span, identifier, None))
        }
    }

    // Parses a macro invokation's arguments
    fn parse_macro_invok_args(&mut self, paren_span: Span) -> PResult<MacroInvokArgs> {
        if self.peek_next().is_none() {
            self.session
                .struct_bug(
                    "Found non-whitespace after macro invokation, but found no tokens".to_string(),
                )
                .emit();

            return Err(());
        }

        let mut args = Vec::new();

        loop {
            let (arg, is_last) = self.parse_macro_invok_arg(paren_span)?;

            args.push(arg);

            if is_last {
                break;
            }
        }

        Ok(MacroInvokArgs::from_vec(args))
    }

    // Parses a single macro invokation argument, ended by a comma, or a `)`
    //
    // No preprocessor directives are allowed as argument parts, but other macro invokations are
    // allowed.
    //
    fn parse_macro_invok_arg(&mut self, paren_span: Span) -> PResult<(MacroInvokArg, bool)> {
        let mut span = Span::new(0, 0, 0);

        let mut contents = Vec::new();
        let mut benign_tokens = Vec::new();
        let mut comma_span = None;
        let mut close_paren_span = None;
        let mut is_last = false;

        if let Some(&token) = self.consume_next() {
            let token_span = token.as_span();

            match token.kind {
                TokenKind::SymbolComma => {
                    comma_span = Some(token_span);

                    span.start = token_span.start;
                    span.file = token_span.file;
                }
                TokenKind::SymbolRightParen => {
                    close_paren_span = Some(token.as_span());
                    is_last = true;

                    span.start = token_span.start;
                    span.file = token_span.file;
                }
                TokenKind::Newline => {
                    self.session
                        .struct_span_error(
                            paren_span,
                            "Macro invokation requires closing `)`".to_string(),
                        )
                        .emit();

                    return Err(());
                }
                TokenKind::DirectiveDefine
                | TokenKind::DirectiveMacro
                | TokenKind::DirectiveEndmacro
                | TokenKind::DirectiveUndef
                | TokenKind::DirectiveUnmacro
                | TokenKind::DirectiveRepeat
                | TokenKind::DirectiveEndRepeat
                | TokenKind::DirectiveInclude
                | TokenKind::DirectiveIf
                | TokenKind::DirectiveIfNot
                | TokenKind::DirectiveIfDef
                | TokenKind::DirectiveIfNotDef
                | TokenKind::DirectiveElseIf
                | TokenKind::DirectiveElseIfNot
                | TokenKind::DirectiveElseIfDef
                | TokenKind::DirectiveElseIfNotDef
                | TokenKind::DirectiveElse
                | TokenKind::DirectiveEndIf => {
                    self.session
                        .struct_error("Not allowed in macro arguments".to_string())
                        .span_label(token.as_span(), "found preprocessor directive".to_string())
                        .emit();

                    return Err(());
                }
                TokenKind::Identifier => {
                    let snippet = self.session.span_to_snippet(&token_span);
                    let ident_str = snippet.as_slice();

                    // Tests if this is an instruction or not
                    if Opcode::from(ident_str) != Opcode::Bogus {
                        // If it is
                        // Just push it
                        benign_tokens.push(token);

                        span.end = token.as_span().end;
                    } else {
                        // If it isn't, it is going to be parsed as a macro invokation
                        let macro_invok = self.parse_macro_invok(token.as_span(), ident_str)?;

                        // If we have captured any tokens before this
                        if !benign_tokens.is_empty() {
                            let benign_tokens_node = BenignTokens::from_vec(benign_tokens);
                            contents.push(PASTNode::BenignTokens(benign_tokens_node));

                            benign_tokens = Vec::new();
                        }

                        // Update this just in case it is the last part of the contents
                        span.end = macro_invok.span.end;

                        contents.push(PASTNode::MacroInvok(macro_invok));
                    }

                    span.start = token_span.start;
                    span.file = token_span.file;
                }
                _ => {
                    benign_tokens.push(token);

                    span.start = token_span.start;
                    span.file = token_span.file;
                }
            }
        }

        while let Some(&token) = self.consume_next() {
            match token.kind {
                TokenKind::SymbolComma => {
                    comma_span = Some(token.as_span());
                    break;
                }
                TokenKind::SymbolRightParen => {
                    close_paren_span = Some(token.as_span());
                    is_last = true;
                    break;
                }
                TokenKind::Newline => {
                    self.session
                        .struct_span_error(
                            paren_span,
                            "Macro invokation requires closing `)`".to_string(),
                        )
                        .emit();

                    return Err(());
                }
                TokenKind::DirectiveDefine
                | TokenKind::DirectiveMacro
                | TokenKind::DirectiveEndmacro
                | TokenKind::DirectiveUndef
                | TokenKind::DirectiveUnmacro
                | TokenKind::DirectiveRepeat
                | TokenKind::DirectiveEndRepeat
                | TokenKind::DirectiveInclude
                | TokenKind::DirectiveIf
                | TokenKind::DirectiveIfNot
                | TokenKind::DirectiveIfDef
                | TokenKind::DirectiveIfNotDef
                | TokenKind::DirectiveElseIf
                | TokenKind::DirectiveElseIfNot
                | TokenKind::DirectiveElseIfDef
                | TokenKind::DirectiveElseIfNotDef
                | TokenKind::DirectiveElse
                | TokenKind::DirectiveEndIf => {
                    self.session
                        .struct_error("Not allowed in macro arguments".to_string())
                        .span_label(token.as_span(), "found preprocessor directive".to_string())
                        .emit();

                    return Err(());
                }
                TokenKind::Identifier => {
                    let snippet = self.session.span_to_snippet(&token.as_span());
                    let ident_str = snippet.as_slice();

                    // Tests if this is an instruction or not
                    if Opcode::from(ident_str) != Opcode::Bogus {
                        // If it is
                        // Just push it
                        benign_tokens.push(token);

                        span.end = token.as_span().end;
                    } else {
                        // If it isn't, it is going to be parsed as a macro invokation
                        let macro_invok = self.parse_macro_invok(token.as_span(), ident_str)?;

                        // If we have captured any tokens before this
                        if !benign_tokens.is_empty() {
                            let benign_tokens_node = BenignTokens::from_vec(benign_tokens);
                            contents.push(PASTNode::BenignTokens(benign_tokens_node));

                            benign_tokens = Vec::new();
                        }

                        // Update this just in case it is the last part of the contents
                        span.end = macro_invok.span.end;

                        contents.push(PASTNode::MacroInvok(macro_invok));
                    }
                }
                _ => {
                    benign_tokens.push(token);
                }
            }
        }

        // Check if benign_tokens didn't end empty
        if !benign_tokens.is_empty() {
            contents.push(PASTNode::BenignTokens(BenignTokens::from_vec(
                benign_tokens,
            )));
        }

        // If we just have nothing
        if contents.is_empty() {
            // This is always an error
            if let Some(comma_span) = comma_span {
                self.session
                    .struct_span_error(comma_span, "no arguments after comma".to_string())
                    .emit();
            } else if let Some(close_paren_span) = close_paren_span {
                self.session
                    .struct_span_error(close_paren_span, "expected argument before `)`".to_string())
                    .emit();
            }

            return Err(());
        } else {
            span.end = self.last_token.unwrap().as_span().end;
        }

        Ok((MacroInvokArg::new(span, contents), is_last))
    }

    // Peeks the next token from the Parser's tokens
    fn peek_next(&self) -> Option<&Token> {
        self.tokens.get(self.token_cursor)
    }

    // Consumes the next token from the Parser's tokens
    fn consume_next(&mut self) -> Option<&Token> {
        let token = self.tokens.get(self.token_cursor)?;

        self.token_cursor += 1;
        self.last_token = Some(*token);

        Some(token)
    }

    // Emits a bug diagnostic and Err(()) if the token was not what we assumed it to be
    fn assert_next(&mut self, token_kind: TokenKind) -> PResult<Span> {
        if let Some(&token) = self.consume_next() {
            if token.kind == token_kind {
                Ok(token.as_span())
            } else {
                self.session
                    .struct_bug(format!(
                        "token assertion failed: {:?}, found {:?}",
                        token_kind, token.kind
                    ))
                    .emit();
                Err(())
            }
        } else {
            // If it doesn't exist, that is also a problem
            self.session
                .struct_bug(format!(
                    "{:?} token assumed to exist, found None",
                    token_kind
                ))
                .emit();
            Err(())
        }
    }

    // Skips whitespace if there is any, not including newlines
    //
    // Returns true if there was any, false if not
    fn skip_whitespace(&mut self) -> bool {
        let mut was_whitespace = false;

        while self.peek_next().is_some() && self.peek_next().unwrap().kind == TokenKind::Whitespace
        {
            was_whitespace = true;

            // Increment the token cursor
            self.token_cursor += 1;
        }

        was_whitespace
    }

    // Parses an identifier, or returns an Err(())
    //
    // This will emit a diagnostic if the next token is not an identifier
    //
    fn parse_ident(&mut self) -> PResult<Ident> {
        if let Some(&token) = self.consume_next() {
            if token.kind == TokenKind::Identifier {
                let span = token.as_span();
                let snippet = self.session.span_to_snippet(&span);

                let mut hasher = DefaultHasher::new();
                hasher.write(snippet.as_slice().as_bytes());
                let hash = hasher.finish();

                Ok(Ident { span, hash })
            } else {
                self.struct_err_expected_found(token.as_span(), "identifier")
                    .emit();

                Err(())
            }
        } else {
            self.struct_err_expected_eof(self.last_token.unwrap().as_span(), "identifier")
                .emit();

            Err(())
        }
    }

    fn struct_err_expected_eof(&self, last: Span, expected: &str) -> DiagnosticBuilder<'_> {
        let message = format!("expected {}", expected);
        let mut db = self.session.struct_error(message);

        db.span_label(last, "found end of file".to_string());

        db
    }

    fn struct_err_expected_found(&self, found: Span, expected: &str) -> DiagnosticBuilder<'_> {
        let message = format!("expected {}", expected);
        let mut db = self.session.struct_error(message);

        db.span_label(
            found,
            format!("found `{}`", self.session.span_to_snippet(&found)),
        );

        db
    }
}

/// Parses an integer literal from the given &str
///
/// This differs from the normal &str::parse() because it supports random `_` characters in the
/// integer. They allow for more easily readable constants
///
pub fn parse_integer_literal(string: &str) -> Result<i32, ()> {
    // This makes sure we only have to allocate once
    let mut no_separators = String::with_capacity(string.len());

    for c in string.chars() {
        if c.is_digit(10) {
            no_separators.push(c);
        } else if c != '_' {
            return Err(());
        }
    }

    Ok(no_separators.parse().unwrap())
}

/// Parses a hexadecimal literal from the given &str
pub fn parse_hexadecimal_literal(string: &str) -> Result<i32, ()> {
    let string = &string[2..];
    let mut no_separators = String::with_capacity(string.len());

    for c in string.chars() {
        if c.is_digit(16) {
            no_separators.push(c);
        } else if c != '_' {
            return Err(());
        }
    }

    Ok(i32::from_str_radix(&no_separators, 16).unwrap())
}

/// Parses a binary literal from the given &str
pub fn parse_binary_literal(string: &str) -> Result<i32, ()> {
    let string = &string[2..];
    let mut no_separators = String::with_capacity(string.len());

    for c in string.chars() {
        if c == '0' || c == '1' {
            no_separators.push(c);
        } else if c != '_' {
            return Err(());
        }
    }

    Ok(i32::from_str_radix(&no_separators, 2).unwrap())
}

/// Parses a float literal from the given &str
pub fn parse_float_literal(string: &str) -> Result<f64, ()> {
    Ok(string.parse().unwrap())
}