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
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
|
/* SPDX-License-Identifier: Unlicense
*
* This program translates Sierra m68k assembly dialect to GNU AS m68k dialect.
*
* NOTE: Unicode is not supported, ASCII only.
*/
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef TRACE_LEXER
#define TRACE_LEXER 0
#endif
#ifndef TRACE_PARSER
#define TRACE_PARSER 0
#endif
#if defined(__GNUC__) || defined(__clang__)
#define UNREACHABLE __builtin_unreachable
#else
#define UNREACHABLE()
#endif
#define E_NIMPL "not implemented"
#define E_UNREACH "unreachable code reached"
#define E_EXPR "'(', ')', unary operator, binary operator, number or symbol"
#define E_EXPR_NONREG "symbol that is not a register when parsing expression"
#define E_EXPR_OPEN "'(', number or symbol"
#define E_EXPR_CLOSE "')', '+', '-', '+', '/' or symbol"
#define E_DN "D0, ...D7"
#define E_AN "A0, ...A7, SP"
#define E_AN_DN E_AN " or " E_DN
#define E_REGMASK_DELIM "'/' or '-'"
#define E_REGMASK_TOKEN "'/', '-', " E_AN_DN
#define E_REGMASK_ASCEND "registers in register mask range must be specified " \
"in ascending order"
#define E_EA_PART "D0, ...D7, A0, ...A7, SP, PC or full expression"
#define E_EA_PART_NOT_AN "D0, ...D7, PC or full expression"
#define E_EA_PART_NOT_EXPR E_AN ", " E_DN ", or PC"
#define E_EA_PART_DELIM "',' or ')'"
#define E_EA_INVALID "invalid addressing mode"
#define E_ARG "valid instruction argument"
#define E_MNEMONIC "valid instruction mnemonic"
#define E_INSN_SIZE_SPEC "'.s', '.b', '.w' or '.l'"
#define E_ADDR_SIZE_SPEC "'.b', '.w' or '.l'"
#define E_ADDR_INDIR_SIZE_SPEC "'.w' or '.l'"
#define E_ADDR_INDIR_MULTIPLE_INDEX_REGS "multiple index registers specified"
#define E_ARGS_COUNT "invalid arguments count"
#define E_NL "new line, which is '\\n', '\\r\\n' or '\\r'"
#define E_COMMENT_NL "';' or " E_NL
#define E_INSTR_END "',', " E_COMMENT_NL
#define E_LABELED_STMT "':', '=', '==' or " E_MNEMONIC
#define E_DIRECTIVE "directive"
#define E_STMT_BEGIN "label, " E_MNEMONIC ", " E_DIRECTIVE " or " E_NL
#define E_UNKNOWN_DRC "unknown directive"
#define E_STR "string"
#define E_ID "identifier"
#define E_NESTED_DEF "nested .def ... .endef blocks are illegal"
#define E_NMATCH_ENDEF ".endef directive without matching .def"
#define ERR 0
#define OK 1
#define CONTINUE 2
enum token_type {
TT_NONE = 0,
TT_NEWLINE,
TT_ESCAPE,
TT_DOT,
TT_COMMA,
TT_PLUS,
TT_MINUS,
TT_ASTERISK,
TT_SLASH,
TT_EQ,
TT_EQ_DOUBLE,
TT_COLON,
TT_PERCENT,
TT_LSHIFT,
TT_RSHIFT,
TT_HASH,
TT_BANG,
TT_TILDE,
TT_AMPERSAND,
TT_PIPE,
TT_CAP,
TT_STRING,
TT_ID,
TT_DOT_ID,
TT_NUMDEC,
TT_NUMOCT,
TT_NUMHEX,
TT_LPAREN,
TT_RPAREN,
TT_LBRACKET,
TT_RBRACKET,
TT_RBRACE,
TT_LBRACE,
TT_COMMENT_ASTERISK,
TT_COMMENT_SEMICOLON,
};
struct token {
enum token_type type;
size_t offset;
size_t length;
};
enum lex_error {
LE_NONE = 0,
LE_SOME,
};
enum lex_state {
LS_FREE = 0,
LS_CR,
LS_LSHIFT,
LS_RSHIFT,
LS_EQ,
LS_DOT,
LS_DOT_ID,
LS_ID,
LS_NUMOCTHEX,
LS_NUMOCT,
LS_NUMHEX,
LS_NUMDEC,
LS_STRING,
LS_STRING_ESC,
LS_COMMENT_ASTERISK,
LS_COMMENT_SEMICOLON,
LS_ERROR,
LS_EOF,
};
struct line_pos_info {
unsigned long line_num;
unsigned long column_num;
unsigned long line_offset;
};
struct lex {
// State variables
enum lex_state state;
enum lex_error error;
size_t cursor;
size_t tok_offset;
bool inside_line;
// Input data buffer
FILE *input_stream;
char *input;
size_t input_size;
// Tokens table
FILE *tokbuf_stream;
struct token *tokbuf;
size_t tokbuf_size;
size_t tokens_count;
};
enum stmt_type {
ST_NONE = 0,
ST_LABEL,
ST_INSTRUCTION,
ST_ASSIGNMENT,
ST_COMMENT,
ST_DIRECTIVE,
};
enum mnemonic {
MN_NONE = 0,
MN_ABCD,
MN_ADD,
MN_ADDA,
MN_ADDI,
MN_ADDQ,
MN_ADDX,
MN_AND,
MN_ANDI,
MN_ASL,
MN_ASR,
MN_BRA,
MN_BSR,
MN_BCC,
MN_BCS,
MN_BEQ,
MN_BGE,
MN_BGT,
MN_BHI,
MN_BLE,
MN_BLS,
MN_BLT,
MN_BMI,
MN_BNE,
MN_BPL,
MN_BVC,
MN_BVS,
MN_BCHG,
MN_BCLR,
MN_BSET,
MN_BTST,
MN_CHK,
MN_CLR,
MN_CMP,
MN_CMPA,
MN_CMPI,
MN_CMPM,
MN_DBT,
MN_DBF,
MN_DBCC,
MN_DBCS,
MN_DBEQ,
MN_DBGE,
MN_DBGT,
MN_DBHI,
MN_DBLE,
MN_DBLS,
MN_DBLT,
MN_DBMI,
MN_DBNE,
MN_DBPL,
MN_DBVC,
MN_DBVS,
MN_DIVU,
MN_DIVS,
MN_EORI,
MN_EXG,
MN_EXT,
MN_ILLEGAL,
MN_JMP,
MN_JSR,
MN_LEA,
MN_LINK,
MN_LSL,
MN_LSR,
MN_MOVE,
MN_MOVEA,
MN_MOVEM,
MN_MOVEP,
MN_MOVEQ,
MN_MULS,
MN_MULU,
MN_NBCD,
MN_NEG,
MN_NEGX,
MN_NOP,
MN_NOT,
MN_OR,
MN_ORI,
MN_PEA,
MN_RESET,
MN_ROL,
MN_ROR,
MN_ROXL,
MN_ROXR,
MN_RTE,
MN_RTR,
MN_RTS,
MN_SBCD,
MN_ST,
MN_SF,
MN_SCC,
MN_SCS,
MN_SEQ,
MN_SGE,
MN_SGT,
MN_SHI,
MN_SLE,
MN_SLS,
MN_SLT,
MN_SMT,
MN_SNE,
MN_SPL,
MN_SVC,
MN_SVS,
MN_STOP,
MN_SUB,
MN_SUBA,
MN_SUBI,
MN_SUBQ,
MN_SUBX,
MN_SWAP,
MN_TAS,
MN_TRAP,
MN_TRAPV,
MN_TST,
MN_UNLK,
MNEMONICS_COUNT,
};
enum directive_type {
DT_NONE = 0,
DT_ALIGN,
DT_ASCII,
DT_BIN,
DT_BSECTION,
DT_BSS,
DT_BYTE,
DT_CMNT,
DT_COMM,
DT_DATA,
DT_DEF,
DT_DIM,
DT_DOUBLE,
DT_DSECTION,
DT_ECHO,
DT_ELIFDEF,
DT_ELSE,
DT_END,
DT_ENDC,
DT_ENDEF,
DT_ENDIF,
DT_ENDS,
DT_EXTEND,
DT_EXTERN,
DT_FILE,
DT_FILL,
DT_FLOAT,
DT_FPDATA,
DT_GLOBL,
DT_IFDEF,
DT_IFNDEF,
DT_INCLUDE,
DT_LCOMM,
DT_LINE,
DT_LN,
DT_LONG,
DT_OPT,
DT_ORG,
DT_PACKED,
DT_PAGE,
DT_REORG,
DT_SCL,
DT_SECTION,
DT_SHORT,
DT_SINGLE,
DT_SIZE,
DT_SPACE,
DT_STRUCT,
DT_TAG,
DT_TEXT,
DT_TSECTION,
DT_TYPE,
DT_VAL,
DT_WORD,
DT_XDEF,
DT_XREF,
DIRECTIVES_COUNT,
};
enum opsize {
OPSIZE_NONE = 0,
OPSIZE_S,
OPSIZE_B,
OPSIZE_W,
OPSIZE_L,
};
enum arg_type {
ARG_NONE = 0,
ARG_DN,
ARG_AN,
ARG_AN_ADDR,
ARG_AN_ADDR_INCR,
ARG_AN_ADDR_DECR,
ARG_AN_ADDR_16,
ARG_AN_ADDR_8_XI,
ARG_ADDR_WORD,
ARG_ADDR_LONG,
ARG_ADDR_UNSPEC,
ARG_PC_ADDR_16,
ARG_PC_ADDR_8_XI,
ARG_IMMEDIATE,
ARG_REGMASK,
ARG_SR,
ARG_CCR,
ARG_USP,
};
enum args_count {
ARGS_COUNT_UNKNOWN = 0,
ARGS_COUNT_0,
ARGS_COUNT_1,
ARGS_COUNT_1_2,
ARGS_COUNT_2,
};
struct expr_tokens_span {
size_t first_token, num_tokens;
};
struct arg {
enum arg_type type;
uint16_t regmask; ///< For regmask (movem only)
uint8_t xn; ///< For Dn, An, (An), -(An), (An)+, (d16,An)
uint8_t xi; ///< For (d8,An,Xi) and (d8,PC,Xi), it has 0x8 mask set if An
enum opsize briefext_size;
struct expr_tokens_span expr;
size_t first_token, num_tokens; ///< Argument tokens span
};
struct instruction {
enum mnemonic mnemonic;
enum opsize opsize;
struct arg arg1, arg2;
};
struct directive {
enum directive_type type;
size_t name_token; /// Directive self first token
size_t first_token, num_tokens; /// Directive arguments tokens span
};
struct stmt {
enum stmt_type type;
union {
struct instruction instruction;
struct directive directive;
};
size_t label_token;
size_t first_token, num_tokens; // Statement tokens span, may be NULL
size_t comment_token;
};
struct symbol {
size_t offset; // Byte offset in continuous null terminated symbol buffer
// Instead of strcmp every item in symtab we can compare hashes and get O(N)
// for search.
uint32_t hash;
};
enum pars_error {
PE_NONE = 0,
PE_LEX,
PE_SOME,
};
enum reg_type {
REG_NONE = 0,
REG_DN,
REG_AN,
REG_PC,
REG_SR,
REG_CCR,
REG_USP,
};
enum recognized_token_type {
RTT_NONE = 0,
RTT_REG, // TT_ID
RTT_NUMBER, // TT_NUMHEX, TT_NUMOCT and TT_NUMDEC
};
struct token_recognition {
enum recognized_token_type type;
union {
struct {
enum reg_type reg;
uint8_t reg_num;
}; // For RTT_REG
int32_t number; // For TT_ID
size_t symbol_id; // For TT_ID and TT_DOT_ID, see (struct pars).symtab
};
};
struct pars {
const struct lex *lex;
// State
size_t cur_tok_id;
enum pars_error error;
bool in_sat; /// Indicates whether inside .def ... .endef block or not
// Statement table
FILE *stmttab_stream;
struct stmt *stmttab;
size_t stmttab_size;
// Symbol table
FILE *symtab_stream;
struct sym *symtab;
size_t symtab_size;
// Symbol buffer for symbol table
FILE *symbuf_stream;
char *symbuf;
size_t symbuf_size;
};
struct assem {
const struct pars *pars;
};
static int pars_parse_arg_inside_parens(
struct pars *const self, struct arg *const arg);
const char *const g_escape_table[256] = {
"\\x00", "\\x01", "\\x02", "\\x03", "\\x04", "\\x05", "\\x06", "\\x07",
"\\x08", "\\t", "\\n", "\\x0b", "\\x0c", "\\r", "\\x0e", "\\x0f", "\\x10",
"\\x11", "\\x12", "\\x13", "\\x14", "\\x15", "\\x16", "\\x17", "\\x18",
"\\x19", "\\x1a", "\\x1b", "\\x1c", "\\x1d", "\\x1e", "\\x1f", " ", "!",
"\\\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0",
"1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "\\<", "=", "\\>", "?",
"@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\\\\",
"]", "^", "_", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"{", "|", "}", "~", "\\x7f", "\\x80", "\\x81", "\\x82", "\\x83", "\\x84",
"\\x85", "\\x86", "\\x87", "\\x88", "\\x89", "\\x8a", "\\x8b", "\\x8c",
"\\x8d", "\\x8e", "\\x8f", "\\x90", "\\x91", "\\x92", "\\x93", "\\x94",
"\\x95", "\\x96", "\\x97", "\\x98", "\\x99", "\\x9a", "\\x9b", "\\x9c",
"\\x9d", "\\x9e", "\\x9f", "\\xa0", "\\xa1", "\\xa2", "\\xa3", "\\xa4",
"\\xa5", "\\xa6", "\\xa7", "\\xa8", "\\xa9", "\\xaa", "\\xab", "\\xac",
"\\xad", "\\xae", "\\xaf", "\\xb0", "\\xb1", "\\xb2", "\\xb3", "\\xb4",
"\\xb5", "\\xb6", "\\xb7", "\\xb8", "\\xb9", "\\xba", "\\xbb", "\\xbc",
"\\xbd", "\\xbe", "\\xbf", "\\xc0", "\\xc1", "\\xc2", "\\xc3", "\\xc4",
"\\xc5", "\\xc6", "\\xc7", "\\xc8", "\\xc9", "\\xca", "\\xcb", "\\xcc",
"\\xcd", "\\xce", "\\xcf", "\\xd0", "\\xd1", "\\xd2", "\\xd3", "\\xd4",
"\\xd5", "\\xd6", "\\xd7", "\\xd8", "\\xd9", "\\xda", "\\xdb", "\\xdc",
"\\xdd", "\\xde", "\\xdf", "\\xe0", "\\xe1", "\\xe2", "\\xe3", "\\xe4",
"\\xe5", "\\xe6", "\\xe7", "\\xe8", "\\xe9", "\\xea", "\\xeb", "\\xec",
"\\xed", "\\xee", "\\xef", "\\xf0", "\\xf1", "\\xf2", "\\xf3", "\\xf4",
"\\xf5", "\\xf6", "\\xf7", "\\xf8", "\\xf9", "\\xfa", "\\xfb", "\\xfc",
"\\xfd", "\\xfe",
};
const struct mnemonic_meta {
const char *str;
enum args_count args_count;
} g_mnemmonics[MNEMONICS_COUNT] = {
{ "none", ARGS_COUNT_0 },
{ "abcd", ARGS_COUNT_2 },
{ "add", ARGS_COUNT_2 },
{ "adda", ARGS_COUNT_2 },
{ "addi", ARGS_COUNT_2 },
{ "addq", ARGS_COUNT_2 },
{ "addx", ARGS_COUNT_2 },
{ "and", ARGS_COUNT_2 },
{ "andi", ARGS_COUNT_2 },
{ "asl", ARGS_COUNT_1_2 },
{ "asr", ARGS_COUNT_1_2 },
{ "bra", ARGS_COUNT_1 },
{ "bsr", ARGS_COUNT_1 },
{ "bcc", ARGS_COUNT_1 },
{ "bcs", ARGS_COUNT_1 },
{ "beq", ARGS_COUNT_1 },
{ "bge", ARGS_COUNT_1 },
{ "bgt", ARGS_COUNT_1 },
{ "bhi", ARGS_COUNT_1 },
{ "ble", ARGS_COUNT_1 },
{ "bls", ARGS_COUNT_1 },
{ "blt", ARGS_COUNT_1 },
{ "bmi", ARGS_COUNT_1 },
{ "bne", ARGS_COUNT_1 },
{ "bpl", ARGS_COUNT_1 },
{ "bvc", ARGS_COUNT_1 },
{ "bvs", ARGS_COUNT_1 },
{ "bchg", ARGS_COUNT_2 },
{ "bclr", ARGS_COUNT_2 },
{ "bset", ARGS_COUNT_2 },
{ "btst", ARGS_COUNT_2 },
{ "chk", ARGS_COUNT_2 },
{ "clr", ARGS_COUNT_1 },
{ "cmp", ARGS_COUNT_2 },
{ "cmpa", ARGS_COUNT_2 },
{ "cmpi", ARGS_COUNT_2 },
{ "cmpm", ARGS_COUNT_2 },
{ "dbt", ARGS_COUNT_2 },
{ "dbf", ARGS_COUNT_2 },
{ "dbcc", ARGS_COUNT_2 },
{ "dbcs", ARGS_COUNT_2 },
{ "dbeq", ARGS_COUNT_2 },
{ "dbge", ARGS_COUNT_2 },
{ "dbgt", ARGS_COUNT_2 },
{ "dbhi", ARGS_COUNT_2 },
{ "dble", ARGS_COUNT_2 },
{ "dbls", ARGS_COUNT_2 },
{ "dblt", ARGS_COUNT_2 },
{ "dbmi", ARGS_COUNT_2 },
{ "dbne", ARGS_COUNT_2 },
{ "dbpl", ARGS_COUNT_2 },
{ "dbvc", ARGS_COUNT_2 },
{ "dbvs", ARGS_COUNT_2 },
{ "divu", ARGS_COUNT_2 },
{ "divs", ARGS_COUNT_2 },
{ "eori", ARGS_COUNT_2 },
{ "exg", ARGS_COUNT_2 },
{ "ext", ARGS_COUNT_1 },
{ "illegal", ARGS_COUNT_0 },
{ "jmp", ARGS_COUNT_1 },
{ "jsr", ARGS_COUNT_1 },
{ "lea", ARGS_COUNT_2 },
{ "link", ARGS_COUNT_2 },
{ "lsl", ARGS_COUNT_1_2 },
{ "lsr", ARGS_COUNT_1_2 },
{ "move", ARGS_COUNT_2 },
{ "movea", ARGS_COUNT_2 },
{ "movem", ARGS_COUNT_2 },
{ "movep", ARGS_COUNT_2 },
{ "moveq", ARGS_COUNT_2 },
{ "muls", ARGS_COUNT_2 },
{ "mulu", ARGS_COUNT_2 },
{ "nbcd", ARGS_COUNT_1 },
{ "neg", ARGS_COUNT_1 },
{ "negx", ARGS_COUNT_1 },
{ "nop", ARGS_COUNT_0 },
{ "not", ARGS_COUNT_1 },
{ "or", ARGS_COUNT_2 },
{ "ori", ARGS_COUNT_2 },
{ "pea", ARGS_COUNT_1 },
{ "reset", ARGS_COUNT_0 },
{ "rol", ARGS_COUNT_1_2 },
{ "ror", ARGS_COUNT_1_2 },
{ "roxl", ARGS_COUNT_1_2 },
{ "roxr", ARGS_COUNT_1_2 },
{ "rte", ARGS_COUNT_0 },
{ "rtr", ARGS_COUNT_0 },
{ "rts", ARGS_COUNT_0 },
{ "sbcd", ARGS_COUNT_2 },
{ "st", ARGS_COUNT_1 },
{ "sf", ARGS_COUNT_1 },
{ "scc", ARGS_COUNT_1 },
{ "scs", ARGS_COUNT_1 },
{ "seq", ARGS_COUNT_1 },
{ "sge", ARGS_COUNT_1 },
{ "sgt", ARGS_COUNT_1 },
{ "shi", ARGS_COUNT_1 },
{ "sle", ARGS_COUNT_1 },
{ "sls", ARGS_COUNT_1 },
{ "slt", ARGS_COUNT_1 },
{ "smt", ARGS_COUNT_1 },
{ "sne", ARGS_COUNT_1 },
{ "spl", ARGS_COUNT_1 },
{ "svc", ARGS_COUNT_1 },
{ "svs", ARGS_COUNT_1 },
{ "stop", ARGS_COUNT_1 },
{ "sub", ARGS_COUNT_2 },
{ "suba", ARGS_COUNT_2 },
{ "subi", ARGS_COUNT_2 },
{ "subq", ARGS_COUNT_2 },
{ "subx", ARGS_COUNT_2 },
{ "swap", ARGS_COUNT_1 },
{ "tas", ARGS_COUNT_1 },
{ "trap", ARGS_COUNT_1 },
{ "trapv", ARGS_COUNT_0 },
{ "tst", ARGS_COUNT_1 },
{ "unlk", ARGS_COUNT_1 },
};
static int pars_directive_skip(struct pars *, enum directive_type, size_t);
static int pars_directive_handler_def(struct pars *, enum directive_type, size_t);
static int pars_directive_handler_endef(struct pars *, enum directive_type, size_t);
const struct directive_description {
const char *str;
int (*handler)(struct pars *, enum directive_type, size_t lable_id);
} g_directives[DIRECTIVES_COUNT] = {
{ "", NULL, },
{ "align", pars_directive_skip, },
{ "ascii", pars_directive_skip, },
{ "bin", pars_directive_skip, },
{ "bsection", pars_directive_skip, },
{ "bss", pars_directive_skip, },
{ "byte", pars_directive_skip, },
{ "cmnt", pars_directive_skip, },
{ "comm", pars_directive_skip, },
{ "data", pars_directive_skip, },
{ "def", pars_directive_handler_def, },
{ "dim", pars_directive_skip, },
{ "double", pars_directive_skip, },
{ "dsection", pars_directive_skip, },
{ "echo", pars_directive_skip, },
{ "elifdef", pars_directive_skip, },
{ "else", pars_directive_skip, },
{ "end", pars_directive_skip, },
{ "endc", pars_directive_skip, },
{ "endef", pars_directive_handler_endef, },
{ "endif", pars_directive_skip, },
{ "ends", pars_directive_skip, },
{ "extend", pars_directive_skip, },
{ "extern", pars_directive_skip, },
{ "file", pars_directive_skip, },
{ "fill", pars_directive_skip, },
{ "float", pars_directive_skip, },
{ "fpdata", pars_directive_skip, },
{ "globl", pars_directive_skip, },
{ "ifdef", pars_directive_skip, },
{ "ifndef", pars_directive_skip, },
{ "include", pars_directive_skip, },
{ "lcomm", pars_directive_skip, },
{ "line", pars_directive_skip, },
{ "ln", pars_directive_skip, },
{ "long", pars_directive_skip, },
{ "opt", pars_directive_skip, },
{ "org", pars_directive_skip, },
{ "packed", pars_directive_skip, },
{ "page", pars_directive_skip, },
{ "reorg", pars_directive_skip, },
{ "scl", pars_directive_skip, },
{ "section", pars_directive_skip, },
{ "short", pars_directive_skip, },
{ "single", pars_directive_skip, },
{ "size", pars_directive_skip, },
{ "space", pars_directive_skip, },
{ "struct", pars_directive_skip, },
{ "tag", pars_directive_skip, },
{ "text", pars_directive_skip, },
{ "tsection", pars_directive_skip, },
{ "type", pars_directive_skip, },
{ "val", pars_directive_skip, },
{ "word", pars_directive_skip, },
{ "xdef", pars_directive_skip, },
{ "xref", pars_directive_skip, },
};
static bool should_be_escaped(const int c)
{
return c < ' ' || c == '"' || c == '\\' || c == '<' || c == '>' || c > '~';
}
static bool is_oct(const int c)
{
return c >= '0' && c <= '7';
}
static bool is_dec(const int c)
{
return c >= '0' && c <= '9';
}
static bool is_hex(const int c)
{
return is_dec(c) || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f');
}
static bool is_alphabetic(const int c)
{
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
static bool is_alphanum(const int c)
{
return is_dec(c) || is_alphabetic(c);
}
static int printed_size(const char c)
{
if (c < ' ' || c > '~') {
return sizeof("\\x00")-1;
}
if (c == '"' || c == '\\') {
return sizeof("\\\\")-1;
}
return 1;
}
static bool token_is_number(const enum token_type type)
{
return type == TT_NUMHEX || type == TT_NUMDEC || type == TT_NUMOCT;
}
static bool token_is_binary_operator(const enum token_type type)
{
return type == TT_PLUS || type == TT_MINUS ||
type == TT_ASTERISK || type == TT_SLASH || type == TT_PERCENT ||
type == TT_RSHIFT || type == TT_RSHIFT ||
type == TT_AMPERSAND || type == TT_CAP ||
type == TT_PIPE || type == TT_BANG;
}
static bool token_is_regmask_delimiter(const enum token_type type)
{
return type == TT_SLASH || type == TT_MINUS;
}
static int fprint_string_escaped(
const char *const str, const size_t length, FILE *const stream)
{
int written = 0;
for (size_t i = 0; i < length; i++, written += printed_size(str[i])) {
if (should_be_escaped(str[i])) {
fputs(g_escape_table[(unsigned char)str[i]], stream);
} else {
fputc(str[i], stream);
}
}
return written;
}
static const char *token_type_to_string(const enum token_type type)
{
switch (type) {
case TT_NONE: return "NONE";
case TT_NEWLINE: return "NEWLINE";
case TT_ESCAPE: return "ESCAPE";
case TT_DOT: return "DOT";
case TT_COMMA: return "COMMA";
case TT_PLUS: return "PLUS";
case TT_MINUS: return "MINUS";
case TT_ASTERISK: return "ASTERISK";
case TT_SLASH: return "SLASH";
case TT_EQ: return "EQ";
case TT_EQ_DOUBLE: return "EQ_DOUBLE";
case TT_COLON: return "COLON";
case TT_PERCENT: return "PERCENT";
case TT_LSHIFT: return "LSHIFT";
case TT_RSHIFT: return "RSHIFT";
case TT_HASH: return "HASH";
case TT_BANG: return "BANG";
case TT_TILDE: return "TILDE";
case TT_AMPERSAND: return "AMPERSAND";
case TT_PIPE: return "PIPE";
case TT_CAP: return "CAP";
case TT_STRING: return "STRING";
case TT_ID: return "ID";
case TT_DOT_ID: return "DOT_ID";
case TT_NUMDEC: return "NUMDEC";
case TT_NUMOCT: return "NUMOCT";
case TT_NUMHEX: return "NUMHEX";
case TT_LPAREN: return "LPAREN";
case TT_RPAREN: return "RPAREN";
case TT_LBRACKET: return "LBRACKET";
case TT_RBRACKET: return "RBRACKET";
case TT_LBRACE: return "LBRACE";
case TT_RBRACE: return "RBRACE";
case TT_COMMENT_ASTERISK: return "COMMENT";
case TT_COMMENT_SEMICOLON: return "COMMENT";
}
UNREACHABLE();
return "_UNKNOWN";
}
static int fprint_token_debug(const char *const input, struct token *token, FILE *const stream)
{
int res = fprintf(stream, "%s<", token_type_to_string(token->type));
if (res == -1) {
return -1;
}
int written = res;
res = fprint_string_escaped(input + token->offset, token->length, stream);
if (res == -1) {
return -1;
}
written += res;
res = fputs(">\n", stream);
if (res == -1) {
return -1;
}
written += res;
return written;
}
static int fwrite_token(const struct token *const token, FILE *const stream)
{
const int res = fwrite(token, sizeof *token, 1, stream);
assert(res == 1);
return res;
}
static int lex_init(struct lex *const self)
{
*self = (struct lex){
.input_stream = open_memstream(&self->input, &self->input_size),
.tokbuf_stream = open_memstream(
(char **)&self->tokbuf, &self->tokbuf_size),
};
assert(self->input_stream != NULL);
assert(self->tokbuf_stream != NULL);
// Place a dummy token at 0 index, so first real token will be at index 1.
// This is needed for parser, so it can use zero to indicate absence of
// token.
fwrite_token(&(struct token){TT_NONE}, self->tokbuf_stream);
return OK;
}
static void lex_yield_token(struct lex *const self, const struct token *const token)
{
self->inside_line = (token->type != TT_NEWLINE) && (token->type != TT_ESCAPE);
fwrite_token(token, self->tokbuf_stream);
self->tokens_count++;
}
static const char *lex_state_error_string(
const enum lex_state state, const bool inside_line)
{
if (!inside_line) {
assert(state == LS_FREE);
return "'*', ';', '0', '[1-9]', '[a-zA-Z_]', ',', '.', '(', ')', '+', "
"'-', '=', ':', '%', '#', ' ', '\\t', '\\r', '\\n', '\\r\\n' "
"or EOF";
}
switch (state) {
case LS_FREE:
return "';', '0', '[1-9]', '[a-zA-Z_]', ',', '.', '(', ')', '+', "
"'-', '=', ':', '%', '#', ' ', '\\t', '\\r', '\\n', '\\r\\n' "
"or EOF";
case LS_NUMOCTHEX:
return "';', '[0-7]', [xX], ',', '.', '(', ')', '+', "
"'-', '=', ':', '%', '#', ' ', '\\t', '\\r', '\\n', '\\r\\n' "
"or EOF";
case LS_NUMOCT:
return "';', '[0-7]' , ',', '.', '(', ')', '+', "
"'-', '=', ':', '%', '#', ' ', '\\t', '\\r', '\\n', '\\r\\n' "
"or EOF";
case LS_NUMHEX:
return "';', '[0-9a-fA-F]' , ',', '.', '(', ')', '+', "
"'-', '=', ':', '%', '#', ' ', '\\t', '\\r', '\\n', '\\r\\n' "
"or EOF";
case LS_NUMDEC:
return "';', '[0-9]' , ',', '.', '(', ')', '+', "
"'-', '=', ':', '%', '#', ' ', '\\t', '\\r', '\\n', '\\r\\n' "
"or EOF";
case LS_LSHIFT:
return "'<'";
case LS_RSHIFT:
return "'>'";
case LS_CR:
case LS_EQ:
case LS_DOT:
case LS_DOT_ID:
case LS_ID:
case LS_STRING:
case LS_STRING_ESC:
case LS_COMMENT_ASTERISK:
case LS_COMMENT_SEMICOLON:
case LS_ERROR:
case LS_EOF:
UNREACHABLE();
break;
}
return "???";
}
static struct line_pos_info lex_get_line_pos_info(
const struct lex *const self, const size_t cursor)
{
struct line_pos_info l = {0, 0, 0};
bool cr = false;
for (size_t i = 0; i < cursor; i++) {
const char c = self->input[i];
if (c == '\r') {
cr = true;
l.line_offset = i + 1;
l.line_num++;
l.column_num = 0;
} else if (c == '\n') {
if (!cr) {
l.line_num++;
}
cr = false;
l.line_offset = i + 1;
l.column_num = 0;
} else {
cr = false;
l.column_num++;
}
}
return l;
}
static size_t find_line_length(const char *const str)
{
for (size_t i = 0;; i++) {
const char c = str[i];
if (c == '\n' || c == '\r' || c == '\000') {
return i;
}
}
return 0;
}
static int lex_yield_error(struct lex *const self, const int c)
{
fflush(self->input_stream);
const size_t cursor = self->cursor;
const struct line_pos_info l = lex_get_line_pos_info(self, cursor);
{
// Read out the rest of the line
int c;
do {
c = getc(stdin);
const char c_char = (c == EOF) ? 0 : c;
fwrite(&c_char, sizeof c_char, 1, self->input_stream);
} while (c != EOF && c != '\n' && c != '\r');
fflush(self->input_stream);
}
const unsigned char c_char = (c == EOF) ? 0 : c;
fprintf(
stderr,
"<stdin>:%lu:%lu: lexing error: expected %s, found '",
l.line_num + 1,
l.column_num + 1,
lex_state_error_string(self->state, self->inside_line));
fputs(g_escape_table[c_char], stderr);
fputs("'\n", stderr);
const char *const line = self->input + l.line_offset;
const size_t line_length = find_line_length(line);
fprintf(stderr, "%5lu | %.*s\n", l.line_num, (int)line_length, line);
fputs(" | ", stderr);
for (size_t i = 0; i < l.column_num; i++) {
if (self->input[l.line_offset + i] == '\t') {
fputc('\t', stderr);
} else {
fputc(' ', stderr);
}
}
fputs("^\n", stderr);
fprintf(stderr, "<stdin>: %lu bytes parsed\n", cursor);
self->state = LS_ERROR;
return ERR;
}
static int lex_handle_next(struct lex *const self, const int c)
{
switch (self->state) {
case LS_FREE:
if (is_alphabetic(c) || c == '_') {
self->tok_offset = self->cursor;
self->state = LS_ID;
} else if (c == '0') {
self->tok_offset = self->cursor;
self->state = LS_NUMOCTHEX;
} else if (is_dec(c)) {
self->tok_offset = self->cursor;
self->state = LS_NUMDEC;
} else if (c == '@') {
self->tok_offset = self->cursor;
self->state = LS_NUMOCT;
} else if (c == '$') {
self->tok_offset = self->cursor;
self->state = LS_NUMHEX;
} else if (c == '"') {
self->tok_offset = self->cursor;
self->state = LS_STRING;
} else if (c == ';') {
self->tok_offset = self->cursor;
self->state = LS_COMMENT_SEMICOLON;
} else if (c == '<') {
self->tok_offset = self->cursor;
self->state = LS_LSHIFT;
} else if (c == '>') {
self->tok_offset = self->cursor;
self->state = LS_RSHIFT;
} else if (c == '.') {
self->tok_offset = self->cursor;
self->state = LS_DOT;
} else if (c == ',') {
lex_yield_token(self, &(struct token){TT_COMMA, self->cursor, 1});
} else if (c == '(') {
lex_yield_token(self, &(struct token){TT_LPAREN, self->cursor, 1});
} else if (c == ')') {
lex_yield_token(self, &(struct token){TT_RPAREN, self->cursor, 1});
} else if (c == '[') {
lex_yield_token(self, &(struct token){TT_LBRACKET, self->cursor, 1});
} else if (c == ']') {
lex_yield_token(self, &(struct token){TT_RBRACKET, self->cursor, 1});
} else if (c == '{') {
lex_yield_token(self, &(struct token){TT_LBRACE, self->cursor, 1});
} else if (c == '{') {
lex_yield_token(self, &(struct token){TT_RBRACE, self->cursor, 1});
} else if (c == '+') {
lex_yield_token(self, &(struct token){TT_PLUS, self->cursor, 1});
} else if (c == '-') {
lex_yield_token(self, &(struct token){TT_MINUS, self->cursor, 1});
} else if (c == '*') {
if (self->inside_line) {
lex_yield_token(
self, &(struct token){TT_ASTERISK, self->cursor, 1});
} else {
self->tok_offset = self->cursor;
self->state = LS_COMMENT_ASTERISK;
}
} else if (c == '/') {
lex_yield_token(self, &(struct token){TT_SLASH, self->cursor, 1});
} else if (c == '=') {
self->tok_offset = self->cursor;
self->state = LS_EQ;
} else if (c == ':') {
lex_yield_token(self, &(struct token){TT_COLON, self->cursor, 1});
} else if (c == '%') {
lex_yield_token(self, &(struct token){TT_PERCENT, self->cursor, 1});
} else if (c == '#') {
lex_yield_token(self, &(struct token){TT_HASH, self->cursor, 1});
} else if (c == '!') {
lex_yield_token(self, &(struct token){TT_BANG, self->cursor, 1});
} else if (c == '~') {
lex_yield_token(self, &(struct token){TT_TILDE, self->cursor, 1});
} else if (c == '&') {
lex_yield_token(self, &(struct token){TT_AMPERSAND, self->cursor, 1});
} else if (c == '|') {
lex_yield_token(self, &(struct token){TT_PIPE, self->cursor, 1});
} else if (c == '^') {
lex_yield_token(self, &(struct token){TT_CAP, self->cursor, 1});
} else if (c == '\r') {
self->tok_offset = self->cursor;
self->state = LS_CR;
} else if (c == '\n') {
lex_yield_token(self, &(struct token){TT_NEWLINE, self->cursor, 1});
} else if (c == '\\') {
lex_yield_token(self, &(struct token){TT_ESCAPE, self->cursor, 1});
} else if (c == ' ' || c == '\t') {
// ignore spaces and tabs
} else if (c == EOF) {
self->state = LS_EOF;
} else if (c == '\x1a') {
// Ignore "End of file" character
} else {
return lex_yield_error(self, c);
}
break;
case LS_CR: // Accumulate CRLF into single token
{
const size_t size = c == '\n' ? 2 : 1; // 2 for CRLF, 1 for just CR
const struct token token = {TT_NEWLINE, self->tok_offset, size};
lex_yield_token(self, &token);
self->state = LS_FREE;
if (c != '\n') {
// It is just CR, handle this char in LS_FREE state then
return lex_handle_next(self, c);
}
}
break;
case LS_LSHIFT:
if (c == '<') {
const size_t length = self->cursor - self->tok_offset;
const struct token token = {TT_LSHIFT, self->tok_offset, length};
lex_yield_token(self, &token);
self->state = LS_FREE;
} else {
return lex_yield_error(self, c);
}
break;
case LS_RSHIFT:
if (c == '>') {
const size_t length = self->cursor - self->tok_offset;
const struct token token = {TT_RSHIFT, self->tok_offset, length};
lex_yield_token(self, &token);
self->state = LS_FREE;
} else {
return lex_yield_error(self, c);
}
break;
case LS_EQ:
{
const size_t length = (c == '=') ? 2 : 1;
const enum token_type type = (c == '=') ? TT_EQ_DOUBLE : TT_EQ;
const struct token token = {type, self->tok_offset, length};
lex_yield_token(self, &token);
}
self->state = LS_FREE;
if (c != '=') {
// It is just single eq "=", handle this char in LS_FREE state then
return lex_handle_next(self, c);
}
break;
case LS_DOT:
if (is_alphanum(c) || c == '_') {
self->state = LS_DOT_ID;
} else {
lex_yield_token(self, &(struct token){TT_DOT, self->tok_offset, 1});
self->state = LS_FREE;
return lex_handle_next(self, c);
}
break;
case LS_DOT_ID:
if (!is_alphanum(c) && c != '_') {
const size_t length = self->cursor - self->tok_offset;
const struct token token = {TT_DOT_ID, self->tok_offset, length};
lex_yield_token(self, &token);
self->state = LS_FREE;
return lex_handle_next(self, c);
}
break;
case LS_ID:
if (!is_alphanum(c) && c != '_') {
const size_t length = self->cursor - self->tok_offset;
const struct token token = {TT_ID, self->tok_offset, length};
lex_yield_token(self, &token);
self->state = LS_FREE;
return lex_handle_next(self, c);
}
break;
case LS_NUMOCTHEX:
if (c == 'x' || c == 'X') {
self->state = LS_NUMHEX;
} else if (is_oct(c)) {
self->state = LS_NUMOCT;
} else if (is_alphabetic(c) || c == '_') {
return lex_yield_error(self, c);
} else {
assert((self->cursor - self->tok_offset) == 1);
const struct token token = {TT_NUMDEC, self->tok_offset, 1};
lex_yield_token(self, &token);
// It was just zero, handle this char in LS_FREE state then
self->state = LS_FREE;
return lex_handle_next(self, c);
}
break;
case LS_NUMOCT:
if (is_alphabetic(c) || c == '_') {
return lex_yield_error(self, c);
} else if (!is_oct(c)) {
const size_t length = self->cursor - self->tok_offset;
const struct token token = {TT_NUMOCT, self->tok_offset, length};
lex_yield_token(self, &token);
// This token is finished, handle this char in LS_FREE state
self->state = LS_FREE;
return lex_handle_next(self, c);
}
break;
case LS_NUMHEX:
if (is_hex(c)) {
// Keep calm
} else if (is_alphabetic(c) || c == '_') {
// Panik!
return lex_yield_error(self, c);
} else {
const size_t length = self->cursor - self->tok_offset;
const struct token token = {TT_NUMHEX, self->tok_offset, length};
lex_yield_token(self, &token);
// This token is finished, handle this char in LS_FREE state
self->state = LS_FREE;
return lex_handle_next(self, c);
}
break;
case LS_NUMDEC:
if (is_alphabetic(c) || c == '_') {
return lex_yield_error(self, c);
} else if (!is_dec(c)) {
const size_t length = self->cursor - self->tok_offset;
const struct token token = {TT_NUMDEC, self->tok_offset, length};
lex_yield_token(self, &token);
// This token is finished, handle this char in LS_FREE state
self->state = LS_FREE;
return lex_handle_next(self, c);
}
break;
case LS_STRING:
if (c == '\\') {
self->state = LS_STRING_ESC;
} else if (c == '"') {
const size_t length = self->cursor - self->tok_offset + 1;
const struct token token = {TT_STRING, self->tok_offset, length};
lex_yield_token(self, &token);
// This token is finished
self->state = LS_FREE;
}
break;
case LS_STRING_ESC:
self->state = LS_STRING;
break;
case LS_COMMENT_ASTERISK:
if (c == '\r' || c == '\n') {
const size_t length = self->cursor - self->tok_offset;
const struct token token = {TT_COMMENT_ASTERISK, self->tok_offset, length};
lex_yield_token(self, &token);
// This token is finished, handle this char in LS_FREE state
self->state = LS_FREE;
return lex_handle_next(self, c);
}
break;
case LS_COMMENT_SEMICOLON:
if (c == '\r' || c == '\n') {
const size_t length = self->cursor - self->tok_offset;
const struct token token = {TT_COMMENT_SEMICOLON, self->tok_offset, length};
lex_yield_token(self, &token);
// This token is finished, handle this char in LS_FREE state
self->state = LS_FREE;
return lex_handle_next(self, c);
}
break;
case LS_ERROR:
return ERR;
case LS_EOF:
UNREACHABLE();
}
return CONTINUE;
}
/** Advance lexer to produce new token.
* \returns EOF if end of file reached.
* \returns ERR if error encountered and lexing cannot continue.
* \returns OK has one or more new tokens parsed.
*/
static int lex_next(struct lex *const self, FILE *const stream)
{
for (;; self->cursor++) {
const int c = fgetc(stream);
const char c_char = (c == EOF) ? 0 : c;
fwrite(&c_char, sizeof c_char, 1, self->input_stream);
const int ret = lex_handle_next(self, c);
if (OK == ret) {
return OK;
} else if (ERR == ret) {
return ERR;
}
if (c == EOF) {
// Add a hidden EOF token of 0 size
lex_yield_token(self, &(struct token){TT_NONE, self->cursor, 0});
break;
}
}
return EOF;
}
/** Run lexer until the end of the input reached
* \returns OK if lexing finished successfully
* \returns ERR if error encountered and lexing cannot continue.
*/
static int lex_run(struct lex *const self, FILE *const stream)
{
int res;
do {
res = lex_next(self, stream);
if (res == OK) {
res = 0;
} else if (res == ERR) {
return ERR;
}
} while (res != EOF);
fflush(self->input_stream);
fflush(self->tokbuf_stream);
return OK;
}
static void lex_destroy(struct lex *const self)
{
fclose(self->input_stream);
free(self->input);
fclose(self->tokbuf_stream);
free(self->tokbuf);
}
static enum args_count get_args_count_for_mnemonic(const enum mnemonic m)
{
assert(m < MNEMONICS_COUNT);
return g_mnemmonics[m].args_count;
}
static const char *mnemonic_to_string(const enum mnemonic m)
{
assert(m < MNEMONICS_COUNT);
return g_mnemmonics[m].str;
}
static const char *directive_to_string(const enum directive_type t) {
assert(t < DIRECTIVES_COUNT);
return g_directives[t].str;
}
static const char *opsize_to_string(const enum opsize s)
{
switch (s) {
case OPSIZE_NONE: return "none";
case OPSIZE_S: return "short";
case OPSIZE_B: return "byte";
case OPSIZE_W: return "word";
case OPSIZE_L: return "long";
}
UNREACHABLE();
return "_unknown";
}
static char opsize_to_char(const enum opsize s)
{
switch (s) {
case OPSIZE_NONE: return '_';
case OPSIZE_S: return 's';
case OPSIZE_B: return 'b';
case OPSIZE_W: return 'w';
case OPSIZE_L: return 'l';
}
UNREACHABLE();
return '?';
}
static enum mnemonic get_mnemonic_from_identifier(
const char *const str, const size_t str_length)
{
if (str_length > 7) {
return MN_NONE;
}
char mnemonic_str[8] = {0};
for (size_t i = 0; i < str_length; i++) {
mnemonic_str[i] = tolower(str[i]);
}
// Start from 1 since - is dummy NONE
for (size_t i = 1; i < MNEMONICS_COUNT; i++) {
if (0 == strcmp(mnemonic_str, g_mnemmonics[i].str)) {
return (enum mnemonic)i;
}
}
return MN_NONE;
}
static enum directive_type get_directive_from_identifier(
const char *const str, const size_t str_length)
{
// The longest directive have 8 chars (without leading dot), e.g.
// "bsection" or "external".
if (str_length > 8) {
return DT_NONE;
}
char directive_str[9] = {0};
for (size_t i = 0; i < str_length; i++) {
directive_str[i] = tolower(str[i]);
}
// Start from 1 since - is dummy NONE
for (size_t i = 1; i < DIRECTIVES_COUNT; i++) {
if (0 == strcmp(directive_str, g_directives[i].str)) {
return (enum directive_type)i;
}
}
return DT_NONE;
}
static const char *arg_type_to_string(const enum arg_type type)
{
switch (type) {
case ARG_NONE: return "NONE";
case ARG_DN: return "Dn";
case ARG_AN: return "An";
case ARG_AN_ADDR: return "(An)";
case ARG_AN_ADDR_INCR: return "(An)+";
case ARG_AN_ADDR_DECR: return "-(An)";
case ARG_AN_ADDR_16: return "(d16,An)";
case ARG_AN_ADDR_8_XI: return "(d8,An,Xi)";
case ARG_ADDR_WORD: return "(xxx).w";
case ARG_ADDR_LONG: return "(xxx).l";
case ARG_ADDR_UNSPEC: return "(xxx).?";
case ARG_PC_ADDR_16: return "(d16,PC)";
case ARG_PC_ADDR_8_XI: return "(d8,PC,Xn)";
case ARG_IMMEDIATE: return "#imm";
case ARG_REGMASK: return "REGMASK";
case ARG_SR: return "SR";
case ARG_CCR: return "CCR";
case ARG_USP: return "USP";
}
UNREACHABLE();
return "_UNKNOWN";
}
static int pars_init(struct pars *const self, const struct lex *const lex)
{
*self = (struct pars){
.lex = lex,
.stmttab_stream = open_memstream(
(char **)&self->stmttab, &self->stmttab_size),
.symtab_stream = open_memstream(
(char **)&self->symtab, &self->symtab_size),
.symbuf_stream = open_memstream(&self->symbuf, &self->symbuf_size),
};
assert(self->stmttab_stream != NULL);
assert(self->symtab_stream != NULL);
assert(self->symbuf_stream != NULL);
return OK;
}
static bool pars_is_eof_reached(const struct pars *const self)
{
return self->cur_tok_id >= self->lex->tokens_count;
}
static const char *stmt_type_to_string(const enum stmt_type type)
{
switch (type) {
case ST_NONE: return "NONE";
case ST_LABEL: return "LABEL";
case ST_INSTRUCTION: return "INSTRUCTION";
case ST_ASSIGNMENT: return "ASSIGNMENT";
case ST_COMMENT: return "COMMENT";
case ST_DIRECTIVE: return "DIRECTIVE";
}
return "_UNKNOWN";
}
static int fprint_tokens(
const struct lex *const lex,
const size_t first_token,
const size_t num_tokens,
FILE *const s)
{
for (size_t i = 0; i < num_tokens; i++) {
const struct token token = lex->tokbuf[first_token + i];
if (token.type == TT_NEWLINE) {
break;
}
if (i > 0) {
fputc(' ', s);
}
fprintf(s, "\"%.*s\"", (int)token.length, lex->input + token.offset);
}
return 0;
}
static void fprint_expr(
const struct lex *const lex,
const struct expr_tokens_span *const expr,
FILE *const s)
{
fputc('[', s);
for (size_t i = 0; i < expr->num_tokens; i++) {
const struct token token = lex->tokbuf[expr->first_token + i];
if (token.type == TT_NEWLINE) {
break;
}
fprintf(s, "%.*s", (int)token.length, lex->input + token.offset);
}
fputc(']', s);
}
static void fprint_arg_debug(
const struct lex *const lex,
const struct arg *const arg,
FILE *const s)
{
fprintf(s, "(%s", arg_type_to_string(arg->type));
switch (arg->type) {
case ARG_DN:
fprintf(s, " reg [d%d]", arg->xn);
break;
case ARG_AN:
case ARG_AN_ADDR:
case ARG_AN_ADDR_INCR:
case ARG_AN_ADDR_DECR:
fprintf(s, " reg [a%d]", arg->xn);
break;
case ARG_AN_ADDR_16:
fprintf(s, " reg [a%d]", arg->xn);
fprintf(s, " d16 "), fprint_expr(lex, &arg->expr, s);
break;
case ARG_AN_ADDR_8_XI:
fprintf(s, " reg [a%d]", arg->xn);
fprintf(s, " d8 "), fprint_expr(lex, &arg->expr, s);
fprintf(s, " xi [%c%d]", arg->xi & 0x8 ? 'a' : 'd', arg->xi & 0x7);
{
const char size = arg->briefext_size == OPSIZE_L ? 'l' : 'w';
fprintf(s, " briefext_size [%c]", size);
}
break;
case ARG_ADDR_WORD:
case ARG_ADDR_LONG:
case ARG_ADDR_UNSPEC:
fprintf(s, " addr "), fprint_expr(lex, &arg->expr, s);
break;
case ARG_PC_ADDR_16:
fprintf(s, " reg [pc]");
fprintf(s, " d16 "), fprint_expr(lex, &arg->expr, s);
break;
case ARG_PC_ADDR_8_XI:
fprintf(s, " reg [pc]");
fprintf(s, " d8 "), fprint_expr(lex, &arg->expr, s);
fprintf(s, " xi [%c%d]", arg->xi & 0x8 ? 'a' : 'd', arg->xi & 0x7);
break;
case ARG_IMMEDIATE:
fprintf(s, " value "), fprint_expr(lex, &arg->expr, s);
break;
case ARG_REGMASK:
fprintf(s, " regs [");
{
bool leading_space = false;
for (unsigned i = 0; i < 8; i++) {
if (arg->regmask & (1 << i)) {
fprintf(s, "%sd%d", leading_space ? " " : "", i);
leading_space = true;
}
}
for (unsigned i = 0; i < 8; i++) {
if (arg->regmask & (1 << (i + 8))) {
fprintf(s, "%sa%d", leading_space ? " " : "", i);
leading_space = true;
}
}
}
fprintf(s, "]");
break;
case ARG_SR:
fprintf(s, "reg [sr]");
break;
case ARG_CCR:
fprintf(s, "reg [ccr]");
break;
case ARG_USP:
fprintf(s, "reg [usp]");
break;
case ARG_NONE:
break;
}
fprintf(s, " raw-tokens [");
fprint_tokens(lex, arg->first_token, arg->num_tokens, s);
fprintf(s, "])");
}
static int fprint_stmt_debug(
const struct lex *const lex,
struct stmt *const stmt,
FILE *const s)
{
assert(stmt);
fprintf(s, "(%s", stmt_type_to_string(stmt->type));
if (stmt->label_token) {
const struct token label = lex->tokbuf[stmt->label_token];
fprintf(
s,
"\n\t(label \"%.*s\")",
(int)label.length,
lex->input + label.offset);
}
if (stmt->type == ST_INSTRUCTION) {
fprintf(
s,
"\n\t(mnemonic \"%s\")",
mnemonic_to_string(stmt->instruction.mnemonic));
fprintf(s, "\n\t(size %s)", opsize_to_string(stmt->instruction.opsize));
if (stmt->instruction.arg1.type != ARG_NONE) {
fprintf(s, "\n\t(arg1 ");
fprint_arg_debug(lex, &stmt->instruction.arg1, s);
fprintf(s, ")");
}
if (stmt->instruction.arg2.type != ARG_NONE) {
assert(stmt->instruction.arg1.type != ARG_NONE);
fprintf(s, "\n\t(arg2 ");
fprint_arg_debug(lex, &stmt->instruction.arg2, s);
fprintf(s, ")");
}
} else if (stmt->type == ST_DIRECTIVE) {
fprintf(
s,
"\n\t(name \"%s\")",
directive_to_string(stmt->directive.type));
if (stmt->directive.first_token && stmt->directive.num_tokens) {
fprintf(s, "\n\t(arg (raw-tokens [");
fprint_tokens(
lex,
stmt->directive.first_token,
stmt->directive.num_tokens,
s);
fprintf(s, "]))");
}
}
if (stmt->comment_token) {
const struct token comment = lex->tokbuf[stmt->comment_token];
fprintf(
s,
"\n\t(comment \"%.*s\")",
(int)comment.length,
lex->input + comment.offset);
}
fprintf(s, "\n\t(raw-tokens [");
fprint_tokens(lex, stmt->first_token, stmt->num_tokens, s);
fprintf(s, "]))\n");
return 0;
}
static int fwrite_stmt(const struct stmt *const stmt, FILE *const stream)
{
const int res = fwrite(stmt, sizeof *stmt, 1, stream);
assert(res == 1);
return res;
}
static struct token pars_peek(const struct pars *const self)
{
return self->lex->tokbuf[self->cur_tok_id];
}
static struct token pars_peek_more(
const struct pars *const self, const size_t more)
{
return self->lex->tokbuf[self->cur_tok_id + more];
}
static size_t pars_commit(struct pars *const self)
{
return self->cur_tok_id++;
}
static void pars_skip_to_newline(struct pars *const self)
{
while (!pars_is_eof_reached(self)) {
const struct token nl = pars_peek(self);
pars_commit(self);
if (nl.type == TT_NEWLINE) {
return;
}
}
}
static int pars_yield_error_msg(
struct pars *const self,
const size_t token_id,
const char *const msg)
{
const struct token token = self->lex->tokbuf[token_id];
const struct line_pos_info l =
lex_get_line_pos_info(self->lex, token.offset);
fprintf(
stderr,
"<stdin>:%lu:%lu: parsing error: %s\n",
l.line_num + 1,
l.column_num + 1,
msg);
const char *const line = self->lex->input + l.line_offset;
const size_t line_length = find_line_length(line);
fprintf(stderr, "%5lu | %.*s\n", l.line_num, (int)line_length, line);
fputs(" | ", stderr);
for (size_t i = 0; i < l.column_num; i++) {
if (self->lex->input[l.line_offset + i] == '\t') {
fputc('\t', stderr);
} else {
fputc(' ', stderr);
}
}
fputs("^\n", stderr);
pars_skip_to_newline(self);
return ERR;
}
static int pars_yield_error_expected_str(
struct pars *const self,
const struct line_pos_info l,
const char *const found,
const size_t found_length,
const char *const expected)
{
fprintf(
stderr,
"<stdin>:%lu:%lu: parsing error: expected %s, found '",
l.line_num + 1,
l.column_num + 1,
expected);
fprint_string_escaped(found, found_length, stderr);
fputs("'\n", stderr);
const char *const line = self->lex->input + l.line_offset;
const size_t line_length = find_line_length(line);
fprintf( stderr, "%5lu | %.*s\n", l.line_num + 1, (int)line_length, line);
fputs(" | ", stderr);
for (size_t i = 0; i < l.column_num; i++) {
if (self->lex->input[l.line_offset + i] == '\t') {
fputc('\t', stderr);
} else {
fputc(' ', stderr);
}
}
fputc('^', stderr);
for (size_t i = 1; i < found_length; i++) {
fputc('~', stderr);
}
fputc('\n', stderr);
pars_skip_to_newline(self);
return ERR;
}
static int pars_yield_error(
struct pars *const self,
const size_t token_id,
const char *const expected)
{
const struct token token = self->lex->tokbuf[token_id];
const struct line_pos_info l =
lex_get_line_pos_info(self->lex, token.offset);
const char *const found = self->lex->input + token.offset;
return pars_yield_error_expected_str(self, l, found, token.length, expected);
}
static int pars_yield_error_eof(
struct pars *const self, const char *const expected)
{
const struct token token = self->lex->tokbuf[self->cur_tok_id];
const struct line_pos_info l =
lex_get_line_pos_info(self->lex, token.offset);
return pars_yield_error_expected_str(
self, l, "EOF", (sizeof "EOF") - 1, expected);
}
enum opsize get_opsize_from_specifier(const char size_specifier)
{
switch (tolower(size_specifier)) {
case 's': return OPSIZE_S;
case 'b': return OPSIZE_B;
case 'w': return OPSIZE_W;
case 'l': return OPSIZE_L;
}
return OPSIZE_NONE;
}
static bool is_pc(const char *const str)
{
return (str[0] == 'p' && str[1] == 'c') ||
(str[0] == 'P' && str[1] == 'C');
}
static bool is_sp(const char *const str)
{
return (str[0] == 's' && str[1] == 'p') ||
(str[0] == 'S' && str[1] == 'P');
}
static bool is_sr(const char *const str)
{
return (str[0] == 's' && str[1] == 'r') ||
(str[0] == 'S' && str[1] == 'R');
}
static bool is_ccr(const char *const str)
{
return
((str[0] == 'c' && str[1] == 'c' && str[2] == 'r') ||
(str[0] == 'C' && str[1] == 'C' && str[2] == 'R'));
}
static bool is_usp(const char *const str)
{
return
((str[0] == 'u' && str[1] == 's' && str[2] == 'p') ||
(str[0] == 'U' && str[1] == 'S' && str[2] == 'P'));
}
static struct token_recognition pars_recognize_token(
const struct pars *const self, const struct token token)
{
const char *const str = self->lex->input + token.offset;
if (token.type == TT_ID) {
if (token.length == 2) {
if (tolower(str[0]) == 'a' && is_oct(str[1])) {
return (struct token_recognition){
.type = RTT_REG,
.reg = REG_AN,
.reg_num = str[1] - '0',
};
} else if (tolower(str[0]) == 'd' && is_oct(str[1])) {
return (struct token_recognition){
.type = RTT_REG,
.reg = REG_DN,
.reg_num = str[1] - '0',
};
} else if (is_sp(str)) {
return (struct token_recognition){
.type = RTT_REG,
.reg = REG_AN,
.reg_num = 7,
};
} else if (is_pc(str)) {
return (struct token_recognition){
.type = RTT_REG,
.reg = REG_PC,
};
} else if (is_sr(str)) {
return (struct token_recognition){
.type = RTT_REG,
.reg = REG_SR,
};
}
} else if (token.length == 3) {
if (is_ccr(str)) {
return (struct token_recognition){
.type = RTT_REG,
.reg = REG_DN,
};
} else if (is_usp(str)) {
return (struct token_recognition){
.type = RTT_REG,
.reg = REG_USP,
};
}
}
} else if (token.type == TT_NUMDEC) {
// TODO
} else if (token.type == TT_NUMOCT) {
// TODO
} else if (token.type == TT_NUMHEX) {
// TODO
}
return (struct token_recognition){0};
}
static int pars_parse_expr(
struct pars *const self, struct expr_tokens_span *const expr)
{
// This function is called only when expression is expected unconditionally,
// so if the first token cannot be a part of expression, then error must be
// yielded.
const size_t first_token_id = self->cur_tok_id;
unsigned nesting = 0;
// Otherwise expect open parenthesis, number, or unary operator.
bool expect_close_or_binary = false;
while (1) {
if (pars_is_eof_reached(self)) {
if (nesting != 0) {
assert(pars_is_eof_reached(self));
return pars_yield_error_eof(
self,
expect_close_or_binary ? E_EXPR_CLOSE : E_EXPR_OPEN);
}
break;
}
const struct token token = pars_peek(self);
if (token.type == TT_LPAREN) {
if (expect_close_or_binary) {
if (nesting == 0) {
break;
}
return pars_yield_error(self, self->cur_tok_id, E_EXPR_CLOSE);
} else {
nesting++;
}
} else if (token.type == TT_MINUS) {
// Minus is both unary and binary operator, so it does not care
// about expression parsing state
expect_close_or_binary = false;
} else if (token.type == TT_TILDE) {
if (expect_close_or_binary) {
return pars_yield_error(self, self->cur_tok_id, E_EXPR_CLOSE);
}
} else if (token.type == TT_ID) {
if (expect_close_or_binary) {
return pars_yield_error(self, self->cur_tok_id, E_EXPR_CLOSE);
}
if (pars_recognize_token(self, token).type == RTT_REG) {
return pars_yield_error(self, self->cur_tok_id, E_EXPR_NONREG);
}
expect_close_or_binary = true;
} else if (token_is_number(token.type)) {
if (expect_close_or_binary) {
return pars_yield_error(self, self->cur_tok_id, E_EXPR_CLOSE);
}
expect_close_or_binary = true;
} else if (token_is_binary_operator(token.type)) {
if (!expect_close_or_binary) {
return pars_yield_error(self, self->cur_tok_id, E_EXPR_OPEN);
}
expect_close_or_binary = false;
} else if (token.type == TT_RPAREN) {
if (!expect_close_or_binary) {
return pars_yield_error(self, self->cur_tok_id, E_EXPR_OPEN);
}
if (nesting == 0) {
// This is not my closing parenthesis, should stop
break;
}
nesting--;
} else {
if (nesting == 0 && expect_close_or_binary) {
break;
}
return pars_yield_error(
self,
self->cur_tok_id,
expect_close_or_binary ? E_EXPR_CLOSE : E_EXPR_OPEN);
}
pars_commit(self);
}
assert(first_token_id != self->cur_tok_id);
*expr = (struct expr_tokens_span){
.first_token = first_token_id,
.num_tokens = self->cur_tok_id - first_token_id,
};
return OK;
}
static int pars_parse_comment_and_newline2(
struct pars *const self,
size_t *const output_comment_id,
const bool allow_escape)
{
size_t comment_id = 0;
if (!pars_is_eof_reached(self)) {
// Try parse comment
const struct token token1 = pars_peek(self);
const bool is_comment = token1.type == TT_COMMENT_ASTERISK ||
token1.type == TT_COMMENT_SEMICOLON;
if (is_comment) {
comment_id = pars_commit(self);
}
}
if (!pars_is_eof_reached(self)) {
// There must be a new line if not EOF
const size_t nl_id = pars_commit(self);
const struct token nl = self->lex->tokbuf[nl_id];
if (nl.type != TT_NEWLINE && (allow_escape && nl.type != TT_ESCAPE)) {
return pars_yield_error(
self, nl_id, comment_id ? E_NL : E_COMMENT_NL);
}
}
*output_comment_id = comment_id;
return OK;
}
static int pars_parse_comment_and_newline(
struct pars *const self, size_t *const output_comment_id)
{
return pars_parse_comment_and_newline2(self, output_comment_id, false);
}
static int pars_finish_directive(
struct pars *const self,
const size_t label_id,
const struct directive directive)
{
// Finish parsing instruction, expect comment or newline, or even escape
// symbol in some cases.
const bool allow_escape = directive.type == DT_DEF ||
directive.type == DT_DIM || directive.type == DT_LINE ||
directive.type == DT_SCL || directive.type == DT_SIZE ||
directive.type == DT_TAG || directive.type == DT_TYPE ||
directive.type == DT_VAL ;
size_t comment_id = 0;
const int ret = pars_parse_comment_and_newline2(
self, &comment_id, allow_escape);
if (ret != OK) {
return ret;
}
const size_t first_token = label_id ? label_id : directive.name_token;
const struct stmt stmt = {
.type = ST_DIRECTIVE,
.directive = directive,
.label_token = label_id,
.comment_token = comment_id,
.first_token = first_token,
.num_tokens = self->cur_tok_id - first_token,
};
fwrite_stmt(&stmt, self->stmttab_stream);
return OK;
}
static int pars_directive_skip(
struct pars *const self,
const enum directive_type drc,
const size_t label_id)
{
const size_t name_token = self->cur_tok_id - 1;
const size_t first_token = self->cur_tok_id;
size_t num_tokens = 0;
while (1) {
const struct token token = pars_peek(self);
const bool is_end = token.type == TT_COMMENT_SEMICOLON ||
token.type == TT_NEWLINE || token.type == TT_ESCAPE;
if (is_end) {
break;
}
pars_commit(self);
num_tokens++;
}
const struct directive directive = { drc, name_token, first_token, num_tokens };
return pars_finish_directive(self, label_id, directive);
}
static int pars_directive_handler_def(
struct pars *const self,
const enum directive_type drc,
const size_t label_id)
{
const size_t name_token = self->cur_tok_id - 1;
const struct token token = pars_peek(self);
if (token.type != TT_ID) {
return pars_yield_error(self, self->cur_tok_id, E_ID);
}
if (self->in_sat) {
return pars_yield_error_msg(self, self->cur_tok_id, E_NESTED_DEF);
}
self->in_sat = true;
const struct directive directive = { drc, name_token, pars_commit(self), 1 };
return pars_finish_directive(self, label_id, directive);
}
static int pars_directive_handler_endef(
struct pars *const self,
const enum directive_type drc,
const size_t label_id)
{
if (!self->in_sat) {
return pars_yield_error_msg(self, self->cur_tok_id, E_NMATCH_ENDEF);
}
self->in_sat = false;
const size_t name_token = self->cur_tok_id - 1;
const struct directive directive = { drc, name_token, 0, 0 };
return pars_finish_directive(self, label_id, directive);
}
static int pars_parse_direc(struct pars *const self, const size_t label_id)
{
const struct token dotid = pars_peek(self);
// Get rid of leading dot in the string pointer and in the length as well by
// adding and subtracting 1 respectively
enum directive_type d = get_directive_from_identifier(
self->lex->input + dotid.offset + 1, dotid.length - 1);
if (d == DT_NONE) {
return pars_yield_error_msg(self, self->cur_tok_id, E_UNKNOWN_DRC);
}
pars_commit(self);
return g_directives[d].handler(self, d, label_id);
}
static int pars_parse_arg_after_prefix_expr(
struct pars *const self, struct arg *const arg)
{
// At this point a single expression has been parsed and committed.
// It can be one of:
// - Standalone expression
// - Standalone expression with size suffix like ".l"
// - Prefix expression followed by (An), (PC), (An,Xn) or (PC,Xn)
if (pars_is_eof_reached(self)) {
// It was a standalone expression without size suffix, yield an
// argument from here
arg->type = ARG_ADDR_UNSPEC;
return OK;
}
struct token token0 = pars_peek(self);
if (token0.type == TT_DOT_ID) {
// It must be a size specifier, or error otherwise
const size_t size_spec_id = pars_commit(self);
if (token0.length != 2) {
return pars_yield_error(self, size_spec_id, E_ADDR_SIZE_SPEC);
}
const enum opsize addrsize =
get_opsize_from_specifier(self->lex->input[token0.offset + 1]);
if (addrsize == OPSIZE_NONE || addrsize == OPSIZE_S) {
return pars_yield_error(self, size_spec_id, E_ADDR_SIZE_SPEC);
}
arg->type = addrsize == OPSIZE_L ? ARG_ADDR_LONG : ARG_ADDR_WORD;
} else if (token0.type != TT_LPAREN) {
// It was a standalone expression without size suffix, yield an
// argument from here
arg->type = ARG_ADDR_UNSPEC;
return OK;
}
// Suffix must be read anyway
if (pars_peek(self).type == TT_LPAREN) {
// It is a prefix expression for (An), (PC), (An,Xn) or (PC,Xn)
pars_commit(self);
return pars_parse_arg_inside_parens(self, arg);
}
// It is a standalone expression with or without size suffix, yield an
// argument from here
return OK;
}
static int pars_parse_arg_starts_with_minus(
struct pars *const self, struct arg *const arg)
{
// At this point cur_tok_id points to the minus that has been peeked, but
// not committed.
const size_t first_token_id = self->cur_tok_id;
if (pars_is_eof_reached(self)) {
pars_commit(self); // The minus token
// Just single minus is invalid expression
return pars_yield_error_eof(self, "'(' or expression");
}
if (pars_peek_more(self, 1).type == TT_LPAREN) {
// It is still either expression or -(An)
if (pars_is_eof_reached(self)) {
// "-(" is invalid expression
pars_commit(self), pars_commit(self); // Commit "-" and "("
return pars_yield_error_eof(self, "An or expression");
}
const struct token token2 = pars_peek_more(self, 2);
if (token2.type == TT_ID) {
struct token_recognition r = pars_recognize_token(self, token2);
if (r.type == RTT_REG && r.reg == REG_AN) {
// It is definitely -(An). Commit all previous tokens and
// expect closing parenthesis.
self->cur_tok_id += 3;
const size_t rparen_id = pars_commit(self);
const struct token rparen = self->lex->tokbuf[rparen_id];
if (rparen.type == TT_RPAREN) {
// Perfect!
*arg = (struct arg){
.type = ARG_AN_ADDR_DECR,
.xn = r.reg_num,
.first_token = first_token_id,
.num_tokens = self->cur_tok_id - first_token_id,
};
return OK;
} else {
// But it has to be a closing parenthesis!
return pars_yield_error(self, rparen_id, "')'");
}
}
}
}
// Otherwise it is expression - either prefix or standalone
const int ret = pars_parse_expr(self, &arg->expr);
if (ret != OK) {
return ret;
}
return pars_parse_arg_after_prefix_expr(self, arg);
}
struct inside_parens_state {
bool an1_found, an2_found, dn_found, pc_found;
enum opsize size;
uint8_t an1, an2, dn;
};
static int pars_parse_arg_inside_parens_single_item(
struct pars *const self,
struct arg *const arg,
struct inside_parens_state *const state)
{
const struct token token0 = pars_peek(self);
if (token0.type == TT_ID) {
// It it may be An/Dn/PC register
struct token_recognition r = pars_recognize_token(self, token0);
if (r.type == RTT_REG) {
// This is definitely a register or regmask.
bool it_is_pc = false;
const size_t token0_id = pars_commit(self);
struct token_recognition r = pars_recognize_token(self, token0);
switch (r.reg) {
case REG_DN:
state->dn_found = true;
state->dn = r.reg_num;
const struct token token_size_spec = pars_peek(self);
if (token_size_spec.type == TT_DOT_ID) {
// It must be a size specifier, or error otherwise
const size_t size_spec_id = pars_commit(self);
if (token_size_spec.length != 2) {
return pars_yield_error(
self, size_spec_id, E_ADDR_INDIR_SIZE_SPEC);
}
const char c = self->lex->input[token_size_spec.offset + 1];
const enum opsize addrsize = get_opsize_from_specifier(c);
if (addrsize != OPSIZE_W && addrsize != OPSIZE_L) {
return pars_yield_error(
self, size_spec_id, E_ADDR_INDIR_SIZE_SPEC);
}
if (state->size != OPSIZE_NONE) {
return pars_yield_error_msg(
self,
size_spec_id,
E_ADDR_INDIR_MULTIPLE_INDEX_REGS);
}
state->size = addrsize;
}
break;
case REG_AN:
if (!state->an1_found) {
state->an1_found = true;
state->an1 = r.reg_num;
} else if (!state->an2_found) {
state->an2_found = true;
state->an2 = r.reg_num;
} else {
return pars_yield_error(
self, token0_id, E_EA_PART_NOT_AN);
}
break;
case REG_PC:
state->pc_found = true;
it_is_pc = true;
break;
case REG_NONE:
UNREACHABLE();
case REG_SR:
case REG_CCR:
case REG_USP:
return pars_yield_error(self, token0_id, E_EA_PART);
}
if (!it_is_pc) {
const struct token token_size_spec = pars_peek(self);
if (token_size_spec.type == TT_DOT_ID) {
// It must be a size specifier, or error otherwise
const size_t size_spec_id = pars_commit(self);
if (token_size_spec.length != 2) {
return pars_yield_error(
self, size_spec_id, E_ADDR_INDIR_SIZE_SPEC);
}
const char c = self->lex->input[token_size_spec.offset + 1];
const enum opsize addrsize = get_opsize_from_specifier(c);
if (addrsize != OPSIZE_W && addrsize != OPSIZE_L) {
return pars_yield_error(
self, size_spec_id, E_ADDR_INDIR_SIZE_SPEC);
}
if (state->size != OPSIZE_NONE) {
return pars_yield_error_msg(
self,
size_spec_id,
E_ADDR_INDIR_MULTIPLE_INDEX_REGS);
}
state->size = addrsize;
}
}
}
} else if (arg->expr.first_token == 0) {
const int ret = pars_parse_expr(self, &arg->expr);
if (ret != OK) {
return ret;
}
const struct token token_size_spec = pars_peek(self);
if (token_size_spec.type == TT_DOT_ID) {
// It must be a size specifier, or error otherwise
const size_t size_spec_id = pars_commit(self);
if (token_size_spec.length != 2) {
return pars_yield_error(self, size_spec_id, E_ADDR_SIZE_SPEC);
}
const char c = self->lex->input[token_size_spec.offset + 1];
const enum opsize addrsize = get_opsize_from_specifier(c);
if (addrsize == OPSIZE_NONE || addrsize == OPSIZE_S) {
return pars_yield_error(self, size_spec_id, E_ADDR_SIZE_SPEC);
}
// Just skip it, because it does not matter
}
} else {
return pars_yield_error(self, self->cur_tok_id, E_EA_PART_NOT_EXPR);
}
return OK;
}
static int pars_parse_arg_inside_parens(
struct pars *const self, struct arg *const arg)
{
// At this point cur_tok_id points after the first opening parenthesis that
// has been parsed (committed).
// It can be
// - (expr)(An)
// - (expr)(An,Xi) or (expr)(Xi,An)
// - (expr)(An,Xi.w) or (expr)(Xi.w,An)
// - (expr)(PC,Xi) or (expr)(Xi,PC)
// - (expr)(PC,Xi.w) or (expr)(Xi.w,PC)
// - (An) or (An)+
// - (An,expr) or (expr,An)
// - (PC,expr) or (expr,PC)
// - (An,expr,Xi) in any order (6 variants)
// - (An,expr,Xi.w) in any order (6 variants)
// - (PC,expr,Xi) in any order (6 variants)
// - (PC,expr,Xi.w) in any order (6 variants)
unsigned parts = arg->expr.first_token ? 1 : 0;
struct inside_parens_state state = {0};
while (parts < 3) {
if (pars_is_eof_reached(self)) {
return pars_yield_error_eof(self, E_EA_PART);
}
const int ret = pars_parse_arg_inside_parens_single_item(self, arg, &state);
if (ret != OK) {
return ret;
}
parts++;
if (pars_is_eof_reached(self)) {
return pars_yield_error_eof(self, E_EA_PART_DELIM);
}
const struct token delim = pars_peek(self);
const size_t delim_id = pars_commit(self);
if (delim.type == TT_COMMA) {
continue;
} else if (delim.type == TT_RPAREN) {
if (parts == 1 && arg->expr.first_token) {
assert(!state.an1_found && !state.an2_found && !state.dn_found && !state.pc_found);
// It turns out we are inside of expression, so this closing
// parenthesis is part of it. Let's accumulate it and move
// on.
arg->expr.first_token--;
arg->expr.num_tokens += 2;
return pars_parse_arg_after_prefix_expr(self, arg);
} else {
break;
}
} else {
return pars_yield_error(self, delim_id, E_EA_PART);
}
}
if (parts == 1 && state.an1_found) {
// It is either (An) or (An)+
assert(!state.pc_found && !state.dn_found && !arg->expr.first_token);
if (pars_is_eof_reached(self)) {
arg->type = ARG_AN_ADDR;
} else {
const struct token plus = pars_peek(self);
if (plus.type == TT_PLUS) {
pars_commit(self);
arg->type = ARG_AN_ADDR_INCR;
} else {
arg->type = ARG_AN_ADDR;
}
}
arg->xn = state.an1;
arg->num_tokens = self->cur_tok_id - arg->first_token;
return OK;
} else if (parts == 2 && state.an1_found && arg->expr.first_token) {
// It is (An,d16) or (d16,An)
assert(!state.an2_found && !state.pc_found && !state.dn_found);
arg->type = ARG_AN_ADDR_16;
arg->xn = state.an1;
arg->num_tokens = self->cur_tok_id - arg->first_token;
return OK;
} else if (parts == 2 && state.pc_found && arg->expr.first_token) {
// It is (PC,d16) or (d16,PC)
assert(!state.an1_found && !state.an2_found && !state.dn_found);
arg->type = ARG_PC_ADDR_16;
arg->num_tokens = self->cur_tok_id - arg->first_token;
return OK;
} else if (parts == 3 && state.pc_found && arg->expr.first_token && (state.an1_found || state.dn_found)) {
// It is (d8,PC,Xn)
assert((state.an1_found && !state.dn_found) || (!state.an1_found && state.dn_found));
arg->type = ARG_PC_ADDR_8_XI;
arg->xi = state.an1_found ? (state.an1 | 0x8) : state.dn;
arg->num_tokens = self->cur_tok_id - arg->first_token;
arg->briefext_size = state.size;
return OK;
} else if (parts == 3 && state.an1_found && arg->expr.first_token && (state.an2_found || state.dn_found)) {
// It is (d8,An,Xn)
assert((state.an2_found && !state.dn_found) || (!state.an2_found && state.dn_found));
arg->type = ARG_AN_ADDR_8_XI;
arg->xi = state.an2_found ? (state.an2 | 0x8) : state.dn;
arg->num_tokens = self->cur_tok_id - arg->first_token;
arg->briefext_size = state.size;
return OK;
}
return pars_yield_error_msg(self, self->cur_tok_id, E_EA_INVALID);
}
static int pars_parse_arg_regmask(
struct pars *const self, struct arg *const arg)
{
// At this point cur_tok_id points to the register token that has been
// peeked, but not committed.
bool range = false, delimiter = true, range_an = false;
uint16_t regmask = 0;
bool reg_found = false;
uint8_t reg = 0;
while (1) {
if (pars_is_eof_reached(self)) {
if (range) {
return pars_yield_error_eof(self, range_an ? E_AN : E_DN);
}
return OK;
}
const struct token token = pars_peek(self);
if (token.type == TT_ID) {
struct token_recognition r = pars_recognize_token(self, token);
if (r.type == RTT_REG) {
if (r.reg == REG_AN) {
if (range) {
assert(reg_found);
if (!range_an) {
return pars_yield_error(
self, self->cur_tok_id, E_AN);
}
if (r.reg_num < reg) {
return pars_yield_error_msg(
self, self->cur_tok_id, E_REGMASK_ASCEND);
}
range = false;
for (int i = reg; i <= r.reg_num; i++) {
regmask |= 1 << (i + 8);
}
reg_found = false;
} else if (delimiter) {
delimiter = false;
reg_found = true;
reg = r.reg_num;
range_an = true;
} else {
return pars_yield_error(
self, self->cur_tok_id, E_REGMASK_DELIM);
}
} else if (r.reg == REG_DN) {
if (range) {
assert(reg_found);
if (range_an) {
return pars_yield_error(
self, self->cur_tok_id, E_DN);
}
if (r.reg_num < reg) {
return pars_yield_error_msg(
self, self->cur_tok_id, E_REGMASK_ASCEND);
}
range = false;
for (int i = reg; i <= r.reg_num; i++) {
regmask |= 1 << i;
}
reg_found = false;
} else if (delimiter) {
delimiter = false;
reg_found = true;
reg = r.reg_num;
range_an = false;
} else {
return pars_yield_error(
self, self->cur_tok_id, E_REGMASK_DELIM);
}
} else {
return pars_yield_error(
self, self->cur_tok_id,
(range || delimiter) ? E_AN_DN : E_REGMASK_DELIM);
}
} else {
return pars_yield_error(
self, self->cur_tok_id,
(range || delimiter) ? E_AN_DN : E_REGMASK_DELIM);
}
} else if (token.type == TT_SLASH) {
if (range || delimiter) {
return pars_yield_error(self, self->cur_tok_id, E_AN_DN);
}
if (reg_found) {
reg_found = false;
regmask |= 1 << (reg + (range_an ? 8 : 0));
}
delimiter = true;
} else if (token.type == TT_MINUS) {
if (range || delimiter) {
return pars_yield_error(self, self->cur_tok_id, E_AN_DN);
}
range = true;
} else if (regmask) {
// Do not commit here because it is not ours token
if (reg_found) {
reg_found = false;
regmask |= 1 << (reg + (range_an ? 8 : 0));
}
arg->type = ARG_REGMASK;
arg->regmask = regmask;
return OK;
} else {
return pars_yield_error(
self, self->cur_tok_id,
(range || delimiter) ? E_AN_DN : E_REGMASK_DELIM);
}
pars_commit(self);
}
UNREACHABLE();
return pars_yield_error_msg(self, ++self->cur_tok_id, E_UNREACH);
}
static int pars_parse_arg(
struct pars *const self, struct arg *const arg)
{
if (pars_is_eof_reached(self)) {
return OK;
}
const size_t first_token_id = self->cur_tok_id;
arg->first_token = first_token_id;
const struct token token0 = pars_peek(self);
if (token0.type == TT_HASH) {
// Definitely an immediate value expression
pars_commit(self);
const int ret = pars_parse_expr(self, &arg->expr);
if (ret != OK) {
return ret;
}
arg->type = ARG_IMMEDIATE;
arg->num_tokens = self->cur_tok_id - first_token_id;
return OK;
} else if (token0.type == TT_MINUS) {
// It is either expression or -(An)
return pars_parse_arg_starts_with_minus(self, arg);
} else if (token0.type == TT_TILDE || token_is_number(token0.type)) {
// Tilde is unary operation, so it must be an expression
const int ret = pars_parse_expr(self, &arg->expr);
if (ret != OK) {
return ret;
}
return pars_parse_arg_after_prefix_expr(self, arg);
} else if (token0.type == TT_LPAREN) {
// It is either expression or addressing mode (An) / (An)+ / (d16,An) /
// (d8,An,Xn) / (d8,PC,Xn) / (d16,An)
pars_commit(self);
return pars_parse_arg_inside_parens(self, arg);
} else if (token0.type == TT_ID) {
// It is either expression, regmask or just An/Dn/PC/SR/SP/CCR register
struct token_recognition r = pars_recognize_token(self, token0);
if (r.type == RTT_REG) {
// This is definitely a register or regmask.
switch (r.reg) {
case REG_NONE:
UNREACHABLE();
return pars_yield_error_msg(self, first_token_id, E_UNREACH);
case REG_DN:
if (token_is_regmask_delimiter(pars_peek_more(self, 1).type)) {
// Note: the register is not committed
return pars_parse_arg_regmask(self, arg);
}
arg->type = ARG_DN;
arg->xn = r.reg_num;
break;
case REG_AN:
if (token_is_regmask_delimiter(pars_peek_more(self, 1).type)) {
// Note: the register is not committed
return pars_parse_arg_regmask(self, arg);
}
arg->type = ARG_AN;
arg->xn = r.reg_num;
break;
case REG_PC:
return pars_yield_error(self, first_token_id, E_AN_DN);
case REG_SR:
arg->type = ARG_SR;
break;
case REG_CCR:
arg->type = ARG_CCR;
break;
case REG_USP:
arg->type = ARG_USP;
break;
}
pars_commit(self);
arg->num_tokens = self->cur_tok_id - first_token_id;
return OK;
} else {
const int ret = pars_parse_expr(self, &arg->expr);
if (ret != OK) {
return ret;
}
return pars_parse_arg_after_prefix_expr(self, arg);
}
}
return OK;
}
static int pars_yield_instruction(
struct pars *const self,
const size_t label_id,
const size_t comment_id,
const size_t mnemonic_id,
const enum opsize opsize,
const struct arg *const arg1,
const struct arg *const arg2)
{
const struct token mnemonic_token = self->lex->tokbuf[mnemonic_id];
const enum mnemonic mnemonic = get_mnemonic_from_identifier(
self->lex->input + mnemonic_token.offset, mnemonic_token.length);
if (mnemonic == MN_NONE) {
return pars_yield_error(self, mnemonic_id, E_MNEMONIC);
}
if (arg2->type != ARG_NONE) {
assert(arg1->type != ARG_NONE);
}
if (arg1->type == ARG_NONE) {
assert(arg1->type == ARG_NONE);
}
const enum args_count args_count = get_args_count_for_mnemonic(mnemonic);
// Validate instruction arguments count
switch (args_count) {
case ARGS_COUNT_UNKNOWN:
UNREACHABLE();
break;
case ARGS_COUNT_0:
if (arg1->type != ARG_NONE) {
return pars_yield_error_msg(self, arg1->first_token, E_ARGS_COUNT);
}
break;
case ARGS_COUNT_1:
if (arg1->type == ARG_NONE) {
return pars_yield_error_msg(self, mnemonic_id, E_ARGS_COUNT);
} else if (arg2->type != ARG_NONE) {
return pars_yield_error_msg(self, arg2->first_token, E_ARGS_COUNT);
}
break;
case ARGS_COUNT_1_2:
if (arg1->type == ARG_NONE) {
return pars_yield_error_msg(self, mnemonic_id, E_ARGS_COUNT);
}
break;
case ARGS_COUNT_2:
if (arg1->type == ARG_NONE || arg2->type == ARG_NONE) {
return pars_yield_error_msg(self, mnemonic_id, E_ARGS_COUNT);
}
break;
}
const size_t first_token_id = label_id ? label_id : mnemonic_id;
const struct stmt stmt = {
.type = ST_INSTRUCTION,
.instruction = {
.mnemonic = mnemonic,
.opsize = opsize,
.arg1 = arg1 ? *arg1 : (struct arg){0},
.arg2 = arg2 ? *arg2 : (struct arg){0},
},
.label_token = label_id,
.comment_token = comment_id,
.first_token = first_token_id,
.num_tokens = self->cur_tok_id - first_token_id,
};
fwrite_stmt(&stmt, self->stmttab_stream);
return OK;
}
static int pars_parse_instruction_args(
struct pars *const self,
const size_t label_id,
const size_t mnemonic_id,
const enum opsize opsize)
{
struct arg arg1 = {0}, arg2 = {0};
// Try parse first argument
const int res1 = pars_parse_arg(self, &arg1);
if (res1 != OK) {
return res1;
}
if (arg1.type != ARG_NONE) {
if (!pars_is_eof_reached(self)) {
const struct token token = pars_peek(self);
if (token.type == TT_COMMA) {
pars_commit(self);
// Try parse second argument
if (pars_is_eof_reached(self)) {
return pars_yield_error_eof(self, E_ARG);
}
if (pars_peek(self).type == TT_NEWLINE) {
return pars_yield_error(self, self->cur_tok_id, E_ARG);
}
const int res2 = pars_parse_arg(self, &arg2);
if (res2 != OK) {
return res2;
}
} else if (token.type != TT_COMMENT_SEMICOLON && token.type != TT_NEWLINE) {
return pars_yield_error(self, self->cur_tok_id, E_INSTR_END);
}
}
}
// Finish parsing instruction, expect comment or newline
size_t comment_id = 0;
const int ret = pars_parse_comment_and_newline(self, &comment_id);
if (ret != OK) {
return ret;
}
return pars_yield_instruction(
self, label_id, comment_id, mnemonic_id, opsize, &arg1, &arg2);
}
static int pars_parse_instruction(
struct pars *const self,
const size_t label_id,
const size_t mnemonic_id)
{
if (pars_is_eof_reached(self)) {
return pars_yield_error_eof(self, E_MNEMONIC);
}
const struct token size_spec = pars_peek(self);
if (size_spec.type == TT_DOT_ID) {
const size_t size_spec_id = pars_commit(self);
// Size specifier
if (size_spec.length != 2) {
return pars_yield_error(self, size_spec_id, E_INSN_SIZE_SPEC);
}
const enum opsize opsize =
get_opsize_from_specifier(self->lex->input[size_spec.offset + 1]);
if (opsize == OPSIZE_NONE) {
return pars_yield_error(self, size_spec_id, E_INSN_SIZE_SPEC);
}
return pars_parse_instruction_args(self, label_id, mnemonic_id, opsize);
}
return pars_parse_instruction_args(
self, label_id, mnemonic_id, OPSIZE_NONE);
}
static int pars_parse_assignment(
struct pars *const self, const size_t label_id, const size_t symbol_id)
{
// TODO
(void) label_id;
(void) symbol_id;
return pars_yield_error_msg(self, self->cur_tok_id, E_NIMPL);
}
static int pars_yield_label_comment(
struct pars *const self, const size_t label_id, const size_t comment_id)
{
if (label_id || comment_id) {
const size_t first_token = label_id ? label_id : comment_id;
struct stmt stmt = {
.type = label_id ? ST_LABEL : ST_COMMENT,
.label_token = label_id,
.comment_token = comment_id,
.first_token = first_token,
.num_tokens = self->cur_tok_id - first_token,
};
fwrite_stmt(&stmt, self->stmttab_stream);
}
return OK;
}
static int pars_parse_labeled_statement(
struct pars *const self, const size_t label_id)
{
const struct token token1 = pars_peek(self);
const bool is_comment = token1.type == TT_COMMENT_ASTERISK ||
token1.type == TT_COMMENT_SEMICOLON;
if (is_comment) {
return pars_yield_label_comment(self, label_id, pars_commit(self));
} else if (token1.type == TT_NEWLINE) {
pars_commit(self);
return pars_yield_label_comment(self, label_id, 0);
} else if (token1.type == TT_ID) {
const size_t token1_id = pars_commit(self);
if (pars_is_eof_reached(self)) {
return pars_yield_error_eof(self, E_LABELED_STMT);
}
const struct token token2 = pars_peek(self);
if (!label_id && token2.type == TT_COLON) {
pars_commit(self);
return pars_parse_labeled_statement(self, token1_id);
} else if (token2.type == TT_EQ || token2.type == TT_EQ_DOUBLE) {
pars_commit(self);
return pars_parse_assignment(self, label_id, token1_id);
}
return pars_parse_instruction(self, label_id, token1_id);
} else if (token1.type == TT_DOT_ID) {
return pars_parse_direc(self, label_id);
}
return pars_yield_error(self, self->cur_tok_id, E_STMT_BEGIN);
}
static int pars_parse_statement(struct pars *const self)
{
return pars_parse_labeled_statement(self, 0);
}
/** Run parser until the end of the input reached
* \returns OK if parsing finished successfully
* \returns ERR if error encountered and parsing cannot continue.
*/
static int pars_run(struct pars *const self)
{
// Skip dummy token at position 0
self->cur_tok_id = 1;
// Leave dummy statement at position 0
fwrite_stmt(&(struct stmt){0}, self->stmttab_stream);
int ret = OK;
while (self->cur_tok_id < self->lex->tokens_count) {
ret = pars_parse_statement(self);
if (ret != OK) {
// Don't really care about parsing errors right now
ret = OK;
}
}
fflush(self->stmttab_stream);
fflush(self->symtab_stream);
fflush(self->symbuf_stream);
return ret;
}
static void pars_destroy(struct pars *const self)
{
fclose(self->stmttab_stream);
free(self->stmttab);
fclose(self->symtab_stream);
free(self->symtab);
fclose(self->symbuf_stream);
free(self->symbuf);
}
static bool is_bcc(const enum mnemonic mnemonic)
{
switch (mnemonic) {
case MN_BRA:
case MN_BSR:
case MN_BCC:
case MN_BCS:
case MN_BEQ:
case MN_BGE:
case MN_BGT:
case MN_BHI:
case MN_BLE:
case MN_BLS:
case MN_BLT:
case MN_BMI:
case MN_BNE:
case MN_BPL:
case MN_BVC:
case MN_BVS:
return true;
default:
break;
}
return false;
}
static int assem_init(struct assem *const self, const struct pars *const pars)
{
*self = (struct assem){
.pars = pars,
};
return OK;
}
static int assem_resolve(struct assem *const self)
{
(void) self;
return OK;
}
static void emit_token_id(
const struct lex *const lex,
const struct token *const token,
FILE *const s)
{
assert(token->type == TT_ID);
if (lex->input[token->offset] == '_') {
// Strip leading underscore
// FIXME It should be sort of an option that may be disabled.
fprintf(s, "%.*s", (int)token->length - 1, lex->input + token->offset + 1);
} else if (lex->input[token->offset] == 'L') {
// Add leading dot to all local symbols (they start with 'L').
// FIXME It should be sort of an option that may be disabled.
fprintf(s, ".%.*s", (int)token->length, lex->input + token->offset);
} else {
fprintf(s, "%.*s", (int)token->length, lex->input + token->offset);
}
}
static void emit_expr(
const struct lex *const lex,
const struct expr_tokens_span *const expr,
FILE *const s)
{
for (size_t i = 0; i < expr->num_tokens; i++) {
const struct token token = lex->tokbuf[expr->first_token + i];
if (token.type == TT_NEWLINE) {
break;
} else if (token.type == TT_ID) {
emit_token_id(lex, &token, s);
} else {
fprintf(s, "%.*s", (int)token.length, lex->input + token.offset);
}
}
}
static void emit_arg(
const struct lex *const lex,
const struct arg *const arg,
FILE *const s)
{
switch (arg->type) {
case ARG_DN:
fprintf(s, "%%d%d", arg->xn);
break;
case ARG_AN:
fprintf(s, "%%a%d", arg->xn);
break;
case ARG_AN_ADDR:
fprintf(s, "%%a%d@", arg->xn);
break;
case ARG_AN_ADDR_INCR:
fprintf(s, "%%a%d@+", arg->xn);
break;
case ARG_AN_ADDR_DECR:
fprintf(s, "%%a%d@-", arg->xn);
break;
case ARG_AN_ADDR_16:
fprintf(s, "%%a%d@(", arg->xn);
emit_expr(lex, &arg->expr, s);
fprintf(s, ")");
break;
case ARG_AN_ADDR_8_XI:
fprintf(s, "%%a%d@(", arg->xn);
emit_expr(lex, &arg->expr, s);
{
const char reg_type = arg->xi & 0x8 ? 'a' : 'd';
const char size = arg->briefext_size == OPSIZE_L ? 'l' : 'w';
fprintf(s, ",%%%c%d:%c)", reg_type, arg->xi & 0x7, size);
}
break;
case ARG_ADDR_WORD:
emit_expr(lex, &arg->expr, s), fprintf(s, ".w");
break;
case ARG_ADDR_LONG:
emit_expr(lex, &arg->expr, s), fprintf(s, ".l");
break;
case ARG_ADDR_UNSPEC:
emit_expr(lex, &arg->expr, s);
break;
case ARG_PC_ADDR_16:
fprintf(s, "%%pc@(");
emit_expr(lex, &arg->expr, s);
fprintf(s, ")");
break;
case ARG_PC_ADDR_8_XI:
fprintf(s, "%%pc@(");
emit_expr(lex, &arg->expr, s);
{
const char reg_type = arg->xi & 0x8 ? 'a' : 'd';
const char size = arg->briefext_size == OPSIZE_L ? 'l' : 'w';
fprintf(s, ",%%%c%d:%c)", reg_type, arg->xi & 0x7, size);
}
break;
case ARG_IMMEDIATE:
fprintf(s, "#"), emit_expr(lex, &arg->expr, s);
break;
case ARG_REGMASK:
{
// TODO make it concise
bool leading_space = false;
for (unsigned i = 0; i < 8; i++) {
if (arg->regmask & (1 << i)) {
fprintf(s, "%s%%d%d", leading_space ? "/" : "", i);
leading_space = true;
}
}
for (unsigned i = 0; i < 8; i++) {
if (arg->regmask & (1 << (i + 8))) {
fprintf(s, "%s%%a%d", leading_space ? "/" : "", i);
leading_space = true;
}
}
}
break;
case ARG_SR:
fprintf(s, "%%sr");
break;
case ARG_CCR:
fprintf(s, "%%ccr");
break;
case ARG_USP:
fprintf(s, "%%usp");
break;
case ARG_NONE:
break;
}
}
static void emit_directive_same(
const struct lex *const lex,
const struct directive *const dir,
FILE *const s)
{
const struct token name_token = lex->tokbuf[dir->name_token];
fprintf(s, "\t%.*s", (int)name_token.length, lex->input + name_token.offset);
if (dir->num_tokens) {
fprintf(s, "\t");
}
for (size_t i = 0; i < dir->num_tokens; i++) {
const struct token token = lex->tokbuf[dir->first_token + i];
if (token.type == TT_ID) {
emit_token_id(lex, &token, s);
} else {
fprintf(s, "%.*s ", (int)token.length, lex->input + token.offset);
}
}
}
static void emit_directive_byte(
const struct lex *const lex,
const struct directive *const dir,
FILE *const s)
{
if (dir->num_tokens < 1) {
// We won't emit this because it is invalid
return;
}
if (lex->tokbuf[dir->first_token].type == TT_STRING) {
fprintf(s, "\t.ascii\t");
} else {
fprintf(s, "\t.byte\t");
}
for (size_t i = 0; i < dir->num_tokens; i++) {
const struct token token = lex->tokbuf[dir->first_token + i];
fprintf(s, "%.*s ", (int)token.length, lex->input + token.offset);
}
}
static enum opsize assem_resolve_bcc(
struct assem *const self,
const size_t stmt_number)
{
const struct pars *const pars = self->pars;
(void) pars;
(void) stmt_number;
// TODO impl real resolving
return OPSIZE_S;
}
static int assem_emit(struct assem *const self, FILE *const stream)
{
const struct lex *const lex = self->pars->lex;
const struct pars *const pars = self->pars;
if (TRACE_LEXER) {
for (size_t i = 1; i < lex->tokbuf_size / (sizeof *lex->tokbuf); i++) {
fprint_token_debug(lex->input, &lex->tokbuf[i], stream);
}
}
if (TRACE_PARSER) {
for (size_t i = 1; i < pars->stmttab_size / (sizeof *pars->stmttab); i++) {
fprint_stmt_debug(lex, pars->stmttab + i, stream);
}
}
for (size_t i = 1; i < pars->stmttab_size / (sizeof *pars->stmttab); i++) {
const struct stmt *stmt = pars->stmttab + i;
if (stmt->label_token) {
const struct token token = lex->tokbuf[stmt->label_token];
if (token.type == TT_ID) {
emit_token_id(lex, &token, stream);
fprintf(stream, ":");
} else {
fprintf(stream, "%.*s:", (int)token.length, lex->input + token.offset);
}
}
if (stmt->type == ST_INSTRUCTION) {
const struct instruction instr = stmt->instruction;
fprintf(stream, "\t%s", mnemonic_to_string(instr.mnemonic));
if (instr.opsize != OPSIZE_NONE) {
fprintf(stream, ".%c", opsize_to_char(instr.opsize));
} else if (is_bcc(instr.mnemonic)) {
enum opsize opsize = assem_resolve_bcc(self, i);
fprintf(stream, ".%c", opsize_to_char(opsize));
}
if (instr.arg1.type != ARG_NONE) {
fprintf(stream, " ");
emit_arg(lex, &instr.arg1, stream);
if (instr.arg2.type != ARG_NONE) {
fprintf(stream, ", ");
emit_arg(lex, &instr.arg2, stream);
}
}
} else if (stmt->type == ST_DIRECTIVE) {
const struct directive *dir = &stmt->directive;
switch (dir->type) {
case DT_ALIGN:
case DT_FILE:
case DT_GLOBL:
case DT_TEXT:
emit_directive_same(lex, dir, stream);
break;
case DT_ASCII:
case DT_BYTE:
emit_directive_byte(lex, dir, stream);
break;
default:
break;
}
}
if (stmt->comment_token) {
const struct token token = lex->tokbuf[stmt->comment_token];
fprintf(stream, " %.*s", (int)token.length, lex->input + token.offset);
}
fprintf(stream, "\n");
}
return OK;
}
static void assem_destroy(struct assem *const self)
{
(void) self;
}
int main(const int argc, char *const argv[])
{
// No fucks given about arguments for now
(void)argc;
(void)argv;
struct lex lex;
struct pars pars;
if (OK != lex_init(&lex)) {
return EXIT_FAILURE;
}
// Tokenize assembly program text
if (OK != lex_run(&lex, stdin)) {
lex_destroy(&lex);
return EXIT_FAILURE;
}
// Parser needs final lexer state to access parsed tokens and input data
if (OK != pars_init(&pars, &lex)) {
lex_destroy(&lex);
return EXIT_FAILURE;
}
// Parse assembly program text
if (OK != pars_run(&pars)) {
pars_destroy(&pars);
lex_destroy(&lex);
return EXIT_FAILURE;
}
struct assem assem;
// Allocate and populate code table and metadata table from parsed data.
// Assembler needs parser's and lexer's final state to access parsed
// structure, tokens and input.
if (OK != assem_init(&assem, &pars)) {
pars_destroy(&pars);
lex_destroy(&lex);
return EXIT_FAILURE;
}
// Resolve all ambiguities
if (OK != assem_resolve(&assem)) {
assem_destroy(&assem);
pars_destroy(&pars);
lex_destroy(&lex);
return EXIT_FAILURE;
}
// Emit unambiguous assembly language program text for specified dialect
// (currently m68k GNU AS only is supported)
if (OK != assem_emit(&assem, stdout)) {
assem_destroy(&assem);
pars_destroy(&pars);
lex_destroy(&lex);
return EXIT_FAILURE;
}
assem_destroy(&assem);
pars_destroy(&pars);
lex_destroy(&lex);
}
|