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
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
|
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include <strings.h>
// Vector utils
#define VECT_MAX_GROW 100
#define VECT_MIN_SIZE 4
typedef struct {
size_t _el_sz, count, size;
void *data;
} Vector;
Vector vect_init(size_t item_size) {
Vector out = {0};
out._el_sz = item_size;
out.size = VECT_MIN_SIZE;
out.count = 0;
out.data = malloc(out.size * out._el_sz);
return out;
}
void _vect_grow(Vector *v) {
v->size += VECT_MAX_GROW;
v->data = realloc(v->data, v->size * v->_el_sz);
}
void _vect_shrink(Vector *v) {
if (v->size / 2 > VECT_MIN_SIZE) {
v->size = v->size / 2;
v->data = realloc(v->data, v->size * v->_el_sz);
}
}
bool vect_remove(Vector *v, size_t index) {
if (index >= v->count) {
return false;
}
char *remove = v->data + (index * v->_el_sz);
char *override = v->data + (index + 1) * v->_el_sz;
for(size_t i = 0; i < (v->count - index - 1) * v->_el_sz; i++) {
remove[i] = override[i];
}
v->count -= 1;
if (v->count < v->size / 4) {
_vect_shrink(v);
}
return true;
}
void vect_pop(Vector *v) {
vect_remove(v, v->count - 1);
}
bool vect_insert(Vector *v, size_t index, void *el) {
if (index > v->count) {
return false;
}
char *new_spot = v->data + (v->count + 1) * v->_el_sz;
char *old_spot = v->data + v->count * v->_el_sz;
for (size_t i = 0; i < (v->count - index) * v->_el_sz; i++) {
*new_spot = *old_spot;
new_spot--;
old_spot--;
}
for (size_t i = 0; i < v->_el_sz; i++) {
old_spot[i] = ((char *)el)[i];
}
v->count += 1;
if (v->count == v->size - 1) {
_vect_grow(v);
}
return true;
}
void vect_push(Vector *v, void *el) {
vect_insert(v, v->count, el);
}
void vect_push_string(Vector *v, char *str) {
if (v->_el_sz != sizeof(char)) {
return;
}
for (size_t i = 0; str[i] != 0; i++) {
vect_insert(v, v->count, str + i);
}
}
void vect_push_free_string(Vector *v, char *str) {
vect_push_string(v, str);
free(str);
}
void *vect_get(Vector *v, size_t index) {
if (index >= v->count) {
return NULL;
}
return v->data + (v->_el_sz * index);
}
Vector vect_clone(Vector *v) {
Vector out = {0};
out._el_sz = v->_el_sz;
out.count = 0;
out.size = v->count + 1;
out.data = malloc((out.count + 1) * out._el_sz);
char *former = v->data;
char *latter = out.data;
for(size_t i = 0; i < out.count * out._el_sz; i++) {
latter[i] = former[i];
}
return out;
}
Vector vect_from_string(char *s) {
Vector out = vect_init(1);
size_t i = 0;
while(s[i] != 0) {
vect_push(&out, s + i++);
}
return out;
}
// Returns the vector data as a null-terminated string
// do NOT free this pointer unless you discard the vector.
// Not safe to use this string at the same time as you are
// adding or removing from the vector. Consider cloning the
// vector if you must have both, or want an independant copy
// of the string.
char *vect_as_string(Vector *v) {
((char*)v->data)[v->count] = 0;
return v->data;
}
void vect_end(Vector *v) {
v->_el_sz = 0;
v->count = 0;
v->size = 0;
free(v->data);
v->data = NULL;
}
// Artifacts (vect of strings)
typedef Vector Artifact;
/* Splits the string via the given character, and
* stores the split strings in an artifact
*/
Artifact art_from_str(const char *str, char split) {
Artifact out = vect_init(sizeof(char *));
char *cur = malloc(1);
cur[0] = 0;
int cur_len = 0;
for (int i = 0; str[i] != 0; i++) {
if (str[i] == split) {
cur[cur_len] = 0;
vect_push(&out, &cur);
cur = malloc(1);
cur_len = 0;
} else {
cur_len += 1;
cur = realloc(cur, cur_len + 1);
cur[cur_len - 1] = str[i];
}
}
if (cur_len > 0) {
cur[cur_len] = 0;
vect_push(&out, &cur);
} else {
free(cur);
}
return out;
}
// Joins the string together with the provided character in between
// must free the returned data after use.
char *art_to_str(Artifact *art, char join) {
char *out = malloc(1);
int out_len = 0;
for (size_t i = 0; i < art->count; i++) {
char ** cpy = vect_get(art, i);
for(int j = 0; (*cpy)[j] != 0; j++) {
out[out_len] = (*cpy)[j];
out_len += 1;
out = realloc(out, out_len + 1);
}
if (i < art->count - 1) {
out[out_len] = join;
out_len += 1;
out = realloc(out, out_len + 1);
}
}
out[out_len] = 0;
return out;
}
// Pops a string off the end of the artifact,
// freeing the data associated
void art_pop_str(Artifact *art) {
if (art->count == 0)
return;
char ** to_free = vect_get(art, art->count - 1);
free(*to_free);
vect_pop(art);
}
// Copies a string onto the artifact,
// you must free the original string
// manually if it was malloc-ed
void art_add_str(Artifact *art, char *str) {
Vector copy = vect_from_string(str);
char * copy_ptr = vect_as_string(©);
vect_push(art, ©_ptr);
}
// a = a + b
void art_add_art(Artifact *a, Artifact *b) {
for(size_t i = 0; i < b->count; i++) {
art_add_str(a, *(char **)vect_get(b, i));
}
}
// Weather the string str is contained in the artifact
bool art_contains(Artifact *a, char *str) {
for (size_t i = 0; i < a->count; i++) {
char **cur = vect_get(a, i);
if (strcmp(str, *cur) == 0)
return true;
}
return false;
}
// Frees all strings in the artifact,
// then calls vect_end
void art_end(Artifact *art) {
char **to_free = art->data;
for(size_t i = 0; i < art->count; i++) {
free(to_free[i]);
}
vect_end(art);
}
// Compile Data - CompData holds final program as it is assembled
typedef struct {
Vector header, data, text;
} CompData;
CompData cdat_init() {
CompData out = {0};
out.header = vect_from_string("");
out.data = vect_from_string("");
out.text = vect_from_string("");
return out;
}
void cdat_add(CompData *a, CompData *b) {
vect_push_string(&a->header, vect_as_string(&b->header));
vect_push_string(&a->data, vect_as_string(&b->data));
vect_push_string(&a->text, vect_as_string(&b->text));
}
void cdat_write_to_file(CompData *cdat, FILE *fout) {
fprintf(fout, "bits 64\n");
fprintf(fout, "\n%s\n", vect_as_string(&(cdat->header)));
fprintf(fout, "section .data\n%s\n", vect_as_string(&(cdat->data)));
fprintf(fout, "section .text\n%s\n", vect_as_string(&(cdat->text)));
fflush(fout);
}
void cdat_end(CompData *cdat) {
vect_end(&(cdat->header));
vect_end(&(cdat->data));
vect_end(&(cdat->text));
}
// Gen utils
char *int_to_str(int i) {
Vector v = vect_init(sizeof(char));
char to_push = '0';
bool minus = false;
// check negative
if(i < 0) {
i = -i;
minus = true;
}
// zero case
if(i == 0) {
vect_push(&v, &to_push);
}
// get all digits (in reverse order)
while(i > 0) {
to_push = '0' + i % 10;
i = i / 10;
vect_push(&v, &to_push);
}
// handle negative
if(minus) {
to_push = '-';
vect_push(&v, &to_push);
}
// reverse string
for(size_t idx = 0; idx < v.count / 2; idx++) {
to_push = *(char*)vect_get(&v, idx);
((char*)v.data)[idx] = ((char*)v.data)[v.count - (idx + 1)];
((char*)v.data)[v.count - (idx + 1)] = to_push;
}
//push 0
to_push = 0;
vect_push(&v, &to_push);
return v.data;
}
// Types
typedef struct Module {
char *name;
bool exported;
Vector types, vars, funcs, submods;
struct Module *parent;
} Module;
typedef struct {
char *name; // Name of the type
int size; // Size (bytes) of the type
Vector members; // Member variables (Stored as variables)
Module *module; // Module (for methods and member-type resolution) to tie the type to.
} Type;
typedef struct {
char *name;
Type *type;
Vector ptr_chain;
int location; // negative one for on stack, negative two for literal, zero for in data section, positive for in register
int offset; // offset for member variables (if this is a literal, it represents the actual value)
Module *mod; // Only used in the case of a data section variable;
} Variable;
#define LOC_LITL -2
#define LOC_STCK -1
#define LOC_DATA 0
#define PTYPE_NONE -2
#define PTYPE_PTR -1
#define PTYPE_REF 0
#define PTYPE_ARR 1
typedef struct {
char *name;
Vector inputs, outputs;
Module *module;
} Function;
typedef struct Scope {
char *name;
Module *current;
Vector stack_vars, reg_vars;
struct Scope *parent;
int next_const;
int next_bool;
} Scope;
// Copies the name, does not copy the module.
// Types should be freed at the end of the second pass,
// as they are shared among all variable structs
Type typ_init(char *name, Module *module) {
Type out = {0};
Vector name_cpy = vect_from_string(name);
out.name = vect_as_string(&name_cpy);
out.members = vect_init(sizeof(Variable));
out.module = module;
out.size = 0;
return out;
}
void var_end(Variable *v);
// Deep end, will free all memory associated with the
// struct, including name and sub-member variables
void typ_end(Type *t) {
free(t->name);
t->module = NULL;
for (size_t i = 0; i < t->members.count; i++) {
Variable *to_end = vect_get(&(t->members), i);
var_end(to_end);
}
vect_end(&(t->members));
}
Type TYP_INBUILT[] = {
{"uint8", 1, {0}, NULL},
{"uint16", 2, {0}, NULL},
{"uint32", 4, {0}, NULL},
{"uint64", 8, {0}, NULL},
{"uint", 8, {0}, NULL}, // Platform max uint
{"int8", 1, {0}, NULL},
{"int16", 2, {0}, NULL},
{"int32", 4, {0}, NULL},
{"int64", 8, {0}, NULL},
{"int", 8, {0}, NULL}, // Platform max int
{"float32", 4, {0}, NULL},
{"float64", 8, {0}, NULL},
{"float", 8, {0}, NULL}, // Platform max float
{"bool", 1, {0}, NULL},
{"void", 8, {0}, NULL}, // Untyped pointer
};
Type *typ_get_inbuilt(char *name) {
for (size_t i = 0; i < sizeof(TYP_INBUILT)/sizeof(Type); i++) {
if (strcmp(TYP_INBUILT[i].name, name) == 0) {
return &(TYP_INBUILT[i]);
}
}
return NULL;
}
bool is_inbuilt(char *name) {
for (size_t i = 0; i < sizeof(TYP_INBUILT)/sizeof(Type); i++) {
if (strcmp(TYP_INBUILT[i].name, name) == 0) {
return true;
}
}
return false;
}
// SCOPE FUNCTIONS
Scope scope_init(char *name, Module *mod) {
Scope out = {0};
Vector cpy = vect_from_string(name);
out.name = vect_as_string(&cpy);
out.stack_vars = vect_init(sizeof(Variable));
out.reg_vars = vect_init(sizeof(Variable));
out.current = mod;
out.next_const = 0;
out.next_bool = 0;
return out;
}
void scope_end(Scope *s) {
free(s->name);
for(size_t i = 0; i < s->stack_vars.count; i++) {
Variable *v = vect_get(&s->stack_vars, i);
var_end(v);
}
vect_end(&s->stack_vars);
for(size_t i = 0; i < s->reg_vars.count; i++) {
Variable *v = vect_get(&s->reg_vars, i);
var_end(v);
}
vect_end(&s->reg_vars);
}
// Label generation
void _scope_name_rec(Scope *s, Vector *v) {
// Base case
if (s == NULL)
return;
_scope_name_rec(s->parent, v);
// Add # before name if not directly from module
if (s->parent != NULL)
vect_push_string(v, "#");
vect_push_string(v, s->name);
}
char *mod_label_prefix(Module *m);
Vector _scope_base_label(Scope *s) {
Vector out = vect_from_string("");
vect_push_free_string(&out, mod_label_prefix(s->current));
_scope_name_rec(s, &out);
return out;
}
char *scope_label_start(Scope *s) {
Vector out = _scope_base_label(s);
vect_push_string(&out, "#start");
return vect_as_string(&out);
}
char *scope_label_rep(Scope *s) {
Vector out = _scope_base_label(s);
vect_push_string(&out, "#rep");
return vect_as_string(&out);
}
char *scope_label_end(Scope *s) {
Vector out = _scope_base_label(s);
vect_push_string(&out, "#end");
return vect_as_string(&out);
}
char *scope_gen_const_label(Scope *s) {
Vector out = _scope_base_label(s);
vect_push_string(&out, "#const");
vect_push_free_string(&out, int_to_str(s->next_const));
s->next_const++;
return vect_as_string(&out);
}
char *scope_gen_bool_label(Scope *s) {
Vector out = _scope_base_label(s);
vect_push_string(&out, "#bool");
vect_push_free_string(&out, int_to_str(s->next_bool));
return vect_as_string(&out);
}
void scope_adv_bool_label(Scope *s) {
s->next_bool++;
}
// Variables
// Initializes the variable, copying name, not deep copying type as it is a pointer.
Variable var_init(char *name, Type *type) {
Variable out = {0};
Vector name_cpy = vect_from_string(name);
out.name = vect_as_string(&name_cpy);
out.type = type;
out.ptr_chain = vect_init(sizeof(int));
out.location = 0;
out.offset = 0;
out.mod = NULL;
return out;
}
Variable var_copy(Variable *to_copy) {
Variable out = var_init(to_copy->name, to_copy->type);
out.location = to_copy->location;
out.offset = to_copy->offset;
out.mod = to_copy->mod;
for (size_t i = 0; i < to_copy->ptr_chain.count; i++) {
int *ptr_orig = vect_get(&(to_copy->ptr_chain), i);
vect_push(&(out.ptr_chain), ptr_orig);
}
return out;
}
// Simple cleanup for variables while the second pass is ongoing.
void var_end(Variable *v) {
free(v->name);
vect_end(&(v->ptr_chain));
}
// Variable operations
// Valid prefixes for fasm, take size of data - 1 = index of prefix.
char *PREFIXES[] = {
"byte ",
"word ",
"",
"dword ",
"",
"",
"",
"qword "
};
/// Remember to free!
char *_gen_address(char *prefix, char *base, char *offset, int mult, int add, bool rel) {
Vector out = vect_init(sizeof(char));
vect_push_string(&out, prefix);
if (rel)
vect_push_string(&out, "[rel ");
else
vect_push_string(&out, "[");
vect_push_string(&out, base);
if (offset != NULL && mult > 0) {
vect_push_string(&out, " + ");
vect_push_string(&out, offset);
if(mult > 1) {
vect_push_string(&out, "*");
char *mstr = int_to_str(mult);
vect_push_string(&out, mstr);
free(mstr);
}
}
if(add != 0) {
if (add > 0) {
vect_push_string(&out, " + ");
} else {
vect_push_string(&out, " - ");
add = -add;
}
char *astr = int_to_str(add);
vect_push_string(&out, astr);
free(astr);
}
vect_push_string(&out, "]");
return vect_as_string(&out);
}
// Type coercion engine
// TODO: all
Variable _op_coerce(Variable *base, Variable *to_coerce) {
Variable out = {0};
return out;
}
// TODO: Operations on variables
// remember for location: negative = on stack, zero = in DS, positive = in register
// Only values allowed in registers are in-built types and primitives (pointers/references)
// Other values must be in data section or on stack
// De-referencing = changing from a pointer to a reference
// referencing = changing from a variable to a pointer (can only be done for non-literals on stack or in DS)
// indexing returns a reference to the memory
// with an array => pointer + 8 bytes (length of array at start) + index * size of data
// with a pointer => pointer + index * size of data
// Get the last value from ptr_chain
int _var_ptr_type(Variable *v) {
if(v->ptr_chain.count < 1) {
// Return an invalid value if ptr_chain has no values.
return PTYPE_NONE;
}
return ((int*)v->ptr_chain.data)[v->ptr_chain.count - 1];
}
// Get the first non-reference value from ptr_chain
int _var_first_nonref(Variable *v) {
int *chk;
for(size_t i = v->ptr_chain.count; i > 0; i--) {
chk = vect_get(&v->ptr_chain, i - 1);
if(*chk != PTYPE_REF) {
return *chk;
}
}
return -2;
}
// Valid registers to use in operations:
// rax (1), rdx (4), rsi (5), rdi (6). Other registers assumed to be used by
// variables
// 1 - rax; 2 - rbx; 3 - rcx; 4 - rdx; 5 - rsi; 6 - rdi; 7 - rsp; 8 - rbp; 9-16: r8-r15
char *_op_get_register(int reg, int size) {
Vector out = vect_init(sizeof(char));
char add = 'r';
switch(size) {
case 1:
case 2:
if (reg < 9)
break;
case 4:
if (reg < 9)
add = 'e';
case 8:
vect_push(&out, &add);
break;
default:
printf("ERROR: invalid register size %d (this is a compiler issue)\n", size);
vect_push(&out, &add);
vect_push_string(&out, "; Invalid register size");
break;
}
switch(reg) {
case 1:
case 2:
case 3:
case 4:
add = 'a' + (reg - 1);
break;
case 5:
case 7:
add = 's';
break;
case 6:
add = 'd';
break;
case 8:
add = 'b';
break;
default:
if(reg > 8) {
char *tmp = int_to_str(reg - 1);
vect_push_string(&out, tmp);
free(tmp);
}
add = 0;
break;
}
if (add > 0)
vect_push(&out, &add);
add = 'x';
switch (reg) {
// Cases rsi, rdi, rsp, rbp need extra character
case 5:
case 6:
add = 'i';
case 7:
case 8:
if (add == 'x') {
add = 'p';
}
if (size == 1) {
vect_push(&out, &add);
}
case 1:
case 2:
case 3:
case 4:
// Add l if lower 8 bits, just push x otherwise
if(size == 1) {
add = 'l';
}
vect_push(&out, &add);
break;
default:
// r8 - r15
if (size == 1) {
add = 'b';
} else if (size == 2) {
add = 'w';
} else if (size == 4) {
add = 'd';
}
if (size < 8) {
vect_push(&out, &add);
}
break;
}
return vect_as_string(&out);
}
int _var_size(Variable *var) {
if (var->location == LOC_LITL) {
return -1;
}
size_t count = var->ptr_chain.count;
int *ptype;
while(count > 0) {
ptype = vect_get(&var->ptr_chain, count - 1);
if (*ptype != PTYPE_REF) {
return 8;
}
count--;
}
return var->type->size;
}
// The size of the element if you were to strip off one
// pointer chain value. useful for indexing
int _var_strip_size(Variable *var) {
if (var->location == LOC_LITL) {
return -1;
} else if (var->ptr_chain.count == 0) {
return var->type->size;
}
size_t count = var->ptr_chain.count - 1;
int *ptype;
while(count > 0) {
ptype = vect_get(&var->ptr_chain, count - 1);
if (*ptype != PTYPE_REF) {
return 8;
}
count--;
}
return var->type->size;
}
// Pure size in the sense that references count as pointers,
// so returns 8 if reference, pointer, or array.
int _var_pure_size(Variable *var) {
if (var->location == LOC_LITL) {
return -1;
}
if ( var->ptr_chain.count > 0 ) {
return 8;
}
return var->type->size;
}
char *mod_label_prefix(Module *m);
// Get the full label in the data section
// for address generation
char *_var_get_datalabel(Variable *var) {
Vector v = vect_from_string("");
vect_push_free_string(&v, mod_label_prefix(var->mod));
vect_push_string(&v, var->name);
return vect_as_string(&v);
}
// Gets the location of a variable. Can not get the location
// properly if the variable is a reference.
char *_op_get_location(Variable *var) {
char *out = NULL;
if (var->location == LOC_LITL) {
out = int_to_str(var->offset);
} else if(var->location == LOC_STCK) {
// Invert because stack grows down (and stack index starts at 1)
out = _gen_address("", "rbp", "", 0, var->offset, false);
} else if (var->location == LOC_DATA) {
// Stored in data sec
char *name = _var_get_datalabel(var);
out = _gen_address("", name, "", 0, var->offset, true);
free(name);
} else {
// Stored in register. Our job here is not to assume
// what it will be used for (in the case it is a reference)
// so we use pure size
out = _op_get_register(var->location, _var_pure_size(var));
}
return out;
}
// Can only be used on variables contained in a register.
void var_chg_register(CompData *out, Variable *swap, int new_reg) {
if(swap->location == new_reg || swap->location == LOC_DATA || swap->location == LOC_STCK)
return;
if (swap->location == LOC_LITL) {
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, _op_get_register(new_reg, 8));
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, int_to_str(swap->offset));
vect_push_string(&out->text, " ; Store literal\n\n");
swap->offset = 0;
} else {
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, _op_get_register(new_reg, _var_pure_size(swap)));
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, _op_get_register(swap->location, _var_pure_size(swap)));
vect_push_string(&out->text, " ; Register swap\n\n");
}
swap->location = new_reg;
}
// Dereference a pointer variable into a new variable "store".
// Store is copied from "from" variable, so it should be empty (will not be freed).
// In other words, it takes a pointer variable and turns it into a reference,
// which can be used in other var operations like member variables, struct moving,
// or value setting.
void var_op_dereference(CompData *out, Variable *store, Variable *from) {
*store = var_copy(from);
if(from->ptr_chain.count < 1) {
printf("WARNING: var_op_dereference called on variable which is not a pointer!\n");
return;
}
// If we are not in a register, or we are a multiref not already in rsi
if (from->location < 1 || (_var_ptr_type(from) == PTYPE_REF && from->location != 5 && from->ptr_chain.count > 1)) {
// Generate initial move (from -> rsi)
if (_var_ptr_type(from) > 1)
// If in-place array, generate reference by lea
vect_push_string(&out->text, "\tlea rsi, ");
else
// If pointer, generate reference by mov
vect_push_string(&out->text, "\tmov rsi, ");
vect_push_free_string(&out->text, _op_get_location(from));
vect_push_string(&out->text, "; Move for dereference\n");
// Location -> rsi
store->location = 5;
}
if (from->location == LOC_LITL)
store->offset = 0;
// Keep de-referencing until we reach the pointer (or ptr_chain bottoms out).
int *current;
while(store->ptr_chain.count > 1) {
current = vect_get(&store->ptr_chain, store->ptr_chain.count - 1);
if (*current != PTYPE_REF)
break;
vect_push_string(&out->text, "\tmov rsi, [rsi] ; Dereference\n");
vect_pop(&store->ptr_chain);
}
// pointer type -> ref
current = vect_get(&store->ptr_chain, store->ptr_chain.count - 1);
*current = PTYPE_REF;
}
// Index into an array by "index" elements. Store the reference to the value in "store".
// The "store" variable should be freed or empty before calling this function.
void var_op_index(CompData *out, Variable *store, Variable *from, Variable *index) {
// Generate a reference to the data we will output.
// we will do pointer math on store based on ptype of from.
var_op_dereference(out, store, from);
// First, we'll calculate where the index is coming from
char *idx_by = NULL;
if (index->location == LOC_LITL) {
idx_by = int_to_str(index->offset);
} else if(_var_ptr_type(index) == PTYPE_REF) {
vect_push_string(&out->text, "\tmov rdx, ");
vect_push_string(&out->text, _op_get_location(index));
vect_push_string(&out->text, " ; !!! DEREF IN INDEX !!!\n");
int *cur;
for(size_t i = index->ptr_chain.count - 1; i > 0; i--) {
cur = vect_get(&index->ptr_chain, i - 1);
if (*cur == PTYPE_REF) {
vect_push_string(&out->text, "\tmov rdx, [rdx] ; deref\n");
} else
break;
}
idx_by = _gen_address(PREFIXES[_var_size(index) - 1], "rdx", "", 0, 0, false);
} else {
if (index->location == LOC_STCK || index->location == LOC_DATA) {
Vector tmp = vect_from_string(PREFIXES[index->type->size - 1]);
vect_push_free_string(&tmp, _op_get_location(index));
idx_by = vect_as_string(&tmp);
} else {
idx_by = _op_get_register(index->location, _var_size(index));
}
}
// What type of move we will use on the index
// to get it into rax
switch(_var_size(index)) {
case 8:
// Standard move
vect_push_string(&out->text, "\tmov rax, ");
break;
case 4:
// mov into 4 byte register zeros out upper four bytes of the corrosponding 8 byte register
vect_push_string(&out->text, "\tmov eax, ");
break;
case 2:
case 1:
// Zero extension
vect_push_string(&out->text, "\tmovzx rax, ");
break;
default:
vect_push_string(&out->text, "\tmov rax, ");
}
// Get index into rax
vect_push_free_string(&out->text, idx_by);
vect_push_string(&out->text, " ; Pre-index\n");
if(_var_strip_size(from) > 1) {
// To multiply by the var size, we load the var size into rdx, then
// multiply by it.
vect_push_string(&out->text, "\tmov rdx, ");
vect_push_free_string(&out->text, int_to_str(_var_strip_size(from)));
vect_push_string(&out->text, " ; Size of element held by ptr (pre-index)\n");
vect_push_string(&out->text, "\tmul rdx ; Index multiplication by data size\n");
}
vect_push_string(&out->text, "\tlea rsi, ");
if (_var_first_nonref(from) == PTYPE_PTR) {
char *reg = _op_get_register(store->location, 8);
vect_push_free_string(&out->text, _gen_address("", reg, "rax", 1, 0, false));
free(reg);
} else if (_var_first_nonref(from) == PTYPE_ARR) {
// Additional offset due to arrays containing a length at the start
char *reg = _op_get_register(store->location, 8);
vect_push_free_string(&out->text, _gen_address("", reg, "rax", 1, 8, false));
free(reg);
} else {
vect_push_string(&out->text, "rsi ; COMPILER ERROR!");
}
vect_push_string(&out->text, " ; Index complete.\n\n");
store->location = 5;
}
// Pure set simply copies data from one source to another, disregarding
// pointer arithmatic. Should not be used to set the value of data reference variables
// point to, but can be used to directly set the location that reference
// variables point to for things like function parameter passing.
// Should only be used when you can garantee that both types are equal and
// you are not setting by reference
void var_op_pure_set(CompData *out, Variable *store, Variable *from) {
if (store->location == LOC_LITL) {
printf("ERROR: Can't set a literal value by pure set.\n");
return;
} else if (_var_pure_size(from) != _var_pure_size(store) && from->location != LOC_LITL) {
printf("ERROR: Can't set one variable to the other as their pure sizes are different!\n");
return;
}
if (from->location == LOC_LITL) {
vect_push_string(&out->text, "\tmov ");
if (store->location < 1) {
// Must be done in case of a very large value
vect_push_string(&out->text, "rsi, ");
vect_push_free_string(&out->text, _op_get_location(from));
vect_push_string(&out->text, "\n");
// Store to data
vect_push_string(&out->text, "\tmov ");
vect_push_string(&out->text, PREFIXES[_var_pure_size(store) - 1]);
vect_push_free_string(&out->text, _op_get_location(store));
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, _op_get_register(5, _var_pure_size(store)));
vect_push_string(&out->text, "; literal move\n\n");
} else {
vect_push_free_string(&out->text, _op_get_location(store));
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, _op_get_location(from));
vect_push_string(&out->text, "; literal move\n\n");
}
} else if (!is_inbuilt(from->type->name) && from->ptr_chain.count == 0) {
// Pure struct move
vect_push_string(&out->text, "\tlea rsi, ");
vect_push_free_string(&out->text, _op_get_location(from));
vect_push_string(&out->text, "\n");
vect_push_string(&out->text, "\tlea rdi, ");
vect_push_free_string(&out->text, _op_get_location(store));
vect_push_string(&out->text, "\n");
vect_push_string(&out->text, "\tmov rcx, ");
vect_push_free_string(&out->text, int_to_str(_var_pure_size(from)));
vect_push_string(&out->text, "\n");
vect_push_string(&out->text, "\trep movsb ; Move struct complete\n\n");
} else if (from->location < 1 && store->location < 1) {
// Both in memory, use rsi as temp storage for move
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, _op_get_register(5, _var_pure_size(from)));
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, _op_get_location(from));
vect_push_string(&out->text, "\n");
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, _op_get_location(store));
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, _op_get_register(5, _var_pure_size(from)));
vect_push_string(&out->text, " ; Memory swap complete\n\n");
} else {
// Register to register
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, _op_get_location(store));
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, _op_get_location(from));
vect_push_string(&out->text, "; Register move\n\n");
}
}
// Specific setting rules for pointers
void _var_op_set_ptr(CompData *out, Variable *store, Variable *from) {
// Pointer coercion should always work
char *mov_from;
char *mov_to;
// First deref from var, then deref store variable, then move.
if(_var_ptr_type(store) != PTYPE_REF) {
mov_to = _op_get_location(store);
} else {
// Need to deref
vect_push_string(&out->text, "\tmov rdi, ");
vect_push_free_string(&out->text, _op_get_location(store));
vect_push_string(&out->text, " ; Move for ptr set dest deref\n");
int *cur;
for (size_t i = store->ptr_chain.count - 1; i > 0; i--) {
cur = vect_get(&store->ptr_chain, i - 1);
if (*cur == PTYPE_REF) {
vect_push_string(&out->text, "\tmov rdi, [rdi]\n");
} else {
break;
}
}
mov_to = _gen_address("", "rdi", "", 0, 0, false);
}
if (_var_ptr_type(from) != PTYPE_REF) {
if (from->location > 0 || from->location == LOC_LITL) {
mov_from = _op_get_location(from);
} else if (store->location > 0 && _var_ptr_type(store) != PTYPE_REF) {
mov_from = _op_get_location(from);
} else {
vect_push_string(&out->text, "\tmov rsi, ");
vect_push_free_string(&out->text, _op_get_location(from));
vect_push_string(&out->text, " ; Move for ptr set\n");
mov_from = _op_get_register(5, 8);
}
} else {
// Need to deref
vect_push_string(&out->text, "\tmov rsi, ");
vect_push_free_string(&out->text, _op_get_location(from));
vect_push_string(&out->text, " ; Move for ptr set source deref\n");
int *cur;
for (size_t i = from->ptr_chain.count - 1; i > 0; i--) {
cur = vect_get(&from->ptr_chain, i - 1);
if (*cur == PTYPE_REF) {
vect_push_string(&out->text, "\tmov rsi, [rsi]\n");
} else {
break;
}
}
switch (_var_size(from)) {
case 1:
vect_push_string(&out->text, "\tmovzx rsi, byte [rsi]\n");
break;
case 2:
vect_push_string(&out->text, "\tmovzx rsi, word [rsi]\n");
break;
case 4:
vect_push_string(&out->text, "\tmov esi, dword [rsi]\n");
break;
case 8:
vect_push_string(&out->text, "\tmov rsi, [rsi]\n");
break;
}
mov_from = _op_get_register(5, 8);
}
vect_push_string(&out->text, "\tmov ");
vect_push_string(&out->text, mov_to);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, mov_from);
vect_push_string(&out->text, " ; Ptr set final\n");
if (_var_first_nonref(store) == PTYPE_PTR && _var_first_nonref(from) == PTYPE_ARR) {
vect_push_string(&out->text, "\tadd ");
if (mov_to[0] == '[')
vect_push_string(&out->text, " qword ");
vect_push_string(&out->text, mov_to);
vect_push_string(&out->text, ", ");
vect_push_string(&out->text, "8 ; Reference to first el in array\n\n");
} else {
vect_push_string(&out->text, "\n");
}
free(mov_to);
return;
}
char *_var_get_store(CompData *out, Variable *store) {
if (_var_ptr_type(store) == PTYPE_REF){
vect_push_string(&out->text, "\tmov rdi, ");
vect_push_free_string(&out->text, _op_get_location(store));
vect_push_string(&out->text, " ; pre-deref for inbuilt mov (store)\n");
for(size_t i = store->ptr_chain.count - 1; i > 0; i--){
int *cur = vect_get(&store->ptr_chain, i);
if (cur == PTYPE_REF) {
vect_push_string(&out->text, "\tmov rdi, [rdi] ; deref for mov\n");
} else
break; // Should not happen
}
return _gen_address(PREFIXES[_var_size(store) - 1], "rdi", "", 0, 0, false);
} else if (store->location == 0) {
char *name = _var_get_datalabel(store);
return _gen_address(PREFIXES[_var_size(store) - 1], name, "", 0, 0, true);
free(name);
} else if (store->location == LOC_LITL) {
vect_push_string(&out->text, "\tmov rdi, ");
vect_push_free_string(&out->text, int_to_str(store->offset));
vect_push_string(&out->text, "; litl set\n");
if (store->type != NULL)
return _op_get_register(6, _var_size(store));
return _op_get_register(6, 8);
var_end(store);
*store = var_init("#store", typ_get_inbuilt("int"));
store->location = 6;
} else if (store->location < 0) {
return _gen_address(PREFIXES[_var_size(store) - 1], "rbp", "", 0, store->offset, false);
} else {
return _op_get_location(store);
}
}
char *_var_get_from(CompData *out, Variable *store, Variable *from) {
char *mov_from = NULL;
if (_var_ptr_type(from) == PTYPE_REF) {
vect_push_string(&out->text, "\tmov rsi, ");
vect_push_free_string(&out->text, _op_get_location(from));
vect_push_string(&out->text, " ; pre-deref for inbuilt mov (from)\n");
for(size_t i = from->ptr_chain.count - 1; i > 0; i--){
int *cur = vect_get(&from->ptr_chain, i);
if (cur == PTYPE_REF) {
vect_push_string(&out->text, "\tmov rsi, [rsi] ; deref for mov\n");
} else
break; // Should not happen
}
// Final deref (store actual value in rsi)
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, _op_get_register(5, _var_size(from)));
vect_push_string(&out->text, ", ");
vect_push_string(&out->text, PREFIXES[_var_size(from) - 1]);
vect_push_string(&out->text, "[rsi] ; pre-deref for inbuilt mov (from)\n");
mov_from = _op_get_register(5, _var_size(from));
} else if (from->location > 0) {
mov_from = _op_get_register(from->location, _var_size(from));
} else if (from->location == LOC_LITL) {
if (store->location == LOC_LITL) {
vect_push_string(&out->text, "\tmov rsi, ");
vect_push_free_string(&out->text, int_to_str(from->offset));
vect_push_string(&out->text, "; litl set\n");
if (store->type != NULL)
return _op_get_register(5, store->type->size);
return _op_get_register(5, 8);
} else if (store->location < 1 || _var_ptr_type(store) == PTYPE_REF) {
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, _op_get_register(5, _var_size(store)));
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, int_to_str(from->offset));
vect_push_string(&out->text, "; litl set for inbuilt mov (from)\n");
mov_from = _op_get_register(5, _var_size(store));
} else {
mov_from = int_to_str(from->offset);
}
} else if (store->location < 1 || _var_ptr_type(store) == PTYPE_REF) {
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, _op_get_register(5, _var_size(from)));
vect_push_string(&out->text, ", ");
vect_push_string(&out->text, _op_get_location(from));
vect_push_string(&out->text, " ; pre-load for mov (from)\n");
mov_from = _op_get_register(5, _var_size(from));
} else if (from->location == 0) {
// from in data sec
char *name = _var_get_datalabel(from);
mov_from = _gen_address(PREFIXES[_var_size(from) - 1], name, "", 0, 0, true);
free(name);
} else {
// from on stack
mov_from = _gen_address(PREFIXES[_var_size(from) - 1], "rbp", "", 0, from->offset, false);
}
// Match sign of data if required.
if (from->location != LOC_LITL && _var_size(from) < _var_size(store)) {
// Store larger than from (extend sign)
if(from->type->name[0] == 'i' && store->type->name[0] == 'i') {
if (_var_size(from) < 4)
vect_push_string(&out->text, "\tmovsx rsi, ");
else
vect_push_string(&out->text, "\tmovsxd rsi, ");
} else {
if(_var_size(from) < 4)
vect_push_string(&out->text, "\tmovzx rsi, ");
else
vect_push_string(&out->text, "\tmovzxd rsi, ");
}
vect_push_free_string(&out->text, mov_from);
vect_push_string(&out->text, " ; Sign extension for mov\n");
mov_from = _op_get_register(5, _var_size(store));
} else if (from->location != LOC_LITL && _var_size(from) > _var_size(store)) {
// Store smaller than from (recompute mov_from)
if (_var_ptr_type(from) == PTYPE_REF) {
} else if (from->location > 0) {
free(mov_from);
mov_from = _op_get_register(from->location, _var_size(store));
}
}
return mov_from;
}
// Common func to move one variable to another in the case of two
// inbuilts
void _var_op_set_inbuilt(CompData *out, Variable *store, Variable *from) {
char *mov_from;
char *mov_to;
// Cases for source/dest:
// register
// stack
// data
// reference
// Cases for types
// uint - range from 1 to 8 bytes - zx expansion
// int - range from 1 to 8 bytes - sx expansion
// bool - always 1 byte
// float - not impl
// void - should only be used to represent ptrs, so we should not see it here.
// In case of references
mov_to = _var_get_store(out, store);
mov_from = _var_get_from(out, store, from);
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, mov_to);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, mov_from);
vect_push_string(&out->text, " ; Finish mov_inbuilt\n\n");
}
// Tries it's best to coerce the data from "from" into a format
// which will be accepted by "store", following refences in the process.
// This is similar to a normal move operation.
void var_op_set(CompData *out, Variable *store, Variable *from) {
if(_var_first_nonref(store) == PTYPE_PTR || _var_first_nonref(store) == PTYPE_ARR) {
_var_op_set_ptr(out, store, from);
return;
}
if (store->location == LOC_LITL) {
if (from->location == LOC_LITL)
store->offset = from->offset;
else
printf("ERROR: Unable to set a non-literal equal to a literal value\n\n");
return;
}
if (from->location == LOC_LITL) {
if (is_inbuilt(store->type->name) == true)
_var_op_set_inbuilt(out, store, from);
else
printf("ERROR: Unable to set a struct equal to a literal value\n\n");
return;
}
if(is_inbuilt(store->type->name) != is_inbuilt(from->type->name)) {
printf("ERROR: Unable to coerce types when one is inbuilt and the other is not.\n\n");
return;
}
if(is_inbuilt(from->type->name)) {
// Inbuilt types like int, uint, void, etc.
_var_op_set_inbuilt(out, store, from);
} else {
// Two structs, we should only copy as much data as we can from one to another,
// and so will defer to the storage variable for how much to transfer
// since we will be using movsb, we first should mov the from struct into
// rsi.
if (from->location < 1) {
vect_push_string(&out->text, "\tlea rsi, ");
} else {
vect_push_string(&out->text, "\tmov rsi, ");
}
vect_push_free_string(&out->text, _op_get_location(from));
vect_push_string(&out->text, " ; Initial mov to rsi\n");
// Handle the case where the from struct is a reference
size_t i = from->ptr_chain.count;
if (from->location > 0)
i--;
for (; i > 0; i--) {
int *cur = vect_get(&from->ptr_chain, i - 1);
if (*cur == PTYPE_REF)
vect_push_string(&out->text, "\tlea rsi, [rsi] ; Deref\n");
else
break;
}
// load the location of the storeage var into rdi
if (store->location < 1) {
vect_push_string(&out->text, "\tlea rdi, ");
} else {
vect_push_string(&out->text, "\tmov rdi, ");
}
vect_push_free_string(&out->text, _op_get_location(store));
vect_push_string(&out->text, " ; Initial mov to rdi\n");
i = store->ptr_chain.count;
if (store->location > 0)
i--;
for (; i > 0; i--) {
int *cur = vect_get(&store->ptr_chain, i - 1);
if (*cur == PTYPE_REF)
vect_push_string(&out->text, "\tlea rsi, [rsi] ; Deref\n");
else
break;
}
// We can move up to the minimum number of bytes btwn the two structs
vect_push_string(&out->text, "\tmov rcx, ");
if (_var_size(from) < _var_size(store)) {
vect_push_free_string(&out->text, int_to_str(_var_size(from)));
} else {
vect_push_free_string(&out->text, int_to_str(_var_size(store)));
}
vect_push_string(&out->text, "\n\trep movsb ; Complete struct move\n\n");
}
}
// Take a variable on the stack or in data section, and load a reference
// to it's location in memory
void var_op_reference(CompData *out, Variable *store, Variable *from) {
if (from->location == LOC_LITL) {
printf("ERROR: Unable to do dereference with literal value\n\n");
return;
}
*store = var_copy(from);
if (store->ptr_chain.count > 0) {
for(size_t i = 0; i < store->ptr_chain.count; i++) {
int *cur = vect_get(&store->ptr_chain, i);
if (*cur == PTYPE_REF) {
*cur = PTYPE_PTR;
break;
}
}
} else {
int ref = PTYPE_REF;
vect_push(&store->ptr_chain, &ref);
}
store->location = 5;
store->offset = 0;
if(from->ptr_chain.count > 0 && _var_ptr_type(from) == PTYPE_REF) {
// The value is a reference to data, so we should just copy it
var_op_pure_set(out, store, from);
return;
}
if(from->location > 0) {
// Can't generate reference if variable is in register
printf("FATAL: (Compiler error) attempt to generate reference to a variable in a register.\n");
return;
}
vect_push_string(&out->text, "\tlea ");
vect_push_free_string(&out->text, _op_get_register(5, _var_pure_size(store)));
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, _op_get_location(from));
vect_push_string(&out->text, " ; Generate reference\n");
vect_push_string(&out->text, "\n");
}
Variable var_op_member(CompData *data, Variable *from, char *member) {
Variable out = {0};
out.name = NULL; // This is how you can check weather we succeeded
if (from->location == LOC_LITL) {
printf("ERROR: Unable to take member from literal value");
return out;
}
if (from->ptr_chain.count > 1 || (from->ptr_chain.count == 1 && _var_ptr_type(from) != PTYPE_REF)) {
printf("ERROR: Can't generate member for pointer!\n");
return out;
}
for (size_t i = 0; i < from->type->members.count; i++) {
Variable *mem = vect_get(&from->type->members, i);
if (strcmp(mem->name, member) == 0) {
out = var_copy(mem);
break;
}
}
if (out.name == NULL)
return out;
// Copy ptr_chain so when using the variable we follow all references
for(size_t i = 0; i < from->ptr_chain.count; i++) {
int *cur = vect_get(&from->ptr_chain, i);
vect_push(&out.ptr_chain, cur);
}
// Copy location
out.location = from->location;
// If the variable is in the data section, we should copy
// the name as well so references are properly handled
if (out.location != 5 && _var_ptr_type(&out) == PTYPE_REF) {
out.location = 5;
var_op_pure_set(data, &out, from);
} else if(out.location == LOC_DATA) {
free(out.name);
Vector name = vect_from_string(from->name);
out.name = vect_as_string(&name);
}
if (out.location == 5 && out.offset > 0) {
vect_push_string(&data->text, "\tadd rsi, ");
vect_push_free_string(&data->text, int_to_str(out.offset));
vect_push_string(&data->text, "; Member generation in reference\n");
out.offset = 0;
} else {
// If from is already offset, we should base our new offset on the old one.
out.offset += from->offset;
}
return out;
}
// Adds "base" with "add" and sets "base" to the result
void var_op_add(CompData *out, Variable *base, Variable *add) {
if(base->location == LOC_LITL) {
if (add->location == LOC_LITL)
base->offset += add->offset;
return;
}
char *add_store;
char *add_from;
add_store = _var_get_store(out, base);
add_from = _var_get_from(out, base, add);
vect_push_string(&out->text, "\tadd ");
vect_push_free_string(&out->text, add_store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, add_from);
vect_push_string(&out->text, "; complete add\n\n");
}
// Subtracts "sub" from "base" and sets "base" to the result
void var_op_sub(CompData *out, Variable *base, Variable *sub) {
if(base->location == LOC_LITL) {
if (sub->location == LOC_LITL)
base->offset -= sub->offset;
return;
}
char *sub_store;
char *sub_from;
sub_store = _var_get_store(out, base);
sub_from = _var_get_from(out, base, sub);
vect_push_string(&out->text, "\tsub ");
vect_push_free_string(&out->text, sub_store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, sub_from);
vect_push_string(&out->text, "; complete sub\n\n");
}
// Ands "base" with "and" and sets "base" to the result
void var_op_and(CompData *out, Variable *base, Variable *and) {
if(base->location == LOC_LITL) {
if (and->location == LOC_LITL)
base->offset &= and->offset;
return;
}
char *and_store;
char *and_from;
and_store = _var_get_store(out, base);
and_from = _var_get_from(out, base, and);
vect_push_string(&out->text, "\tand ");
vect_push_free_string(&out->text, and_store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, and_from);
vect_push_string(&out->text, "; complete and\n\n");
}
// Ors "base" with "or" and sets "base" to the result
void var_op_or(CompData *out, Variable *base, Variable *or) {
if(base->location == LOC_LITL) {
if (or->location == LOC_LITL)
base->offset |= or->offset;
return;
}
char *or_store;
char *or_from;
or_store = _var_get_store(out, base);
or_from = _var_get_from(out, base, or);
vect_push_string(&out->text, "\tor ");
vect_push_free_string(&out->text, or_store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, or_from);
vect_push_string(&out->text, "; complete or\n\n");
}
// Xors "base" with "xor" and sets "base" to the result
void var_op_xor(CompData *out, Variable *base, Variable *xor) {
if(base->location == LOC_LITL) {
if (xor->location == LOC_LITL)
base->offset ^= xor->offset;
return;
}
char *xor_store;
char *xor_from;
xor_store = _var_get_store(out, base);
xor_from = _var_get_from(out, base, xor);
vect_push_string(&out->text, "\txor ");
vect_push_free_string(&out->text, xor_store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, xor_from);
vect_push_string(&out->text, "; complete xor\n\n");
}
// nors "base" with "nor" and sets "base" to the result
void var_op_nor(CompData *out, Variable *base, Variable *nor) {
if(base->location == LOC_LITL) {
if (nor->location == LOC_LITL)
base->offset |= ~nor->offset;
return;
}
char *nor_store;
char *nor_from;
nor_store = _var_get_store(out, base);
nor_from = _var_get_from(out, base, nor);
vect_push_string(&out->text, "\tor ");
vect_push_free_string(&out->text, nor_store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, nor_from);
vect_push_string(&out->text, "\n\tnot ");
vect_push_free_string(&out->text, nor_store);
vect_push_string(&out->text, " ; Complete nor\n");
}
// nands "base" with "nand" and sets "base" to the result
void var_op_nand(CompData *out, Variable *base, Variable *nand) {
if(base->location == LOC_LITL) {
if (nand->location == LOC_LITL) {
base->offset &= ~nand->offset;
}
return;
}
char *nand_store = _var_get_store(out, base);
char *nand_from = _var_get_from(out, base, nand);
vect_push_string(&out->text, "\tand ");
vect_push_free_string(&out->text, nand_store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, nand_from);
vect_push_string(&out->text, "\n\tnot ");
vect_push_free_string(&out->text, nand_store);
vect_push_string(&out->text, " ; Complete nand\n");
}
// xands "base" with "xand" and sets "base" to the result
void var_op_xand(CompData *out, Variable *base, Variable *xand) {
if(base->location == LOC_LITL) {
if (xand->location == LOC_LITL)
base->offset ^= ~xand->offset;
return;
}
char *xand_store = _var_get_store(out, base);
char *xand_from = _var_get_from(out, base, xand);
vect_push_string(&out->text, "\txor ");
vect_push_free_string(&out->text, xand_store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, xand_from);
vect_push_string(&out->text, "\n\tnot ");
vect_push_free_string(&out->text, xand_store);
vect_push_string(&out->text, " ; Complete xand\n");
}
// bit inversion of base
void var_op_not(CompData *out, Variable *base) {
if(base->location == LOC_LITL) {
base->offset = ~base->offset;
return;
}
char *not_store = _var_get_store(out, base);
if (base->type != NULL && strcmp(base->type->name, "bool") == 0) {
// boolean not
vect_push_string(&out->text, "\tnot ");
vect_push_string(&out->text, not_store);
vect_push_string(&out->text, "\n");
vect_push_string(&out->text, "\tand ");
vect_push_free_string(&out->text, not_store);
vect_push_string(&out->text, ", 1 ; Complete and\n");
} else {
// normal not
vect_push_string(&out->text, "\tnot ");
vect_push_free_string(&out->text, not_store);
vect_push_string(&out->text, " ; Complete not\n");
}
}
// test base with itself
void var_op_test(CompData *out, Variable *base) {
if(base->location == LOC_LITL) {
vect_push_string(&out->text, "\tmov rax, ");
vect_push_free_string(&out->text, int_to_str(base->offset));
vect_push_string(&out->text, "\n");
vect_push_string(&out->text, "\ttest rax, rax ; lit test\n\n");
return;
}
char *test_store = _var_get_store(out, base);
char *test_from = _var_get_from(out, base, base);
vect_push_string(&out->text, "\ttest ");
vect_push_free_string(&out->text, test_store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, test_from);
vect_push_string(&out->text, " ; Complete test\n");
}
// bit shift base left by "bsl"
void var_op_bsl(CompData *out, Variable *base, Variable *bsl) {
if(base->location == LOC_LITL) {
if (bsl->location == LOC_LITL)
base->offset = base->offset << bsl->offset;
return;
}
char *bsl_store = _var_get_store(out, base);
char *bsl_from;
if (bsl->location == LOC_LITL) {
bsl_from = int_to_str(bsl->offset % 128);
} else {
Variable cx = var_copy(bsl);
cx.offset = 0;
cx.mod = NULL;
cx.location = 3;
var_op_pure_set(out, &cx, bsl);
var_end(&cx);
bsl_from = _op_get_register(3, 1);
}
// Signed and unsigned shift are the same
vect_push_string(&out->text, "\tshl ");
vect_push_free_string(&out->text, bsl_store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, bsl_from);
vect_push_string(&out->text, " ; Complete shift left\n");
}
// bit shift base right by "bsr"
void var_op_bsr(CompData *out, Variable *base, Variable *bsr) {
if(base->location == LOC_LITL) {
if (bsr->location == LOC_LITL)
base->offset = base->offset >> bsr->offset;
return;
}
char *bsr_store = _var_get_store(out, base);
char *bsr_from;
if (bsr->location == LOC_LITL) {
bsr_from = int_to_str(bsr->offset % 256);
} else {
Variable cx = var_copy(bsr);
cx.offset = 0;
cx.mod = NULL;
cx.location = 3;
var_op_pure_set(out, &cx, bsr);
var_end(&cx);
bsr_from = _op_get_register(3, 1);
}
if (is_inbuilt(base->type->name) && base->type->name[0] == 'i') {
// integer shift
vect_push_string(&out->text, "\tsar ");
} else {
// unsigned shift
vect_push_string(&out->text, "\tshr ");
}
vect_push_free_string(&out->text, bsr_store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, bsr_from);
vect_push_string(&out->text, " ; Complete not\n");
}
Variable var_op_cmpbase(CompData *out, Variable *base, Variable *cmp, char *cc) {
char *store = _var_get_store(out, base);
int tmp_loc = base->location;
if (cmp->location == LOC_LITL) {
base->location = LOC_LITL;
}
char *from = _var_get_from(out, base, cmp);
if (cmp->location == LOC_LITL) {
base->location = tmp_loc;
}
// cmp
vect_push_string(&out->text, "\tcmp ");
vect_push_free_string(&out->text, store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, from);
vect_push_string(&out->text, "\n");
// prime rax and rdx
vect_push_string(&out->text, "\tmov rax, 0\n");
vect_push_string(&out->text, "\tmov rdx, 1\n");
// Store bool value in rax and test so jumps make sense
vect_push_string(&out->text, "\tcmov");
vect_push_string(&out->text, cc);
vect_push_string(&out->text, " rax, rdx ; bool gen\n");
vect_push_string(&out->text, "\ttest rax, rax ; less than test\n\n");
// Generate variable
Variable v = var_init("#bool", typ_get_inbuilt("bool"));
v.location = 1;
return v;
}
void var_op_le(CompData *out, Variable *base, Variable *cmp) {
Variable tmp;
if (base->location == LOC_LITL || (is_inbuilt(base->type->name) && base->type->name[0] == 'i')) {
// int compare
tmp = var_op_cmpbase(out, base, cmp, "le");
} else {
tmp = var_op_cmpbase(out, base, cmp, "be");
}
var_end(base);
*base = tmp;
}
void var_op_ge(CompData *out, Variable *base, Variable *cmp) {
Variable tmp;
if (base->location == LOC_LITL || (is_inbuilt(base->type->name) && base->type->name[0] == 'i')) {
// int compare
tmp = var_op_cmpbase(out, base, cmp, "ge");
} else {
tmp = var_op_cmpbase(out, base, cmp, "ae");
}
var_end(base);
*base = tmp;
}
void var_op_lt(CompData *out, Variable *base, Variable *cmp) {
Variable tmp;
if (base->location == LOC_LITL || (is_inbuilt(base->type->name) && base->type->name[0] == 'i')) {
// int compare
tmp = var_op_cmpbase(out, base, cmp, "l");
} else {
tmp = var_op_cmpbase(out, base, cmp, "b");
}
var_end(base);
*base = tmp;
}
void var_op_gt(CompData *out, Variable *base, Variable *cmp) {
Variable tmp;
if (base->location == LOC_LITL || (is_inbuilt(base->type->name) && base->type->name[0] == 'i')) {
// int compare
tmp = var_op_cmpbase(out, base, cmp, "g");
} else {
tmp = var_op_cmpbase(out, base, cmp, "a");
}
var_end(base);
*base = tmp;
}
void var_op_eq(CompData *out, Variable *base, Variable *cmp) {
Variable tmp = var_op_cmpbase(out, base, cmp, "e");
var_end(base);
*base = tmp;
}
void var_op_ne(CompData *out, Variable *base, Variable *cmp) {
Variable tmp = var_op_cmpbase(out, base, cmp, "ne");
var_end(base);
*base = tmp;
}
void var_op_inc(CompData *out, Variable *lhs) {
if (lhs->location == LOC_LITL) {
lhs->offset++;
}
char *store = _var_get_store(out, lhs);
vect_push_string(&out->text, "\tinc ");
vect_push_free_string(&out->text, store);
vect_push_string(&out->text, " ; Increment\n\n");
}
void var_op_dec(CompData *out, Variable *lhs) {
if (lhs->location == LOC_LITL) {
lhs->offset--;
}
char *store = _var_get_store(out, lhs);
vect_push_string(&out->text, "\tdec ");
vect_push_free_string(&out->text, store);
vect_push_string(&out->text, " ; Decrement\n\n");
}
// Multiplies "base" by "mul" and sets "base" to the result.
void var_op_mul(CompData *out, Variable *base, Variable *mul) {
if(base->location == LOC_LITL) {
if (mul->location == LOC_LITL)
base->offset *= mul->offset;
return;
}
if (mul->location == 1) {
var_chg_register(out, mul, 3);
}
if(base->type->name[0] == 'i') {
// Integer mul
char *store = _var_get_store(out, base);
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, _op_get_register(1, _var_size(base)));
vect_push_string(&out->text, ", ");
vect_push_string(&out->text, store);
vect_push_string(&out->text, "; pre-mul mov\n");
if (mul->location == LOC_LITL) {
vect_push_string(&out->text, "\tmov rcx, ");
vect_push_free_string(&out->text, int_to_str(mul->offset));
vect_push_string(&out->text, "; literal load\n");
vect_push_string(&out->text, "\timul ");
vect_push_free_string(&out->text, _op_get_register(3, _var_size(base)));
vect_push_string(&out->text, "; imul\n");
} else {
char *from = _var_get_from(out, base, mul);
vect_push_string(&out->text, "\timul ");
vect_push_free_string(&out->text, from);
vect_push_string(&out->text, "; imul\n");
}
// move back after mul
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, _op_get_register(1, _var_size(base)));
vect_push_string(&out->text, "; post-mul mov\n");
} else {
char *store = _var_get_store(out, base);
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, _op_get_register(1, _var_size(base)));
vect_push_string(&out->text, ", ");
vect_push_string(&out->text, store);
vect_push_string(&out->text, "; pre-mul mov\n");
if (mul->location == LOC_LITL) {
vect_push_string(&out->text, "\tmov rcx, ");
vect_push_free_string(&out->text, int_to_str(mul->offset));
vect_push_string(&out->text, "; literal load\n");
vect_push_string(&out->text, "\tmul ");
vect_push_free_string(&out->text, _op_get_register(3, _var_size(base)));
vect_push_string(&out->text, "; mul\n");
} else {
char *from = _var_get_from(out, base, mul);
vect_push_string(&out->text, "\tmul ");
vect_push_free_string(&out->text, from);
vect_push_string(&out->text, "; mul\n");
}
// move back after mul
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, _op_get_register(1, _var_size(base)));
vect_push_string(&out->text, "; post-mul mov\n");
}
}
// Divides "base" by "div" and sets "base" to the result
void var_op_div(CompData *out, Variable *base, Variable *div) {
if(base->location == LOC_LITL) {
if (div->location == LOC_LITL)
base->offset /= div->offset;
return;
}
// zero out rdx before divide
vect_push_string(&out->text, "\txor rdx, rdx ; Clear rdx for divide\n");
char *div_by;
if (base->type->name[0] == 'i') {
// mov into rax
char *store = _var_get_store(out, base);
switch(_var_size(base)) {
case 4:
vect_push_string(&out->text, "\tmovsxd rax, ");
break;
case 8:
vect_push_string(&out->text, "\tmov rax, ");
break;
default:
vect_push_string(&out->text, "\tmovsx rax, ");
break;
}
vect_push_free_string(&out->text, store);
vect_push_string(&out->text, "; initial mov\n\n");
// Calculate div_by
if(_var_size(base) > _var_size(div) && div->location == LOC_LITL) {
vect_push_string(&out->text, "\tmov rcx, ");
vect_push_free_string(&out->text, int_to_str(div->offset));
vect_push_string(&out->text, "\n");
div_by = _op_get_register(3, _var_size(base));
} else {
div_by = _var_get_from(out, base, div);
}
// Do div
vect_push_string(&out->text, "\tidiv ");
vect_push_free_string(&out->text, div_by);
vect_push_string(&out->text, "; div\n");
} else {
// mov into rax
char *store = _var_get_store(out, base);
switch(_var_size(base)) {
case 4:
vect_push_string(&out->text, "\tmov eax, ");
break;
case 8:
vect_push_string(&out->text, "\tmov rax, ");
break;
default:
vect_push_string(&out->text, "\tmovzx rax, ");
}
vect_push_free_string(&out->text, store);
vect_push_string(&out->text, "; initial mov\n\n");
// Calculate div by
if(_var_size(base) > _var_size(div) && div->location == LOC_LITL) {
vect_push_string(&out->text, "\tmov rcx, ");
vect_push_free_string(&out->text, int_to_str(div->offset));
vect_push_string(&out->text, "\n");
div_by = _op_get_register(3, _var_size(base));
} else {
div_by = _var_get_from(out, base, div);
}
// Do div
vect_push_string(&out->text, "\tdiv ");
vect_push_free_string(&out->text, div_by);
vect_push_string(&out->text, "; div\n");
}
// Mov back to base
char *store = _var_get_store(out, base);
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, _op_get_register(1, _var_size(base)));
vect_push_string(&out->text, "; final mov for div\n\n");
}
// Divides "base" by "mod" and sets "base" to the remainder
void var_op_mod(CompData *out, Variable *base, Variable *mod) {
if(base->location == LOC_LITL) {
if (mod->location == LOC_LITL)
base->offset %= mod->offset;
return;
}
// zero out rdx before divide
vect_push_string(&out->text, "\txor rdx, rdx ; Clear rdx for divide\n");
char *div_by;
if (base->type->name[0] == 'i') {
// mov into rax
char *store = _var_get_store(out, base);
switch(_var_size(base)) {
case 4:
vect_push_string(&out->text, "\tmovsxd rax, ");
break;
case 8:
vect_push_string(&out->text, "\tmov rax, ");
break;
default:
vect_push_string(&out->text, "\tmovsx rax, ");
break;
}
vect_push_free_string(&out->text, store);
vect_push_string(&out->text, "; initial mov\n\n");
// Calculate div_by
if(_var_size(base) > _var_size(mod) && mod->location == LOC_LITL) {
vect_push_string(&out->text, "\tmov rcx, ");
vect_push_free_string(&out->text, int_to_str(mod->offset));
vect_push_string(&out->text, "\n");
div_by = _op_get_register(3, _var_size(base));
} else {
div_by = _var_get_from(out, base, mod);
}
// Do div
vect_push_string(&out->text, "\tidiv ");
vect_push_free_string(&out->text, div_by);
vect_push_string(&out->text, "; div\n");
} else {
// mov into rax
char *store = _var_get_store(out, base);
switch(_var_size(base)) {
case 4:
vect_push_string(&out->text, "\tmov eax, ");
break;
case 8:
vect_push_string(&out->text, "\tmov rax, ");
break;
default:
vect_push_string(&out->text, "\tmovzx rax, ");
}
vect_push_free_string(&out->text, store);
vect_push_string(&out->text, "; initial mov\n\n");
// Calculate div by
if(_var_size(base) > _var_size(mod) && mod->location == LOC_LITL) {
vect_push_string(&out->text, "\tmov rcx, ");
vect_push_free_string(&out->text, int_to_str(mod->offset));
vect_push_string(&out->text, "\n");
div_by = _op_get_register(3, _var_size(base));
} else {
div_by = _var_get_from(out, base, mod);
}
// Do div
vect_push_string(&out->text, "\tdiv ");
vect_push_free_string(&out->text, div_by);
vect_push_string(&out->text, "; div\n");
}
// Mov back to base
char *store = _var_get_store(out, base);
vect_push_string(&out->text, "\tmov ");
vect_push_free_string(&out->text, store);
vect_push_string(&out->text, ", ");
vect_push_free_string(&out->text, _op_get_register(4, _var_size(base)));
vect_push_string(&out->text, "; final mov for mod\n\n");
}
// Functions
Function func_init(char *name, Module *module) {
Function out = {0};
Vector name_cpy = vect_from_string(name);
out.name = vect_as_string(&name_cpy);
out.module = module;
out.inputs = vect_init(sizeof(Variable));
out.outputs = vect_init(sizeof(Variable));
return out;
}
void func_end(Function *func) {
free(func->name);
func->module = NULL;
for(size_t i = 0; i < func->inputs.count; i++) {
Variable *to_end = vect_get(&(func->inputs), i);
var_end(to_end);
}
vect_end(&(func->inputs));
for(size_t i = 0; i < func->outputs.count; i++) {
Variable *to_end = vect_get(&(func->outputs), i);
var_end(to_end);
}
vect_end(&(func->outputs));
}
// Modules
Module mod_init(char *name, Module *parent, bool export) {
Module out = {0};
Vector name_cpy = vect_from_string(name);
out.name = vect_as_string(&name_cpy);
out.parent = parent;
out.exported = export;
out.types = vect_init(sizeof(Type));
out.vars = vect_init(sizeof(Variable));
out.funcs = vect_init(sizeof(Function));
out.submods = vect_init(sizeof(Module));
return out;
}
#define FT_VAR 0
#define FT_FUN 1
#define FT_TYP 2
void *mod_find_rec(Module *mod, Artifact *art, size_t sub, int find_type) {
// Not at end of art, need to go deeper
if (sub + 1 < art->count) {
char **to_check = vect_get(art, sub);
Vector e_check = vect_from_string("@@"); // In case it is a variable inside an enum
Vector t_check = vect_from_string("_#"); // In case it is a function inside a method block
vect_push_string(&e_check, *to_check);
vect_as_string(&e_check);
vect_push_string(&t_check, *to_check);
vect_as_string(&t_check);
void *out = NULL;
for (size_t i = 0; i < mod->submods.count; i++) {
Module *m = vect_get(&(mod->submods), i);
if (
strcmp(m->name, *to_check) == 0 ||
strcmp(m->name, e_check.data) == 0 ||
strcmp(m->name, t_check.data) == 0
) {
out = mod_find_rec(m, art, sub + 1, find_type);
break;
}
}
vect_end(&e_check);
vect_end(&t_check);
if (out != NULL)
return out;
} else if (art->count > 0) {
Vector *search = NULL;
char **to_check = vect_get(art, art->count - 1);
switch(find_type) {
case FT_VAR:
search = &(mod->vars);
break;
case FT_FUN:
search = &(mod->funcs);
break;
case FT_TYP:
search = &(mod->types);
break;
default:
printf("FATAL: Compiler error, mod_find_rec called with find_type value %d\n", find_type);
return NULL;
}
for (size_t i = 0; i < search->count; i++) {
void *e = vect_get(search, i);
if (find_type == FT_VAR && strcmp(((Variable *)e)->name, *to_check) == 0) {
return e;
} else if (find_type == FT_FUN && strcmp(((Function *)e)->name, *to_check) == 0) {
return e;
} else if (find_type == FT_TYP && strcmp(((Type *)e)->name, *to_check) == 0) {
return e;
}
}
}
if (mod->parent == NULL || sub > 0)
return NULL;
return mod_find_rec(mod->parent, art, 0, find_type);
}
Type *mod_find_type(Module *mod, Artifact *art) {
Type *out = NULL;
if (art->count == 1) {
char ** name = vect_get(art, 0);
out = typ_get_inbuilt(*name);
}
if (out == NULL)
out = mod_find_rec(mod, art, 0, FT_TYP);
return out;
}
Function *mod_find_func(Module *mod, Artifact *art) {
return mod_find_rec(mod, art, 0, FT_FUN);
}
Variable *mod_find_var(Module *mod, Artifact *art) {
return mod_find_rec(mod, art, 0, FT_VAR);
}
Module *mod_find_sub(Module *mod, char *chk) {
for(size_t i = 0; i < mod->submods.count; i++) {
Module *m = vect_get(&mod->submods, i);
if(strcmp(m->name, chk) == 0)
return m;
}
return NULL;
}
void mod_full_path_rec(Module *m, Vector *v) {
if(m->parent != NULL)
mod_full_path_rec(m->parent, v);
char dot = '.';
if(v->count > 0)
vect_push(v, &dot);
vect_push_string(v, m->name);
}
char *mod_full_path(Module *m) {
Vector out = vect_init(sizeof(char));
mod_full_path_rec(m, &out);
return vect_as_string(&out);
}
Vector _mod_label_prefix(Module *m) {
if (m == NULL) {
Vector out = vect_from_string("");
return out;
}
Vector out = _mod_label_prefix(m->parent);
vect_push_string(&out, m->name);
if (out.count > 0) {
vect_push_string(&out, ".");
}
return out;
}
char *mod_label_prefix(Module *m) {
Vector out = _mod_label_prefix(m);
return vect_as_string(&out);
}
// Recursive end of all modules. To be called at the end
// of the compilation on the root module. Cleans everything
// in the modules except for the tokenizations.
void mod_deep_end(Module *mod) {
free(mod->name);
for(size_t i = 0; i < mod->vars.count; i++) {
Variable *v = vect_get(&(mod->vars), i);
var_end(v);
}
for(size_t i = 0; i < mod->funcs.count; i++) {
Function *f = vect_get(&(mod->funcs), i);
func_end(f);
}
for(size_t i = 0; i < mod->submods.count; i++) {
Module *m = vect_get(&(mod->submods), i);
mod_deep_end(m);
}
for(size_t i = 0; i < mod->types.count; i++) {
Type *t = vect_get(&(mod->types), i);
typ_end(t);
}
vect_end(&(mod->vars));
vect_end(&(mod->funcs));
vect_end(&(mod->submods));
vect_end(&(mod->types));
}
// Tokenizer
typedef struct {
char *data;
int line, col;
int type;
} Token;
bool tok_str_eq(Token *tok, const char *cmp) {
if (tok == NULL)
return false;
return strcmp(tok->data, cmp) == 0;
}
bool tok_eq(Token *a, Token *b) {
return strcmp(a->data, b->data) == 0 && a->type == b->type;
}
#define TT_DEFWORD 0
#define TT_KEYWORD 1
#define TT_KEYTYPE 2
#define TT_LITERAL 3
#define TT_AUGMENT 4
#define TT_DELIMIT 5
#define TT_SPLITTR 6
char *KEYWORDS = "module,export,asm,if,else,loop,label,goto,continue,break,return,import,as,using,struct,method,interface,enum,implements,operator,is";
char *KEYTYPES = "uint8,uint16,uint32,uint64,uint,int8,int16,int32,int64,int,float32,float64,float,comp64,comp,bool,vect,void,type";
char *LITERALS = "false,true";
char *RESERVED = "~`!@#$%^&*()[]{}+-=\"\'\\|:;/?>.<,";
char *OPS = "~`!%&|^*/+-=.<>@";
char *MULTI_OPS = "==,&&,||,^^,!==,!&&,!||,!^^,!<,!>,<<,>>,!&,!|,!^,++,--,>==,<==,+=,-=,*=,/=,%=,!=,&=,|=,^=,~=,`=,len";
char *DELIMS = "()[]{}";
char *MULTI_DELIMS = ";:#";
bool in_csv(char *csv, char *match) {
int along = 0;
for (int i = 0; csv[i] != 0; i++) {
if (csv[i] == ',') {
if(along >= 0 && match[along] == 0)
return true;
along = 0;
} else if (along >= 0 && match[along] == csv[i]) {
along++;
} else {
along = -1;
}
}
return along >= 0 && match[along] == 0;
}
bool is_reserved(char c) {
return strchr(RESERVED, c) != NULL;
}
bool is_delim(char *data) {
int l = strlen(data);
if (l == 1 && strchr(DELIMS, data[0]) != NULL)
return true;
else if (l == 2) {
if (strchr(MULTI_DELIMS, data[0]) != NULL)
return (data[1] == data[0] && data[0] != '#') || data[1] == '/';
else if (strchr(MULTI_DELIMS, data[1]) != NULL)
return (data[0] == '/');
}
return false;
}
int token_type(char*data) {
int l = strlen(data);
// Invalid token
if (l < 1)
return -1;
if (is_delim(data))
return TT_DELIMIT;
else if (is_reserved(data[0]) && l == 1) {
if (strchr(OPS, data[0]) != NULL)
return TT_AUGMENT;
else if (data[0] == ',' || data[0] == ';' || data[0] == ':')
return TT_SPLITTR;
} else if (in_csv(MULTI_OPS, data)) {
return TT_AUGMENT;
} else if (in_csv(KEYTYPES, data)) {
return TT_KEYTYPE;
} else if (in_csv(KEYWORDS, data)) {
return TT_KEYWORD;
} else if (in_csv(LITERALS, data)){
return TT_LITERAL;
}
return TT_DEFWORD;
}
Token parse_string_literal(int *ch, int *line, int *col, FILE *fin) {
char first = *ch;
Vector str = vect_init(sizeof(char));
vect_push(&str, &first);
Token out = {0};
out.line = *line;
out.col = *col;
out.type = TT_LITERAL;
*ch = fgetc(fin);
*col += 1;
char add = 0;
while (*ch != first && *ch != EOF) {
add = *ch;
if (*ch == '\\') {
vect_push(&str, &add);
*ch = fgetc(fin);
*col += 1;
if (*ch != EOF) {
if (*ch == '\n') {
*line += 1;
*col = 1;
}
add = *ch;
vect_push(&str, &add);
*ch = fgetc(fin);
*col += 1;
}
} else {
if (*ch == '\n') {
*line += 1;
*col = 1;
}
vect_push(&str, &add);
*ch = fgetc(fin);
*col += 1;
}
}
vect_push(&str, &first);
if (*ch == first)
*ch = fgetc(fin);
out.data = vect_as_string(&str);
return out;
}
Token parse_numeric_literal(int *next, int *line, int *col, FILE *fin) {
Token out = {0};
out.col = *col;
out.line = *line;
out.type = TT_LITERAL;
Vector num = vect_init(sizeof(char));
char ch = *next;
vect_push(&num, &ch);
bool dec = false;
while (*next != EOF) {
*next = fgetc(fin);
*col += 1;
if (*next == '.' && dec) {
break;
} else if (*next == '.') {
dec = true;
}
if (*next < '0' || *next > '9') {
break;
} else {
ch = *next;
vect_push(&num, &ch);
}
}
out.data = vect_as_string(&num);
return out;
}
void parse_reserved_tokens(int *next, Vector *out, int *line, int *col, FILE *fin) {
Token tmp = {0};
tmp.col = *col;
tmp.line = *line;
Vector res = vect_init(sizeof(char));
char add = *next;
vect_push(&res, &add);
*next = fgetc(fin);
*col += 1;
while (*next != EOF) {
add = *next;
if (!is_reserved(add) || add == '"' || add == '\'') {
break;
}
vect_push(&res, &add);
int after = token_type(vect_as_string(&res));
if (after == TT_DEFWORD) {
vect_pop(&res);
tmp.data = vect_as_string(&res);
tmp.type = token_type(tmp.data);
vect_push(out, &tmp);
res = vect_init(sizeof(char));
vect_push(&res, &add);
tmp.col = *col;
}
*next = fgetc(fin);
*col += 1;
}
if (res.count > 0) {
tmp.data = vect_as_string(&res);
tmp.type = token_type(tmp.data);
vect_push(out, &tmp);
}
}
Token parse_word_token(int *next, int *line, int *col, FILE *fin) {
Token out = {0};
out.line = *line;
out.col = *col;
Vector str = vect_init(sizeof(char));
char add = *next;
while (*next != EOF) {
if (isspace(*next) != 0 || is_reserved(add)) {
break;
} else {
vect_push(&str, &add);
}
*next = fgetc(fin);
add = *next;
*col += 1;
}
out.data = vect_as_string(&str);
out.type = token_type(out.data);
return out;
}
void parse_nl_token(Vector *out, int *line, int *col) {
Token add = {0};
add.col = *col;
add.line = *line;
add.type = TT_SPLITTR;
add.data = malloc(sizeof(char) * 2);
add.data[0] = '\n';
add.data[1] = 0;
vect_push(out, &add);
*col = 1;
*line += 1;
}
void parse_comment(int *ch, FILE *fin) {
while(*ch != '\n' && *ch != EOF) {
*ch = fgetc(fin);
}
}
Vector parse_file(FILE *fin) {
Vector out = vect_init(sizeof(Token));
int line = 1, col = 1;
int check = fgetc(fin);
Token add = {0};
while (check != EOF) {
add.type = -1;
if (isspace(check) && check != '\n') {
check = fgetc(fin);
col++;
} else if (check == '#') {
parse_comment(&check, fin);
} else if (check == '\"' || check == '\'') {
add = parse_string_literal(&check, &line, &col, fin);
} else if (check >= '0' && check <= '9') {
add = parse_numeric_literal(&check, &line, &col, fin);
} else if (is_reserved(check)) {
parse_reserved_tokens(&check, &out, &line, &col, fin);
} else if(check != '\n') {
add = parse_word_token(&check, &line, &col, fin);
}
if (add.type >= 0)
vect_push(&out, &add);
if (check == '\n') {
parse_nl_token(&out, &line, &col);
check = fgetc(fin);
}
}
return out;
}
// Compiler funcs
#define BT_FUNCTION 0
#define BT_METHOD 1
#define BT_OPERATOR 2
#define BT_INTERFACE 3
#define BT_MODULE 4
#define BT_CONTROL 5
#define BT_ENUM 6
#define BT_LAMBDA 7
unsigned long tnsl_parse_binary(char *data) {
unsigned long out = 0;
for(size_t i = 2; data[i] != 0; i++) {
if (data[i] != '0' && data[i] != '1') {
return out;
}
out = out << 1;
if(data[i] == 1)
out++;
}
return out;
}
unsigned long tnsl_parse_octal(char *data) {
unsigned long out = 0;
for(size_t i = 2; data[i] != 0; i++) {
if (data[i] < '0' || data[i] > '7') {
return out;
}
out = out << 3;
out += (data[i] - '0');
}
return out;
}
unsigned long tnsl_parse_decimal(char *data) {
unsigned long out = 0;
for(size_t i = 0; data[i] != 0; i++) {
if (data[i] < '0' || data[i] > '9')
return out;
out = out * 10;
out += (data[i] - '0');
}
return out;
}
unsigned long tnsl_parse_hex(char *data) {
unsigned long out = 0;
for(size_t i = 2; data[i] != 0; i++) {
char tmp = data[i];
if (tmp >= 'a') {
tmp -= ('a' - 10);
} else if (tmp >= 'A') {
tmp -= ('A' - 10);
} else if (tmp > '0') {
tmp -= '0';
}
if (tmp > 15) {
return out;
}
out = out << 4;
out += tmp;
}
return out;
}
unsigned long tnsl_parse_number (Token *numeric_literal) {
int l = strlen(numeric_literal->data);
if (l > 2 && numeric_literal->data[0] == '0' && numeric_literal->data[1] > '9') {
switch (numeric_literal->data[1]) {
case 'B':
case 'b':
return tnsl_parse_binary(numeric_literal->data);
case 'O':
case 'o':
return tnsl_parse_octal(numeric_literal->data);
case 'X':
case 'x':
return tnsl_parse_hex(numeric_literal->data);
default:
printf("ERROR: Unknown prefix for number (0%c) at %d:%d\n\n", numeric_literal->data[1], numeric_literal->line, numeric_literal->col);
return 0;
}
}
return tnsl_parse_decimal(numeric_literal->data);
}
Token *tnsl_find_last_token(Vector *tokens, size_t pos) {
if (pos >= tokens->count && tokens->count > 0)
return vect_get(tokens, tokens->count - 1);
else if (tokens->count > 0)
return vect_get(tokens, pos);
return NULL;
}
int tnsl_next_non_nl(Vector *tokens, size_t pos) {
Token *t = vect_get(tokens, ++pos);
while (t != NULL && tok_str_eq(t, "\n")) {
t = vect_get(tokens, ++pos);
}
return pos;
}
// Returns a variable which can be constructed into
// a type.
// name = fully qualified type name
// location = next token after type
// ptr_chain = full pointer chain of the type
Variable tnsl_parse_type(Vector *tokens, size_t cur) {
Vector ftn = vect_init(sizeof(char));
Vector ptr = vect_init(sizeof(int));
Variable err = {0};
err.name = NULL;
err.location = LOC_LITL;
err.offset = 0;
err.type = NULL;
int add = 0;
// Pre loop
for (; cur < tokens->count; cur++) {
Token *t = vect_get(tokens, cur);
if (t == NULL) {
vect_end(&ftn);
vect_end(&ptr);
return err;
} else if (t->type == TT_KEYTYPE || t->type == TT_DEFWORD) {
break;
} else if (t->type == TT_AUGMENT) {
if (tok_str_eq(t, "~")) {
add = PTYPE_PTR;
vect_push(&ptr, &add);
} else {
vect_end(&ftn);
vect_end(&ptr);
return err;
}
} else if (t->type == TT_DELIMIT) {
if (tok_str_eq(t, "{")) {
cur++;
t = vect_get(tokens, cur);
if (t->type == TT_DELIMIT && tok_str_eq(t, "}")) {
add = PTYPE_ARR;
} else if (t->type == TT_LITERAL && t->data[0] >= '0' && t->data[0] <= '9') {
// This functionality is not well implemented yet, but it is supposed to
// represent a fixed-size array
add = tnsl_parse_number(t);
vect_push(&ptr, &add);
cur++;
t = vect_get(tokens, cur);
if (t->type != TT_DELIMIT || !tok_str_eq(t, "}")) {
vect_end(&ftn);
vect_end(&ptr);
return err;
}
}
vect_push(&ptr, &add);
} else {
vect_end(&ftn);
vect_end(&ptr);
return err;
}
} else {
vect_end(&ftn);
vect_end(&ptr);
return err;
}
}
// Get the full type name (ftn)
// includes the parent module names if
// dot delineation is used.
Token *t = vect_get(tokens, cur);
if(t == NULL) {
vect_end(&ftn);
vect_end(&ptr);
return err;
} else if (t->type == TT_KEYTYPE) {
vect_push_string(&ftn, t->data);
cur++;
} else if (t->type == TT_DEFWORD) {
for(; cur < tokens->count; cur++) {
t = vect_get(tokens, cur);
if (t != NULL && t->type == TT_DEFWORD) {
vect_push_string(&ftn, t->data);
} else {
vect_end(&ftn);
vect_end(&ptr);
return err;
}
cur++;
t = vect_get(tokens, cur);
if (t != NULL && t->type == TT_AUGMENT && tok_str_eq(t, ".")) {
vect_push_string(&ftn, t->data);
} else {
break;
}
}
}
t = vect_get(tokens, cur);
if (t != NULL && tok_str_eq(t, "`")) {
add = PTYPE_REF;
vect_push(&ptr, &add);
cur++;
}
Variable out = {0};
out.name = vect_as_string(&ftn);
out.type = NULL;
out.location = cur;
out.ptr_chain = ptr;
return out;
}
bool tnsl_is_def(Vector *tokens, size_t cur) {
Variable to_free = tnsl_parse_type(tokens, cur);
if (to_free.name == NULL) {
return false;
}
free(to_free.name);
vect_end(&(to_free.ptr_chain));
Token *next = vect_get(tokens, to_free.location);
if (next != NULL && next->type == TT_DEFWORD) {
return true;
}
return false;
}
bool tnsl_is_boolean() {
return false;
}
int tnsl_find_closing(Vector *tokens, size_t cur) {
char closing = 0;
Token *first = vect_get(tokens, cur);
Token *check;
if (tok_str_eq(first, "(")) {
closing = ')';
} else if (tok_str_eq(first, "[")) {
closing = ']';
} else if (tok_str_eq(first, "{")) {
closing = '}';
} else if (tok_str_eq(first, "/;") || tok_str_eq(first, ";;")) {
closing = ';';
} else {
return -1;
}
cur += 1;
int paren = 0, brak = 0, squig = 0, block = 0;
for(; cur < tokens->count; cur++) {
check = vect_get(tokens, cur);
if (check->type == TT_DELIMIT) {
if (check->data[0] == closing && paren == 0 && brak == 0 && squig == 0 && block == 0) {
return cur;
}
switch (check->data[0]) {
case '(':
paren += 1;
break;
case '[':
brak += 1;
break;
case '{':
squig += 1;
break;
case ')':
paren -= 1;
break;
case ']':
brak -= 1;
break;
case '}':
squig -= 1;
break;
}
if (tok_str_eq(check, "/;"))
block += 1;
else if (tok_str_eq(check, ";/"))
block -= 1;
if (paren < 0 || brak < 0 || squig < 0 || block < 0) {
printf("Unmatched closing delimiter at {line %d, col %d, \"%s\"}\n", check->line, check->col, check->data);
printf("Looking for closing delimiter for {line %d, col %d, \"%s\"}\n\n", first->line, first->col, first->data);
return -1;
}
}
}
printf("Could not find closing for delimiter (line %d, col %d, \"%s\")\n\n", first->line, first->col, first->data);
return -1;
}
Vector tnsl_find_all_pointers(Vector *tokens, size_t start, size_t end) {
Vector out = vect_init(sizeof(char*));
for(start++;start < end; start++) {
Token *cur = vect_get(tokens, start);
if (tok_str_eq(cur, "~")) {
start++;
cur = vect_get(tokens, start);
if(cur->type == TT_DEFWORD) {
Vector data = vect_from_string(cur->data);
char *str = vect_as_string(&data);
vect_push(&out, &str);
}
}
}
return out;
}
char tnsl_unquote_char(char *str) {
if(str == NULL)
return 0;
if(*str == '\\') {
switch(str[1]) {
case '\\':
return '\\';
case '\'':
return '\'';
case '"':
return '"';
case 'n':
return '\n';
case 'r':
return '\r';
case '0':
return 0;
case 't':
return '\t';
}
}
return str[0];
}
Vector tnsl_unquote_str(char *literal) {
int len = strlen(literal);
Vector str_out = vect_init(sizeof(char));
if (len < 2)
return str_out;
char end = literal[0];
for(int i = 1; i < len; i++) {
if(literal[i] == end)
break;
else if (literal[i] == '\\') {
char tmp = tnsl_unquote_char(literal + i);
vect_push(&str_out, &tmp);
i++;
} else
vect_push(&str_out, literal + i);
}
return str_out;
}
int tnsl_block_type(Vector *tokens, size_t cur) {
for (cur++; cur < tokens->count; cur++) {
Token *t = vect_get(tokens, cur);
if (tok_str_eq(t, "\n")) {
return BT_LAMBDA;
} else if (t->type == TT_DEFWORD) {
return BT_FUNCTION;
} else if (t->type == TT_KEYWORD) {
if (tok_str_eq(t, "loop") || tok_str_eq(t, "if") || tok_str_eq(t, "else")) {
return BT_CONTROL;
} else if (tok_str_eq(t, "export") || tok_str_eq(t, "module")) {
return BT_MODULE;
} else if (tok_str_eq(t, "method")) {
return BT_METHOD;
} else if (tok_str_eq(t, "enum")) {
return BT_ENUM;
} else if (tok_str_eq(t, "operator")) {
printf("WARNING: Operator block not implemented (Found at %d:%d)\n\n", t->line, t->col);
return BT_OPERATOR;
} else if (tok_str_eq(t, "interface")) {
printf("WARNING: Interface block not implemented (Found at %d:%d)\n\n", t->line, t->col);
return BT_INTERFACE;
} else {
printf("ERROR: Invalid keyword when parsing block (%s at %d:%d)\n\n", t->data, t->line, t->col);
return -1;
}
} else if (t->type == TT_DELIMIT) {
int next = tnsl_find_closing(tokens, cur);
if (next < 0)
return -1;
cur = next;
}
}
return -1;
}
// Phase 1 - Module building
bool p1_error = false;
void p1_parse_params(Vector *var_list, Vector *tokens, size_t *pos) {
int end = tnsl_find_closing(tokens, *pos);
Token *t = vect_get(tokens, *pos);
if (end < 0) {
printf("ERROR: Could not find closing when parsing parameter list \"%s\" (%d:%d)\n", t->data, t->line, t->col);
p1_error = true;
return;
}
Variable current_type = {0};
current_type.name = NULL;
current_type.type = NULL;
for(*pos = tnsl_next_non_nl(tokens, *pos); *pos < (size_t) end; *pos = tnsl_next_non_nl(tokens, *pos)) {
size_t next = tnsl_next_non_nl(tokens, *pos);
t = vect_get(tokens, tnsl_next_non_nl(tokens, *pos));
if(!tok_str_eq(t, ",") && next < (size_t) end) {
if(current_type.name != NULL) {
free(current_type.name);
vect_end(&(current_type.ptr_chain));
}
current_type = tnsl_parse_type(tokens, *pos);
if (current_type.location > 0)
*pos = tnsl_next_non_nl(tokens, current_type.location - 1);
}
t = vect_get(tokens, *pos);
if (current_type.name == NULL) {
printf("ERROR: Expected a valid type.\n");
printf(" \"%s\" line %d column %d\n\n", t->data, t->line, t->col);
p1_error = true;
break;
} else if (t->type != TT_DEFWORD) {
printf("ERROR: Unexpected token in member/parameter list (was looking for a user defined name)\n");
printf(" \"%s\" line %d column %d\n\n", t->data, t->line, t->col);
p1_error = true;
break;
}
// The name of the variable is "<User defined name> <Dot deliniated type string>"
// this is specifically so that types may be defined out of order, and will be
// cleaned up when p1_size_structs is called.
Variable member = var_copy(¤t_type);
member.location = -1;
Vector name_type = vect_from_string(t->data);
vect_push_string(&name_type, " ");
vect_push_string(&name_type, member.name);
free(member.name);
member.name = vect_as_string(&name_type);
// Add the member to the struct (the member's type will be resolved later)
vect_push(var_list, &member);
*pos = tnsl_next_non_nl(tokens, *pos);
t = vect_get(tokens, *pos);
if (*pos >= (size_t)end) {
break;
} else if (tok_str_eq(t, ",") != true) {
printf("ERROR: Unexpected token in member list (was looking for a comma to separate members)\n");
printf(" \"%s\" line %d column %d\n\n", t->data, t->line, t->col);
p1_error = true;
break;
}
}
if (current_type.name != NULL) {
free(current_type.name);
vect_end(&(current_type.ptr_chain));
}
*pos = end;
}
void p1_parse_type_list(Vector *var_list, Vector *tokens, size_t *pos) {
int end = tnsl_find_closing(tokens, *pos);
Token *t = vect_get(tokens, *pos);
if (end < 0) {
printf("ERROR: Could not find closing when parsing parameter list \"%s\" (%d:%d)\n", t->data, t->line, t->col);
p1_error = true;
return;
}
for(*pos += 1; *pos < (size_t) end;) {
Variable to_add = tnsl_parse_type(tokens, *pos);
if(to_add.location < 0) {
t = vect_get(tokens, *pos);
printf("ERROR: Could not parse type when in type list ~(%d:%d)\n", t->line, t->col);
p1_error = true;
break;
}
*pos = to_add.location;
to_add.location = -1;
vect_push(var_list, &to_add);
}
*pos = end;
}
void p1_parse_struct(Module *add, Vector *tokens, size_t *pos) {
Token *s = vect_get(tokens, *pos);
Token *t = vect_get(tokens, *pos + 1);
if (tok_str_eq(s, "struct") == false) {
printf("COMPILER ERROR: p1_parse_struct was called on a non-struct token. Aborting.\n\n");
p1_error = true;
return;
} else if (t == NULL || t->type != TT_DEFWORD) {
printf("ERROR: Expected a user defined name after 'struct' keyword %d:%d\n\n", s->line, s->col);
p1_error = true;
return;
}
Type to_add = typ_init(t->data, add);
*pos += 2;
int closing = tnsl_find_closing(tokens, *pos);
t = vect_get(tokens, *pos);
if(closing < 0 || tok_str_eq(t, "{") != true) {
printf("ERROR: Expected a member list (Types and member names enclosed with '{}') when defining struct.\n");
printf(" Place one after token \"%s\" line %d column %d\n\n", t->data, t->line, t->col);
p1_error = true;
typ_end(&to_add);
return;
}
p1_parse_params(&(to_add.members), tokens, pos);
vect_push(&(add->types), &to_add);
}
void p1_parse_def(Module *root, Vector *tokens, size_t *pos) {
Variable type = tnsl_parse_type(tokens, *pos);
*pos = type.location;
type.mod = root;
Token *t = vect_get(tokens, *pos);
if (t == NULL || t->type != TT_DEFWORD) {
printf("ERROR: p1_parse_def was called but did not find a defword after the type. (%d:%d)\n\n", t->line, t->col);
*pos -= 1;
return;
}
for(;*pos < tokens->count; *pos += 1) {
t = vect_get(tokens, *pos);
if (t == NULL || t->type != TT_DEFWORD) {
break;
}
Variable to_add = var_copy(&type);
free(to_add.name);
to_add.location = *pos;
Vector name = vect_from_string(t->data);
vect_push_string(&name, " ");
vect_push_string(&name, type.name);
to_add.name = vect_as_string(&name);
vect_push(&root->vars, &to_add);
*pos += 1;
t = vect_get(tokens, *pos);
if (tok_str_eq(t, "=")) {
for(*pos += 1; *pos < tokens->count; *pos += 1) {
t = vect_get(tokens, *pos);
if (tok_str_eq(t, ",")) {
break;
} else if(t->type == TT_SPLITTR) {
*pos -= 1;
break;
} else if (t->type == TT_DELIMIT) {
*pos = tnsl_find_closing(tokens, *pos);
}
}
} else if (tok_str_eq(t, ",")) {
continue;
} else {
break;
}
}
*pos -= 1;
var_end(&type);
}
void p1_parse_enum(Module *root, Vector *tokens, size_t *pos) {
int end = tnsl_find_closing(tokens, *pos);
Token *t = vect_get(tokens, *pos);
if (end < 0) {
printf("ERROR: Could not find closing for enum \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p1_error = true;
return;
}
*pos += 2;
t = vect_get(tokens, *pos);
if (t == NULL || t->type != TT_DEFWORD) {
t = tnsl_find_last_token(tokens, *pos);
printf("ERROR: Expected user defined name for enum \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
*pos = end;
return;
}
Vector name = vect_from_string("@@");
vect_push_string(&name, t->data);
Module out = mod_init(vect_as_string(&name), root, root->exported);
vect_end(&name);
*pos += 1;
t = vect_get(tokens, *pos);
if (t == NULL || !tok_str_eq(t, "[")) {
printf("ERROR: Expected a type after enum name (enclose the type in []) (%d:%d)\n\n", t->line, t->col);
p1_error = true;
vect_push(&root->submods, &out);
*pos = end;
return;
}
*pos += 1;
Variable e_type = tnsl_parse_type(tokens, *pos);
*pos = tnsl_next_non_nl(tokens, e_type.location); // Past the closing bracket
for (;*pos < (size_t)end; *pos = tnsl_next_non_nl(tokens, *pos)) {
t = vect_get(tokens, *pos);
if (t == NULL || t->type != TT_DEFWORD) {
printf("ERROR: Unexpected token in enum block (expected user defined name) (%d:%d)\n\n", t->line, t->col);
p1_error = true;
break;
}
Variable to_add = var_copy(&e_type);
free(to_add.name);
to_add.location = *pos;
Vector name = vect_from_string(t->data);
vect_push_string(&name, " ");
vect_push_string(&name, e_type.name);
to_add.name = vect_as_string(&name);
vect_push(&out.vars, &to_add);
*pos = tnsl_next_non_nl(tokens, *pos);
t = vect_get(tokens, *pos);
if (tok_str_eq(t, "=")) {
for(*pos = tnsl_next_non_nl(tokens, *pos); *pos < tokens->count; *pos = tnsl_next_non_nl(tokens, *pos)) {
t = vect_get(tokens, *pos);
if (tok_str_eq(t, ",")) {
break;
} else if(t->type == TT_SPLITTR) {
*pos -= 1;
break;
} else if (t->type == TT_DELIMIT) {
*pos = tnsl_find_closing(tokens, *pos);
}
}
} else if (tok_str_eq(t, ",") || *pos >= (size_t)end) {
continue;
} else {
printf("ERROR: Expected an assignment (= <value>) or a comma after user defined word in enum block \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p1_error = true;
break;
}
}
vect_push(&root->submods, &out);
var_end(&e_type);
*pos = end;
}
void p1_parse_function(Module *root, Vector *tokens, size_t *pos) {
int end = tnsl_find_closing(tokens, *pos);
if (end < 0)
return;
Function out = func_init("", root);
for (*pos += 1; *pos < (size_t)end; *pos += 1) {
Token *t = vect_get(tokens, *pos);
if(t->type == TT_DEFWORD) {
free(out.name);
Vector copy = vect_from_string(t->data);
out.name = vect_as_string(©);
for(size_t i = 0; i < root->funcs.count; i++) {
Function *chk = vect_get(&root->funcs, i);
if(strcmp(chk->name, out.name) == 0) {
printf("ERROR: Redefinition of function with name '%s' at (%d:%d)\n", out.name, t->line, t->col);
func_end(&out);
*pos = end;
return;
}
}
} else if (tok_str_eq(t, "(")) {
p1_parse_params(&(out.inputs), tokens, pos);
} else if (tok_str_eq(t, "[")) {
p1_parse_type_list(&(out.outputs), tokens, pos);
} else {
break;
}
}
vect_push(&(root->funcs), &out);
*pos = end;
}
void p1_parse_method(Module *root, Vector *tokens, size_t *pos) {
int end = tnsl_find_closing(tokens, *pos);
Token *t = vect_get(tokens, *pos);
if (end < 0) {
printf("ERROR: Could not find closing for block \"%s\" at (%d:%d)\n\n", t->data, t->line, t->col);
p1_error = true;
return;
}
*pos += 2;
t = vect_get(tokens, *pos);
if (t == NULL || t->type != TT_DEFWORD) {
printf("ERROR: Expected user defined type while parsing method block. \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p1_error = true;
*pos = end;
return;
}
Vector mod_name = vect_from_string("_#");
vect_push_string(&mod_name, t->data);
Module out = mod_init(vect_as_string(&mod_name), root, root->exported);
vect_end(&mod_name);
for (*pos += 1; *pos < end; *pos += 1) {
t = vect_get(tokens, *pos);
if (tok_str_eq(t, "/;") || tok_str_eq(t, ";;")) {
if (tnsl_block_type(tokens, *pos) == BT_FUNCTION) {
p1_parse_function(&out, tokens, pos);
}
t = vect_get(tokens, *pos);
if(tok_str_eq(t, ";;"))
*pos -= 1;
}
}
vect_push(&(root->submods), &out);
*pos = end;
}
void p1_file_loop(Artifact *path, Module *root, Vector *tokens, size_t start, size_t end);
void p1_parse_module(Artifact *path, Module *root, Vector *tokens, size_t *pos) {
int end = tnsl_find_closing(tokens, *pos);
Token *t = vect_get(tokens, *pos);
if (end < 0) {
t = tnsl_find_last_token(tokens, *pos);
printf("ERROR: Unable to find closing for module block \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
return;
}
*pos += 1;
t = vect_get(tokens, *pos);
bool export = false;
if (tok_str_eq(t, "export")) {
export = true;
*pos += 1;
}
*pos += 1;
t = vect_get(tokens, *pos);
if (t == NULL || t->type != TT_DEFWORD) {
t = tnsl_find_last_token(tokens, *pos - 1);
if (t != NULL) {
printf("ERROR: Expected user defined module name after token \"%s\" (%d:%d) %d\n\n", t->data, t->line, t->col, t->type);
}
p1_error = true;
*pos = end;
return;
}
char *name = t->data;
Module *out = NULL;
for(size_t i = 0; i < root->submods.count; i++) {
Module *chk = vect_get(&root->submods, i);
if (strcmp(chk->name, name) == 0) {
out = chk;
break;
}
}
if (out == NULL) {
Module tmp = mod_init(name, root, export);
p1_file_loop(path, &tmp, tokens, *pos, end);
vect_push(&(root->submods), &tmp);
} else {
p1_file_loop(path, out, tokens, *pos, end);
vect_push(&(root->submods), out);
}
*pos = end;
}
void p1_parse_file(Artifact *path, Module *root) {
char *full_path = art_to_str(path, '/');
FILE *fin = fopen(full_path, "r");
if (fin == NULL) {
printf("Unable to open file %s for reading.\n\n", full_path);
free(full_path);
return;
}
free(full_path);
Vector tokens = parse_file(fin);
fclose(fin);
p1_file_loop(path, root, &tokens, 0, tokens.count);
for (size_t i = 0; i < tokens.count; i++) {
Token *t = vect_get(&tokens, i);
free(t->data);
}
vect_end(&tokens);
}
void p1_file_loop(Artifact *path, Module *root, Vector *tokens, size_t start, size_t end) {
for(;start < end; start++) {
Token *t = vect_get(tokens, start);
if (t->type == TT_SPLITTR && tok_str_eq(t, ":")) {
t = vect_get(tokens, ++start);
if (t == NULL || !tok_str_eq(t, "import")) {
t = tnsl_find_last_token(tokens, start);
printf("ERROR: Comptime declarations are not implemented other than 'import' \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p1_error = true;
continue;
}
t = vect_get(tokens, ++start);
if(t != NULL && t->type == TT_LITERAL) {
// Process new path to follow using old path.
char *cpy = art_to_str(path, '/');
Artifact new_path = art_from_str(cpy, '/');
free(cpy);
// Pop off file name
art_pop_str(&new_path);
// Copy token data (something like "path/to/file.tnsl" including the quotes)
// This path is relative to the current file
Vector v = vect_from_string(t->data);
// Pop off last quote, replace with \0
vect_pop(&v);
vect_as_string(&v);
// Remove starting quote by indexing into data
Artifact addon = art_from_str((char *)v.data + 1, '/');
// No more need for copy string
vect_end(&v);
// Add relative path to current folder
art_add_art(&new_path, &addon);
// no more need for path relative to file
art_end(&addon);
p1_parse_file(&new_path, root);
// Cleanup last remaining artifact
art_end(&new_path);
}
} else if (t->type == TT_DELIMIT && (tok_str_eq(t, "/;") || tok_str_eq(t, ";;"))) {
size_t block_start = start;
switch(tnsl_block_type(tokens, start)) {
case BT_FUNCTION:
p1_parse_function(root, tokens, &start);
break;
case BT_MODULE:
p1_parse_module(path, root, tokens, &start);
break;
case BT_METHOD:
p1_parse_method(root, tokens, &start);
break;
case BT_ENUM:
p1_parse_enum(root, tokens, &start);
break;
case BT_CONTROL:
case BT_INTERFACE:
case BT_OPERATOR:
printf("ERROR: Block type not implemented \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p1_error = true;
break;
default:
printf("ERROR: Unknown block type \"%s\" at file root (%d:%d)\n\n", t->data, t->line, t->col);
p1_error = true;
break;
}
t = vect_get(tokens, start);
if (start == block_start) {
int chk = tnsl_find_closing(tokens, start);
if (chk < 0)
printf("ERROR: Could not find closing for \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
else
start = chk;
} else if (tok_str_eq(t, ";;")) {
start--;
}
} else if (t->type == TT_KEYWORD && tok_str_eq(t, "struct")) {
p1_parse_struct(root, tokens, &start);
} else if (tnsl_is_def(tokens, start)) {
p1_parse_def(root, tokens, &start);
}
}
}
void p1_size_type (Module *root, Type *t) {
if (t->size == -1)
return;
int sum = 0;
t->size = -1;
Vector tmp = vect_from_string("_#");
vect_push_string(&tmp, t->name);
t->module = mod_find_sub(root, vect_as_string(&tmp));
vect_end(&tmp);
for(size_t i = 0; i < t->members.count; i++) {
Variable *var = vect_get(&t->members, i);
char *n_end = strchr(var->name, ' ');
if (n_end == NULL) {
printf("COMPILER ERROR: Did not properly assure type %s had all members with both name and RTN (size_type)\n", t->name);
printf("\toffending member: %s\n", var->name);
p1_error = true;
sum = -2;
break;
}
*n_end = 0;
Vector name = vect_from_string(var->name);
Artifact rta = art_from_str(n_end + 1, '.');
free(var->name);
var->name = vect_as_string(&name);
var->offset = sum;
Type *mt = mod_find_type(root, &rta);
art_end(&rta);
if(mt == NULL) {
// Could not find type
char *rtn = art_to_str(&rta, '.');
printf("ERROR: Could not find type %s when parsing type %s.\n\n", rtn, t->name);
p1_error = true;
free(rtn);
break;
} else if (var->ptr_chain.count > 0) {
// Pointer to type, don't need to size
sum += 8;
var->type = mt;
continue;
} else if (mt->size == -1) {
// Cycle in type definition
printf("ERROR: Cyclical type definition %s -> %s\n\n", mt->name, t->name);
p1_error = true;
sum = -1;
break;
} else if (mt->size == 0 && mt->module != NULL) {
// Need to size this type as well
p1_size_type(mt->module, mt);
}
sum += mt->size;
var->type = mt;
}
t->size = sum;
}
void p1_resolve_func_types(Module *root, Function *func) {
bool method = root->name != NULL && strlen(root->name) > 1 && root->name[0] == '_' && root->name[1] == '#';
int reg = 1;
if (method)
reg = 2;
int stack_accum = 0;
for (size_t i = 0; i < func->outputs.count; i++) {
Variable *var = vect_get(&func->outputs, i);
Artifact rtn = art_from_str(var->name, '.');
Type *t = mod_find_type(root, &rtn);
if(t == NULL) {
char *rt = art_to_str(&rtn, '.');
printf("ERROR: Could not find type %s for function %s\n\n", rt, func->name);
free(rt);
art_end(&rtn);
break;
}
art_end(&rtn);
Vector name = vect_from_string(t->name);
free(var->name);
var->name = vect_as_string(&name);
var->type = t;
// Check where the output should be stored
if (
(
// is struct
!is_inbuilt(var->type->name)
&& // and not by reference
var->ptr_chain.count == 0
)
|| // or we are an array with predefined size (stack array)
_var_ptr_type(var) > 1
|| // or we ran out of registers
reg > 6
) {
// The output should be stored on the stack
var->location = LOC_STCK;
stack_accum += _var_pure_size(var);
var->offset = stack_accum;
} else {
// The output should be stored in a register
var->location = reg;
var->offset = 0;
reg++;
}
}
reg = 1;
if (method)
reg = 2;
// Stack accum not reset because the stack would get clobbered
for (size_t i = 0; i < func->inputs.count; i++) {
Variable *var = vect_get(&func->inputs, i);
char *n_end = strchr(var->name, ' ');
if (n_end == NULL) {
printf("COMPILER ERROR: Did not properly assure function %s had all parameters with both name and RTN (resolve_func_types)\n\n", func->name);
p1_error = true;
break;
}
Artifact rtn = art_from_str(n_end + 1, '.');
Type *t = mod_find_type(root, &rtn);
if(t == NULL) {
char *rt = art_to_str(&rtn, '.');
printf("ERROR: Could not find type %s for function %s\n\n", rt, func->name);
free(rt);
art_end(&rtn);
break;
}
art_end(&rtn);
*n_end = 0;
Vector name = vect_from_string(var->name);
free(var->name);
var->name = vect_as_string(&name);
var->type = t;
// Check where the input should be read from
if (
(
// is struct
!is_inbuilt(var->type->name)
&& // and not by reference
var->ptr_chain.count == 0
)
|| // or we are an array with predefined size (stack array)
_var_ptr_type(var) > 1
|| // or we ran out of registers
reg > 6
) {
// The output should be stored on the stack
var->location = LOC_STCK;
stack_accum += _var_pure_size(var);
var->offset = stack_accum;
} else {
// The output should be stored in a register
var->location = reg;
var->offset = 0;
reg++;
}
}
// Stack variables will be pushed on in reverse order for a call
// so we need to invert all the variable offsets
// we are adding 8 here because we assume a return pointer right where
// rbp is located
for(size_t i = 0; i < func->outputs.count; i++) {
Variable *var = vect_get(&func->outputs, i);
if(var->location == LOC_STCK)
var->offset = 8 + stack_accum - var->offset;
}
for(size_t i = 0; i < func->inputs.count; i++) {
Variable *var = vect_get(&func->inputs, i);
if(var->location == LOC_STCK)
var->offset = 8 + stack_accum - var->offset;
}
}
void p1_resolve_types(Module *root) {
for(size_t i = 0; i < root->types.count; i++) {
p1_size_type(root, vect_get(&root->types, i));
}
for(size_t i = 0; i < root->submods.count; i++) {
Module *s = vect_get(&root->submods, i);
s->parent = root;
p1_resolve_types(s);
}
for(size_t i = 0; i < root->funcs.count; i++) {
Function *f = vect_get(&root->funcs, i);
f->module = root;
p1_resolve_func_types(root, f);
// when created, the function was on the stack. Make sure it is not anymore
}
for (size_t i = 0; i < root->vars.count; i++) {
Variable *v = vect_get(&root->vars, i);
// when created, the module was on the stack. Make sure it is not anymore.
v->mod = root;
char *n_end = strchr(v->name, ' ');
if (n_end == NULL) {
printf("COMPILER ERROR: Not properly formatted variable name \"%s\"\n\n", v->name);
p1_error = true;
continue;
}
Artifact rtn = art_from_str(n_end + 1, '.');
*n_end = 0;
Vector name = vect_from_string("");
vect_push_free_string(&name, v->name);
v->name = vect_as_string(&name);
Type *t = mod_find_type(root, &rtn);
if (t == NULL) {
char *rts = art_to_str(&rtn, '.');
printf("ERROR: Could not find type \"%s\" for variable \"%s\"\n\n", rts, v->name);
free(rts);
art_end(&rtn);
p1_error = true;
continue;
}
art_end(&rtn);
v->type = t;
}
}
void phase_1(Artifact *path, Module *root) {
p1_parse_file(path, root);
p1_resolve_types(root);
}
// Phase 2
// Sub scopes
Scope scope_subscope(Scope *s, char *name) {
Vector n = vect_from_string(name);
vect_push_string(&n, "#");
vect_push_free_string(&n, int_to_str(s->next_const));
s->next_const++;
Scope out = scope_init(vect_as_string(&n), s->current);
out.parent = s;
vect_end(&n);
return out;
}
bool scope_name_eq(Scope *s, char *name) {
char *pound = strchr(s->name, '#');
*pound = 0;
bool test = strcmp(s->name, name) == 0;
*pound = '#';
return test;
}
// Scope variable creation and management
int _scope_next_stack_loc(Scope *s, int size) {
int sum = -56 - size;
if (s->parent != NULL)
sum = _scope_next_stack_loc(s->parent, size);
for (size_t i = 0; i < s->stack_vars.count; i++) {
Variable *v = vect_get(&s->stack_vars, i);
if (v->offset - size < sum) {
sum = v->offset - size;
}
}
return sum;
}
// Tmp reg masks
#define RMSK_B 0b001
#define RMSK_8 0b010
#define RMSK_9 0b100
// Main reg masks
#define RMSK_10 0b000001000
#define RMSK_11 0b000010000
#define RMSK_12 0b000100000
#define RMSK_13 0b001000000
#define RMSK_14 0b010000000
#define RMSK_15 0b100000000
// Generate a bitmask representing available registers
int _scope_avail_reg(Scope *s) {
int mask = 0b111111111;
if (s->parent != NULL) {
mask = _scope_avail_reg(s->parent);
}
for (size_t i = 0; i < s->reg_vars.count; i++) {
Variable *v = vect_get(&s->reg_vars, i);
int vmask = 0;
if (v->location == 2) {
vmask = RMSK_B;
} else if (v->location > 8) {
vmask = 1;
vmask = vmask << (v->location - 8);
}
mask &= ~vmask;
}
return mask;
}
// Creates a new tmp variable from an existing variable
// ALL TEMP VARIABLES SHOULD BE FREED BEFORE CREATING MORE
// PERSISTANT VARIABLES TO PREVENT STACK CLUTTER!!!!!!
Variable scope_mk_tmp(Scope *s, CompData *data, Variable *v) {
Variable out = var_copy(v);
while (_var_ptr_type(&out) == PTYPE_REF) {
vect_pop(&out.ptr_chain);
}
int p_typ = _var_ptr_type(v);
free(out.name);
Vector nm = vect_from_string("#tmp");
out.name = vect_as_string(&nm);
if ((is_inbuilt(v->type->name) && p_typ < 1) || p_typ == PTYPE_PTR || p_typ == PTYPE_PTR) {
int regs = _scope_avail_reg(s);
if (regs & 0b111) {
if (regs & RMSK_B) {
out.location = 2;
} else if (regs & RMSK_8) {
out.location = 9;
} else if (regs & RMSK_9) {
out.location = 10;
}
out.offset = 0;
var_op_set(data, &out, v);
vect_push(&s->reg_vars, &out);
return var_copy(&out);
}
}
int loc = _scope_next_stack_loc(s, _var_pure_size(v));
out.location = LOC_STCK;
out.offset = loc;
var_op_set(data, &out, v);
vect_push(&s->stack_vars, &out);
return var_copy(&out);
}
// Creates a new tmp variable from an existing variable
// ALL TEMP VARIABLES SHOULD BE FREED BEFORE CREATING MORE
// PERSISTANT VARIABLES TO PREVENT STACK CLUTTER!!!!!!
Variable scope_mk_pure_tmp(Scope *s, CompData *data, Variable *v) {
Variable out = var_copy(v);
int p_typ = _var_ptr_type(v);
free(out.name);
Vector nm = vect_from_string("#tmp");
out.name = vect_as_string(&nm);
if ((is_inbuilt(v->type->name) && p_typ < 1) || p_typ == PTYPE_PTR || p_typ == PTYPE_PTR) {
int regs = _scope_avail_reg(s);
if (regs & 0b111) {
if (regs & RMSK_B) {
out.location = 2;
} else if (regs & RMSK_8) {
out.location = 9;
} else if (regs & RMSK_9) {
out.location = 10;
}
out.offset = 0;
var_op_pure_set(data, &out, v);
vect_push(&s->reg_vars, &out);
return var_copy(&out);
}
}
int loc = _scope_next_stack_loc(s, _var_pure_size(v));
out.location = LOC_STCK;
out.offset = loc;
var_op_pure_set(data, &out, v);
vect_push(&s->stack_vars, &out);
return var_copy(&out);
}
// Create a new variable on the stack
// MAKE SURE ALL TMP STACK IS FREED BEFORE THIS IS DONE
Variable scope_mk_stack(Scope *s, CompData *data, Variable *v) {
Variable out = var_copy(v);
int loc = _scope_next_stack_loc(s, _var_pure_size(v));
out.location = LOC_STCK;
out.offset = loc;
vect_push_string(&data->text, "\tlea rsp, [rbp - ");
vect_push_free_string(&data->text, int_to_str(-loc));
vect_push_string(&data->text, "]; Stack variable\n");
vect_push(&s->stack_vars, &out);
return var_copy(&out);
}
// Checks if a variable is a tmp variable in the scope
bool scope_is_tmp(Variable *v) {
return strcmp(v->name, "#tmp") == 0;
}
void _scope_free_tmp_reg(Scope *s, Variable *v) {
for (size_t i = 0; i < s->reg_vars.count; i++) {
Variable *to_free = vect_get(&s->reg_vars, i);
if (to_free->location == v->location) {
var_end(to_free);
vect_remove(&s->reg_vars, i);
i--;
}
}
}
void _scope_free_stack_var(Scope *s, CompData *data, Variable *v) {
int new_top = -56;
int target_top = v->offset;
for (size_t i = 0; i < s->stack_vars.count; i++) {
Variable *to_free = vect_get(&s->stack_vars, i);
if(to_free->offset == target_top) {
var_end(to_free);
vect_remove(&s->stack_vars, i);
i--;
} else if (new_top > to_free->offset) {
new_top = to_free->offset;
}
}
if (new_top > target_top) {
// Restore rsp
vect_push_string(&data->text, "\tlea rsp, [rbp - ");
vect_push_free_string(&data->text, int_to_str(-new_top));
vect_push_string(&data->text, "]; Tmp variable removed\n");
}
}
// Free a tmp variable in the scope
void scope_free_tmp(Scope *s, CompData *data, Variable *v) {
if (v->location > 0) {
_scope_free_tmp_reg(s, v);
} else {
_scope_free_stack_var(s, data, v);
}
var_end(v);
}
void scope_free_to(Scope *s, CompData *data, Variable *v) {
bool freed = false;
for (size_t i = s->stack_vars.count; i > 0; i--) {
Variable *cur = vect_get(&s->stack_vars, i - 1);
if (cur->offset < v->offset || v->offset == 0) {
var_end(cur);
vect_pop(&s->stack_vars);
freed = true;
} else {
break;
}
}
if (freed || v->offset == 0) {
int next_loc = _scope_next_stack_loc(s, 0);
vect_push_string(&data->text, "\tlea rsp, [rbp - ");
vect_push_free_string(&data->text, int_to_str(-next_loc));
vect_push_string(&data->text, "]; Scope free to\n");
}
}
Variable scope_get_stack_pin(Scope *s) {
Variable out = {0};
out.offset = 0;
if (s->stack_vars.count > 0) {
Variable *last = vect_get(&s->stack_vars, s->stack_vars.count - 1);
out = var_copy(last);
}
return out;
}
void scope_free_all_tmp(Scope* s, CompData *data) {
for (size_t i = 0; i < s->reg_vars.count; i++) {
Variable *to_free = vect_get(&s->reg_vars, i);
if (to_free->location < RMSK_10) {
var_end(to_free);
vect_remove(&s->reg_vars, i);
i--;
}
}
int new_top = 0;
for (size_t i = 0; i < s->stack_vars.count; i++) {
Variable *to_free = vect_get(&s->stack_vars, i);
if(strcmp(to_free->name, "#tmp") == 0) {
var_end(to_free);
vect_remove(&s->stack_vars, i);
i--;
if (new_top == 0) {
new_top = -56;
}
} else if (new_top > to_free->offset) {
new_top = to_free->offset;
}
}
if (new_top > 0) {
// Restore rsp
vect_push_string(&data->text, "\tlea rsp, [rbp - ");
vect_push_free_string(&data->text, int_to_str(-new_top));
vect_push_string(&data->text, "]; All tmp free\n");
}
}
// Create a tmp variable specifically on the stack
Variable scope_mk_stmp(Scope *s, CompData *data, Variable *v)
{
Variable out = var_copy(v);
Vector name = vect_from_string("#tmp");
out.name = vect_as_string(&name);
int loc = _scope_next_stack_loc(s, _var_pure_size(v));
out.location = LOC_STCK;
out.offset = loc;
vect_push_string(&data->text, "\tlea rsp, [rbp - ");
vect_push_free_string(&data->text, int_to_str(-loc));
vect_push_string(&data->text, "]; Stack variable\n");
vect_push(&s->stack_vars, &out);
return var_copy(&out);
}
// Generate a new variable in the scope
Variable scope_mk_var(Scope *s, CompData *data, Variable *v) {
Variable out = var_copy(v);
int p_typ = _var_ptr_type(v);
if ((is_inbuilt(v->type->name) && p_typ < 1) || p_typ == PTYPE_PTR || p_typ == PTYPE_PTR) {
int regs = _scope_avail_reg(s);
if (regs > 0b111) {
if (regs & RMSK_10) {
out.location = 11;
} else if (regs & RMSK_11) {
out.location = 12;
} else if (regs & RMSK_12) {
out.location = 13;
} else if (regs & RMSK_13) {
out.location = 14;
} else if (regs & RMSK_14) {
out.location = 15;
} else if (regs & RMSK_15) {
out.location = 16;
}
out.offset = 0;
vect_push(&s->reg_vars, &out);
return var_copy(&out);
}
}
int loc = _scope_next_stack_loc(s, _var_pure_size(v));
out.location = LOC_STCK;
out.offset = loc;
vect_push_string(&data->text, "\tlea rsp, [rbp - ");
vect_push_free_string(&data->text, int_to_str(-loc));
vect_push_string(&data->text, "]; Stack variable\n");
vect_push(&s->stack_vars, &out);
return var_copy(&out);
}
Variable _scope_get_var(Scope *s, char *name) {
for (size_t i = 0; i < s->reg_vars.count; i++) {
Variable *v = vect_get(&s->reg_vars, i);
if (strcmp(v->name, name) == 0)
return var_copy(v);
}
for (size_t i = 0; i < s->stack_vars.count; i++) {
Variable *v = vect_get(&s->stack_vars, i);
if (strcmp(v->name, name) == 0)
return var_copy(v);
}
if (s->parent == NULL) {
Variable out = {0};
out.name = NULL;
return out;
}
return _scope_get_var(s->parent, name);
}
Variable scope_get_var(Scope *s, Artifact *name) {
Variable out = {0};
out.name = NULL;
if (name->count == 1) {
char *full = art_to_str(name, '.');
out = _scope_get_var(s, full);
free(full);
}
if (out.name != NULL)
return out;
Variable *mod_search = mod_find_var(s->current, name);
if (mod_search == NULL)
return out;
out = var_copy(mod_search);
out.location = 0;
out.offset = 0;
return out;
}
// TODO: Scope ops like sub-scoping, variable management
// conditional handling, data-section parts for function
// literals, etc.
bool p2_error = false;
/* Op order
* first is parens (not handled here)
*
* 0: `
* dereference
*
* 1: .
* get member or method
*
* 2: ~
* Get reference
*
* 3: ++ --
* Increment/decrement
*
* 4: len
* length of array or type
*
* 5: * / %
* Multiplication/division
*
* 6: + -
* Addition/subtraction
*
* 7: ! & | ^ << >> !& !| !^
* Bitwise operations (and boolean not)
*
* 8: == !== < > !< !> <== >==
* Boolean compare
*
* 9: && || ^^ !&& !|| !^^
* Boolean logic
*
* 10: = *= /= %= += -= etc.
* Assignment operators
*/
// TODO: Test
// returns the integer prescident of the operator (lower means first)
int op_order(Token *t) {
if (t == NULL || t->type != TT_AUGMENT) {
printf("COMPILER ERROR: op_order called on null or non-augment token ");
if (t == NULL)
printf("NULL\n\n");
else
printf(" \"%s\" (%d:%d)", t->data, t->line, t->col);
return -1;
}
int l = strlen(t->data);
if(l == 1) {
switch(t->data[0]) {
case '`':
return 0;
case '.':
return 1;
case '~':
return 2;
case '*':
case '/':
case '%':
return 5;
case '+':
case '-':
return 6;
case '!':
case '&':
case '|':
case '^':
return 7;
case '<':
case '>':
return 8;
case '=':
return 10;
}
} else if (l == 2) {
if(t->data[0] == t->data[1]) {
if (t->data[1] == '+' || t->data[1] == '-')
return 3;
if (t->data[0] == '<' || t->data[0] == '>')
return 7;
if (t->data[0] == '=')
return 8;
return 9;
}
if (t->data[1] == '<' || t->data[1] == '>')
return 8;
if (t->data[1] == '=')
return 10;
if (t->data[0] == '!')
return 7;
} else if (l == 3) {
if(tok_str_eq(t, "len"))
return 4;
if(t->data[1] == '=')
return 8;
return 9;
}
return -1;
}
Variable _eval(Scope *s, CompData *data, Vector *tokens, size_t start, size_t end);
Variable _eval_call(Scope *s, CompData *data, Vector *tokens, Function *f, Variable *self, size_t start) {
Variable out = {0};
out.name = NULL;
Variable pin = scope_get_stack_pin(s);
// First, load all stack-based outputs onto the stack
// and set the output
for (size_t i = 0; i < f->outputs.count; i++) {
Variable *cur = vect_get(&f->outputs, i);
if (cur->location == LOC_STCK) {
Variable store = scope_mk_stmp(s, data, cur);
if (i == 0) {
out = store;
} else {
var_end(&store);
}
} else if (i == 0) {
out = var_copy(cur);
}
}
// Second, evaluate all stack-based parameters
int max = tnsl_find_closing(tokens, start);
size_t pstart = start + 1;
size_t pend = start + 1;
for(size_t i = 0; i < f->inputs.count; i++) {
Variable *cur = vect_get(&f->inputs, i);
// preprocess, find end of current param
while (pend < max) {
Token *psep = vect_get(tokens, pend);
if (tok_str_eq(psep, ")") || tok_str_eq(psep, ",")) {
break;
} else if (psep->type == TT_DELIMIT) {
pend = tnsl_find_closing(tokens, pend);
}
pend++;
}
if (cur->location == LOC_STCK) {
// create tmp var
Variable set = scope_mk_stmp(s, data, cur);
Variable from = _eval(s, data, tokens, pstart, pend);
if (from.name == NULL) {
Token *p = vect_get(tokens, pstart);
printf("ERROR: Expected value for parameter \"%s\" in call to function \"%s\" (%d:%d)\n", cur->name, f->name, p->line, p->col);
p2_error = true;
i = f->inputs.count;
break;
}
// eval and set
if (_var_ptr_type(&set) == PTYPE_REF)
var_op_pure_set(data, &set, &from);
else
var_op_set(data, &set, &from);
scope_free_to(s, data, &set);
var_end(&from);
var_end(&set);
}
if (pend < max) {
pend = pend + 1;
pstart = pend;
}
}
// Third, evaluate all register based parameters
Vector inputs = vect_init(sizeof(Variable));
Variable inpin = scope_get_stack_pin(s);
// handle self for methods
if (self != NULL) {
Variable from = {0};
if (_var_ptr_type(self) == PTYPE_NONE) {
var_op_reference(data, &from, self);
} else
from = var_copy(self);
Variable set = scope_mk_stmp(s, data, &from);
var_op_pure_set(data, &set, &from);
var_end(&from);
vect_push(&inputs, &set);
}
pstart = start + 1;
pend = start + 1;
for(size_t i = 0; i < f->inputs.count; i++) {
Variable *cur = vect_get(&f->inputs, i);
// preprocess, find end of current param
while (pend < max) {
Token *psep = vect_get(tokens, pend);
if (tok_str_eq(psep, ")") || tok_str_eq(psep, ",")) {
break;
} else if (psep->type == TT_DELIMIT) {
pend = tnsl_find_closing(tokens, pend);
}
pend++;
}
if (cur->location > 0) {
// create tmp var
Variable set = scope_mk_stmp(s, data, cur);
// eval and set
Variable from = _eval(s, data, tokens, pstart, pend);
if (from.name == NULL) {
Token *p = vect_get(tokens, pstart);
printf("ERROR: Expected value for parameter \"%s\" in call to function \"%s\" (%d:%d)\n", cur->name, f->name, p->line, p->col);
p2_error = true;
i = f->inputs.count;
break;
}
if (_var_ptr_type(&set) == PTYPE_REF)
var_op_pure_set(data, &set, &from);
else
var_op_set(data, &set, &from);
// cleanup
scope_free_to(s, data, &set);
var_end(&from);
vect_push(&inputs, &set);
}
if (pend < max) {
pend = pend + 1;
pstart = pend;
}
}
// Fifth, move all register based parameters into their correct registers
for(size_t i = 0; i < inputs.count; i++) {
Variable *cur = vect_get(&inputs, i);
// create tmp var
Variable set = var_copy(cur);
set.location = i + 1;
// eval and set
var_op_pure_set(data, &set, cur);
// cleanup
var_end(cur);
}
vect_end(&inputs);
// set stack to where it needs to be for call
scope_free_to(s, data, &inpin);
if (inpin.name != NULL) {
var_end(&inpin);
}
// Sixth, make call
vect_push_string(&data->text, "\tcall ");
vect_push_free_string(&data->text, mod_label_prefix(f->module));
vect_push_string(&data->text, f->name);
vect_push_string(&data->text, "; Function call\n\n");
// Seventh, return output
scope_free_to(s, data, &pin);
if (out.name != NULL) {
var_end(&pin);
}
return out;
}
Variable _eval_dot(Scope *s, CompData *data, Vector *tokens, size_t start, size_t end) {
Token *t = vect_get(tokens, start);
Artifact name = art_from_str(t->data, '.');
if (start == end - 1) {
Variable v = scope_get_var(s, &name);
if (v.name == NULL) {
printf("ERROR: Failed to find singlet variable or call in dot chain \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
}
art_end(&name);
return v;
}
Variable v = scope_get_var(s, &name);
// Match with first possible variable
start = tnsl_next_non_nl(tokens, start);
for (; start < end; start = tnsl_next_non_nl(tokens, start)) {
// Try match variable
if (v.name != NULL) {
art_end(&name);
name = art_from_str("", '.');
break;
}
// Try expand artifact, or call
t = vect_get(tokens, start);
if (tok_str_eq(t, ".")) {
start++;
t = vect_get(tokens, start);
if (t->type != TT_DEFWORD) {
printf("ERROR: Expected defword after '.' operator but found \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
return v;
}
art_add_str(&name, t->data);
v = scope_get_var(s, &name);
} else if (tok_str_eq(t, "(")) {
// Call
break;
} else {
printf("ERROR: Failed to find variable or call in dot chain \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
return v;
}
}
for (; start < end; start = tnsl_next_non_nl(tokens, start)) {
t = vect_get(tokens, start);
// After found var, or in call. We need to check.
if (tok_str_eq(t, "(")) {
if (v.name == NULL) {
Function *f = mod_find_func(s->current, &name);
if (f == NULL) {
t = vect_get(tokens, start - 1);
printf("ERROR: Could not find function \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
art_end(&name);
return v;
}
v = _eval_call(s, data, tokens, f, NULL, start);
} else {
Function *m = mod_find_func(v.type->module, &name);
if (m == NULL) {
t = vect_get(tokens, start - 1);
printf("ERROR: Could not find function \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
art_end(&name);
return v;
}
Variable tmp = _eval_call(s, data, tokens, m, &v, start);
var_end(&v);
v = tmp;
}
art_end(&name);
start = tnsl_find_closing(tokens, start);
name = art_from_str("", '.');
} else if (tok_str_eq(t, "`")) {
Variable store;
var_op_dereference(data, &store, &v);
var_end(&v);
v = store;
} else if (tok_str_eq(t, ".")) {
Token *next = vect_get(tokens, start + 1);
if (next == NULL || next->type != TT_DEFWORD) {
printf("ERROR: Expected defword after dot in dotchain: \"%s\" (%d:%d)\n", t->data, t->line, t->col);
art_end(&name);
return v;
}
char *m_name = next->data;
next = vect_get(tokens, start + 2);
if (next == NULL || !tok_str_eq(next, "(")) {
Variable m = var_op_member(data, &v, m_name);
if (m.name == NULL) {
printf("ERROR: Unable to find member variable: \"%s\" of variable \"%s\" (%d:%d)\n", next->data, v.name, next->line, next->col);
art_end(&name);
return v;
}
var_end(&v);
v = m;
} else if (tok_str_eq(next, "(")) {
art_add_str(&name, m_name);
}
start++;
}
}
art_end(&name);
return v;
}
Variable _eval_literal(Scope *s, CompData *data, Vector *tokens, size_t literal) {
Variable out = var_init("#literal", NULL);
Token *t = vect_get(tokens, literal);
if (t->data[0] == '"') {
// handle str
Vector str_dat = tnsl_unquote_str(t->data);
char *label = scope_gen_const_label(s);
vect_push_string(&data->data, label);
vect_push_string(&data->data, "#ptr:\n\tdq ");
vect_push_free_string(&data->data, int_to_str(str_dat.count));
if (str_dat.count > 0)
vect_push_string(&data->data, "\n\tdb ");
for (size_t i = 0; i < str_dat.count; i++) {
char *ch = vect_get(&str_dat, i);
vect_push_free_string(&data->data, int_to_str(*ch));
if (i < str_dat.count - 1) {
vect_push_string(&data->data, ", ");
}
}
vect_push_string(&data->data, "\n");
vect_end(&str_dat);
var_end(&out);
vect_push_string(&data->data, label);
vect_push_string(&data->data, ":\n\tdq ");
vect_push_string(&data->data, label);
vect_push_string(&data->data, "#ptr\n\n");
out = var_init(label, typ_get_inbuilt("uint8"));
out.mod = NULL;
out.location = LOC_DATA;
free(label);
int arr_t = PTYPE_ARR;
vect_push(&out.ptr_chain, &arr_t);
} else if (tok_str_eq(t, "false") || tok_str_eq(t, "true")) {
out.type = typ_get_inbuilt("bool");
if (tok_str_eq(t, "true")) {
vect_push_string(&data->text, "\tmov rax, 1\n");
vect_push_string(&data->text, "\ttest rax, rax ; literal bool\n\n");
out.offset = 1;
} else {
vect_push_string(&data->text, "\tmov rax, 0\n");
vect_push_string(&data->text, "\ttest rax, rax ; literal bool\n\n");
out.offset = 0;
}
out.location = LOC_LITL;
} else {
out.location = LOC_LITL;
out.type = typ_get_inbuilt("int");
if (t->data[0] == '\'')
out.offset = tnsl_unquote_char(t->data + 1);
else
out.offset = tnsl_parse_number(t);
}
return out;
}
// Main implementation, recursive
Variable _eval(Scope *s, CompData *data, Vector *tokens, size_t start, size_t end) {
Token *t = vect_get(tokens, start);
if (start == end - 1 && t->type == TT_LITERAL) {
return _eval_literal(s, data, tokens, start);
}
int op = -1;
int op_pos = 0;
int delim = -1;
for(size_t i = start; i < end; i++) {
t = vect_get(tokens, i);
if (t->type == TT_DELIMIT) {
if(delim < 0) {
delim = i;
}
int dcl = tnsl_find_closing(tokens, i);
if (dcl < 0) {
printf("ERROR: could not find closing for delimiter \"%s\" (%d:%d)\n", t->data, t->line, t->col);
p2_error = true;
i = end;
} else {
i = dcl;
}
} else if (t->type == TT_AUGMENT) {
if (op_order(t) > op || (op_order(t) == op && op == 9)) {
op = op_order(t);
op_pos = i;
}
}
}
// Found first delim and last lowest priority op
Variable out;
out.name = NULL;
out.location = LOC_LITL;
if (op < 2){
// handle dot chain
Token *d = vect_get(tokens, delim);
if (delim == -1 || (d->data[0] == '(' && delim > start)) {
// Handle dot chains and calls
out = _eval_dot(s, data, tokens, start, end);
if (out.location == 5) {
Variable tmp = scope_mk_pure_tmp(s, data, &out);
var_end(&out);
out = tmp;
}
return out;
}
// Handle delim
int dcl = tnsl_find_closing(tokens, delim);
switch (d->data[0]){
case '(':
if (dcl < end - 1) {
// Extra tokens after paren are not yet supported
d = vect_get(tokens, dcl);
printf("Unexpected token after parenthesis \"%s\" (%d:%d)\n\n", d->data, d->line, d->col);
return out;
} else {
// Eval paren as expression
return _eval(s, data, tokens, start + 1, end - 1);
}
case '[':
printf("Explicit type casts are not yet supported, sorry (%d:%d)\n\n", d->line, d->col);
return out;
case '{':
if (delim > start) {
// Index
Variable index = _eval(s, data, tokens, delim + 1, dcl);
Variable to_index = _eval(s, data, tokens, start, delim);
Variable store;
var_op_index(data, &store, &to_index, &index);
var_end(&index);
var_end(&to_index);
to_index = scope_mk_pure_tmp(s, data, &store);
var_end(&store);
return to_index;
} else if (dcl < end - 1) {
// Invalid
p2_error = true;
printf("Unexpected tokens after composite value (%d:%d)\n\n", d->line, d->col);
return out;
}
printf("Composite values in blocks are not yet supported, sorry (%d;%d)\n\n", d->line, d->col);
p2_error = true;
return out;
case '/':
printf("Anonymous blocks as values are not yet supported, sorry (%d:%d)\n\n", d->line, d->col);
default:
p2_error = true;
return out;
}
}
Token *op_token = vect_get(tokens, op_pos);
// Based on op_token, split the two halves and recurse.
// if boolean, eval left to right, not right to left
if (op == 9) {
Variable lhs = _eval(s, data, tokens, start, op_pos);
char chk = op_token->data[0];
if (op_token->data[0] == '!') {
printf("WARN: TO IMPL BOOLEAN NOT\n");
chk = op_token->data[1];
}
Variable rhs;
if (chk == '&') {
vect_push_string(&data->text, "\tjz ");
vect_push_free_string(&data->text, scope_gen_bool_label(s));
vect_push_string(&data->text, " ; boolean and\n");
rhs = _eval(s, data, tokens, op_pos + 1, end);
} else if (chk == '|') {
vect_push_string(&data->text, "\tjnz ");
vect_push_free_string(&data->text, scope_gen_bool_label(s));
vect_push_string(&data->text, " ; boolean or\n");
rhs = _eval(s, data, tokens, op_pos + 1, end);
} else if (chk == '^') {
}
vect_push_free_string(&data->text, scope_gen_bool_label(s));
vect_push_string(&data->text, ": ; boolean end\n");
scope_adv_bool_label(s);
var_end(&rhs);
return lhs;
}
if (op_pos == start) {
Variable rhs = _eval(s, data, tokens, op_pos + 1, end);
if (op_token->data[0] == '~') {
Variable store;
var_op_reference(data, &store, &rhs);
var_end(&rhs);
int *ptype = vect_get(&store.ptr_chain, store.ptr_chain.count - 1);
*ptype = PTYPE_PTR;
rhs = scope_mk_tmp(s, data, &store);
var_end(&store);
return rhs;
} else if (op_token->data[0] == '!') {
out = scope_mk_tmp(s, data, &rhs);
var_end(&rhs);
var_op_not(data, &out);
return out;
} else if (tok_str_eq(op_token, "len")){
out = var_init("#literal", typ_get_inbuilt("uint"));
out.location = LOC_LITL;
out.offset = _var_size(&rhs);
var_end(&rhs);
return out;
} else {
printf("ERROR: Unexpected prefix token\n");
p2_error = true;
return rhs;
}
} else if (op_pos == end - 1) {
Variable lhs = _eval(s, data, tokens, start, op_pos);
if (tok_str_eq(op_token, "++")) {
var_op_inc(data, &lhs);
} else if (tok_str_eq(op_token, "--")) {
var_op_dec(data, &lhs);
} else {
printf("ERROR: Unexpected suffix token\n");
p2_error = true;
}
return lhs;
}
Variable rhs = _eval(s, data, tokens, op_pos + 1, end);
if (rhs.name == NULL) {
return out;
}
out = _eval(s, data, tokens, start, op_pos);
if (out.name == NULL) {
return rhs;
}
if (op != 10 && (!scope_is_tmp(&out) || _var_ptr_type(&out) == PTYPE_REF)) {
Variable tmp = scope_mk_tmp(s, data, &out);
if (scope_is_tmp(&out))
scope_free_tmp(s, data, &out);
else
var_end(&out);
out = tmp;
}
if (strlen(op_token->data) == 1) {
switch(op_token->data[0]) {
case '+':
var_op_add(data, &out, &rhs);
break;
case '-':
var_op_sub(data, &out, &rhs);
break;
case '*':
var_op_mul(data, &out, &rhs);
break;
case '/':
var_op_div(data, &out, &rhs);
break;
case '%':
var_op_mod(data, &out, &rhs);
break;
case '|':
var_op_or(data, &out, &rhs);
break;
case '&':
var_op_and(data, &out, &rhs);
break;
case '^':
var_op_xor(data, &out, &rhs);
break;
case '=':
var_op_set(data, &out, &rhs);
break;
case '<':
var_op_lt(data, &out, &rhs);
break;
case '>':
var_op_gt(data, &out, &rhs);
break;
}
} else if (strlen(op_token->data) == 2){
switch(op_token->data[0]) {
case '!':
if (op_token->data[1] == '&') {
var_op_nand(data, &out, &rhs);
} else if (op_token->data[1] == '|') {
var_op_nor(data, &out, &rhs);
} else if (op_token->data[1] == '^') {
var_op_xand(data, &out, &rhs);
} else if (op_token->data[1] == '<') {
var_op_ge(data, &out, &rhs);
} else if (op_token->data[1] == '>') {
var_op_le(data, &out, &rhs);
}
break;
case '=':
var_op_eq(data, &out, &rhs);
break;
case '<':
var_op_bsl(data, &out, &rhs);
break;
case '>':
var_op_bsr(data, &out, &rhs);
break;
}
} else if (strlen(op_token->data) == 3){
switch(op_token->data[0]) {
case '!':
if (op_token->data[1] == '=') {
var_op_ne(data, &out, &rhs);
}
break;
case '<':
var_op_le(data, &out, &rhs);
break;
case '>':
var_op_ge(data, &out, &rhs);
break;
}
}
if (scope_is_tmp(&rhs)) {
scope_free_tmp(s, data, &rhs);
} else {
var_end(&rhs);
}
return out;
}
// TODO: Operator evaluation, variable members, literals, function calls
Variable eval(Scope *s, CompData *out, Vector *tokens, size_t *pos, bool keep, Variable *out_type) {
Variable store;
size_t start = *pos;
size_t end = start;
for (; end < tokens->count; end++) {
Token *chk = vect_get(tokens, end);
if(chk->type == TT_SPLITTR) {
break;
} else if (chk->type == TT_DELIMIT) {
int i = tnsl_find_closing(tokens, end);
if(i > 0) {
end = i;
continue;
}
break;
}
}
store = _eval(s, out, tokens, start, end);
scope_free_all_tmp(s, out);
if (keep) {
Variable tmp = var_copy(out_type);
var_op_set(out, &tmp, &store);
var_end(&store);
store = tmp;
}
*pos = end;
return store;
}
void eval_strict_zero(CompData *out, Vector *tokens, Variable *v) {
int size = _var_pure_size(v);
bool array = false;
if (_var_ptr_type(v) < 2 && _var_ptr_type(v) > PTYPE_NONE) {
size = 8;
} else if (_var_ptr_type(v) > 1) {
size = v->type->size * _var_ptr_type(v);
}
vect_push_free_string(&out->data, _var_get_datalabel(v));
vect_push_string(&out->data, ":\n");
if (array) {
vect_push_string(&out->data, "\tdq ");
vect_push_free_string(&out->data, int_to_str(_var_ptr_type(v)));
vect_push_string(&out->data, "\n");
}
vect_push_string(&out->data, "\tdb 0");
for (int i = 1; i < size; i++) {
vect_push_string(&out->data, ", 0");
}
vect_push_string(&out->data, "\n\n");
}
void eval_strict_literal(Vector *out, Vector *tokens, Variable *v, size_t start) {
Token *cur = vect_get(tokens, start);
if (cur->type != TT_LITERAL) {
printf("ERROR: Expected literal value, got \"%s\" (%d:%d)\n\n", cur->data, cur->line, cur->col);
p2_error = true;
return;
} else if (cur->data[0] == '"') {
printf("ERROR: Unexpected string literal (wanted numeric or character value), got \"%s\" (%d:%d)\n\n", cur->data, cur->line, cur->col);
p2_error = true;
return;
}
char *numstr;
if (cur->data[0] == '\'') {
numstr = int_to_str(tnsl_unquote_char(cur->data));
} else {
numstr = int_to_str(tnsl_parse_number(cur));
}
char *str;
switch(_var_size(v)) {
case 1:
str = "\tdb ";
case 2:
str = "\tdw ";
case 4:
str = "\tdd ";
case 8:
str = "\tdq ";
}
vect_push_string(out, str);
vect_push_free_string(out, numstr);
vect_push_string(out, "; Numeric literal\n");
}
void eval_strict_composite(Module *mod, Vector *out, Vector *tokens, Variable *v, size_t start, char *datalab, int *ntharr);
void eval_strict_ptr(Module *mod, Vector *out, Vector *tokens, Variable *v, size_t start, char *datalab, int *ntharr);
void eval_strict_arr(Module *mod, Vector *out, Vector *tokens, Variable *v, size_t start, char *datalab, int *ntharr) {
Vector store = vect_from_string(datalab);
vect_push_string(&store, "#ptr");
vect_push_free_string(&store, int_to_str(*ntharr));
vect_push_string(&store, ":\n");
*ntharr += 1;
// TODO array eval loop
Variable strip = var_copy(v);
vect_pop(&strip.ptr_chain);
Token *cur = vect_get(tokens, start);
if (cur->data[0] == '\"') {
Vector data = tnsl_unquote_str(cur->data);
vect_push_string(&store, "\tdq ");
vect_push_free_string(&store, int_to_str(data.count));
vect_push_string(&store, "\n");
// char array
switch(_var_pure_size(&strip)) {
default:
case 1:
vect_push_string(&store, "\tdb ");
break;
case 2:
vect_push_string(&store, "\tdw ");
break;
case 4:
vect_push_string(&store, "\tdd ");
break;
case 8:
vect_push_string(&store, "\tdq ");
break;
}
for(size_t i = 0; i < data.count; i++) {
char *num = vect_get(&data, i);
vect_push_free_string(&store, int_to_str(*num));
if (i + 1 < data.count) {
vect_push_string(&store, ", ");
}
}
if (data.count == 0) {
vect_push_string(&store, "0");
}
vect_push_string(&store, "\n");
} else if (cur->data[0] == '{') {
// Traditional array
int end = tnsl_find_closing(tokens, start);
int count = 0;
bool first = true;
start++;
for (size_t i = start; i < end; i++) {
cur = vect_get(tokens, i);
if(tok_str_eq(cur, ",")) {
first = true;
} else {
if (first) {
count++;
first = false;
}
if (cur->type == TT_DELIMIT) {
i = tnsl_find_closing(tokens, i);
}
}
}
vect_push_string(&store, "\tdq ");
vect_push_free_string(&store, int_to_str(count));
vect_push_string(&store, "\n");
first = true;
for (; start < end; start++) {
cur = vect_get(tokens, start);
if(tok_str_eq(cur, ",")) {
first = true;
} else {
if (first) {
first = false;
if (_var_ptr_type(&strip) > 1) {
eval_strict_arr(mod, &store, tokens, &strip, start, datalab, ntharr);
} else if (_var_ptr_type(&strip) > PTYPE_NONE) {
eval_strict_ptr(mod, &store, tokens, &strip, start, datalab, ntharr);
} else if (!is_inbuilt(strip.type->name)) {
eval_strict_composite(mod, &store, tokens, &strip, start, datalab, ntharr);
} else {
eval_strict_literal(&store, tokens, &strip, start);
}
}
if (cur->type == TT_DELIMIT) {
start = tnsl_find_closing(tokens, start);
}
}
}
} else {
printf("ERROR: Expected array but found \"%s\" (%d:%d)\n\n", cur->data, cur->line, cur->col);
}
var_end(&strip);
// Overwrite out
if (_var_ptr_type(v) < 2) {
vect_push_string(&store, vect_as_string(out));
vect_end(out);
*out = store;
} else {
vect_push_string(out, vect_as_string(&store));
vect_end(&store);
}
}
void eval_strict_ptr(Module *mod, Vector *out, Vector *tokens, Variable *v, size_t start, char *datalab, int *ntharr) {
Token *cur = vect_get(tokens, start);
if (tok_str_eq(cur, "~")) {
// define qword pointer to existing label
Artifact v_art = art_from_str("", '.');
for (start++; ;start++) {
cur = vect_get(tokens, start);
if (cur == NULL) {
cur = tnsl_find_last_token(tokens, start);
break;
} else if (cur->type == TT_DEFWORD) {
art_add_str(&v_art, cur->data);
} else if (tok_str_eq(cur, "\n") || tok_str_eq(cur, ",")) {
break;
} else if (!tok_str_eq(cur, ".")) {
printf("ERROR: Unexpected token in pointer declaration (file level) \"%s\", (%d:%d)\n\n", cur->data, cur->line, cur->col);
p2_error = true;
break;
}
}
// Find var and get data label
Variable *ptr = mod_find_var(mod, &v_art);
if (ptr == NULL) {
char *v_name = art_to_str(&v_art, '.');
printf("ERROR: Could not find variable \"%s\" for pointer value (%d:%d)\n\n", v_name, cur->line, cur->col);
free(v_name);
}
vect_push_string(out, "\tdq ");
vect_push_free_string(out, _var_get_datalabel(ptr));
vect_push_string(out, "\n");
} else if (tok_str_eq(cur, "{") || cur->data[0] == '\"') {
// Harder, define array
vect_push_string(out, "\tdq ");
vect_push_string(out, datalab);
vect_push_string(out, "#ptr");
vect_push_free_string(out, int_to_str(*ntharr));
if (_var_ptr_type(v) < 1) {
vect_push_string(out, " + 8 ; ref to pointer\n");
} else {
vect_push_string(out, " ; ref to pointer\n");
}
eval_strict_arr(mod, out, tokens, v, start, datalab, ntharr);
} else if (cur->type == TT_LITERAL){
// Literal value interpreted as memory location
eval_strict_literal(out, tokens, v, start);
} else {
// Not impl
printf("ERROR: Unexpected token when parsing a pointer value at \"%s\" (%d:%d)\n\n", cur->data, cur->line, cur->col);
p2_error = true;
}
}
void eval_strict_composite(Module *mod, Vector *out, Vector *tokens, Variable *v, size_t start, char *datalab, int *ntharr) {
Token *cur = vect_get(tokens, start);
if (!tok_str_eq(cur, "{")) {
printf("ERROR: Expected composite value (enclosed with '{}'), got \"%s\" (%d:%d)\n\n", cur->data, cur->line, cur->col);
p2_error = true;
return;
}
int last = tnsl_find_closing(tokens, start);
if (last < 0) {
printf("ERROR: Could not find closing '}' for composite value (%d:%d)\n\n", cur->line, cur->col);
p2_error = true;
return;
}
size_t subvar = 0;
bool first = true;
for (start++; start < last; start++) {
Token *cur = vect_get(tokens, start);
if(tok_str_eq(cur, ",")) {
first = true;
} else {
if (first) {
Variable *sub = vect_get(&v->type->members, subvar);
first = false;
if (_var_ptr_type(sub) > 1) {
eval_strict_arr(mod, out, tokens, sub, start, datalab, ntharr);
} else if (_var_ptr_type(sub) > PTYPE_NONE) {
eval_strict_ptr(mod, out, tokens, sub, start, datalab, ntharr);
} else if (!is_inbuilt(sub->type->name)) {
eval_strict_composite(mod, out, tokens, sub, start, datalab, ntharr);
} else {
eval_strict_literal(out, tokens, sub, start);
}
subvar++;
}
if (cur->type == TT_DELIMIT) {
start = tnsl_find_closing(tokens, start);
}
}
}
}
void eval_strict(CompData *out, Vector *tokens, Variable *v, size_t start) {
char *datalab = _var_get_datalabel(v);
Vector store = vect_from_string(datalab);
vect_push_string(&store, ":\n");
int ntharr = 0;
if (_var_ptr_type(v) > 1) {
eval_strict_arr(v->mod, &store, tokens, v, start + 2, datalab, &ntharr);
} else if (_var_ptr_type(v) > PTYPE_NONE) {
eval_strict_ptr(v->mod, &store, tokens, v, start + 2, datalab, &ntharr);
} else if (!is_inbuilt(v->type->name)) {
eval_strict_composite(v->mod, &store, tokens, v, start + 2, datalab, &ntharr);
} else {
eval_strict_literal(&store, tokens, v, start + 2);
}
vect_push_string(&out->data, vect_as_string(&store));
free(datalab);
vect_end(&store);
}
// Compile a top-level definition
void p2_compile_fdef(Module *root, CompData *out, Vector *tokens, size_t *pos) {
Variable type = tnsl_parse_type(tokens, *pos);
*pos = type.location;
var_end(&type);
size_t start = *pos;
Variable *cur;
while (*pos < tokens->count && !tok_str_eq(vect_get(tokens, *pos), "\n")) {
Token *t = vect_get(tokens, *pos);
if (start == *pos) {
if (t->type != TT_DEFWORD) {
printf("ERROR: Expected variable name (file), got \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
return;
}
Artifact v_art = art_from_str(t->data, '.');
cur = mod_find_var(root, &v_art);
art_end(&v_art);
if (cur == NULL) {
printf("ERROR: Definition should have been cataloged but was not \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
return;
} else if (cur->location == 0) {
printf("ERROR: Redefinition of variable \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
return;
}
} else if (t->type == TT_DELIMIT) {
*pos = tnsl_find_closing(tokens, *pos);
} else if (tok_str_eq(t, ",")) {
if (*pos - start > 1) {
eval_strict(out, tokens, cur, start);
} else if(*pos - start > 0) {
eval_strict_zero(out, tokens, cur);
}
start = *pos + 1;
}
*pos += 1;
}
if (*pos - start > 1) {
eval_strict(out, tokens, cur, start);
} else if(*pos - start > 0) {
eval_strict_zero(out, tokens, cur);
}
}
// Compiles a variable definition inside a function block
void p2_compile_def(Scope *s, CompData *out, Vector *tokens, size_t *pos, Vector *p_list) {
Variable type = tnsl_parse_type(tokens, *pos);
*pos = type.location;
Artifact t_art = art_from_str(type.name, '.');
type.type = mod_find_type(s->current, &t_art);
art_end(&t_art);
size_t start = *pos;
while (*pos < tokens->count) {
Token *t = vect_get(tokens, *pos);
if (start == *pos) {
if (t->type != TT_DEFWORD) {
printf("ERROR: Expected variable name, got \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
return;
}
// Define new scope var
free(type.name);
Vector nm = vect_from_string(t->data);
type.name = vect_as_string(&nm);
Variable tmp;
if (_var_ptr_type(&type) != PTYPE_REF && art_contains(p_list, type.name)) {
tmp = scope_mk_stack(s, out, &type);
} else {
tmp = scope_mk_var(s, out, &type);
}
var_end(&tmp);
} else if (t->type == TT_DELIMIT) {
*pos = tnsl_find_closing(tokens, *pos);
} else if (tok_str_eq(t, ",")) {
// Split def
if(*pos - start > 1) {
Variable store = _eval(s, out, tokens, start, *pos);
scope_free_all_tmp(s, out);
var_end(&store);
}
start = *pos + 1;
} else if (tok_str_eq(t, ";") || tok_str_eq(t, "\n")) {
break;
}
*pos += 1;
}
var_end(&type);
if (*pos - start > 1) {
Variable store = _eval(s, out, tokens, start, *pos);
scope_free_all_tmp(s, out);
var_end(&store);
}
}
// TODO (depends on top-level defs working)
void p2_compile_enum(Module *root, CompData *out, Vector *tokens, size_t *pos) {
int end = tnsl_find_closing(tokens, *pos);
Token *t = vect_get(tokens, *pos);
if(end < 0) {
printf("ERROR: Could not find closing for enum \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
return;
}
}
void _p2_func_scope_end(CompData *out, Scope *fs) {
// No multi returns atm
vect_push_string(&out->text, "\tlea rsp, [rbp - 56]\n");
vect_push_string(&out->text, "\tpop r15\n");
vect_push_string(&out->text, "\tpop r14\n");
vect_push_string(&out->text, "\tpop r13\n");
vect_push_string(&out->text, "\tpop r12\n");
vect_push_string(&out->text, "\tpop r11\n");
vect_push_string(&out->text, "\tpop r10\n");
vect_push_string(&out->text, "\tpop rbp\n"); // restore stack frame
vect_push_string(&out->text, "\tret ; Scope end\n");
}
void p2_compile_control(Scope *s, Function *f, CompData *out, Vector *tokens, size_t *pos, Vector *p_list);
void p2_wrap_control(Scope *s, Function *f, CompData *out, Vector *tokens, size_t *pos, Vector *p_list) {
Scope sub = scope_subscope(s, "wrap");
int end;
Token *cur;
bool first = true;
for (;*pos < tokens->count;) {
end = tnsl_find_closing(tokens, *pos);
cur = vect_get(tokens, *pos);
if (end < 0 || (!tok_str_eq(cur, "/;") && !tok_str_eq(cur, ";;"))) {
break;
}
cur = vect_get(tokens, *pos + 1);
if (tok_str_eq(cur, "if") && first) {
p2_compile_control(&sub, f, out, tokens, pos, p_list);
first = false;
} else if (tok_str_eq(cur, "else") && !first) {
p2_compile_control(&sub, f, out, tokens, pos, p_list);
} else {
if (tok_str_eq(cur, "else") && first) {
printf("ERROR: Expected if block before else block (%d:%d)\n\n", cur->line, cur->col);
}
break;
}
*pos = end;
}
vect_push_free_string(&out->text, scope_label_end(&sub));
vect_push_string(&out->text, ":\n\n");
scope_end(&sub);
}
// TODO loop blocks, if blocks, else blocks
void p2_compile_control(Scope *s, Function *f, CompData *out, Vector *tokens, size_t *pos, Vector *p_list) {
int end = tnsl_find_closing(tokens, *pos);
Token *t = vect_get(tokens, *pos);
if(end < 0) {
printf("ERROR: Could not find closing for control block \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
return;
}
*pos += 1;
t = vect_get(tokens, *pos);
Scope sub;
// Generate wrap for if if none exists
if (tok_str_eq(t, "if") || tok_str_eq(t, "else")) {
if (s->parent == NULL || !scope_name_eq(s, "wrap")) {
*pos -= 1;
p2_wrap_control(s, f, out, tokens, pos, p_list);
return;
}
}
// Generate subscope
if (tok_str_eq(t, "if") || tok_str_eq(t, "else")) {
t = vect_get(tokens, *pos + 1);
if (tok_str_eq(t, "if")) {
*pos += 1;
sub = scope_subscope(s, "elif");
} else {
t = vect_get(tokens, *pos);
sub = scope_subscope(s, t->data);
}
} else if (t->type != TT_KEYWORD || !tok_str_eq(t, "loop")) {
printf("ERROR: Expected control block type ('loop' or 'if'), found \"%s\" (%d:%d)\n", t->data, t->line, t->col);
p2_error = true;
*pos = end;
return;
} else {
sub = scope_subscope(s, t->data);
}
// Find pre and post control statements
int build = -1;
int rep = -1;
for (*pos += 1; *pos < end; *pos += 1) {
t = vect_get(tokens, *pos);
if (tok_str_eq(t, "(")) {
build = *pos;
*pos = tnsl_find_closing(tokens, *pos);
} else if (tok_str_eq(t, "[")) {
rep = *pos;
*pos = tnsl_find_closing(tokens, *pos);
} else {
break;
}
}
if (build > -1) {
// Generate pre-control statements
size_t start = tnsl_next_non_nl(tokens, build);
int b_end = tnsl_find_closing(tokens, build);
build = start;
for (;start <= build && build <= b_end; build = tnsl_next_non_nl(tokens, build)) {
if (build == start && tnsl_is_def(tokens, start)) {
p2_compile_def(&sub, out, tokens, &start, p_list);
build = start;
}
t = vect_get(tokens, build);
if (tok_str_eq(t, ";") || tok_str_eq(t, ")")) {
if (build != start) {
// Eval, check ending
Variable v = _eval(&sub, out, tokens, start, build);
scope_free_all_tmp(&sub, out);
if (v.type != NULL && strcmp(v.type->name, "bool") == 0 && tok_str_eq(t, ")")) {
build = start - 1;
start = b_end;
vect_push_string(&out->text, "\tjz ");
vect_push_free_string(&out->text, scope_label_end(&sub));
vect_push_string(&out->text, "; Conditional start\n");
} else {
start = build + 1;
}
if (v.name != NULL)
var_end(&v);
} else {
start = build + 1;
}
} else if (t->type == TT_DELIMIT) {
build = tnsl_find_closing(tokens, build);
}
}
if (build > b_end) {
build = -1;
}
}
vect_push_free_string(&out->text, scope_label_start(&sub));
vect_push_string(&out->text, ": ; Start label\n");
// Main loop statements
*pos = tnsl_next_non_nl(tokens, *pos - 1);
for(; *pos < end; *pos = tnsl_next_non_nl(tokens, *pos)) {
t = vect_get(tokens, *pos);
if (tok_str_eq(t, "/;") || tok_str_eq(t, ";;")) {
size_t b_open = *pos;
if(tnsl_block_type(tokens, *pos) == BT_CONTROL) {
p2_compile_control(&sub, f, out, tokens, pos, p_list);
} else {
printf("ERROR: Only control blocks (if, else, loop, switch) are valid inside functions (%d:%d)\n\n", t->line, t->col);
p2_error = true;
*pos = end - 1;
}
if (*pos == b_open) {
*pos = tnsl_find_closing(tokens, b_open);
} else if (tok_str_eq(t, ";;")) {
*pos -= 1;
}
} else if (t->type == TT_KEYWORD) {
if(tok_str_eq(t, "return")) {
t = vect_get(tokens, *pos + 1);
if (f->outputs.count > 0) {
if (*pos + 1 < end && !tok_str_eq(t, "\n")) {
*pos += 1;
Variable *out_type = vect_get(&f->outputs, 0);
Variable e = eval(&sub, out, tokens, pos, true, out_type);
var_end(&e);
} else {
t = vect_get(tokens, *pos);
printf("ERROR: Attempt to return from a function without a value, but the function requires one (%d:%d)", t->line, t->col);
p2_error = true;
}
}
_p2_func_scope_end(out, s);
*pos = end;
} else if (tok_str_eq(t, "asm")) {
t = vect_get(tokens, ++(*pos));
if(t->type != TT_LITERAL || t->data[0] != '"') {
printf("ERROR: Expected string literal after asm keyword (%d:%d)\n", t->line, t->col);
p2_error = true;
} else {
Vector asm_str = tnsl_unquote_str(t->data);
vect_push_string(&out->text, "\t");
vect_push_string(&out->text, vect_as_string(&asm_str));
vect_push_string(&out->text, "; User insert asm\n");
vect_end(&asm_str);
}
} else if (tok_str_eq(t, "continue") || tok_str_eq(t, "break")) {
printf("ERROR: This keyword will be implemented in a future commit \"%s\" (%d:%d)\n", t->data, t->line, t->col);
p2_error = true;
} else {
printf("ERROR: Keyword not implemented inside control blocks \"%s\" (%d:%d)\n", t->data, t->line, t->col);
p2_error = true;
}
} else if (tnsl_is_def(tokens, *pos)) {
p2_compile_def(&sub, out, tokens, pos, p_list);
} else if (*pos == end) {
break;
} else {
// TODO: figure out eval parameter needs (maybe needs start and end size_t?)
// and how eval will play into top level defs (if at all)
Variable e = eval(&sub, out, tokens, pos, false, NULL);
if (e.name != NULL)
var_end(&e);
}
}
vect_push_free_string(&out->text, scope_label_rep(&sub));
vect_push_string(&out->text, ": ; Rep label\n");
if (rep > -1) {
// Generate post-control statements
size_t start = tnsl_next_non_nl(tokens, rep);
int r_end = tnsl_find_closing(tokens, rep);
rep = start;
for (;start <= rep && rep <= r_end; rep = tnsl_next_non_nl(tokens, rep)) {
if (rep == start && tnsl_is_def(tokens, start)) {
p2_compile_def(&sub, out, tokens, &start, p_list);
rep = start;
}
t = vect_get(tokens, rep);
if (tok_str_eq(t, ";") || tok_str_eq(t, "]")) {
if (rep != start) {
// Eval, check ending
Variable v = _eval(&sub, out, tokens, start, rep);
scope_free_all_tmp(&sub, out);
if (v.type != NULL && strcmp(v.type->name, "bool") == 0 && tok_str_eq(t, "]") && scope_name_eq(&sub, "loop")) {
rep = start - 1;
start = r_end;
vect_push_string(&out->text, "\tjnz ");
vect_push_free_string(&out->text, scope_label_start(&sub));
vect_push_string(&out->text, "; Conditional rep\n");
} else {
start = rep + 1;
}
if (v.name != NULL)
var_end(&v);
} else {
start = rep + 1;
}
} else if (t->type == TT_DELIMIT) {
rep = tnsl_find_closing(tokens, rep);
}
}
if (rep > r_end) {
rep = -1;
}
}
Variable free_to = {0};
// Post control
if (scope_name_eq(&sub, "loop")) {
if (build >= 0 && rep < 0) {
// find end of build, re-eval and cond jmp
int b_end = build;
t = vect_get(tokens, b_end);
while(!tok_str_eq(t, ")")) {
if (t->type == TT_DELIMIT) {
b_end = tnsl_find_closing(tokens, b_end);
}
b_end++;
t = vect_get(tokens, b_end);
}
Variable v = _eval(&sub, out, tokens, build, b_end);
scope_free_all_tmp(&sub, out);
vect_push_string(&out->text, "\tjnz ");
vect_push_free_string(&out->text, scope_label_start(&sub));
vect_push_string(&out->text, "; Conditional rep\n");
var_end(&v);
} else if (build < 0 && rep < 0) {
vect_push_string(&out->text, "\tjmp ");
vect_push_free_string(&out->text, scope_label_start(&sub));
vect_push_string(&out->text, "\n");
}
} else {
// Jmp to outer wrap at end of if
scope_free_to(&sub, out, &free_to);
vect_push_string(&out->text, "\tjmp ");
vect_push_free_string(&out->text, scope_label_end(s));
vect_push_string(&out->text, "\n");
}
// Cleanup scope
vect_push_free_string(&out->text, scope_label_end(&sub));
vect_push_string(&out->text, ": ; End label\n");
scope_free_to(&sub, out, &free_to);
scope_end(&sub);
vect_push_string(&out->text, "\n\n");
}
// Handles the 'self' variable in the case where the function is in a method block.
void _p2_handle_method_scope(Module *root, CompData *out, Scope *fs, Function *f) {
// load type for method
Artifact t_art = art_from_str((root->name + 2), '.');
Type *t = mod_find_type(root, &t_art);
art_end(&t_art);
// Create self var
Variable self = var_init("self", t);
self.location = 1;
int pt = PTYPE_REF;
vect_push(&self.ptr_chain, &pt);
// Add to scope
Variable set = scope_mk_var(fs, out, &self);
var_op_pure_set(out, &set, &self);
// clean up vars
var_end(&self);
var_end(&set);
}
void _p2_func_scope_init(Module *root, CompData *out, Scope *fs, Function *f, Vector *p_list) {
// TODO: decide what happens when a function scope is created
// export function if module is exported.
Vector tmp = _scope_base_label(fs);
if (root->exported) {
vect_push_string(&out->header, "global ");
vect_push_string(&out->header, vect_as_string(&tmp));
vect_push_string(&out->header, "\n");
}
// put the label
vect_push_free_string(&out->text, vect_as_string(&tmp));
vect_push_string(&out->text, ":\n");
// Update stack pointers
vect_push_string(&out->text, "\tpush rbp\n");
vect_push_string(&out->text, "\tlea rbp, [rsp + 8]\n");
// Push registers to save callee variables (subject to ABI change)
vect_push_string(&out->text, "\tpush r10\n");
vect_push_string(&out->text, "\tpush r11\n");
vect_push_string(&out->text, "\tpush r12\n");
vect_push_string(&out->text, "\tpush r13\n");
vect_push_string(&out->text, "\tpush r14\n");
vect_push_string(&out->text, "\tpush r15 ; scope init\n\n");
// Load function parameters into expected registers (we assume the stack frame was set up proprely by caller)
for (size_t i = 0; i < f->inputs.count; i++) {
Variable *input = vect_get(&f->inputs, i);
Variable set;
if (_var_ptr_type(input) != PTYPE_REF && art_contains(p_list, input->name)) {
set = scope_mk_stack(fs, out, input);
} else {
set = scope_mk_var(fs, out, input);
}
var_op_pure_set(out, &set, input);
var_end(&set);
}
}
void p2_compile_function(Module *root, CompData *out, Vector *tokens, size_t *pos) {
int end = tnsl_find_closing(tokens, *pos);
Token *start = vect_get(tokens, *pos);
// Pre-checks for end of function and function name so scope can be initialized
if(end < 0) {
printf("ERROR: Could not find closing for function \"%s\" (%d:%d)\n\n", start->data, start->line, start->col);
p2_error = true;
return;
}
Vector p_list = tnsl_find_all_pointers(tokens, *pos, end);
Token *t = vect_get(tokens, *pos);
while (t != NULL && *pos < (size_t)end && t->type != TT_DEFWORD) {
t = vect_get(tokens, ++(*pos));
if(tok_str_eq(t, "\n"))
break;
else if (t->type == TT_DELIMIT && !tok_str_eq(t, ";/") && !tok_str_eq(t, ";;")) {
*pos = tnsl_find_closing(tokens, *pos);
}
}
if(t == NULL || t->type != TT_DEFWORD) {
printf("ERROR: Could not find user defined name for function \"%s\" (%d:%d)\n\n", start->data, start->line, start->col);
p2_error = true;
return;
}
// fart
Artifact f_art = art_from_str(t->data, ' ');
Function *f = mod_find_func(root, &f_art);
art_end(&f_art);
// Scope init
Scope fs = scope_init(t->data, root);
_p2_func_scope_init(root, out, &fs, f, &p_list);
if(root->name != NULL && strlen(root->name) > 1 && root->name[0] == '_' && root->name[1] == '#') {
_p2_handle_method_scope(root, out, &fs, f);
}
while(*pos < (size_t)end) {
t = vect_get(tokens, *pos);
if(tok_str_eq(t, "\n"))
break;
else if (t->type == TT_DELIMIT)
*pos = tnsl_find_closing(tokens, *pos);
*pos += 1;
}
*pos = tnsl_next_non_nl(tokens, *pos);
for (; *pos < (size_t)end; *pos = tnsl_next_non_nl(tokens, *pos)) {
t = vect_get(tokens, *pos);
if (tok_str_eq(t, "/;") || tok_str_eq(t, ";;")) {
size_t b_open = *pos;
if(tnsl_block_type(tokens, *pos) == BT_CONTROL) {
p2_compile_control(&fs, f, out, tokens, pos, &p_list);
} else {
printf("ERROR: Only control blocks (if, else, loop, switch) are valid inside functions (%d:%d)\n\n", t->line, t->col);
p2_error = true;
}
if (*pos == b_open) {
*pos = tnsl_find_closing(tokens, b_open);
} else if (tok_str_eq(t, ";;")) {
*pos -= 1;
}
} else if (t->type == TT_KEYWORD) {
if(tok_str_eq(t, "return")) {
t = vect_get(tokens, *pos + 1);
if (f->outputs.count > 0) {
if (*pos + 1 < end && !tok_str_eq(t, "\n")) {
*pos += 1;
Variable *out_type = vect_get(&f->outputs, 0);
Variable e = eval(&fs, out, tokens, pos, true, out_type);
var_end(&e);
} else {
t = vect_get(tokens, *pos);
printf("ERROR: Attempt to return from a function without a value, but the function requires one (%d:%d)", t->line, t->col);
p2_error = true;
}
}
_p2_func_scope_end(out, &fs);
*pos = end;
scope_end(&fs);
return;
} else if (tok_str_eq(t, "asm")) {
t = vect_get(tokens, ++(*pos));
if(t->type != TT_LITERAL || t->data[0] != '"') {
printf("ERROR: Expected string literal after asm keyword (%d:%d)\n", t->line, t->col);
p2_error = true;
} else {
Vector asm_str = tnsl_unquote_str(t->data);
vect_push_string(&out->text, "\t");
vect_push_string(&out->text, vect_as_string(&asm_str));
vect_push_string(&out->text, "; User insert asm\n");
vect_end(&asm_str);
}
} else {
printf("ERROR: Keyword not implemented inside functions \"%s\" (%d:%d)\n", t->data, t->line, t->col);
p2_error = true;
}
} else if (tnsl_is_def(tokens, *pos)) {
p2_compile_def(&fs, out, tokens, pos, &p_list);
} else {
// TODO: figure out eval parameter needs (maybe needs start and end size_t?)
// and how eval will play into top level defs (if at all)
Variable e = eval(&fs, out, tokens, pos, false, NULL);
var_end(&e);
}
}
if (f->outputs.count > 0) {
printf("ERROR: Expected return value for function (%d:%d)\n\n", t->line, t->col);
p2_error = true;
}
_p2_func_scope_end(out, &fs);
scope_end(&fs);
art_end(&p_list);
*pos = end;
}
void p2_compile_method(Module *root, CompData *out, Vector *tokens, size_t *pos) {
int end = tnsl_find_closing(tokens, *pos);
Token *t = vect_get(tokens, *pos);
if(end < 0) {
printf("ERROR: Could not find closing for method \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
return;
}
*pos += 2;
t = vect_get(tokens, *pos);
if (t == NULL || t->type != TT_DEFWORD) {
printf("ERROR: Expected user defined type after 'method' keyword (%d:%d)\n\n", t->line, t->col);
*pos = end;
p2_error = true;
return;
}
Vector sub_name = vect_from_string("_#");
vect_push_string(&sub_name, t->data);
// TODO: method loop
Module *mmod = mod_find_sub(root, vect_as_string(&sub_name));
vect_end(&sub_name);
for(;*pos < end;*pos = tnsl_next_non_nl(tokens, *pos)) {
t = vect_get(tokens, *pos);
if(tok_str_eq(t, "/;") != true && tok_str_eq(t, ";;") != true) {
continue;
}
p2_compile_function(mmod, out, tokens, pos);
t = vect_get(tokens, *pos);
if(tok_str_eq(t, ";;")) {
*pos -= 1;
}
}
*pos = end;
}
void p2_file_loop(
Artifact *path, Module *root, CompData *out,
Vector *tokens, size_t start, size_t end);
void p2_compile_module(Artifact *path, Module *root, CompData *out, Vector *tokens, size_t *pos) {
int end = tnsl_find_closing(tokens, *pos);
Token *t = tnsl_find_last_token(tokens, *pos);
if (end < 0) {
printf("ERROR: Could not find closing delimiter for module (%d:%d)\n\n", t->line, t->col);
p2_error = true;
return;
}
*pos += 1;
t = vect_get(tokens, *pos);
if(tok_str_eq(t, "export")){
*pos += 1;
}
*pos += 1;
t = vect_get(tokens, *pos);
if (t == NULL || t->type != TT_DEFWORD) {
t = tnsl_find_last_token(tokens, *pos);
printf("ERROR: Expected module name after \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
*pos = end;
return;
}
Module *mod_root = mod_find_sub(root, t->data);
if(mod_root == NULL) {
printf("COMPILER ERROR: Could not find sub module for \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
*pos = end;
return;
}
p2_file_loop(path, mod_root, out, tokens, *pos, end);
*pos = end;
}
CompData p2_compile_file(Artifact *path, Module *root) {
CompData out = cdat_init();
char *full_path = art_to_str(path, '/');
FILE *fin = fopen(full_path, "r");
if (fin == NULL) {
printf("Unable to open file %s for reading.\n\n", full_path);
p2_error = true;
free(full_path);
return out;
}
free(full_path);
Vector tokens = parse_file(fin);
fclose(fin);
p2_file_loop(path, root, &out, &tokens, 0, tokens.count);
for (size_t i = 0; i < tokens.count; i++) {
Token *t = vect_get(&tokens, i);
free(t->data);
}
vect_end(&tokens);
return out;
}
void p2_file_loop(
Artifact *path, Module *root, CompData *out,
Vector *tokens, size_t start, size_t end) {
for(;start < end; start++) {
Token *t = vect_get(tokens, start);
if (t->type == TT_SPLITTR && tok_str_eq(t, ":")) {
t = vect_get(tokens, ++start);
if (t == NULL || !tok_str_eq(t, "import")) {
t = tnsl_find_last_token(tokens, start);
printf("ERROR: Comptime declarations are not implemented other than 'import' \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
continue;
}
t = vect_get(tokens, ++start);
if(t != NULL && t->type == TT_LITERAL) {
// Process new path to follow using old path.
char *cpy = art_to_str(path, '/');
Artifact new_path = art_from_str(cpy, '/');
free(cpy);
// Pop off file name
art_pop_str(&new_path);
// Copy token data (something like "path/to/file.tnsl" including the quotes)
// This path is relative to the current file
Vector v = vect_from_string(t->data);
// Pop off last quote, replace with \0
vect_pop(&v);
vect_as_string(&v);
// Remove starting quote by indexing into data
Artifact addon = art_from_str((char *)v.data + 1, '/');
// No more need for copy string
vect_end(&v);
// Add relative path to current folder
art_add_art(&new_path, &addon);
// no more need for path relative to file
art_end(&addon);
CompData dat = p2_compile_file(&new_path, root);
cdat_add(out, &dat);
cdat_end(&dat);
// Cleanup last remaining artifact
art_end(&new_path);
}
} else if (t->type == TT_DELIMIT && (tok_str_eq(t, "/;") || tok_str_eq(t, ";;"))) {
size_t block_start = start;
switch(tnsl_block_type(tokens, start)) {
case BT_FUNCTION:
p2_compile_function(root, out, tokens, &start);
break;
case BT_MODULE:
p2_compile_module(path, root, out, tokens, &start);
break;
case BT_METHOD:
p2_compile_method(root, out, tokens, &start);
break;
case BT_ENUM:
p2_compile_enum(root, out, tokens, &start);
break;
case BT_CONTROL:
printf("ERROR: Control blocks (if, loop, switch) can only be placed within a function block. (%d:%d)\n\n", t->line, t->col);
p2_error = true;
break;
case BT_INTERFACE:
case BT_OPERATOR:
printf("ERROR: Block type not implemented \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
break;
default:
printf("ERROR: Unknown block type \"%s\" at file root (%d:%d)\n\n", t->data, t->line, t->col);
p2_error = true;
break;
}
t = vect_get(tokens, start);
if (start == block_start) {
int chk = tnsl_find_closing(tokens, start);
if (chk < 0)
printf("ERROR: Could not find closing for \"%s\" (%d:%d)\n\n", t->data, t->line, t->col);
else
start = chk;
} else if (tok_str_eq(t, ";;")) {
start--;
}
} else if (tok_str_eq(t, "asm")) {
// TODO: top level asm should go where?
start++;
t = vect_get(tokens, start);
if(t != NULL && t->type == TT_LITERAL) {
Vector asm_str = tnsl_unquote_str(t->data);
if (asm_str.count > 0) {
vect_push_string(&out->header, vect_as_string(&asm_str));
vect_push_string(&out->header, "\n");
}
vect_end(&asm_str);
}
} else if (tok_str_eq(t, "struct")){
start += 2;
start = tnsl_find_closing(tokens, start);
} else if (tnsl_is_def(tokens, start)) {
p2_compile_fdef(root, out, tokens, &start);
}
}
}
void compile(Artifact *path_in, Artifact *path_out) {
// Root module used for artifact resolution
Module root = mod_init("", NULL, true);
phase_1(path_in, &root);
if (p1_error) {
printf("Parser encountered errors, stopping.\n\n");
mod_deep_end(&root);
return;
}
CompData out = p2_compile_file(path_in, &root);
mod_deep_end(&root);
if (p2_error) {
printf("Compiler encountered errors, stopping.\n\n");
cdat_end(&out);
return;
}
char *full_path = art_to_str(path_out, '/');
FILE *fout = fopen(full_path, "w");
if (fout == NULL) {
printf("Unable to open output file %s for writing.\n\n", full_path);
free(full_path);
cdat_end(&out);
return;
}
free(full_path);
cdat_write_to_file(&out, fout);
fclose(fout);
cdat_end(&out);
}
char *tok_type_strs[] = {
"DEFWORD",
"KEYWORD",
"KEYTYPE",
"LITERAL",
"AUGMENT",
"DELIMIT",
"SPLITTR"
};
void write_token(FILE *out, Token *t) {
fprintf(out, "{line: %d, column: %d, type %s, data: \"%s\"}\n", t->line, t->col, tok_type_strs[t->type], t->data);
}
void tokenize(Artifact *path_in, Artifact *path_out) {
char *full_path = art_to_str(path_in, '/');
FILE *fin = fopen(full_path, "r");
if (fin == NULL) {
printf("Unable to open file %s for reading.\n\n", full_path);
free(full_path);
return;
}
free(full_path);
full_path = art_to_str(path_out, '/');
FILE *fout = fopen(full_path, "w");
if (fout == NULL) {
printf("Unable to open file %s for writing.\n\n", full_path);
free(full_path);
fclose(fin);
return;
}
free(full_path);
Vector tokens = parse_file(fin);
fclose(fin);
for(size_t i = 0; i < tokens.count; i++) {
Token *t = vect_get(&tokens, i);
write_token(fout, t);
free(t->data);
}
fflush(fout);
fclose(fout);
vect_end(&tokens);
}
// Entrypoint
void help() {
printf("\n");
printf("Usage:\n");
printf("\tctc - The TNSL compiler (written in c)\n\n");
printf("\tctc [file in] - compile the given file, writing output assembly in out.asm\n");
printf("\tctc [file in] [file out] - same as before, but write the output assembly to the given filename\n");
printf("\t -h - print this output message\n");
printf("\t -v - print version information\n");
printf("\t -t [file in] - output tokenization of file instead of assembly in out.asm\n");
printf("\t -t [file in] [file out] - output tokenization of file instead of assembly in output file\n");
printf("\n");
}
int main(int argc, char ** argv) {
if (argc < 2 || strcmp(argv[1], "-h") == 0) {
help();
return 1;
} else if (strcmp(argv[1], "-v") == 0) {
printf("C based TNSL Compiler (CTC) - version 0.4.1\n");
return 0;
} else if (strcmp(argv[1], "-t") == 0) {
Artifact in = art_from_str(argv[2], '/');
Artifact out;
if (argc == 3) {
out = art_from_str("out.asm", '/');
} else {
out = art_from_str(argv[3], '/');
}
tokenize(&in, &out);
art_end(&in);
art_end(&out);
return 0;
}
Artifact in = art_from_str(argv[1], '/');
Artifact out;
if (argc == 2) {
out = art_from_str("out.asm", '/');
} else {
out = art_from_str(argv[2], '/');
}
compile(&in, &out);
art_end(&in);
art_end(&out);
return 0;
}
|