aboutsummaryrefslogtreecommitdiff
path: root/src/parser.cpp
blob: 2bf25c7682e82e89ad6b09e4115df21ff350f0ac (plain)
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
#include "parser_pos.cpp"

gb_internal u64 ast_file_vet_flags(AstFile *f) {
	if (f->vet_flags_set) {
		return f->vet_flags;
	}
	return build_context.vet_flags;
}

gb_internal bool ast_file_vet_style(AstFile *f) {
	return (ast_file_vet_flags(f) & VetFlag_Style) != 0;
}


gb_internal bool file_allow_newline(AstFile *f) {
	bool is_strict = build_context.strict_style || ast_file_vet_style(f);
	return !is_strict;
}

gb_internal Token token_end_of_line(AstFile *f, Token tok) {
	u8 const *start = f->tokenizer.start + tok.pos.offset;
	u8 const *s = start;
	while (*s && *s != '\n' && s < f->tokenizer.end) {
		s += 1;
	}
	tok.pos.column += cast(i32)(s - start) - 1;
	return tok;
}

gb_internal gbString get_file_line_as_string(TokenPos const &pos, i32 *offset_) {
	AstFile *file = thread_safe_get_ast_file_from_id(pos.file_id);
	if (file == nullptr) {
		return nullptr;
	}
	isize offset = pos.offset;

	u8 *start = file->tokenizer.start;
	u8 *end = file->tokenizer.end;
	if (start == end) {
		return nullptr;
	}
	isize len = end-start;
	if (len < offset) {
		return nullptr;
	}

	u8 *pos_offset = start+offset;

	u8 *line_start = pos_offset;
	u8 *line_end  = pos_offset;
	while (line_start >= start) {
		if (*line_start == '\n') {
			line_start += 1;
			break;
		}
		line_start -= 1;
	}

	while (line_end < end) {
		if (*line_end == '\n') {
			break;
		}
		line_end += 1;
	}
	String the_line = make_string(line_start, line_end-line_start);
	the_line = string_trim_whitespace(the_line);

	if (offset_) *offset_ = cast(i32)(pos_offset - the_line.text);

	return gb_string_make_length(heap_allocator(), the_line.text, the_line.len);
}



gb_internal isize ast_node_size(AstKind kind) {
	return align_formula_isize(gb_size_of(AstCommonStuff) + ast_variant_sizes[kind], gb_align_of(void *));

}

gb_global std::atomic<isize> global_total_node_memory_allocated;

// NOTE(bill): And this below is why is I/we need a new language! Discriminated unions are a pain in C/C++
gb_internal Ast *alloc_ast_node(AstFile *f, AstKind kind) {
	isize size = ast_node_size(kind);

	Ast *node = cast(Ast *)arena_alloc(&global_thread_local_ast_arena, size, 16);
	node->kind = kind;
	node->file_id = f ? f->id : 0;

	global_total_node_memory_allocated.fetch_add(size);

	return node;
}

gb_internal Ast *clone_ast(Ast *node, AstFile *f = nullptr);
gb_internal Array<Ast *> clone_ast_array(Array<Ast *> const &array, AstFile *f) {
	Array<Ast *> result = {};
	if (array.count > 0) {
		result = array_make<Ast *>(ast_allocator(nullptr), array.count);
		for_array(i, array) {
			result[i] = clone_ast(array[i], f);
		}
	}
	return result;
}
gb_internal Slice<Ast *> clone_ast_array(Slice<Ast *> const &array, AstFile *f) {
	Slice<Ast *> result = {};
	if (array.count > 0) {
		result = slice_clone(ast_allocator(nullptr), array);
		for_array(i, array) {
			result[i] = clone_ast(array[i], f);
		}
	}
	return result;
}

gb_internal Ast *clone_ast(Ast *node, AstFile *f) {
	if (node == nullptr) {
		return nullptr;
	}
	if (f == nullptr) {
		f = node->thread_safe_file();
	}
	Ast *n = alloc_ast_node(f, node->kind);
	gb_memmove(n, node, ast_node_size(node->kind));

	switch (n->kind) {
	default: GB_PANIC("Unhandled Ast %.*s", LIT(ast_strings[n->kind])); break;

	case Ast_Invalid:        break;
	case Ast_Ident:
		n->Ident.entity = nullptr;
		break;
	case Ast_Implicit:       break;
	case Ast_Uninit:         break;
	case Ast_BasicLit:       break;
	case Ast_BasicDirective: break;

	case Ast_PolyType:
		n->PolyType.type           = clone_ast(n->PolyType.type, f);
		n->PolyType.specialization = clone_ast(n->PolyType.specialization, f);
		break;
	case Ast_Ellipsis:
		n->Ellipsis.expr = clone_ast(n->Ellipsis.expr, f);
		break;
	case Ast_ProcGroup:
		n->ProcGroup.args = clone_ast_array(n->ProcGroup.args, f);
		break;
	case Ast_ProcLit:
		n->ProcLit.type = clone_ast(n->ProcLit.type, f);
		n->ProcLit.body = clone_ast(n->ProcLit.body, f);
		n->ProcLit.where_clauses = clone_ast_array(n->ProcLit.where_clauses, f);
		break;
	case Ast_CompoundLit:
		n->CompoundLit.type  = clone_ast(n->CompoundLit.type, f);
		n->CompoundLit.elems = clone_ast_array(n->CompoundLit.elems, f);
		break;

	case Ast_BadExpr: break;
	case Ast_TagExpr:
		n->TagExpr.expr = clone_ast(n->TagExpr.expr, f);
		break;
	case Ast_UnaryExpr:
		n->UnaryExpr.expr = clone_ast(n->UnaryExpr.expr, f);
		break;
	case Ast_BinaryExpr:
		n->BinaryExpr.left  = clone_ast(n->BinaryExpr.left, f);
		n->BinaryExpr.right = clone_ast(n->BinaryExpr.right, f);
		break;
	case Ast_ParenExpr:
		n->ParenExpr.expr = clone_ast(n->ParenExpr.expr, f);
		break;
	case Ast_SelectorExpr:
		n->SelectorExpr.expr = clone_ast(n->SelectorExpr.expr, f);
		n->SelectorExpr.selector = clone_ast(n->SelectorExpr.selector, f);
		break;
	case Ast_ImplicitSelectorExpr:
		n->ImplicitSelectorExpr.selector = clone_ast(n->ImplicitSelectorExpr.selector, f);
		break;
	case Ast_SelectorCallExpr:
		n->SelectorCallExpr.expr = clone_ast(n->SelectorCallExpr.expr, f);
		n->SelectorCallExpr.call = clone_ast(n->SelectorCallExpr.call, f);
		break;
	case Ast_IndexExpr:
		n->IndexExpr.expr  = clone_ast(n->IndexExpr.expr, f);
		n->IndexExpr.index = clone_ast(n->IndexExpr.index, f);
		break;
	case Ast_MatrixIndexExpr:
		n->MatrixIndexExpr.expr  = clone_ast(n->MatrixIndexExpr.expr, f);
		n->MatrixIndexExpr.row_index = clone_ast(n->MatrixIndexExpr.row_index, f);
		n->MatrixIndexExpr.column_index = clone_ast(n->MatrixIndexExpr.column_index, f);
		break;
	case Ast_DerefExpr:
		n->DerefExpr.expr = clone_ast(n->DerefExpr.expr, f);
		break;
	case Ast_SliceExpr:
		n->SliceExpr.expr = clone_ast(n->SliceExpr.expr, f);
		n->SliceExpr.low  = clone_ast(n->SliceExpr.low, f);
		n->SliceExpr.high = clone_ast(n->SliceExpr.high, f);
		break;
	case Ast_CallExpr:
		n->CallExpr.proc = clone_ast(n->CallExpr.proc, f);
		n->CallExpr.args = clone_ast_array(n->CallExpr.args, f);
		break;

	case Ast_FieldValue:
		n->FieldValue.field = clone_ast(n->FieldValue.field, f);
		n->FieldValue.value = clone_ast(n->FieldValue.value, f);
		break;

	case Ast_EnumFieldValue:
		n->EnumFieldValue.name = clone_ast(n->EnumFieldValue.name, f);
		n->EnumFieldValue.value = clone_ast(n->EnumFieldValue.value, f);
		break;

	case Ast_TernaryIfExpr:
		n->TernaryIfExpr.x    = clone_ast(n->TernaryIfExpr.x, f);
		n->TernaryIfExpr.cond = clone_ast(n->TernaryIfExpr.cond, f);
		n->TernaryIfExpr.y    = clone_ast(n->TernaryIfExpr.y, f);
		break;
	case Ast_TernaryWhenExpr:
		n->TernaryWhenExpr.x    = clone_ast(n->TernaryWhenExpr.x, f);
		n->TernaryWhenExpr.cond = clone_ast(n->TernaryWhenExpr.cond, f);
		n->TernaryWhenExpr.y    = clone_ast(n->TernaryWhenExpr.y, f);
		break;
	case Ast_OrElseExpr:
		n->OrElseExpr.x = clone_ast(n->OrElseExpr.x, f);
		n->OrElseExpr.y = clone_ast(n->OrElseExpr.y, f);
		break;
	case Ast_OrReturnExpr:
		n->OrReturnExpr.expr = clone_ast(n->OrReturnExpr.expr, f);
		break;
	case Ast_OrBranchExpr:
		n->OrBranchExpr.label = clone_ast(n->OrBranchExpr.label, f);
		n->OrBranchExpr.expr  = clone_ast(n->OrBranchExpr.expr, f);
		break;
	case Ast_TypeAssertion:
		n->TypeAssertion.expr = clone_ast(n->TypeAssertion.expr, f);
		n->TypeAssertion.type = clone_ast(n->TypeAssertion.type, f);
		break;
	case Ast_TypeCast:
		n->TypeCast.type = clone_ast(n->TypeCast.type, f);
		n->TypeCast.expr = clone_ast(n->TypeCast.expr, f);
		break;
	case Ast_AutoCast:
		n->AutoCast.expr = clone_ast(n->AutoCast.expr, f);
		break;

	case Ast_InlineAsmExpr:
		n->InlineAsmExpr.param_types        = clone_ast_array(n->InlineAsmExpr.param_types, f);
		n->InlineAsmExpr.return_type        = clone_ast(n->InlineAsmExpr.return_type, f);
		n->InlineAsmExpr.asm_string         = clone_ast(n->InlineAsmExpr.asm_string, f);
		n->InlineAsmExpr.constraints_string = clone_ast(n->InlineAsmExpr.constraints_string, f);
		break;

	case Ast_BadStmt:   break;
	case Ast_EmptyStmt: break;
	case Ast_ExprStmt:
		n->ExprStmt.expr = clone_ast(n->ExprStmt.expr, f);
		break;
	case Ast_AssignStmt:
		n->AssignStmt.lhs = clone_ast_array(n->AssignStmt.lhs, f);
		n->AssignStmt.rhs = clone_ast_array(n->AssignStmt.rhs, f);
		break;
	case Ast_BlockStmt:
		n->BlockStmt.label = clone_ast(n->BlockStmt.label, f);
		n->BlockStmt.stmts = clone_ast_array(n->BlockStmt.stmts, f);
		break;
	case Ast_IfStmt:
		n->IfStmt.label = clone_ast(n->IfStmt.label, f);
		n->IfStmt.init = clone_ast(n->IfStmt.init, f);
		n->IfStmt.cond = clone_ast(n->IfStmt.cond, f);
		n->IfStmt.body = clone_ast(n->IfStmt.body, f);
		n->IfStmt.else_stmt = clone_ast(n->IfStmt.else_stmt, f);
		break;
	case Ast_WhenStmt:
		n->WhenStmt.cond = clone_ast(n->WhenStmt.cond, f);
		n->WhenStmt.body = clone_ast(n->WhenStmt.body, f);
		n->WhenStmt.else_stmt = clone_ast(n->WhenStmt.else_stmt, f);
		break;
	case Ast_ReturnStmt:
		n->ReturnStmt.results = clone_ast_array(n->ReturnStmt.results, f);
		break;
	case Ast_ForStmt:
		n->ForStmt.label = clone_ast(n->ForStmt.label, f);
		n->ForStmt.init  = clone_ast(n->ForStmt.init, f);
		n->ForStmt.cond  = clone_ast(n->ForStmt.cond, f);
		n->ForStmt.post  = clone_ast(n->ForStmt.post, f);
		n->ForStmt.body  = clone_ast(n->ForStmt.body, f);
		break;
	case Ast_RangeStmt:
		n->RangeStmt.label = clone_ast(n->RangeStmt.label, f);
		n->RangeStmt.vals  = clone_ast_array(n->RangeStmt.vals, f);
		n->RangeStmt.expr  = clone_ast(n->RangeStmt.expr, f);
		n->RangeStmt.body  = clone_ast(n->RangeStmt.body, f);
		break;
	case Ast_UnrollRangeStmt:
		n->UnrollRangeStmt.val0  = clone_ast(n->UnrollRangeStmt.val0, f);
		n->UnrollRangeStmt.val1  = clone_ast(n->UnrollRangeStmt.val1, f);
		n->UnrollRangeStmt.expr  = clone_ast(n->UnrollRangeStmt.expr, f);
		n->UnrollRangeStmt.body  = clone_ast(n->UnrollRangeStmt.body, f);
		break;
	case Ast_CaseClause:
		n->CaseClause.list  = clone_ast_array(n->CaseClause.list, f);
		n->CaseClause.stmts = clone_ast_array(n->CaseClause.stmts, f);
		n->CaseClause.implicit_entity = nullptr;
		break;
	case Ast_SwitchStmt:
		n->SwitchStmt.label = clone_ast(n->SwitchStmt.label, f);
		n->SwitchStmt.init  = clone_ast(n->SwitchStmt.init, f);
		n->SwitchStmt.tag   = clone_ast(n->SwitchStmt.tag, f);
		n->SwitchStmt.body  = clone_ast(n->SwitchStmt.body, f);
		break;
	case Ast_TypeSwitchStmt:
		n->TypeSwitchStmt.label = clone_ast(n->TypeSwitchStmt.label, f);
		n->TypeSwitchStmt.tag   = clone_ast(n->TypeSwitchStmt.tag, f);
		n->TypeSwitchStmt.body  = clone_ast(n->TypeSwitchStmt.body, f);
		break;
	case Ast_DeferStmt:
		n->DeferStmt.stmt = clone_ast(n->DeferStmt.stmt, f);
		break;
	case Ast_BranchStmt:
		n->BranchStmt.label = clone_ast(n->BranchStmt.label, f);
		break;
	case Ast_UsingStmt:
		n->UsingStmt.list = clone_ast_array(n->UsingStmt.list, f);
		break;

	case Ast_BadDecl: break;

	case Ast_ForeignBlockDecl:
		n->ForeignBlockDecl.foreign_library = clone_ast(n->ForeignBlockDecl.foreign_library, f);
		n->ForeignBlockDecl.body            = clone_ast(n->ForeignBlockDecl.body, f);
		n->ForeignBlockDecl.attributes      = clone_ast_array(n->ForeignBlockDecl.attributes, f);
		break;
	case Ast_Label:
		n->Label.name = clone_ast(n->Label.name, f);
		break;
	case Ast_ValueDecl:
		n->ValueDecl.names  = clone_ast_array(n->ValueDecl.names, f);
		n->ValueDecl.type   = clone_ast(n->ValueDecl.type, f);
		n->ValueDecl.values = clone_ast_array(n->ValueDecl.values, f);
		n->ValueDecl.attributes = clone_ast_array(n->ValueDecl.attributes, f);
		break;

	case Ast_Attribute:
		n->Attribute.elems = clone_ast_array(n->Attribute.elems, f);
		break;
	case Ast_Field:
		n->Field.names = clone_ast_array(n->Field.names, f);
		n->Field.type  = clone_ast(n->Field.type, f);
		break;
	case Ast_BitFieldField:
		n->BitFieldField.name     = clone_ast(n->BitFieldField.name, f);
		n->BitFieldField.type     = clone_ast(n->BitFieldField.type, f);
		n->BitFieldField.bit_size = clone_ast(n->BitFieldField.bit_size, f);
		break;
	case Ast_FieldList:
		n->FieldList.list = clone_ast_array(n->FieldList.list, f);
		break;

	case Ast_TypeidType:
		n->TypeidType.specialization = clone_ast(n->TypeidType.specialization, f);
		break;
	case Ast_HelperType:
		n->HelperType.type = clone_ast(n->HelperType.type, f);
		break;
	case Ast_DistinctType:
		n->DistinctType.type = clone_ast(n->DistinctType.type, f);
		break;
	case Ast_ProcType:
		n->ProcType.params  = clone_ast(n->ProcType.params, f);
		n->ProcType.results = clone_ast(n->ProcType.results, f);
		break;
	case Ast_RelativeType:
		n->RelativeType.tag  = clone_ast(n->RelativeType.tag, f);
		n->RelativeType.type = clone_ast(n->RelativeType.type, f);
		break;
	case Ast_PointerType:
		n->PointerType.type = clone_ast(n->PointerType.type, f);
		n->PointerType.tag  = clone_ast(n->PointerType.tag, f);
		break;
	case Ast_MultiPointerType:
		n->MultiPointerType.type = clone_ast(n->MultiPointerType.type, f);
		break;
	case Ast_ArrayType:
		n->ArrayType.count = clone_ast(n->ArrayType.count, f);
		n->ArrayType.elem  = clone_ast(n->ArrayType.elem, f);
		n->ArrayType.tag   = clone_ast(n->ArrayType.tag, f);
		break;
	case Ast_DynamicArrayType:
		n->DynamicArrayType.elem = clone_ast(n->DynamicArrayType.elem, f);
		break;
	case Ast_StructType:
		n->StructType.fields             = clone_ast_array(n->StructType.fields, f);
		n->StructType.polymorphic_params = clone_ast(n->StructType.polymorphic_params, f);
		n->StructType.align              = clone_ast(n->StructType.align, f);
		n->StructType.field_align        = clone_ast(n->StructType.field_align, f);
		n->StructType.where_clauses      = clone_ast_array(n->StructType.where_clauses, f);
		break;
	case Ast_UnionType:
		n->UnionType.variants = clone_ast_array(n->UnionType.variants, f);
		n->UnionType.polymorphic_params = clone_ast(n->UnionType.polymorphic_params, f);
		n->UnionType.where_clauses = clone_ast_array(n->UnionType.where_clauses, f);
		break;
	case Ast_EnumType:
		n->EnumType.base_type = clone_ast(n->EnumType.base_type, f);
		n->EnumType.fields    = clone_ast_array(n->EnumType.fields, f);
		break;
	case Ast_BitSetType:
		n->BitSetType.elem       = clone_ast(n->BitSetType.elem, f);
		n->BitSetType.underlying = clone_ast(n->BitSetType.underlying, f);
		break;
	case Ast_BitFieldType:
		n->BitFieldType.backing_type = clone_ast(n->BitFieldType.backing_type, f);
		n->BitFieldType.fields = clone_ast_array(n->BitFieldType.fields, f);
		break;
	case Ast_MapType:
		n->MapType.count = clone_ast(n->MapType.count, f);
		n->MapType.key   = clone_ast(n->MapType.key, f);
		n->MapType.value = clone_ast(n->MapType.value, f);
		break;
	case Ast_MatrixType:
		n->MatrixType.row_count    = clone_ast(n->MatrixType.row_count, f);
		n->MatrixType.column_count = clone_ast(n->MatrixType.column_count, f);
		n->MatrixType.elem         = clone_ast(n->MatrixType.elem, f);
		break;
	}

	return n;
}


gb_internal void error(Ast *node, char const *fmt, ...) {
	Token token = {};
	TokenPos end_pos = {};
	if (node != nullptr) {
		token = ast_token(node);
		end_pos = ast_end_pos(node);
	}

	va_list va;
	va_start(va, fmt);
	error_va(token.pos, end_pos, fmt, va);
	va_end(va);
	if (node != nullptr && node->file_id != 0) {
		AstFile *f = node->thread_safe_file();
		f->error_count += 1;
	}
}

gb_internal void syntax_error_with_verbose(Ast *node, char const *fmt, ...) {
	Token token = {};
	TokenPos end_pos = {};
	if (node != nullptr) {
		token = ast_token(node);
		end_pos = ast_end_pos(node);
	}

	va_list va;
	va_start(va, fmt);
	syntax_error_with_verbose_va(token.pos, end_pos, fmt, va);
	va_end(va);
	if (node != nullptr && node->file_id != 0) {
		AstFile *f = node->thread_safe_file();
		f->error_count += 1;
	}
}


gb_internal void error_no_newline(Ast *node, char const *fmt, ...) {
	Token token = {};
	if (node != nullptr) {
		token = ast_token(node);
	}
	va_list va;
	va_start(va, fmt);
	error_no_newline_va(token.pos, fmt, va);
	va_end(va);
	if (node != nullptr && node->file_id != 0) {
		AstFile *f = node->thread_safe_file();
		f->error_count += 1;
	}
}

gb_internal void warning(Ast *node, char const *fmt, ...) {
	Token token = {};
	TokenPos end_pos = {};
	if (node != nullptr) {
		token = ast_token(node);
		end_pos = ast_end_pos(node);
	}
	va_list va;
	va_start(va, fmt);
	warning_va(token.pos, end_pos, fmt, va);
	va_end(va);
}

gb_internal void syntax_error(Ast *node, char const *fmt, ...) {
	Token token = {};
	TokenPos end_pos = {};
	if (node != nullptr) {
		token = ast_token(node);
		end_pos = ast_end_pos(node);
	}
	va_list va;
	va_start(va, fmt);
	syntax_error_va(token.pos, end_pos, fmt, va);
	va_end(va);
	if (node != nullptr && node->file_id != 0) {
		AstFile *f = node->thread_safe_file();
		f->error_count += 1;
	}
}


gb_internal bool ast_node_expect(Ast *node, AstKind kind) {
	if (node->kind != kind) {
		syntax_error(node, "Expected %.*s, got %.*s", LIT(ast_strings[kind]), LIT(ast_strings[node->kind]));
		return false;
	}
	return true;
}
gb_internal bool ast_node_expect2(Ast *node, AstKind kind0, AstKind kind1) {
	if (node->kind != kind0 && node->kind != kind1) {
		syntax_error(node, "Expected %.*s or %.*s, got %.*s", LIT(ast_strings[kind0]), LIT(ast_strings[kind1]), LIT(ast_strings[node->kind]));
		return false;
	}
	return true;
}

gb_internal Ast *ast_bad_expr(AstFile *f, Token begin, Token end) {
	Ast *result = alloc_ast_node(f, Ast_BadExpr);
	result->BadExpr.begin = begin;
	result->BadExpr.end   = end;
	return result;
}

gb_internal Ast *ast_tag_expr(AstFile *f, Token token, Token name, Ast *expr) {
	Ast *result = alloc_ast_node(f, Ast_TagExpr);
	result->TagExpr.token = token;
	result->TagExpr.name = name;
	result->TagExpr.expr = expr;
	return result;
}

gb_internal Ast *ast_unary_expr(AstFile *f, Token op, Ast *expr) {
	Ast *result = alloc_ast_node(f, Ast_UnaryExpr);

	if (expr) switch (expr->kind) {
	case Ast_OrReturnExpr:
		syntax_error_with_verbose(expr, "'or_return' within an unary expression not wrapped in parentheses (...)");
		break;
	case Ast_OrBranchExpr:
		syntax_error_with_verbose(expr, "'or_%.*s' within an unary expression not wrapped in parentheses (...)", LIT(expr->OrBranchExpr.token.string));
		break;
	}

	result->UnaryExpr.op = op;
	result->UnaryExpr.expr = expr;
	return result;
}


gb_internal Ast *ast_binary_expr(AstFile *f, Token op, Ast *left, Ast *right) {
	Ast *result = alloc_ast_node(f, Ast_BinaryExpr);

	if (left == nullptr) {
		syntax_error(op, "No lhs expression for binary expression '%.*s'", LIT(op.string));
		left = ast_bad_expr(f, op, op);
	}
	if (right == nullptr) {
		syntax_error(op, "No rhs expression for binary expression '%.*s'", LIT(op.string));
		right = ast_bad_expr(f, op, op);
	}


	if (left) switch (left->kind) {
	case Ast_OrReturnExpr:
		syntax_error_with_verbose(left, "'or_return' within a binary expression not wrapped in parentheses (...)");
		break;
	case Ast_OrBranchExpr:
		syntax_error_with_verbose(left, "'or_%.*s' within a binary expression not wrapped in parentheses (...)", LIT(left->OrBranchExpr.token.string));
		break;
	}
	if (right) switch (right->kind) {
	case Ast_OrReturnExpr:
		syntax_error_with_verbose(right, "'or_return' within a binary expression not wrapped in parentheses (...)");
		break;
	case Ast_OrBranchExpr:
		syntax_error_with_verbose(right, "'or_%.*s' within a binary expression not wrapped in parentheses (...)", LIT(right->OrBranchExpr.token.string));
		break;
	}

	result->BinaryExpr.op = op;
	result->BinaryExpr.left = left;
	result->BinaryExpr.right = right;

	return result;
}

gb_internal Ast *ast_paren_expr(AstFile *f, Ast *expr, Token open, Token close) {
	Ast *result = alloc_ast_node(f, Ast_ParenExpr);
	result->ParenExpr.expr = expr;
	result->ParenExpr.open = open;
	result->ParenExpr.close = close;
	return result;
}

gb_internal Ast *ast_call_expr(AstFile *f, Ast *proc, Array<Ast *> const &args, Token open, Token close, Token ellipsis) {
	Ast *result = alloc_ast_node(f, Ast_CallExpr);
	result->CallExpr.proc     = proc;
	result->CallExpr.args     = slice_from_array(args);
	result->CallExpr.open     = open;
	result->CallExpr.close    = close;
	result->CallExpr.ellipsis = ellipsis;
	return result;
}


gb_internal Ast *ast_selector_expr(AstFile *f, Token token, Ast *expr, Ast *selector) {
	Ast *result = alloc_ast_node(f, Ast_SelectorExpr);
	result->SelectorExpr.token = token;
	result->SelectorExpr.expr = expr;
	result->SelectorExpr.selector = selector;
	return result;
}

gb_internal Ast *ast_implicit_selector_expr(AstFile *f, Token token, Ast *selector) {
	Ast *result = alloc_ast_node(f, Ast_ImplicitSelectorExpr);
	result->ImplicitSelectorExpr.token = token;
	result->ImplicitSelectorExpr.selector = selector;
	return result;
}

gb_internal Ast *ast_selector_call_expr(AstFile *f, Token token, Ast *expr, Ast *call) {
	Ast *result = alloc_ast_node(f, Ast_SelectorCallExpr);
	result->SelectorCallExpr.token = token;
	result->SelectorCallExpr.expr = expr;
	result->SelectorCallExpr.call = call;
	return result;
}


gb_internal Ast *ast_index_expr(AstFile *f, Ast *expr, Ast *index, Token open, Token close) {
	Ast *result = alloc_ast_node(f, Ast_IndexExpr);
	result->IndexExpr.expr = expr;
	result->IndexExpr.index = index;
	result->IndexExpr.open = open;
	result->IndexExpr.close = close;
	return result;
}


gb_internal Ast *ast_slice_expr(AstFile *f, Ast *expr, Token open, Token close, Token interval, Ast *low, Ast *high) {
	Ast *result = alloc_ast_node(f, Ast_SliceExpr);
	result->SliceExpr.expr = expr;
	result->SliceExpr.open = open;
	result->SliceExpr.close = close;
	result->SliceExpr.interval = interval;
	result->SliceExpr.low = low;
	result->SliceExpr.high = high;
	return result;
}

gb_internal Ast *ast_deref_expr(AstFile *f, Ast *expr, Token op) {
	Ast *result = alloc_ast_node(f, Ast_DerefExpr);
	result->DerefExpr.expr = expr;
	result->DerefExpr.op = op;
	return result;
}


gb_internal Ast *ast_matrix_index_expr(AstFile *f, Ast *expr, Token open, Token close, Token interval, Ast *row, Ast *column) {
	Ast *result = alloc_ast_node(f, Ast_MatrixIndexExpr);
	result->MatrixIndexExpr.expr         = expr;
	result->MatrixIndexExpr.row_index    = row;
	result->MatrixIndexExpr.column_index = column;
	result->MatrixIndexExpr.open         = open;
	result->MatrixIndexExpr.close        = close;
	return result;
}


gb_internal Ast *ast_ident(AstFile *f, Token token) {
	Ast *result = alloc_ast_node(f, Ast_Ident);
	result->Ident.token = token;
	return result;
}

gb_internal Ast *ast_implicit(AstFile *f, Token token) {
	Ast *result = alloc_ast_node(f, Ast_Implicit);
	result->Implicit = token;
	return result;
}
gb_internal Ast *ast_uninit(AstFile *f, Token token) {
	Ast *result = alloc_ast_node(f, Ast_Uninit);
	result->Uninit = token;
	return result;
}

gb_internal ExactValue exact_value_from_token(AstFile *f, Token const &token) {
	String s = token.string;
	switch (token.kind) {
	case Token_Rune:
		if (!unquote_string(ast_allocator(f), &s, 0)) {
			syntax_error(token, "Invalid rune literal");
		}
		break;
	case Token_String:
		if (!unquote_string(ast_allocator(f), &s, 0, s.text[0] == '`')) {
			syntax_error(token, "Invalid string literal");
		}
		break;
	}
	ExactValue value = exact_value_from_basic_literal(token.kind, s);
	if (value.kind == ExactValue_Invalid) {
		syntax_error(token, "Invalid token literal");
	}
	return value;
}

gb_internal String string_value_from_token(AstFile *f, Token const &token) {
	ExactValue value = exact_value_from_token(f, token);
	String str = {};
	if (value.kind == ExactValue_String) {
		str = value.value_string;
	}
	return str;
}


gb_internal Ast *ast_basic_lit(AstFile *f, Token basic_lit) {
	Ast *result = alloc_ast_node(f, Ast_BasicLit);
	result->BasicLit.token = basic_lit;
	result->tav.mode = Addressing_Constant;
	result->tav.value = exact_value_from_token(f, basic_lit);
	return result;
}

gb_internal Ast *ast_basic_directive(AstFile *f, Token token, Token name) {
	Ast *result = alloc_ast_node(f, Ast_BasicDirective);
	result->BasicDirective.token = token;
	result->BasicDirective.name = name;
	return result;
}

gb_internal Ast *ast_ellipsis(AstFile *f, Token token, Ast *expr) {
	Ast *result = alloc_ast_node(f, Ast_Ellipsis);
	result->Ellipsis.token = token;
	result->Ellipsis.expr = expr;
	return result;
}


gb_internal Ast *ast_proc_group(AstFile *f, Token token, Token open, Token close, Array<Ast *> const &args) {
	Ast *result = alloc_ast_node(f, Ast_ProcGroup);
	result->ProcGroup.token = token;
	result->ProcGroup.open  = open;
	result->ProcGroup.close = close;
	result->ProcGroup.args = slice_from_array(args);
	return result;
}

gb_internal Ast *ast_proc_lit(AstFile *f, Ast *type, Ast *body, u64 tags, Token where_token, Array<Ast *> const &where_clauses) {
	Ast *result = alloc_ast_node(f, Ast_ProcLit);
	result->ProcLit.type = type;
	result->ProcLit.body = body;
	result->ProcLit.tags = tags;
	result->ProcLit.where_token = where_token;
	result->ProcLit.where_clauses = slice_from_array(where_clauses);
	return result;
}

gb_internal Ast *ast_field_value(AstFile *f, Ast *field, Ast *value, Token eq) {
	Ast *result = alloc_ast_node(f, Ast_FieldValue);
	result->FieldValue.field = field;
	result->FieldValue.value = value;
	result->FieldValue.eq = eq;
	return result;
}


gb_internal Ast *ast_enum_field_value(AstFile *f, Ast *name, Ast *value, CommentGroup *docs, CommentGroup *comment) {
	Ast *result = alloc_ast_node(f, Ast_EnumFieldValue);
	result->EnumFieldValue.name = name;
	result->EnumFieldValue.value = value;
	result->EnumFieldValue.docs = docs;
	result->EnumFieldValue.comment = comment;
	return result;
}

gb_internal Ast *ast_compound_lit(AstFile *f, Ast *type, Array<Ast *> const &elems, Token open, Token close) {
	Ast *result = alloc_ast_node(f, Ast_CompoundLit);
	result->CompoundLit.type = type;
	result->CompoundLit.elems = slice_from_array(elems);
	result->CompoundLit.open = open;
	result->CompoundLit.close = close;
	return result;
}


gb_internal Ast *ast_ternary_if_expr(AstFile *f, Ast *x, Ast *cond, Ast *y) {
	Ast *result = alloc_ast_node(f, Ast_TernaryIfExpr);
	result->TernaryIfExpr.x = x;
	result->TernaryIfExpr.cond = cond;
	result->TernaryIfExpr.y = y;
	return result;
}
gb_internal Ast *ast_ternary_when_expr(AstFile *f, Ast *x, Ast *cond, Ast *y) {
	Ast *result = alloc_ast_node(f, Ast_TernaryWhenExpr);
	result->TernaryWhenExpr.x = x;
	result->TernaryWhenExpr.cond = cond;
	result->TernaryWhenExpr.y = y;
	return result;
}

gb_internal Ast *ast_or_else_expr(AstFile *f, Ast *x, Token const &token, Ast *y) {
	Ast *result = alloc_ast_node(f, Ast_OrElseExpr);
	result->OrElseExpr.x = x;
	result->OrElseExpr.token = token;
	result->OrElseExpr.y = y;
	return result;
}

gb_internal Ast *ast_or_return_expr(AstFile *f, Ast *expr, Token const &token) {
	Ast *result = alloc_ast_node(f, Ast_OrReturnExpr);
	result->OrReturnExpr.expr = expr;
	result->OrReturnExpr.token = token;
	return result;
}

gb_internal Ast *ast_or_branch_expr(AstFile *f, Ast *expr, Token const &token, Ast *label) {
	Ast *result = alloc_ast_node(f, Ast_OrBranchExpr);
	result->OrBranchExpr.expr = expr;
	result->OrBranchExpr.token = token;
	result->OrBranchExpr.label = label;
	return result;
}

gb_internal Ast *ast_type_assertion(AstFile *f, Ast *expr, Token dot, Ast *type) {
	Ast *result = alloc_ast_node(f, Ast_TypeAssertion);
	result->TypeAssertion.expr = expr;
	result->TypeAssertion.dot  = dot;
	result->TypeAssertion.type = type;
	return result;
}
gb_internal Ast *ast_type_cast(AstFile *f, Token token, Ast *type, Ast *expr) {
	Ast *result = alloc_ast_node(f, Ast_TypeCast);
	result->TypeCast.token = token;
	result->TypeCast.type  = type;
	result->TypeCast.expr  = expr;
	return result;
}
gb_internal Ast *ast_auto_cast(AstFile *f, Token token, Ast *expr) {
	Ast *result = alloc_ast_node(f, Ast_AutoCast);
	result->AutoCast.token = token;
	result->AutoCast.expr  = expr;
	return result;
}


gb_internal Ast *ast_inline_asm_expr(AstFile *f, Token token, Token open, Token close,
                         Array<Ast *> const &param_types,
                         Ast *return_type,
                         Ast *asm_string,
                         Ast *constraints_string,
                         bool has_side_effects,
                         bool is_align_stack,
                         InlineAsmDialectKind dialect) {

	Ast *result = alloc_ast_node(f, Ast_InlineAsmExpr);
	result->InlineAsmExpr.token              = token;
	result->InlineAsmExpr.open               = open;
	result->InlineAsmExpr.close              = close;
	result->InlineAsmExpr.param_types        = slice_from_array(param_types);
	result->InlineAsmExpr.return_type        = return_type;
	result->InlineAsmExpr.asm_string         = asm_string;
	result->InlineAsmExpr.constraints_string = constraints_string;
	result->InlineAsmExpr.has_side_effects   = has_side_effects;
	result->InlineAsmExpr.is_align_stack     = is_align_stack;
	result->InlineAsmExpr.dialect            = dialect;
	return result;
}




gb_internal Ast *ast_bad_stmt(AstFile *f, Token begin, Token end) {
	Ast *result = alloc_ast_node(f, Ast_BadStmt);
	result->BadStmt.begin = begin;
	result->BadStmt.end   = end;
	return result;
}

gb_internal Ast *ast_empty_stmt(AstFile *f, Token token) {
	Ast *result = alloc_ast_node(f, Ast_EmptyStmt);
	result->EmptyStmt.token = token;
	return result;
}

gb_internal Ast *ast_expr_stmt(AstFile *f, Ast *expr) {
	Ast *result = alloc_ast_node(f, Ast_ExprStmt);
	result->ExprStmt.expr = expr;
	return result;
}

gb_internal Ast *ast_assign_stmt(AstFile *f, Token op, Array<Ast *> const &lhs, Array<Ast *> const &rhs) {
	Ast *result = alloc_ast_node(f, Ast_AssignStmt);
	result->AssignStmt.op = op;
	result->AssignStmt.lhs = slice_from_array(lhs);
	result->AssignStmt.rhs = slice_from_array(rhs);
	return result;
}


gb_internal Ast *ast_block_stmt(AstFile *f, Array<Ast *> const &stmts, Token open, Token close) {
	Ast *result = alloc_ast_node(f, Ast_BlockStmt);
	result->BlockStmt.stmts = slice_from_array(stmts);
	result->BlockStmt.open = open;
	result->BlockStmt.close = close;
	return result;
}

gb_internal Ast *ast_if_stmt(AstFile *f, Token token, Ast *init, Ast *cond, Ast *body, Ast *else_stmt) {
	Ast *result = alloc_ast_node(f, Ast_IfStmt);
	result->IfStmt.token = token;
	result->IfStmt.init = init;
	result->IfStmt.cond = cond;
	result->IfStmt.body = body;
	result->IfStmt.else_stmt = else_stmt;
	return result;
}

gb_internal Ast *ast_when_stmt(AstFile *f, Token token, Ast *cond, Ast *body, Ast *else_stmt) {
	Ast *result = alloc_ast_node(f, Ast_WhenStmt);
	result->WhenStmt.token = token;
	result->WhenStmt.cond = cond;
	result->WhenStmt.body = body;
	result->WhenStmt.else_stmt = else_stmt;
	return result;
}


gb_internal Ast *ast_return_stmt(AstFile *f, Token token, Array<Ast *> const &results) {
	Ast *result = alloc_ast_node(f, Ast_ReturnStmt);
	result->ReturnStmt.token = token;
	result->ReturnStmt.results = slice_from_array(results);
	return result;
}


gb_internal Ast *ast_for_stmt(AstFile *f, Token token, Ast *init, Ast *cond, Ast *post, Ast *body) {
	Ast *result = alloc_ast_node(f, Ast_ForStmt);
	result->ForStmt.token = token;
	result->ForStmt.init  = init;
	result->ForStmt.cond  = cond;
	result->ForStmt.post  = post;
	result->ForStmt.body  = body;
	return result;
}

gb_internal Ast *ast_range_stmt(AstFile *f, Token token, Slice<Ast *> vals, Token in_token, Ast *expr, Ast *body) {
	Ast *result = alloc_ast_node(f, Ast_RangeStmt);
	result->RangeStmt.token = token;
	result->RangeStmt.vals = vals;
	result->RangeStmt.in_token = in_token;
	result->RangeStmt.expr  = expr;
	result->RangeStmt.body  = body;
	return result;
}

gb_internal Ast *ast_unroll_range_stmt(AstFile *f, Token unroll_token, Token for_token, Ast *val0, Ast *val1, Token in_token, Ast *expr, Ast *body) {
	Ast *result = alloc_ast_node(f, Ast_UnrollRangeStmt);
	result->UnrollRangeStmt.unroll_token = unroll_token;
	result->UnrollRangeStmt.for_token = for_token;
	result->UnrollRangeStmt.val0 = val0;
	result->UnrollRangeStmt.val1 = val1;
	result->UnrollRangeStmt.in_token = in_token;
	result->UnrollRangeStmt.expr  = expr;
	result->UnrollRangeStmt.body  = body;
	return result;
}

gb_internal Ast *ast_switch_stmt(AstFile *f, Token token, Ast *init, Ast *tag, Ast *body) {
	Ast *result = alloc_ast_node(f, Ast_SwitchStmt);
	result->SwitchStmt.token = token;
	result->SwitchStmt.init  = init;
	result->SwitchStmt.tag   = tag;
	result->SwitchStmt.body  = body;
	result->SwitchStmt.partial = false;
	return result;
}


gb_internal Ast *ast_type_switch_stmt(AstFile *f, Token token, Ast *tag, Ast *body) {
	Ast *result = alloc_ast_node(f, Ast_TypeSwitchStmt);
	result->TypeSwitchStmt.token = token;
	result->TypeSwitchStmt.tag   = tag;
	result->TypeSwitchStmt.body  = body;
	result->TypeSwitchStmt.partial = false;
	return result;
}

gb_internal Ast *ast_case_clause(AstFile *f, Token token, Array<Ast *> const &list, Array<Ast *> const &stmts) {
	Ast *result = alloc_ast_node(f, Ast_CaseClause);
	result->CaseClause.token = token;
	result->CaseClause.list  = slice_from_array(list);
	result->CaseClause.stmts = slice_from_array(stmts);
	return result;
}


gb_internal Ast *ast_defer_stmt(AstFile *f, Token token, Ast *stmt) {
	Ast *result = alloc_ast_node(f, Ast_DeferStmt);
	result->DeferStmt.token = token;
	result->DeferStmt.stmt = stmt;
	return result;
}

gb_internal Ast *ast_branch_stmt(AstFile *f, Token token, Ast *label) {
	Ast *result = alloc_ast_node(f, Ast_BranchStmt);
	result->BranchStmt.token = token;
	result->BranchStmt.label = label;
	return result;
}

gb_internal Ast *ast_using_stmt(AstFile *f, Token token, Array<Ast *> const &list) {
	Ast *result = alloc_ast_node(f, Ast_UsingStmt);
	result->UsingStmt.token = token;
	result->UsingStmt.list  = slice_from_array(list);
	return result;
}



gb_internal Ast *ast_bad_decl(AstFile *f, Token begin, Token end) {
	Ast *result = alloc_ast_node(f, Ast_BadDecl);
	result->BadDecl.begin = begin;
	result->BadDecl.end = end;
	return result;
}

gb_internal Ast *ast_field(AstFile *f, Array<Ast *> const &names, Ast *type, Ast *default_value, u32 flags, Token tag,
               CommentGroup *docs, CommentGroup *comment) {
	Ast *result = alloc_ast_node(f, Ast_Field);
	result->Field.names         = slice_from_array(names);
	result->Field.type          = type;
	result->Field.default_value = default_value;
	result->Field.flags         = flags;
	result->Field.tag           = tag;
	result->Field.docs          = docs;
	result->Field.comment       = comment;
	return result;
}

gb_internal Ast *ast_bit_field_field(AstFile *f, Ast *name, Ast *type, Ast *bit_size, Token tag,
                                     CommentGroup *docs, CommentGroup *comment) {
	Ast *result = alloc_ast_node(f, Ast_BitFieldField);
	result->BitFieldField.name     = name;
	result->BitFieldField.type     = type;
	result->BitFieldField.bit_size = bit_size;
	result->BitFieldField.tag      = tag;
	result->BitFieldField.docs     = docs;
	result->BitFieldField.comment  = comment;
	return result;
}

gb_internal Ast *ast_field_list(AstFile *f, Token token, Array<Ast *> const &list) {
	Ast *result = alloc_ast_node(f, Ast_FieldList);
	result->FieldList.token = token;
	result->FieldList.list  = slice_from_array(list);
	return result;
}

gb_internal Ast *ast_typeid_type(AstFile *f, Token token, Ast *specialization) {
	Ast *result = alloc_ast_node(f, Ast_TypeidType);
	result->TypeidType.token = token;
	result->TypeidType.specialization = specialization;
	return result;
}

gb_internal Ast *ast_helper_type(AstFile *f, Token token, Ast *type) {
	Ast *result = alloc_ast_node(f, Ast_HelperType);
	result->HelperType.token = token;
	result->HelperType.type  = type;
	return result;
}

gb_internal Ast *ast_distinct_type(AstFile *f, Token token, Ast *type) {
	Ast *result = alloc_ast_node(f, Ast_DistinctType);
	result->DistinctType.token = token;
	result->DistinctType.type  = type;
	return result;
}


gb_internal Ast *ast_poly_type(AstFile *f, Token token, Ast *type, Ast *specialization) {
	Ast *result = alloc_ast_node(f, Ast_PolyType);
	result->PolyType.token = token;
	result->PolyType.type   = type;
	result->PolyType.specialization = specialization;
	return result;
}


gb_internal Ast *ast_proc_type(AstFile *f, Token token, Ast *params, Ast *results, u64 tags, ProcCallingConvention calling_convention, bool generic, bool diverging) {
	Ast *result = alloc_ast_node(f, Ast_ProcType);
	result->ProcType.token = token;
	result->ProcType.params = params;
	result->ProcType.results = results;
	result->ProcType.tags = tags;
	result->ProcType.calling_convention = calling_convention;
	result->ProcType.generic = generic;
	result->ProcType.diverging = diverging;
	return result;
}

gb_internal Ast *ast_relative_type(AstFile *f, Ast *tag, Ast *type) {
	Ast *result = alloc_ast_node(f, Ast_RelativeType);
	result->RelativeType.tag  = tag;
	result->RelativeType.type = type;
	return result;
}
gb_internal Ast *ast_pointer_type(AstFile *f, Token token, Ast *type) {
	Ast *result = alloc_ast_node(f, Ast_PointerType);
	result->PointerType.token = token;
	result->PointerType.type = type;
	return result;
}
gb_internal Ast *ast_multi_pointer_type(AstFile *f, Token token, Ast *type) {
	Ast *result = alloc_ast_node(f, Ast_MultiPointerType);
	result->MultiPointerType.token = token;
	result->MultiPointerType.type = type;
	return result;
}
gb_internal Ast *ast_array_type(AstFile *f, Token token, Ast *count, Ast *elem) {
	Ast *result = alloc_ast_node(f, Ast_ArrayType);
	result->ArrayType.token = token;
	result->ArrayType.count = count;
	result->ArrayType.elem = elem;
	return result;
}

gb_internal Ast *ast_dynamic_array_type(AstFile *f, Token token, Ast *elem) {
	Ast *result = alloc_ast_node(f, Ast_DynamicArrayType);
	result->DynamicArrayType.token = token;
	result->DynamicArrayType.elem  = elem;
	return result;
}

gb_internal Ast *ast_struct_type(AstFile *f, Token token, Slice<Ast *> fields, isize field_count,
                     Ast *polymorphic_params, bool is_packed, bool is_raw_union, bool is_no_copy,
                     Ast *align, Ast *field_align,
                     Token where_token, Array<Ast *> const &where_clauses) {
	Ast *result = alloc_ast_node(f, Ast_StructType);
	result->StructType.token              = token;
	result->StructType.fields             = fields;
	result->StructType.field_count        = field_count;
	result->StructType.polymorphic_params = polymorphic_params;
	result->StructType.is_packed          = is_packed;
	result->StructType.is_raw_union       = is_raw_union;
	result->StructType.is_no_copy         = is_no_copy;
	result->StructType.align              = align;
	result->StructType.field_align        = field_align;
	result->StructType.where_token        = where_token;
	result->StructType.where_clauses      = slice_from_array(where_clauses);
	return result;
}


gb_internal Ast *ast_union_type(AstFile *f, Token token, Array<Ast *> const &variants, Ast *polymorphic_params, Ast *align, UnionTypeKind kind,
                    Token where_token, Array<Ast *> const &where_clauses) {
	Ast *result = alloc_ast_node(f, Ast_UnionType);
	result->UnionType.token              = token;
	result->UnionType.variants           = slice_from_array(variants);
	result->UnionType.polymorphic_params = polymorphic_params;
	result->UnionType.align              = align;
	result->UnionType.kind               = kind;
	result->UnionType.where_token        = where_token;
	result->UnionType.where_clauses      = slice_from_array(where_clauses);
	return result;
}


gb_internal Ast *ast_enum_type(AstFile *f, Token token, Ast *base_type, Array<Ast *> const &fields) {
	Ast *result = alloc_ast_node(f, Ast_EnumType);
	result->EnumType.token = token;
	result->EnumType.base_type = base_type;
	result->EnumType.fields = slice_from_array(fields);
	return result;
}

gb_internal Ast *ast_bit_set_type(AstFile *f, Token token, Ast *elem, Ast *underlying) {
	Ast *result = alloc_ast_node(f, Ast_BitSetType);
	result->BitSetType.token = token;
	result->BitSetType.elem = elem;
	result->BitSetType.underlying = underlying;
	return result;
}

gb_internal Ast *ast_bit_field_type(AstFile *f, Token token, Ast *backing_type, Token open, Array<Ast *> const &fields, Token close) {
	Ast *result = alloc_ast_node(f, Ast_BitFieldType);
	result->BitFieldType.token        = token;
	result->BitFieldType.backing_type = backing_type;
	result->BitFieldType.open         = open;
	result->BitFieldType.fields       = slice_from_array(fields);
	result->BitFieldType.close        = close;
	return result;
}


gb_internal Ast *ast_map_type(AstFile *f, Token token, Ast *key, Ast *value) {
	Ast *result = alloc_ast_node(f, Ast_MapType);
	result->MapType.token = token;
	result->MapType.key   = key;
	result->MapType.value = value;
	return result;
}

gb_internal Ast *ast_matrix_type(AstFile *f, Token token, Ast *row_count, Ast *column_count, Ast *elem) {
	Ast *result = alloc_ast_node(f, Ast_MatrixType);
	result->MatrixType.token = token;
	result->MatrixType.row_count = row_count;
	result->MatrixType.column_count = column_count;
	result->MatrixType.elem = elem;
	return result;
}

gb_internal Ast *ast_foreign_block_decl(AstFile *f, Token token, Ast *foreign_library, Ast *body,
                            CommentGroup *docs) {
	Ast *result = alloc_ast_node(f, Ast_ForeignBlockDecl);
	result->ForeignBlockDecl.token           = token;
	result->ForeignBlockDecl.foreign_library = foreign_library;
	result->ForeignBlockDecl.body            = body;
	result->ForeignBlockDecl.docs            = docs;

	result->ForeignBlockDecl.attributes.allocator = ast_allocator(f);
	return result;
}

gb_internal Ast *ast_label_decl(AstFile *f, Token token, Ast *name) {
	Ast *result = alloc_ast_node(f, Ast_Label);
	result->Label.token = token;
	result->Label.name  = name;
	return result;
}

gb_internal Ast *ast_value_decl(AstFile *f, Array<Ast *> const &names, Ast *type, Array<Ast *> const &values, bool is_mutable,
                    CommentGroup *docs, CommentGroup *comment) {
	Ast *result = alloc_ast_node(f, Ast_ValueDecl);
	result->ValueDecl.names      = slice_from_array(names);
	result->ValueDecl.type       = type;
	result->ValueDecl.values     = slice_from_array(values);
	result->ValueDecl.is_mutable = is_mutable;
	result->ValueDecl.docs       = docs;
	result->ValueDecl.comment    = comment;

	result->ValueDecl.attributes.allocator = ast_allocator(f);
	return result;
}

gb_internal Ast *ast_package_decl(AstFile *f, Token token, Token name, CommentGroup *docs, CommentGroup *comment) {
	Ast *result = alloc_ast_node(f, Ast_PackageDecl);
	result->PackageDecl.token       = token;
	result->PackageDecl.name        = name;
	result->PackageDecl.docs        = docs;
	result->PackageDecl.comment     = comment;
	return result;
}

gb_internal Ast *ast_import_decl(AstFile *f, Token token, Token relpath, Token import_name,
                     CommentGroup *docs, CommentGroup *comment) {
	Ast *result = alloc_ast_node(f, Ast_ImportDecl);
	result->ImportDecl.token       = token;
	result->ImportDecl.relpath     = relpath;
	result->ImportDecl.import_name = import_name;
	result->ImportDecl.docs        = docs;
	result->ImportDecl.comment     = comment;
	result->ImportDecl.attributes.allocator = ast_allocator(f);
	return result;
}

gb_internal Ast *ast_foreign_import_decl(AstFile *f, Token token, Array<Token> filepaths, Token library_name,
                             CommentGroup *docs, CommentGroup *comment) {
	Ast *result = alloc_ast_node(f, Ast_ForeignImportDecl);
	result->ForeignImportDecl.token        = token;
	result->ForeignImportDecl.filepaths    = slice_from_array(filepaths);
	result->ForeignImportDecl.library_name = library_name;
	result->ForeignImportDecl.docs         = docs;
	result->ForeignImportDecl.comment      = comment;
	result->ForeignImportDecl.attributes.allocator = ast_allocator(f);

	return result;
}


gb_internal Ast *ast_attribute(AstFile *f, Token token, Token open, Token close, Array<Ast *> const &elems) {
	Ast *result = alloc_ast_node(f, Ast_Attribute);
	result->Attribute.token = token;
	result->Attribute.open  = open;
	result->Attribute.elems = slice_from_array(elems);
	result->Attribute.close = close;
	return result;
}


gb_internal bool next_token0(AstFile *f) {
	if (f->curr_token_index+1 < f->tokens.count) {
		f->curr_token = f->tokens[++f->curr_token_index];
		return true;
	}
	syntax_error(f->curr_token, "Token is EOF");
	return false;
}


gb_internal Token consume_comment(AstFile *f, isize *end_line_) {
	Token tok = f->curr_token;
	GB_ASSERT(tok.kind == Token_Comment);
	isize end_line = tok.pos.line;
	if (tok.string[1] == '*') {
		for (isize i = 2; i < tok.string.len; i++) {
			if (tok.string[i] == '\n') {
				end_line++;
			}
		}
	}

	if (end_line_) *end_line_ = end_line;

	next_token0(f);
	if (f->curr_token.pos.line > tok.pos.line || tok.kind == Token_EOF) {
		end_line++;
	}
	return tok;
}


gb_internal CommentGroup *consume_comment_group(AstFile *f, isize n, isize *end_line_) {
	Array<Token> list = {};
	list.allocator = ast_allocator(f);
	isize end_line = f->curr_token.pos.line;
	if (f->curr_token_index == 1 &&
	    f->prev_token.kind == Token_Comment &&
	    f->prev_token.pos.line+1 == f->curr_token.pos.line) {
		// NOTE(bill): Special logic for the first comment in the file
		array_add(&list, f->prev_token);
	}
	while (f->curr_token.kind == Token_Comment &&
	       f->curr_token.pos.line <= end_line+n) {
		array_add(&list, consume_comment(f, &end_line));
	}

	if (end_line_) *end_line_ = end_line;

	CommentGroup *comments = nullptr;
	if (list.count > 0) {
		comments = gb_alloc_item(permanent_allocator(), CommentGroup);
		comments->list = slice_from_array(list);
		array_add(&f->comments, comments);
	}
	return comments;
}

gb_internal void consume_comment_groups(AstFile *f, Token prev) {
	if (f->curr_token.kind == Token_Comment) {
		CommentGroup *comment = nullptr;
		isize end_line = 0;

		if (f->curr_token.pos.line == prev.pos.line) {
			comment = consume_comment_group(f, 0, &end_line);
			if (f->curr_token.pos.line != end_line || f->curr_token.kind == Token_EOF) {
				f->line_comment = comment;
			}
		}

		end_line = -1;
		while (f->curr_token.kind == Token_Comment) {
			comment = consume_comment_group(f, 1, &end_line);
		}
		if (end_line+1 == f->curr_token.pos.line || end_line < 0) {
			f->lead_comment = comment;
		}

		GB_ASSERT(f->curr_token.kind != Token_Comment);
	}
}

gb_internal gb_inline bool ignore_newlines(AstFile *f) {
	return f->expr_level > 0;
}

gb_internal Token advance_token(AstFile *f) {
	f->lead_comment = nullptr;
	f->line_comment = nullptr;

	f->prev_token_index = f->curr_token_index;
	Token prev = f->prev_token = f->curr_token;

	bool ok = next_token0(f);
	if (ok) {
		switch (f->curr_token.kind) {
		case Token_Comment:
			consume_comment_groups(f, prev);
			break;
		case Token_Semicolon:
			if (ignore_newlines(f) && f->curr_token.string == "\n") {
				advance_token(f);
			}
			break;
		}
	}
	return prev;
}


gb_internal Token peek_token(AstFile *f) {
	for (isize i = f->curr_token_index+1; i < f->tokens.count; i++) {
		Token tok = f->tokens[i];
		if (tok.kind == Token_Comment) {
			continue;
		}
		return tok;
	}
	return {};
}

gb_internal Token peek_token_n(AstFile *f, isize n) {
	Token found = {};
	for (isize i = f->curr_token_index+1; i < f->tokens.count; i++) {
		Token tok = f->tokens[i];
		if (tok.kind == Token_Comment) {
			continue;
		}
		found = tok;
		if (n-- == 0) {
			return found;
		}
	}
	return {};
}


gb_internal bool skip_possible_newline(AstFile *f) {
	if (token_is_newline(f->curr_token)) {
		advance_token(f);
		return true;
	}
	return false;
}

gb_internal bool skip_possible_newline_for_literal(AstFile *f) {
	Token curr = f->curr_token;
	if (token_is_newline(curr)) {
		Token next = peek_token(f);
		if (curr.pos.line+1 >= next.pos.line) {
			switch (next.kind) {
			case Token_OpenBrace:
			case Token_else:
			case Token_where:
				advance_token(f);
				return true;
			}
		}
	}

	return false;
}

gb_internal String token_to_string(Token const &tok) {
	String p = token_strings[tok.kind];
	if (token_is_newline(tok)) {
		p = str_lit("newline");
	}
	return p;
}


gb_internal Token expect_token(AstFile *f, TokenKind kind) {
	Token prev = f->curr_token;
	if (prev.kind != kind) {
		String c = token_strings[kind];
		String p = token_to_string(prev);
		begin_error_block();
		syntax_error(f->curr_token, "Expected '%.*s', got '%.*s'", LIT(c), LIT(p));
		if (kind == Token_Ident) switch (prev.kind) {
		case Token_context:
			error_line("\tSuggestion: '%.*s' is a keyword, would 'ctx' suffice?\n", LIT(prev.string));
			break;
		case Token_package:
			error_line("\tSuggestion: '%.*s' is a keyword, would 'pkg' suffice?\n", LIT(prev.string));
			break;
		default:
			if (token_is_keyword(prev.kind)) {
				error_line("\tNote: '%.*s' is a keyword\n", LIT(prev.string));
			}
			break;
		}

		end_error_block();

		if (prev.kind == Token_EOF) {
			exit_with_errors();
		}
	}

	advance_token(f);
	return prev;
}

gb_internal Token expect_token_after(AstFile *f, TokenKind kind, char const *msg) {
	Token prev = f->prev_token;
	Token curr = f->curr_token;
	if (curr.kind != kind) {
		String p = token_to_string(curr);
		Token token = f->curr_token;
		if (token_is_newline(curr)) {
			token = curr;
			token.pos.column -= 1;
			skip_possible_newline(f);
		}
		syntax_error(token, "Expected '%.*s' after %s, got '%.*s'",
		             LIT(token_strings[kind]),
		             msg,
		             LIT(p));
	}
	advance_token(f);

	if (ast_file_vet_style(f) &&
	    prev.kind == Token_Comma &&
	    prev.pos.line == curr.pos.line) {
		syntax_error(prev, "No need for a trailing comma followed by a %.*s on the same line", LIT(token_strings[kind]));
	}
	return curr;
}


gb_internal bool is_token_range(TokenKind kind) {
	switch (kind) {
	case Token_Ellipsis:
	case Token_RangeFull:
	case Token_RangeHalf:
		return true;
	}
	return false;
}
gb_internal bool is_token_range(Token tok) {
	return is_token_range(tok.kind);
}


gb_internal Token expect_operator(AstFile *f) {
	Token prev = f->curr_token;
	if ((prev.kind == Token_in || prev.kind == Token_not_in) && (f->expr_level >= 0 || f->allow_in_expr)) {
		// okay
	} else if (prev.kind == Token_if || prev.kind == Token_when) {
		// okay
	} else if (prev.kind == Token_or_else || prev.kind == Token_or_return ||
	           prev.kind == Token_or_break || prev.kind == Token_or_continue) {
		// okay
	} else if (!gb_is_between(prev.kind, Token__OperatorBegin+1, Token__OperatorEnd-1)) {
		String p = token_to_string(prev);
		syntax_error(prev, "Expected an operator, got '%.*s'",
		             LIT(p));
	} else if (!f->allow_range && is_token_range(prev)) {
		String p = token_to_string(prev);
		syntax_error(prev, "Expected an non-range operator, got '%.*s'",
		             LIT(p));
	}
	if (prev.kind == Token_Ellipsis) {
		syntax_warning(prev, "'..' for ranges has now been deprecated, prefer '..='");
		f->tokens[f->curr_token_index].flags |= TokenFlag_Replace;
	}
	
	advance_token(f);
	return prev;
}

gb_internal bool allow_token(AstFile *f, TokenKind kind) {
	Token prev = f->curr_token;
	if (prev.kind == kind) {
		advance_token(f);
		return true;
	}
	return false;
}

gb_internal Token expect_closing_brace_of_field_list(AstFile *f) {
	Token token = f->curr_token;
	if (allow_token(f, Token_CloseBrace)) {
		return token;
	}
	bool ok = true;
	if (f->allow_newline) {
		ok = !skip_possible_newline(f);
	}
	if (ok && allow_token(f, Token_Semicolon)) {
		String p = token_to_string(token);
		syntax_error(token_end_of_line(f, f->prev_token), "Expected a comma, got a %.*s", LIT(p));
	}
	return expect_token(f, Token_CloseBrace);
}

gb_internal bool is_blank_ident(String str) {
	if (str.len == 1) {
		return str[0] == '_';
	}
	return false;
}
gb_internal bool is_blank_ident(Token token) {
	if (token.kind == Token_Ident) {
		return is_blank_ident(token.string);
	}
	return false;
}
gb_internal bool is_blank_ident(Ast *node) {
	if (node->kind == Ast_Ident) {
		ast_node(i, Ident, node);
		return is_blank_ident(i->token.string);
	}
	return false;
}



// NOTE(bill): Go to next statement to prevent numerous error messages popping up
gb_internal void fix_advance_to_next_stmt(AstFile *f) {
	for (;;) {
		Token t = f->curr_token;
		switch (t.kind) {
		case Token_EOF:
		case Token_Semicolon:
			return;


		case Token_package:
		case Token_foreign:
		case Token_import:

		case Token_if:
		case Token_for:
		case Token_when:
		case Token_return:
		case Token_switch:
		case Token_defer:
		case Token_using:

		case Token_break:
		case Token_continue:
		case Token_fallthrough:

		case Token_Hash:
		{
			if (t.pos == f->fix_prev_pos &&
			    f->fix_count < PARSER_MAX_FIX_COUNT) {
				f->fix_count++;
				return;
			}
			if (f->fix_prev_pos < t.pos) {
				f->fix_prev_pos = t.pos;
				f->fix_count = 0; // NOTE(bill): Reset
				return;
			}
			// NOTE(bill): Reaching here means there is a parsing bug
		} break;
		}
		advance_token(f);
	}
}

gb_internal Token expect_closing(AstFile *f, TokenKind kind, String const &context) {
	if (f->curr_token.kind != kind &&
	    f->curr_token.kind == Token_Semicolon &&
	    (f->curr_token.string == "\n" || f->curr_token.kind == Token_EOF)) {
	    	if (f->allow_newline) {
			Token tok = f->prev_token;
			tok.pos.column += cast(i32)tok.string.len;
			syntax_error(tok, "Missing ',' before newline in %.*s", LIT(context));
		}
		advance_token(f);
	}
	return expect_token(f, kind);
}

gb_internal void assign_removal_flag_to_semicolon(AstFile *f) {
	// NOTE(bill): this is used for rewriting files to strip unneeded semicolons
	Token *prev_token = &f->tokens[f->prev_token_index];
	Token *curr_token = &f->tokens[f->curr_token_index];
	GB_ASSERT(prev_token->kind == Token_Semicolon);
	if (prev_token->string != ";") {
		return;
	}
	bool ok = false;
	if (curr_token->pos.line > prev_token->pos.line) {
		ok = true;
	} else if (curr_token->pos.line == prev_token->pos.line) {
		switch (curr_token->kind) {
		case Token_CloseBrace:
		case Token_CloseParen:
		case Token_EOF:
			ok = true;
			break;
		}
	}
	if (!ok) {
		return;
	}

	if (build_context.strict_style || (ast_file_vet_flags(f) & VetFlag_Semicolon)) {
		syntax_error(*prev_token, "Found unneeded semicolon");
	}
	prev_token->flags |= TokenFlag_Remove;
}

gb_internal void expect_semicolon(AstFile *f) {
	Token prev_token = {};

	if (allow_token(f, Token_Semicolon)) {
		assign_removal_flag_to_semicolon(f);
		return;
	}
	switch (f->curr_token.kind) {
	case Token_CloseBrace:
	case Token_CloseParen:
		if (f->curr_token.pos.line == f->prev_token.pos.line) {
			return;
		}
		break;
	}

	prev_token = f->prev_token;
	if (prev_token.kind == Token_Semicolon) {
		assign_removal_flag_to_semicolon(f);
		return;
	}

	if (f->curr_token.kind == Token_EOF) {
		return;
	}
	switch (f->curr_token.kind) {
	case Token_EOF:
		return;
	}

	if (f->curr_token.pos.line == f->prev_token.pos.line) {
		String p = token_to_string(f->curr_token);
		prev_token.pos = token_pos_end(prev_token);
		syntax_error(prev_token, "Expected ';', got %.*s", LIT(p));
		fix_advance_to_next_stmt(f);
	}
}


gb_internal Ast *        parse_expr(AstFile *f, bool lhs);
gb_internal Ast *        parse_proc_type(AstFile *f, Token proc_token);
gb_internal Array<Ast *> parse_stmt_list(AstFile *f);
gb_internal Ast *        parse_stmt(AstFile *f);
gb_internal Ast *        parse_body(AstFile *f);
gb_internal Ast *        parse_do_body(AstFile *f, Token const &token, char const *msg);
gb_internal Ast *        parse_block_stmt(AstFile *f, b32 is_when);



gb_internal Ast *parse_ident(AstFile *f, bool allow_poly_names=false) {
	Token token = f->curr_token;
	if (token.kind == Token_Ident) {
		advance_token(f);
	} else if (allow_poly_names && token.kind == Token_Dollar) {
		Token dollar = expect_token(f, Token_Dollar);
		Ast *name = ast_ident(f, expect_token(f, Token_Ident));
		if (is_blank_ident(name)) {
			syntax_error(name, "Invalid polymorphic type definition with a blank identifier");
		}
		return ast_poly_type(f, dollar, name, nullptr);
	} else {
		token.string = str_lit("_");
		expect_token(f, Token_Ident);
	}
	return ast_ident(f, token);
}

gb_internal Ast *parse_tag_expr(AstFile *f, Ast *expression) {
	Token token = expect_token(f, Token_Hash);
	Token name = expect_token(f, Token_Ident);
	return ast_tag_expr(f, token, name, expression);
}

gb_internal Ast *unparen_expr(Ast *node) {
	for (;;) {
		if (node == nullptr) {
			return nullptr;
		}
		if (node->kind != Ast_ParenExpr) {
			return node;
		}
		node = node->ParenExpr.expr;
	}
}

gb_internal Ast *unselector_expr(Ast *node) {
	node = unparen_expr(node);
	if (node == nullptr) {
		return nullptr;
	}
	while (node->kind == Ast_SelectorExpr) {
		node = node->SelectorExpr.selector;
	}
	return node;
}

gb_internal Ast *strip_or_return_expr(Ast *node) {
	for (;;) {
		if (node == nullptr) {
			return node;
		}
		if (node->kind == Ast_OrReturnExpr) {
			node = node->OrReturnExpr.expr;
		} else if (node->kind == Ast_OrBranchExpr) {
			node = node->OrBranchExpr.expr;
		} else if (node->kind == Ast_ParenExpr) {
			node = node->ParenExpr.expr;
		} else {
			return node;
		}
	}
}


gb_internal Ast *parse_value(AstFile *f);

gb_internal Array<Ast *> parse_element_list(AstFile *f) {
	auto elems = array_make<Ast *>(ast_allocator(f));

	while (f->curr_token.kind != Token_CloseBrace &&
	       f->curr_token.kind != Token_EOF) {
		Ast *elem = parse_value(f);
		if (f->curr_token.kind == Token_Eq) {
			Token eq = expect_token(f, Token_Eq);
			Ast *value = parse_value(f);
			elem = ast_field_value(f, elem, value, eq);
		}

		array_add(&elems, elem);

		if (!allow_field_separator(f)) {
			break;
		}
	}

	return elems;
}
gb_internal CommentGroup *consume_line_comment(AstFile *f) {
	CommentGroup *comment = f->line_comment;
	if (f->line_comment == f->lead_comment) {
		f->lead_comment = nullptr;
	}
	f->line_comment = nullptr;
	return comment;

}

gb_internal Array<Ast *> parse_enum_field_list(AstFile *f) {
	auto elems = array_make<Ast *>(ast_allocator(f));

	while (f->curr_token.kind != Token_CloseBrace &&
	       f->curr_token.kind != Token_EOF) {
		CommentGroup *docs = f->lead_comment;
		CommentGroup *comment = nullptr;
		Ast *name = parse_value(f);
		Ast *value = nullptr;
		if (f->curr_token.kind == Token_Eq) {
			Token eq = expect_token(f, Token_Eq);
			value = parse_value(f);
		}

		comment = consume_line_comment(f);

		Ast *elem = ast_enum_field_value(f, name, value, docs, comment);
		array_add(&elems, elem);

		if (!allow_field_separator(f)) {
			break;
		}

		if (!elem->EnumFieldValue.comment) {
			elem->EnumFieldValue.comment = consume_line_comment(f);
		}
	}

	return elems;
}

gb_internal Ast *parse_literal_value(AstFile *f, Ast *type) {
	Array<Ast *> elems = {};
	Token open = expect_token(f, Token_OpenBrace);
	isize expr_level = f->expr_level;
	f->expr_level = 0;
	if (f->curr_token.kind != Token_CloseBrace) {
		elems = parse_element_list(f);
	}
	f->expr_level = expr_level;
	Token close = expect_closing(f, Token_CloseBrace, str_lit("compound literal"));

	return ast_compound_lit(f, type, elems, open, close);
}

gb_internal Ast *parse_value(AstFile *f) {
	if (f->curr_token.kind == Token_OpenBrace) {
		return parse_literal_value(f, nullptr);
	}
	Ast *value;
	bool prev_allow_range = f->allow_range;
	f->allow_range = true;
	value = parse_expr(f, false);
	f->allow_range = prev_allow_range;
	return value;
}

gb_internal Ast *parse_type_or_ident(AstFile *f);


gb_internal void check_proc_add_tag(AstFile *f, Ast *tag_expr, u64 *tags, ProcTag tag, String const &tag_name) {
	if (*tags & tag) {
		syntax_error(tag_expr, "Procedure tag already used: %.*s", LIT(tag_name));
	}
	*tags |= tag;
}

gb_internal bool is_foreign_name_valid(String const &name) {
	if (name.len == 0) {
		return false;
	}
	isize offset = 0;
	while (offset < name.len) {
		Rune rune;
		isize remaining = name.len - offset;
		isize width = utf8_decode(name.text+offset, remaining, &rune);
		if (rune == GB_RUNE_INVALID && width == 1) {
			return false;
		} else if (rune == GB_RUNE_BOM && remaining > 0) {
			return false;
		}

		if (offset == 0) {
			switch (rune) {
			case '-':
			case '$':
			case '.':
			case '_':
				break;
			default:
				if (!gb_char_is_alpha(cast(char)rune))
					return false;
				break;
			}
		} else {
			switch (rune) {
			case '-':
			case '$':
			case '.':
			case '_':
				break;
			default:
				if (!gb_char_is_alphanumeric(cast(char)rune)) {
					return false;
				}
				break;
			}
		}

		offset += width;
	}

	return true;
}

gb_internal void parse_proc_tags(AstFile *f, u64 *tags) {
	GB_ASSERT(tags != nullptr);

	while (f->curr_token.kind == Token_Hash) {
		Ast *tag_expr = parse_tag_expr(f, nullptr);
		ast_node(te, TagExpr, tag_expr);
		String tag_name = te->name.string;

		#define ELSE_IF_ADD_TAG(name) \
		else if (tag_name == #name) { \
			check_proc_add_tag(f, tag_expr, tags, ProcTag_##name, tag_name); \
		}

		if (false) {}
		ELSE_IF_ADD_TAG(optional_ok)
		ELSE_IF_ADD_TAG(optional_allocator_error)
		ELSE_IF_ADD_TAG(require_results)
		ELSE_IF_ADD_TAG(bounds_check)
		ELSE_IF_ADD_TAG(no_bounds_check)
		ELSE_IF_ADD_TAG(type_assert)
		ELSE_IF_ADD_TAG(no_type_assert)
		else {
			syntax_error(tag_expr, "Unknown procedure type tag #%.*s", LIT(tag_name));
		}

		#undef ELSE_IF_ADD_TAG
	}

	if ((*tags & ProcTag_bounds_check) && (*tags & ProcTag_no_bounds_check)) {
		syntax_error(f->curr_token, "You cannot apply both #bounds_check and #no_bounds_check to a procedure");
	}

	if ((*tags & ProcTag_type_assert) && (*tags & ProcTag_no_type_assert)) {
		syntax_error(f->curr_token, "You cannot apply both #type_assert and #no_type_assert to a procedure");
	}
}


gb_internal Array<Ast *> parse_lhs_expr_list    (AstFile *f);
gb_internal Array<Ast *> parse_rhs_expr_list    (AstFile *f);
gb_internal Ast *        parse_simple_stmt      (AstFile *f, u32 flags);
gb_internal Ast *        parse_type             (AstFile *f);
gb_internal Ast *        parse_call_expr        (AstFile *f, Ast *operand);
gb_internal Ast *        parse_struct_field_list(AstFile *f, isize *name_count_);
gb_internal Ast *parse_field_list(AstFile *f, isize *name_count_, u32 allowed_flags, TokenKind follow, bool allow_default_parameters, bool allow_typeid_token);
gb_internal Ast *parse_unary_expr(AstFile *f, bool lhs);


gb_internal Ast *convert_stmt_to_expr(AstFile *f, Ast *statement, String const &kind) {
	if (statement == nullptr) {
		return nullptr;
	}

	if (statement->kind == Ast_ExprStmt) {
		return statement->ExprStmt.expr;
	}

	syntax_error(f->curr_token, "Expected '%.*s', found a simple statement.", LIT(kind));
	Token end = f->curr_token;
	if (f->tokens.count < f->curr_token_index) {
		end = f->tokens[f->curr_token_index+1];
	}
	return ast_bad_expr(f, f->curr_token, end);
}

gb_internal Ast *convert_stmt_to_body(AstFile *f, Ast *stmt) {
	if (stmt->kind == Ast_BlockStmt) {
		syntax_error(stmt, "Expected a normal statement rather than a block statement");
		return stmt;
	}
	if (stmt->kind == Ast_EmptyStmt) {
		syntax_error(stmt, "Expected a non-empty statement");
	}
	GB_ASSERT(is_ast_stmt(stmt) || is_ast_decl(stmt));
	Token open = ast_token(stmt);
	Token close = ast_token(stmt);
	auto stmts = array_make<Ast *>(ast_allocator(f), 0, 1);
	array_add(&stmts, stmt);
	return ast_block_stmt(f, stmts, open, close);
}


gb_internal void check_polymorphic_params_for_type(AstFile *f, Ast *polymorphic_params, Token token) {
	if (polymorphic_params == nullptr) {
		return;
	}
	if (polymorphic_params->kind != Ast_FieldList) {
		return;
	}
	ast_node(fl, FieldList, polymorphic_params);
	for (Ast *field : fl->list) {
		if (field->kind != Ast_Field) {
			continue;
		}
		for (Ast *name : field->Field.names) {
			if (name->kind != field->Field.names[0]->kind) {
				syntax_error(name, "Mixture of polymorphic names using both $ and not for %.*s parameters", LIT(token.string));
				return;
			}
		}
	}
}

gb_internal bool ast_on_same_line(Token const &x, Ast *yp) {
	Token y = ast_token(yp);
	return x.pos.line == y.pos.line;
}

gb_internal Ast *parse_force_inlining_operand(AstFile *f, Token token) {
	Ast *expr = parse_unary_expr(f, false);
	Ast *e = strip_or_return_expr(expr);
	if (e->kind != Ast_ProcLit && e->kind != Ast_CallExpr) {
		syntax_error(expr, "%.*s must be followed by a procedure literal or call, got %.*s", LIT(token.string), LIT(ast_strings[expr->kind]));
		return ast_bad_expr(f, token, f->curr_token);
	}
	ProcInlining pi = ProcInlining_none;
	if (token.kind == Token_Ident) {
		if (token.string == "force_inline") {
			pi = ProcInlining_inline;
		} else if (token.string == "force_no_inline") {
			pi = ProcInlining_no_inline;
		}
	}

	if (pi != ProcInlining_none) {
		if (e->kind == Ast_ProcLit) {
			if (expr->ProcLit.inlining != ProcInlining_none &&
			    expr->ProcLit.inlining != pi) {
				syntax_error(expr, "Cannot apply both '#force_inline' and '#force_no_inline' to a procedure literal");
			}
			expr->ProcLit.inlining = pi;
		} else if (e->kind == Ast_CallExpr) {
			if (expr->CallExpr.inlining != ProcInlining_none &&
			    expr->CallExpr.inlining != pi) {
				syntax_error(expr, "Cannot apply both '#force_inline' and '#force_no_inline' to a procedure call");
			}
			expr->CallExpr.inlining = pi;
		}
	}

	return expr;
}


gb_internal Ast *parse_check_directive_for_statement(Ast *s, Token const &tag_token, u16 state_flag) {
	String name = tag_token.string;

	if (s == nullptr) {
		syntax_error(tag_token, "Invalid operand for #%.*s", LIT(name));
		return nullptr;
	}

	if (s != nullptr && s->kind == Ast_EmptyStmt) {
		if (s->EmptyStmt.token.string == "\n") {
			syntax_error(tag_token, "#%.*s cannot be followed by a newline", LIT(name));
		} else {
			syntax_error(tag_token, "#%.*s cannot be applied to an empty statement ';'", LIT(name));
		}
	}

	if (s->state_flags & state_flag) {
		syntax_error(tag_token, "#%.*s has been applied multiple times", LIT(name));
	}
	s->state_flags |= state_flag;

	switch (state_flag) {
	case StateFlag_bounds_check:
		if ((s->state_flags & StateFlag_no_bounds_check) != 0) {
			syntax_error(tag_token, "#bounds_check and #no_bounds_check cannot be applied together");
		}
		break;
	case StateFlag_no_bounds_check:
		if ((s->state_flags & StateFlag_bounds_check) != 0) {
			syntax_error(tag_token, "#bounds_check and #no_bounds_check cannot be applied together");
		}
		break;
	case StateFlag_type_assert:
		if ((s->state_flags & StateFlag_no_type_assert) != 0) {
			syntax_error(tag_token, "#type_assert and #no_type_assert cannot be applied together");
		}
		break;
	case StateFlag_no_type_assert:
		if ((s->state_flags & StateFlag_type_assert) != 0) {
			syntax_error(tag_token, "#type_assert and #no_type_assert cannot be applied together");
		}
		break;
	}

	switch (state_flag) {
	case StateFlag_bounds_check:
	case StateFlag_no_bounds_check:
	case StateFlag_type_assert:
	case StateFlag_no_type_assert:
		switch (s->kind) {
		case Ast_BlockStmt:
		case Ast_IfStmt:
		case Ast_WhenStmt:
		case Ast_ForStmt:
		case Ast_RangeStmt:
		case Ast_UnrollRangeStmt:
		case Ast_SwitchStmt:
		case Ast_TypeSwitchStmt:
		case Ast_ReturnStmt:
		case Ast_DeferStmt:
		case Ast_AssignStmt:
			// Okay
			break;

		case Ast_ValueDecl:
			if (!s->ValueDecl.is_mutable) {
				syntax_error(tag_token, "#%.*s may only be applied to a variable declaration, and not a constant value declaration", LIT(name));
			}
			break;
		default:
			syntax_error(tag_token, "#%.*s may only be applied to the following statements: '{}', 'if', 'when', 'for', 'switch', 'return', 'defer', assignment, variable declaration", LIT(name));
			break;
		}
		break;
	}

	return s;
}

gb_internal Array<Ast *> parse_union_variant_list(AstFile *f) {
	auto variants = array_make<Ast *>(ast_allocator(f));
	while (f->curr_token.kind != Token_CloseBrace &&
	       f->curr_token.kind != Token_EOF) {
		Ast *type = parse_type(f);
		if (type->kind != Ast_BadExpr) {
			array_add(&variants, type);
		}
		if (!allow_field_separator(f)) {
			break;
		}
	}
	return variants;
}

gb_internal void parser_check_polymorphic_record_parameters(AstFile *f, Ast *polymorphic_params) {
	if (polymorphic_params == nullptr) {
		return;
	}
	if (polymorphic_params->kind != Ast_FieldList) {
		return;
	}


	enum {Unknown, Dollar, Bare} prefix = Unknown;
	gb_unused(prefix);

	for (Ast *field : polymorphic_params->FieldList.list) {
		if (field == nullptr || field->kind != Ast_Field) {
			continue;
		}
		for (Ast *name : field->Field.names) {
			if (name == nullptr) {
				continue;
			}
			bool error = false;

			if (name->kind == Ast_Ident) {
				switch (prefix) {
				case Unknown: prefix = Bare; break;
				case Dollar:  error = true;  break;
				case Bare:                   break;
				}
			} else if (name->kind == Ast_PolyType) {
				switch (prefix) {
				case Unknown: prefix = Dollar; break;
				case Dollar:                   break;
				case Bare:    error = true;    break;
				}
			}
			if (error) {
				syntax_error(name, "Mixture of polymorphic $ names and normal identifiers are not allowed within record parameters");
			}
		}
	}
}


gb_internal Ast *parse_operand(AstFile *f, bool lhs) {
	Ast *operand = nullptr; // Operand
	switch (f->curr_token.kind) {
	case Token_Ident:
		return parse_ident(f);

	case Token_Uninit:
		return ast_uninit(f, expect_token(f, Token_Uninit));

	case Token_context:
		return ast_implicit(f, expect_token(f, Token_context));

	case Token_Integer:
	case Token_Float:
	case Token_Imag:
	case Token_Rune:
		return ast_basic_lit(f, advance_token(f));

	case Token_String:
		return ast_basic_lit(f, advance_token(f));

	case Token_OpenBrace:
		if (!lhs) return parse_literal_value(f, nullptr);
		break;

	case Token_OpenParen: {
		bool allow_newline;
		isize prev_expr_level;
		Token open, close;
		// NOTE(bill): Skip the Paren Expression
		open = expect_token(f, Token_OpenParen);
		if (f->prev_token.kind == Token_CloseParen) {
			close = expect_token(f, Token_CloseParen);
			syntax_error(open, "Invalid parentheses expression with no inside expression");
			return ast_bad_expr(f, open, close);
		}

		prev_expr_level = f->expr_level;
		allow_newline = f->allow_newline;
		if (f->expr_level < 0) {
			f->allow_newline = false;
		}

		// NOTE(bill): enforce it to >0
		f->expr_level = gb_max(f->expr_level, 0)+1;
		operand = parse_expr(f, false);

		f->allow_newline = allow_newline;
		f->expr_level = prev_expr_level;

		close = expect_token(f, Token_CloseParen);
		return ast_paren_expr(f, operand, open, close);
	}

	case Token_distinct: {
		Token token = expect_token(f, Token_distinct);
		Ast *type = parse_type(f);
		return ast_distinct_type(f, token, type);
	}

	case Token_Hash: {
		Token token = expect_token(f, Token_Hash);

		Token name = expect_token(f, Token_Ident);
		if (name.string == "type") {
			return ast_helper_type(f, token, parse_type(f));
		} else if ( name.string == "simd") {
			Ast *tag = ast_basic_directive(f, token, name);
			Ast *original_type = parse_type(f);
			Ast *type = unparen_expr(original_type);
			switch (type->kind) {
			case Ast_ArrayType: type->ArrayType.tag = tag; break;
			default:
				syntax_error(type, "Expected a fixed array type after #%.*s, got %.*s", LIT(name.string), LIT(ast_strings[type->kind]));
				break;
			}
			return original_type;
		} else if (name.string == "soa") {
			Ast *tag = ast_basic_directive(f, token, name);
			Ast *original_type = parse_type(f);
			Ast *type = unparen_expr(original_type);
			switch (type->kind) {
			case Ast_ArrayType:        type->ArrayType.tag        = tag; break;
			case Ast_DynamicArrayType: type->DynamicArrayType.tag = tag; break;
			case Ast_PointerType:      type->PointerType.tag      = tag; break;
			default:
				syntax_error(type, "Expected an array or pointer type after #%.*s, got %.*s", LIT(name.string), LIT(ast_strings[type->kind]));
				break;
			}
			return original_type;
		} else if (name.string == "row_major" ||
		           name.string == "column_major") {
			Ast *original_type = parse_type(f);
			Ast *type = unparen_expr(original_type);
			switch (type->kind) {
			case Ast_MatrixType:
				type->MatrixType.is_row_major = (name.string == "row_major");
				break;
			default:
				syntax_error(type, "Expected a matrix type after #%.*s, got %.*s", LIT(name.string), LIT(ast_strings[type->kind]));
				break;
			}
			return original_type;
		} else if (name.string == "partial") {
			Ast *tag = ast_basic_directive(f, token, name);
			Ast *original_expr = parse_expr(f, lhs);
			Ast *expr = unparen_expr(original_expr);
			if (expr == nullptr) {
				syntax_error(name, "Expected a compound literal after #%.*s", LIT(name.string));
				return ast_bad_expr(f, token, name);
			}
			switch (expr->kind) {
			case Ast_CompoundLit:
				expr->CompoundLit.tag = tag;
				break;
			default:
				syntax_error(expr, "Expected a compound literal after #%.*s, got %.*s", LIT(name.string), LIT(ast_strings[expr->kind]));
				break;
			}
			return original_expr;
		} else if (name.string == "sparse") {
			Ast *tag = ast_basic_directive(f, token, name);
			Ast *original_type = parse_type(f);
			Ast *type = unparen_expr(original_type);
			switch (type->kind) {
			case Ast_ArrayType: type->ArrayType.tag = tag; break;
			default:
				syntax_error(type, "Expected an enumerated array type after #%.*s, got %.*s", LIT(name.string), LIT(ast_strings[type->kind]));
				break;
			}
			return original_type;
		} else if (name.string == "bounds_check") {
			Ast *operand = parse_expr(f, lhs);
			return parse_check_directive_for_statement(operand, name, StateFlag_bounds_check);
		} else if (name.string == "no_bounds_check") {
			Ast *operand = parse_expr(f, lhs);
			return parse_check_directive_for_statement(operand, name, StateFlag_no_bounds_check);
		} else if (name.string == "type_assert") {
			Ast *operand = parse_expr(f, lhs);
			return parse_check_directive_for_statement(operand, name, StateFlag_type_assert);
		} else if (name.string == "no_type_assert") {
			Ast *operand = parse_expr(f, lhs);
			return parse_check_directive_for_statement(operand, name, StateFlag_no_type_assert);
		} else if (name.string == "relative") {
			Ast *tag = ast_basic_directive(f, token, name);
			if (f->curr_token.kind != Token_OpenParen) {
				syntax_error(tag, "expected #relative(<integer type>) <type>");
			} else {
				tag = parse_call_expr(f, tag);
			}
			Ast *type = parse_type(f);
			return ast_relative_type(f, tag, type);
		} else if (name.string == "force_inline" ||
		           name.string == "force_no_inline") {
			return parse_force_inlining_operand(f, name);
		}
		return ast_basic_directive(f, token, name);
	}

	// Parse Procedure Type or Literal or Group
	case Token_proc: {
		Token token = expect_token(f, Token_proc);

		if (f->curr_token.kind == Token_OpenBrace) { // ProcGroup
			Token open = expect_token(f, Token_OpenBrace);

			auto args = array_make<Ast *>(ast_allocator(f));

			while (f->curr_token.kind != Token_CloseBrace &&
			       f->curr_token.kind != Token_EOF) {
				Ast *elem = parse_expr(f, false);
				array_add(&args, elem);

				if (!allow_field_separator(f)) {
					break;
				}
			}

			Token close = expect_token(f, Token_CloseBrace);

			if (args.count == 0) {
				syntax_error(token, "Expected a least 1 argument in a procedure group");
			}

			return ast_proc_group(f, token, open, close, args);
		}


		Ast *type = parse_proc_type(f, token);
		Token where_token = {};
		Array<Ast *> where_clauses = {};
		u64 tags = 0;

		skip_possible_newline_for_literal(f);


		if (f->curr_token.kind == Token_where) {
			where_token = expect_token(f, Token_where);
			isize prev_level = f->expr_level;
			f->expr_level = -1;
			where_clauses = parse_rhs_expr_list(f);
			f->expr_level = prev_level;
		}

		parse_proc_tags(f, &tags);
		if ((tags & ProcTag_require_results) != 0) {
			syntax_error(f->curr_token, "#require_results has now been replaced as an attribute @(require_results) on the declaration");
			tags &= ~ProcTag_require_results;
		}
		GB_ASSERT(type->kind == Ast_ProcType);
		type->ProcType.tags = tags;

		if (f->allow_type && f->expr_level < 0) {
			if (tags != 0) {
				syntax_error(token, "A procedure type cannot have suffix tags");
			}
			if (where_token.kind != Token_Invalid) {
				syntax_error(where_token, "'where' clauses are not allowed on procedure types");
			}
			return type;
		}

		skip_possible_newline_for_literal(f);

		if (allow_token(f, Token_Uninit)) {
			if (where_token.kind != Token_Invalid) {
				syntax_error(where_token, "'where' clauses are not allowed on procedure literals without a defined body (replaced with ---)");
			}
			return ast_proc_lit(f, type, nullptr, tags, where_token, where_clauses);
		} else if (f->curr_token.kind == Token_OpenBrace) {
			Ast *curr_proc = f->curr_proc;
			Ast *body = nullptr;
			f->curr_proc = type;
			body = parse_body(f);
			f->curr_proc = curr_proc;

			// Apply the tags directly to the body rather than the type
			if (tags & ProcTag_no_bounds_check) {
				body->state_flags |= StateFlag_no_bounds_check;
			}
			if (tags & ProcTag_bounds_check) {
				body->state_flags |= StateFlag_bounds_check;
			}
			if (tags & ProcTag_no_type_assert) {
				body->state_flags |= StateFlag_no_type_assert;
			}
			if (tags & ProcTag_type_assert) {
				body->state_flags |= StateFlag_type_assert;
			}

			return ast_proc_lit(f, type, body, tags, where_token, where_clauses);
		} else if (allow_token(f, Token_do)) {
			Ast *curr_proc = f->curr_proc;
			Ast *body = nullptr;
			f->curr_proc = type;
			body = convert_stmt_to_body(f, parse_stmt(f));
			f->curr_proc = curr_proc;

			syntax_error(body, "'do' for procedure bodies is not allowed, prefer {}");

			return ast_proc_lit(f, type, body, tags, where_token, where_clauses);
		}

		if (tags != 0) {
			syntax_error(token, "A procedure type cannot have suffix tags");
		}
		if (where_token.kind != Token_Invalid) {
			syntax_error(where_token, "'where' clauses are not allowed on procedure types");
		}

		return type;
	}


	// Check for Types
	case Token_Dollar: {
		Token token = expect_token(f, Token_Dollar);
		Ast *type = parse_ident(f);
		if (is_blank_ident(type)) {
			syntax_error(type, "Invalid polymorphic type definition with a blank identifier");
		}
		Ast *specialization = nullptr;
		if (allow_token(f, Token_Quo)) {
			specialization = parse_type(f);
		}
		return ast_poly_type(f, token, type, specialization);
	} break;

	case Token_typeid: {
		Token token = expect_token(f, Token_typeid);
		return ast_typeid_type(f, token, nullptr);
	} break;

	case Token_Pointer: {
		Token token = expect_token(f, Token_Pointer);
		Ast *elem = parse_type(f);
		return ast_pointer_type(f, token, elem);
	} break;

	case Token_Mul:
		return parse_unary_expr(f, true);

	case Token_OpenBracket: {
		Token token = expect_token(f, Token_OpenBracket);
		Ast *count_expr = nullptr;
		if (f->curr_token.kind == Token_Pointer) {
			expect_token(f, Token_Pointer);
			expect_token(f, Token_CloseBracket);
			return ast_multi_pointer_type(f, token, parse_type(f));
		} else if (f->curr_token.kind == Token_Question) {
			count_expr = ast_unary_expr(f, expect_token(f, Token_Question), nullptr);
		} else if (allow_token(f, Token_dynamic)) {
			expect_token(f, Token_CloseBracket);
			return ast_dynamic_array_type(f, token, parse_type(f));
		} else if (f->curr_token.kind != Token_CloseBracket) {
			f->expr_level++;
			count_expr = parse_expr(f, false);
			f->expr_level--;
		}
		
		expect_token(f, Token_CloseBracket);
		return ast_array_type(f, token, count_expr, parse_type(f));
	} break;

	case Token_map: {
		Token token = expect_token(f, Token_map);
		Ast *key   = nullptr;
		Ast *value = nullptr;
		Token open, close;

		open  = expect_token_after(f, Token_OpenBracket, "map");
		key   = parse_expr(f, true);
		close = expect_token(f, Token_CloseBracket);
		value = parse_type(f);

		return ast_map_type(f, token, key, value);
	} break;
	
	case Token_matrix: {
		Token token = expect_token(f, Token_matrix);
		Ast *row_count = nullptr;
		Ast *column_count = nullptr;
		Ast *type = nullptr;
		Token open, close;
		
		open  = expect_token_after(f, Token_OpenBracket, "matrix");
		row_count = parse_expr(f, true);
		expect_token(f, Token_Comma);
		column_count = parse_expr(f, true);
		close = expect_token(f, Token_CloseBracket);
		type = parse_type(f);
		
		return ast_matrix_type(f, token, row_count, column_count, type);
	} break;

	case Token_bit_field: {
		Token token = expect_token(f, Token_bit_field);
		isize prev_level;

		prev_level = f->expr_level;
		f->expr_level = -1;

		Ast *backing_type = parse_type_or_ident(f);
		if (backing_type == nullptr) {
			Token token = advance_token(f);
			syntax_error(token, "Expected a backing type for a 'bit_field'");
			backing_type = ast_bad_expr(f, token, f->curr_token);
		}

		skip_possible_newline_for_literal(f);
		Token open = expect_token_after(f, Token_OpenBrace, "bit_field");


		auto fields = array_make<Ast *>(ast_allocator(f), 0, 0);

		while (f->curr_token.kind != Token_CloseBrace &&
		       f->curr_token.kind != Token_EOF) {
			CommentGroup *docs = nullptr;
			CommentGroup *comment = nullptr;

			Ast *name = parse_ident(f);
			bool err_once = false;
			while (allow_token(f, Token_Comma)) {
				Ast *dummy_name = parse_ident(f);
				if (!err_once) {
					error(dummy_name, "'bit_field' fields do not support multiple names per field");
					err_once = true;
				}
			}
			expect_token(f, Token_Colon);
			Ast *type = parse_type(f);
			expect_token(f, Token_Or);
			Ast *bit_size = parse_expr(f, true);

			Token tag = {};
			if (f->curr_token.kind == Token_String) {
				tag = expect_token(f, Token_String);
			}

			Ast *bf_field = ast_bit_field_field(f, name, type, bit_size, tag, docs, comment);
			array_add(&fields, bf_field);

			if (!allow_field_separator(f)) {
				break;
			}
		}

		Token close = expect_closing_brace_of_field_list(f);

		f->expr_level = prev_level;

		return ast_bit_field_type(f, token, backing_type, open, fields, close);
	}


	case Token_struct: {
		Token    token = expect_token(f, Token_struct);
		Ast *polymorphic_params = nullptr;
		bool is_packed          = false;
		bool is_raw_union       = false;
		bool no_copy            = false;
		Ast *align              = nullptr;
		Ast *field_align        = nullptr;

		if (allow_token(f, Token_OpenParen)) {
			isize param_count = 0;
			polymorphic_params = parse_field_list(f, &param_count, 0, Token_CloseParen, true, true);
			if (param_count == 0) {
				syntax_error(polymorphic_params, "Expected at least 1 polymorphic parameter");
				polymorphic_params = nullptr;
			}
			expect_token_after(f, Token_CloseParen, "parameter list");
			check_polymorphic_params_for_type(f, polymorphic_params, token);
		}

		isize prev_level;

		prev_level = f->expr_level;
		f->expr_level = -1;

		while (allow_token(f, Token_Hash)) {
			Token tag = expect_token_after(f, Token_Ident, "#");
			if (tag.string == "packed") {
				if (is_packed) {
					syntax_error(tag, "Duplicate struct tag '#%.*s'", LIT(tag.string));
				}
				is_packed = true;
			} else if (tag.string == "align") {
				if (align) {
					syntax_error(tag, "Duplicate struct tag '#%.*s'", LIT(tag.string));
				}
				align = parse_expr(f, true);
				if (align && align->kind != Ast_ParenExpr) {
					ERROR_BLOCK();
					gbString s = expr_to_string(align);
					syntax_warning(tag, "#align requires parentheses around the expression");
					error_line("\tSuggestion: #align(%s)", s);
					gb_string_free(s);
				}
			} else if (tag.string == "field_align") {
				if (field_align) {
					syntax_error(tag, "Duplicate struct tag '#%.*s'", LIT(tag.string));
				}
				field_align = parse_expr(f, true);
				if (field_align && field_align->kind != Ast_ParenExpr) {
					ERROR_BLOCK();
					gbString s = expr_to_string(field_align);
					syntax_warning(tag, "#field_align requires parentheses around the expression");
					error_line("\tSuggestion: #field_align(%s)", s);
					gb_string_free(s);
				}
			} else if (tag.string == "raw_union") {
				if (is_raw_union) {
					syntax_error(tag, "Duplicate struct tag '#%.*s'", LIT(tag.string));
				}
				is_raw_union = true;
			} else if (tag.string == "no_copy") {
				if (no_copy) {
					syntax_error(tag, "Duplicate struct tag '#%.*s'", LIT(tag.string));
				}
				no_copy = true;
			} else {
				syntax_error(tag, "Invalid struct tag '#%.*s'", LIT(tag.string));
			}
		}

		f->expr_level = prev_level;

		if (is_raw_union && is_packed) {
			is_packed = false;
			syntax_error(token, "'#raw_union' cannot also be '#packed'");
		}

		Token where_token = {};
		Array<Ast *> where_clauses = {};

		skip_possible_newline_for_literal(f);

		if (f->curr_token.kind == Token_where) {
			where_token = expect_token(f, Token_where);
			prev_level = f->expr_level;
			f->expr_level = -1;
			where_clauses = parse_rhs_expr_list(f);
			f->expr_level = prev_level;
		}

		skip_possible_newline_for_literal(f);
		Token open = expect_token_after(f, Token_OpenBrace, "struct");

		isize name_count = 0;
		Ast *fields = parse_struct_field_list(f, &name_count);
		Token close = expect_closing_brace_of_field_list(f);

		Slice<Ast *> decls = {};
		if (fields != nullptr) {
			GB_ASSERT(fields->kind == Ast_FieldList);
			decls = fields->FieldList.list;
		}

		parser_check_polymorphic_record_parameters(f, polymorphic_params);

		return ast_struct_type(f, token, decls, name_count, polymorphic_params, is_packed, is_raw_union, no_copy, align, field_align, where_token, where_clauses);
	} break;

	case Token_union: {
		Token token = expect_token(f, Token_union);
		Ast *polymorphic_params = nullptr;
		Ast *align = nullptr;
		bool no_nil = false;
		bool maybe = false;
		bool shared_nil = false;

		UnionTypeKind union_kind = UnionType_Normal;

		Token start_token = f->curr_token;

		if (allow_token(f, Token_OpenParen)) {
			isize param_count = 0;
			polymorphic_params = parse_field_list(f, &param_count, 0, Token_CloseParen, true, true);
			if (param_count == 0) {
				syntax_error(polymorphic_params, "Expected at least 1 polymorphic parametric");
				polymorphic_params = nullptr;
			}
			expect_token_after(f, Token_CloseParen, "parameter list");
			check_polymorphic_params_for_type(f, polymorphic_params, token);
		}

		while (allow_token(f, Token_Hash)) {
			Token tag = expect_token_after(f, Token_Ident, "#");
			if (tag.string == "align") {
				if (align) {
					syntax_error(tag, "Duplicate union tag '#%.*s'", LIT(tag.string));
				}
				align = parse_expr(f, true);
				if (align && align->kind != Ast_ParenExpr) {
					ERROR_BLOCK();
					gbString s = expr_to_string(align);
					syntax_warning(tag, "#align requires parentheses around the expression");
					error_line("\tSuggestion: #align(%s)", s);
					gb_string_free(s);
				}
			} else if (tag.string == "no_nil") {
				if (no_nil) {
					syntax_error(tag, "Duplicate union tag '#%.*s'", LIT(tag.string));
				}
				no_nil = true;
			} else if (tag.string == "shared_nil") {
				if (shared_nil) {
					syntax_error(tag, "Duplicate union tag '#%.*s'", LIT(tag.string));
				}
				shared_nil = true;
			} else if (tag.string == "maybe") {
				if (maybe) {
					syntax_error(tag, "Duplicate union tag '#%.*s'", LIT(tag.string));
				}
				maybe = true;
			}else {
				syntax_error(tag, "Invalid union tag '#%.*s'", LIT(tag.string));
			}
		}

		if (no_nil && shared_nil) {
			syntax_error(f->curr_token, "#shared_nil and #no_nil cannot be applied together");
		}

		if (maybe) {
			syntax_error(f->curr_token, "#maybe functionality has now been merged with standard 'union' functionality");
		}
		if (no_nil) {
			union_kind = UnionType_no_nil;
		} else if (shared_nil) {
			union_kind = UnionType_shared_nil;
		}

		skip_possible_newline_for_literal(f);

		Token where_token = {};
		Array<Ast *> where_clauses = {};

		if (f->curr_token.kind == Token_where) {
			where_token = expect_token(f, Token_where);
			isize prev_level = f->expr_level;
			f->expr_level = -1;
			where_clauses = parse_rhs_expr_list(f);
			f->expr_level = prev_level;
		}


		skip_possible_newline_for_literal(f);
		Token open = expect_token_after(f, Token_OpenBrace, "union");
		auto variants = parse_union_variant_list(f);
		Token close = expect_closing_brace_of_field_list(f);

		parser_check_polymorphic_record_parameters(f, polymorphic_params);

		return ast_union_type(f, token, variants, polymorphic_params, align, union_kind, where_token, where_clauses);
	} break;

	case Token_enum: {
		Token token = expect_token(f, Token_enum);
		Ast *base_type = nullptr;
		if (f->curr_token.kind != Token_OpenBrace) {
			base_type = parse_type(f);
		}

		skip_possible_newline_for_literal(f);
		Token open = expect_token(f, Token_OpenBrace);

		Array<Ast *> values = parse_enum_field_list(f);
		Token close = expect_closing_brace_of_field_list(f);

		return ast_enum_type(f, token, base_type, values);
	} break;

	case Token_bit_set: {
		Token token = expect_token(f, Token_bit_set);
		expect_token(f, Token_OpenBracket);

		Ast *elem = nullptr;
		Ast *underlying = nullptr;

		bool prev_allow_range = f->allow_range;
		f->allow_range = true;
		elem = parse_expr(f, true);
		f->allow_range = prev_allow_range;

		if (elem == nullptr) {
			syntax_error(token, "Expected a type or range, got nothing");
		}

		if (allow_token(f, Token_Semicolon)) {
			underlying = parse_type(f);
		} else if (allow_token(f, Token_Comma)) {
			String p = token_to_string(f->prev_token);
			syntax_error(token_end_of_line(f, f->prev_token), "Expected a semicolon, got a %.*s", LIT(p));

			underlying = parse_type(f);
		}


		expect_token(f, Token_CloseBracket);
		return ast_bit_set_type(f, token, elem, underlying);
	}

	case Token_asm: {
		Token token = expect_token(f, Token_asm);

		Array<Ast *> param_types = {};
		Ast *return_type = nullptr;
		if (allow_token(f, Token_OpenParen)) {
			param_types = array_make<Ast *>(ast_allocator(f));
			while (f->curr_token.kind != Token_CloseParen && f->curr_token.kind != Token_EOF) {
				Ast *t = parse_type(f);
				array_add(&param_types, t);
				if (f->curr_token.kind != Token_Comma ||
				    f->curr_token.kind == Token_EOF) {
				    break;
				}
				advance_token(f);
			}
			expect_token(f, Token_CloseParen);

			if (allow_token(f, Token_ArrowRight)) {
				return_type = parse_type(f);
			}
		}

		bool has_side_effects = false;
		bool is_align_stack = false;
		InlineAsmDialectKind dialect = InlineAsmDialect_Default;

		while (f->curr_token.kind == Token_Hash) {
			advance_token(f);
			if (f->curr_token.kind == Token_Ident) {
				Token token = advance_token(f);
				String name = token.string;
				if (name == "side_effects") {
					if (has_side_effects) {
						syntax_error(token, "Duplicate directive on inline asm expression: '#side_effects'");
					}
					has_side_effects = true;
				} else if (name == "align_stack") {
					if (is_align_stack) {
						syntax_error(token, "Duplicate directive on inline asm expression: '#align_stack'");
					}
					is_align_stack = true;
				} else if (name == "att") {
					if (dialect == InlineAsmDialect_ATT) {
						syntax_error(token, "Duplicate directive on inline asm expression: '#att'");
					} else if (dialect != InlineAsmDialect_Default) {
						syntax_error(token, "Conflicting asm dialects");
					} else {
						dialect = InlineAsmDialect_ATT;
					}
				} else if (name == "intel") {
					if (dialect == InlineAsmDialect_Intel) {
						syntax_error(token, "Duplicate directive on inline asm expression: '#intel'");
					} else if (dialect != InlineAsmDialect_Default) {
						syntax_error(token, "Conflicting asm dialects");
					} else {
						dialect = InlineAsmDialect_Intel;
					}
				}
			} else {
				syntax_error(f->curr_token, "Expected an identifier after hash");
			}
		}

		skip_possible_newline_for_literal(f);
		Token open = expect_token(f, Token_OpenBrace);
		Ast *asm_string = parse_expr(f, false);
		expect_token(f, Token_Comma);
		Ast *constraints_string = parse_expr(f, false);
		allow_token(f, Token_Comma);
		Token close = expect_closing_brace_of_field_list(f);

		return ast_inline_asm_expr(f, token, open, close, param_types, return_type, asm_string, constraints_string, has_side_effects, is_align_stack, dialect);
	}

	}

	return nullptr;
}

gb_internal bool is_literal_type(Ast *node) {
	node = unparen_expr(node);
	switch (node->kind) {
	case Ast_BadExpr:
	case Ast_Ident:
	case Ast_SelectorExpr:
	case Ast_ArrayType:
	case Ast_StructType:
	case Ast_UnionType:
	case Ast_EnumType:
	case Ast_DynamicArrayType:
	case Ast_MapType:
	case Ast_BitSetType:
	case Ast_MatrixType:
	case Ast_CallExpr:
		return true;
	case Ast_MultiPointerType:
		// For better error messages
		return true;
	}
	return false;
}

gb_internal Ast *parse_call_expr(AstFile *f, Ast *operand) {
	auto args = array_make<Ast *>(ast_allocator(f));
	Token open_paren, close_paren;
	Token ellipsis = {};

	isize prev_expr_level = f->expr_level;
	bool prev_allow_newline = f->allow_newline;
	f->expr_level = 0;
	f->allow_newline = file_allow_newline(f);

	open_paren = expect_token(f, Token_OpenParen);

	bool seen_ellipsis = false;
	while (f->curr_token.kind != Token_CloseParen &&
	       f->curr_token.kind != Token_EOF) {
		if (f->curr_token.kind == Token_Comma) {
			syntax_error(f->curr_token, "Expected an expression not ,");
		} else if (f->curr_token.kind == Token_Eq) {
			syntax_error(f->curr_token, "Expected an expression not =");
		}

		bool prefix_ellipsis = false;
		if (f->curr_token.kind == Token_Ellipsis) {
			prefix_ellipsis = true;
			ellipsis = expect_token(f, Token_Ellipsis);
		}

		Ast *arg = parse_expr(f, false);
		if (f->curr_token.kind == Token_Eq) {
			Token eq = expect_token(f, Token_Eq);

			if (prefix_ellipsis) {
				syntax_error(ellipsis, "'..' must be applied to value rather than the field name");
			}

			Ast *value = parse_value(f);
			arg = ast_field_value(f, arg, value, eq);
		} else if (seen_ellipsis) {
			syntax_error(arg, "Positional arguments are not allowed after '..'");
		}
		array_add(&args, arg);

		if (ellipsis.pos.line != 0) {
			seen_ellipsis = true;
		}

		if (!allow_field_separator(f)) {
			break;
		}
	}
	f->allow_newline = prev_allow_newline;
	f->expr_level = prev_expr_level;
	close_paren = expect_closing(f, Token_CloseParen, str_lit("argument list"));


	Ast *call = ast_call_expr(f, operand, args, open_paren, close_paren, ellipsis);

	Ast *o = unparen_expr(operand);
	if (o->kind == Ast_SelectorExpr && o->SelectorExpr.token.kind == Token_ArrowRight) {
		return ast_selector_call_expr(f, o->SelectorExpr.token, o, call);
	}

	return call;
}

gb_internal void parse_check_or_return(Ast *operand, char const *msg) {
	if (operand == nullptr) {
		return;
	}
	switch (operand->kind) {
	case Ast_OrReturnExpr:
		syntax_error_with_verbose(operand, "'or_return' use within %s is not wrapped in parentheses (...)", msg);
		break;
	case Ast_OrBranchExpr:
		syntax_error_with_verbose(operand, "'or_%.*s' use within %s is not wrapped in parentheses (...)", msg, LIT(operand->OrBranchExpr.token.string));
		break;
	}
}

gb_internal Ast *parse_atom_expr(AstFile *f, Ast *operand, bool lhs) {
	if (operand == nullptr) {
		if (f->allow_type) return nullptr;
		Token begin = f->curr_token;
		syntax_error(begin, "Expected an operand");
		fix_advance_to_next_stmt(f);
		operand = ast_bad_expr(f, begin, f->curr_token);
	}

	bool loop = true;
	while (loop) {
		switch (f->curr_token.kind) {
		case Token_OpenParen:
			parse_check_or_return(operand, "call expression");
			operand = parse_call_expr(f, operand);
			break;

		case Token_Period: {
			Token token = advance_token(f);
			switch (f->curr_token.kind) {
			case Token_Ident:
				parse_check_or_return(operand, "selector expression");
				operand = ast_selector_expr(f, token, operand, parse_ident(f));
				break;
			case Token_OpenParen: {
				parse_check_or_return(operand, "type assertion");
				Token open = expect_token(f, Token_OpenParen);
				Ast *type = parse_type(f);
				Token close = expect_token(f, Token_CloseParen);
				operand = ast_type_assertion(f, operand, token, type);
			} break;

			case Token_Question: {
				parse_check_or_return(operand, ".? based type assertion");
				Token question = expect_token(f, Token_Question);
				Ast *type = ast_unary_expr(f, question, nullptr);
				operand = ast_type_assertion(f, operand, token, type);
			} break;

			default:
				syntax_error(f->curr_token, "Expected a selector");
				advance_token(f);
				operand = ast_bad_expr(f, ast_token(operand), f->curr_token);
				// operand = ast_selector_expr(f, f->curr_token, operand, nullptr);
				break;
			}
		} break;

		case Token_ArrowRight: {
			parse_check_or_return(operand, "-> based call expression");
			Token token = advance_token(f);

			operand = ast_selector_expr(f, token, operand, parse_ident(f));
			// Ast *call = parse_call_expr(f, sel);
			// operand = ast_selector_call_expr(f, token, sel, call);
			break;
		}

		case Token_OpenBracket: {
			bool prev_allow_range = f->allow_range;
			f->allow_range = false;

			Token open = {}, close = {}, interval = {};
			Ast *indices[2] = {};
			bool is_interval = false;

			f->expr_level++;
			open = expect_token(f, Token_OpenBracket);

			switch (f->curr_token.kind) {
			case Token_Ellipsis:
			case Token_RangeFull:
			case Token_RangeHalf:
				// NOTE(bill): Do not err yet
			case Token_Colon:
				break;
			default:
				indices[0] = parse_expr(f, false);
				break;
			}

			switch (f->curr_token.kind) {
			case Token_Ellipsis:
			case Token_RangeFull:
			case Token_RangeHalf:
				syntax_error(f->curr_token, "Expected a colon, not a range");
				/* fallthrough */
			case Token_Comma:  // matrix index
			case Token_Colon:
				interval = advance_token(f);
				is_interval = true;
				if (f->curr_token.kind != Token_CloseBracket &&
				    f->curr_token.kind != Token_EOF) {
					indices[1] = parse_expr(f, false);
				}
				break;
			}


			f->expr_level--;
			close = expect_token(f, Token_CloseBracket);

			if (is_interval) {
				if (interval.kind == Token_Comma) {
					if (indices[0] == nullptr || indices[1] == nullptr) {
						syntax_error(open, "Matrix index expressions require both row and column indices");
					}
					parse_check_or_return(operand, "matrix index expression");
					operand = ast_matrix_index_expr(f, operand, open, close, interval, indices[0], indices[1]);
				} else {
					parse_check_or_return(operand, "slice expression");
					operand = ast_slice_expr(f, operand, open, close, interval, indices[0], indices[1]);
				}
			} else {
				parse_check_or_return(operand, "index expression");
				operand = ast_index_expr(f, operand, indices[0], open, close);
			}

			f->allow_range = prev_allow_range;
		} break;

		case Token_Pointer: // Deference
			parse_check_or_return(operand, "dereference");
			operand = ast_deref_expr(f, operand, expect_token(f, Token_Pointer));
			break;

		case Token_or_return:
			operand = ast_or_return_expr(f, operand, expect_token(f, Token_or_return));
			break;

		case Token_or_break:
		case Token_or_continue:
			{
				Token token = advance_token(f);
				Ast *label = nullptr;
				if (f->curr_token.kind == Token_Ident) {
					label = parse_ident(f);
				}
				operand = ast_or_branch_expr(f, operand, token, label);
			}
			break;

		case Token_OpenBrace:
			if (!lhs && is_literal_type(operand) && f->expr_level >= 0) {
				operand = parse_literal_value(f, operand);
			} else {
				loop = false;
			}
			break;

		case Token_Increment:
		case Token_Decrement:
			if (!lhs) {
				Token token = advance_token(f);
				syntax_error(token, "Postfix '%.*s' operator is not supported", LIT(token.string));
			} else {
				loop = false;
			}
			break;

		default:
			loop = false;
			break;
		}

		lhs = false; // NOTE(bill): 'tis not lhs anymore
	}

	return operand;
}


gb_internal Ast *parse_unary_expr(AstFile *f, bool lhs) {
	switch (f->curr_token.kind) {
	case Token_transmute:
	case Token_cast: {
		Token token = advance_token(f);
		expect_token(f, Token_OpenParen);
		Ast *type = parse_type(f);
		expect_token(f, Token_CloseParen);
		Ast *expr = parse_unary_expr(f, lhs);
		return ast_type_cast(f, token, type, expr);
	}

	case Token_auto_cast: {
		Token token = advance_token(f);
		Ast *expr = parse_unary_expr(f, lhs);
		return ast_auto_cast(f, token, expr);
	}

	case Token_Add:
	case Token_Sub:
	case Token_Xor:
	case Token_And:
	case Token_Not:
	case Token_Mul: // Used for error handling when people do C-like things
	{
		Token token = advance_token(f);
		Ast *expr = parse_unary_expr(f, lhs);
		return ast_unary_expr(f, token, expr);
	}

	case Token_Increment:
	case Token_Decrement: {
		Token token = advance_token(f);
		syntax_error(token, "Unary '%.*s' operator is not supported", LIT(token.string));
		Ast *expr = parse_unary_expr(f, lhs);
		return ast_unary_expr(f, token, expr);
	}


	case Token_Period: {
		Token token = expect_token(f, Token_Period);
		Ast *ident = parse_ident(f);
		return ast_implicit_selector_expr(f, token, ident);
	}
	}

	return parse_atom_expr(f, parse_operand(f, lhs), lhs);
}

gb_internal bool is_ast_range(Ast *expr) {
	if (expr == nullptr) {
		return false;
	}
	if (expr->kind != Ast_BinaryExpr) {
		return false;
	}
	return is_token_range(expr->BinaryExpr.op.kind);
}

// NOTE(bill): result == priority
gb_internal i32 token_precedence(AstFile *f, TokenKind t) {
	switch (t) {
	case Token_Question:
	case Token_if:
	case Token_when:
	case Token_or_else:
		return 1;
	case Token_Ellipsis:
	case Token_RangeFull:
	case Token_RangeHalf:
		if (!f->allow_range) {
			return 0;
		}
		return 2;
	case Token_CmpOr:
		return 3;
	case Token_CmpAnd:
		return 4;
	case Token_CmpEq:
	case Token_NotEq:
	case Token_Lt:
	case Token_Gt:
	case Token_LtEq:
	case Token_GtEq:
		return 5;

	case Token_in:
	case Token_not_in:
		if (f->expr_level < 0 && !f->allow_in_expr) {
			return 0;
		}
		/*fallthrough*/
	case Token_Add:
	case Token_Sub:
	case Token_Or:
	case Token_Xor:
		return 6;
	case Token_Mul:
	case Token_Quo:
	case Token_Mod:
	case Token_ModMod:
	case Token_And:
	case Token_AndNot:
	case Token_Shl:
	case Token_Shr:
		return 7;
	}
	return 0;
}

gb_internal Ast *parse_binary_expr(AstFile *f, bool lhs, i32 prec_in) {
	Ast *expr = parse_unary_expr(f, lhs);
	for (;;) {
		Token op = f->curr_token;
		i32 op_prec = token_precedence(f, op.kind);
		if (op_prec < prec_in) {
			// NOTE(bill): This will also catch operators that are not valid "binary" operators
			break;
		}
		Token prev = f->prev_token;
		switch (op.kind) {
		case Token_if:
		case Token_when:
			if (prev.pos.line < op.pos.line) {
				// NOTE(bill): Check to see if the `if` or `when` is on the same line of the `lhs` condition
				goto loop_end;
			}
			break;
		}
		expect_operator(f); // NOTE(bill): error checks too

		if (op.kind == Token_Question) {
			Ast *cond = expr;
			// Token_Question
			Ast *x = parse_expr(f, lhs);
			Token token_c = expect_token(f, Token_Colon);
			Ast *y = parse_expr(f, lhs);
			expr = ast_ternary_if_expr(f, x, cond, y);
		} else if (op.kind == Token_if || op.kind == Token_when) {
			Ast *x = expr;
			Ast *cond = parse_expr(f, lhs);
			Token tok_else = expect_token(f, Token_else);
			Ast *y = parse_expr(f, lhs);

			switch (op.kind) {
			case Token_if:
				expr = ast_ternary_if_expr(f, x, cond, y);
				break;
			case Token_when:
				expr = ast_ternary_when_expr(f, x, cond, y);
				break;
			}
		} else {
			Ast *right = parse_binary_expr(f, false, op_prec+1);
			if (right == nullptr) {
				syntax_error(op, "Expected expression on the right-hand side of the binary operator '%.*s'", LIT(op.string));
			}
			if (op.kind == Token_or_else) {
				// NOTE(bill): easier to handle its logic different with its own AST kind
				expr = ast_or_else_expr(f, expr, op, right);
			} else {
				expr = ast_binary_expr(f, op, expr, right);
			}
		}

		lhs = false;
	}
	loop_end:;
	return expr;
}

gb_internal Ast *parse_expr(AstFile *f, bool lhs) {
	return parse_binary_expr(f, lhs, 0+1);
}


gb_internal Array<Ast *> parse_expr_list(AstFile *f, bool lhs) {
	bool allow_newline = f->allow_newline;
	f->allow_newline = file_allow_newline(f);

	auto list = array_make<Ast *>(ast_allocator(f));
	for (;;) {
		Ast *e = parse_expr(f, lhs);
		array_add(&list, e);
		if (f->curr_token.kind != Token_Comma ||
		    f->curr_token.kind == Token_EOF) {
		    break;
		}
		advance_token(f);
	}

	f->allow_newline = allow_newline;

	return list;
}

gb_internal Array<Ast *> parse_lhs_expr_list(AstFile *f) {
	return parse_expr_list(f, true);
}

gb_internal Array<Ast *> parse_rhs_expr_list(AstFile *f) {
	return parse_expr_list(f, false);
}

gb_internal Array<Ast *> parse_ident_list(AstFile *f, bool allow_poly_names) {
	auto list = array_make<Ast *>(ast_allocator(f));

	for (;;) {
		array_add(&list, parse_ident(f, allow_poly_names));
		if (f->curr_token.kind != Token_Comma ||
		    f->curr_token.kind == Token_EOF) {
		    break;
		}
		advance_token(f);
	}

	return list;
}

gb_internal Ast *parse_type(AstFile *f) {
	Ast *type = parse_type_or_ident(f);
	if (type == nullptr) {
		Token token = advance_token(f);
		syntax_error(token, "Expected a type");
		return ast_bad_expr(f, token, f->curr_token);
	}
	return type;
}

gb_internal void parse_foreign_block_decl(AstFile *f, Array<Ast *> *decls) {
	Ast *decl = parse_stmt(f);
	switch (decl->kind) {
	case Ast_EmptyStmt:
	case Ast_BadStmt:
	case Ast_BadDecl:
		return;

	case Ast_WhenStmt:
	case Ast_ValueDecl:
		array_add(decls, decl);
		return;

	default:
		syntax_error(decl, "Foreign blocks only allow procedure and variable declarations");
		return;
	}
}

gb_internal Ast *parse_foreign_block(AstFile *f, Token token) {
	CommentGroup *docs = f->lead_comment;
	Ast *foreign_library = nullptr;
	if (f->curr_token.kind == Token_OpenBrace) {
		foreign_library = ast_ident(f, blank_token);
	} else {
		foreign_library = parse_ident(f);
	}
	Token open = {};
	Token close = {};
	auto decls = array_make<Ast *>(ast_allocator(f));

	bool prev_in_foreign_block = f->in_foreign_block;
	defer (f->in_foreign_block = prev_in_foreign_block);
	f->in_foreign_block = true;

	skip_possible_newline_for_literal(f);
	open = expect_token(f, Token_OpenBrace);

	while (f->curr_token.kind != Token_CloseBrace &&
	       f->curr_token.kind != Token_EOF) {
		parse_foreign_block_decl(f, &decls);
	}

	close = expect_token(f, Token_CloseBrace);

	Ast *body = ast_block_stmt(f, decls, open, close);

	Ast *decl = ast_foreign_block_decl(f, token, foreign_library, body, docs);
	expect_semicolon(f);
	return decl;
}

gb_internal void print_comment_group(CommentGroup *group) {
	if (group) {
		for (Token const &token : group->list) {
			gb_printf_err("%.*s\n", LIT(token.string));
		}
		gb_printf_err("\n");
	}
}

gb_internal Ast *parse_value_decl(AstFile *f, Array<Ast *> names, CommentGroup *docs) {
	bool is_mutable = true;

	Array<Ast *> values = {};
	Ast *type = parse_type_or_ident(f);

	if (f->curr_token.kind == Token_Eq ||
	    f->curr_token.kind == Token_Colon) {
		Token sep = {};
		if (!is_mutable) {
			sep = expect_token_after(f, Token_Colon, "type");
		} else {
			sep = advance_token(f);
			is_mutable = sep.kind != Token_Colon;
		}
		values = parse_rhs_expr_list(f);
		if (values.count > names.count) {
			syntax_error(f->curr_token, "Too many values on the right hand side of the declaration");
		} else if (values.count < names.count && !is_mutable) {
			syntax_error(f->curr_token, "All constant declarations must be defined");
		} else if (values.count == 0) {
			syntax_error(f->curr_token, "Expected an expression for this declaration");
		}
	}

	if (is_mutable) {
		if (type == nullptr && values.count == 0) {
			syntax_error(f->curr_token, "Missing variable type or initialization");
			return ast_bad_decl(f, f->curr_token, f->curr_token);
		}
	} else {
		if (type == nullptr && values.count == 0 && names.count > 0) {
			syntax_error(f->curr_token, "Missing constant value");
			return ast_bad_decl(f, f->curr_token, f->curr_token);
		}
	}

	if (values.data == nullptr) {
		values.allocator = ast_allocator(f);
	}

	CommentGroup *end_comment = f->lead_comment;

	if (f->expr_level >= 0) {
		if (f->curr_token.kind == Token_CloseBrace &&
		    f->curr_token.pos.line == f->prev_token.pos.line) {

		} else {
			expect_semicolon(f);
		}
	}

	if (f->curr_proc == nullptr) {
		if (values.count > 0 && names.count != values.count) {
			syntax_error(
				values[0],
				"Expected %td expressions on the right hand side, got %td\n"
				"\tNote: Global declarations do not allow for multi-valued expressions",
				names.count, values.count
			);
		}
	}

	return ast_value_decl(f, names, type, values, is_mutable, docs, end_comment);
}

gb_internal Ast *parse_simple_stmt(AstFile *f, u32 flags) {
	Token token = f->curr_token;
	CommentGroup *docs = f->lead_comment;

	Array<Ast *> lhs = parse_lhs_expr_list(f);
	token = f->curr_token;
	switch (token.kind) {
	case Token_Eq:
	case Token_AddEq:
	case Token_SubEq:
	case Token_MulEq:
	case Token_QuoEq:
	case Token_ModEq:
	case Token_ModModEq:
	case Token_AndEq:
	case Token_OrEq:
	case Token_XorEq:
	case Token_ShlEq:
	case Token_ShrEq:
	case Token_AndNotEq:
	case Token_CmpAndEq:
	case Token_CmpOrEq:
	{
		if (f->curr_proc == nullptr) {
			syntax_error(f->curr_token, "You cannot use a simple statement in the file scope");
			return ast_bad_stmt(f, f->curr_token, f->curr_token);
		}
		advance_token(f);
		Array<Ast *> rhs = parse_rhs_expr_list(f);
		if (rhs.count == 0) {
			syntax_error(token, "No right-hand side in assignment statement.");
			return ast_bad_stmt(f, token, f->curr_token);
		}
		return ast_assign_stmt(f, token, lhs, rhs);
	} break;

	case Token_in:
		if (flags&StmtAllowFlag_In) {
			allow_token(f, Token_in);
			bool prev_allow_range = f->allow_range;
			f->allow_range = true;
			Ast *expr = parse_expr(f, true);
			f->allow_range = prev_allow_range;

			auto rhs = array_make<Ast *>(ast_allocator(f), 0, 1);
			array_add(&rhs, expr);

			return ast_assign_stmt(f, token, lhs, rhs);
		}
		break;

	case Token_Colon:
		expect_token_after(f, Token_Colon, "identifier list");
		if ((flags&StmtAllowFlag_Label) && lhs.count == 1) {
			bool is_partial = false;
			bool is_reverse = false;
			Token partial_token = {};
			if (f->curr_token.kind == Token_Hash) {
				// NOTE(bill): This is purely for error messages
				Token name = peek_token_n(f, 0);
				if (name.kind == Token_Ident && name.string == "partial" &&
				    peek_token_n(f, 1).kind == Token_switch) {
					partial_token = expect_token(f, Token_Hash);
					expect_token(f, Token_Ident);
					is_partial = true;
				} else if (name.kind == Token_Ident && name.string == "reverse" &&
				    peek_token_n(f, 1).kind == Token_for) {
					partial_token = expect_token(f, Token_Hash);
					expect_token(f, Token_Ident);
					is_reverse = true;
				}
			}
			switch (f->curr_token.kind) {
			case Token_OpenBrace: // block statement
			case Token_if:
			case Token_for:
			case Token_switch: {
				Ast *name = lhs[0];
				Ast *label = ast_label_decl(f, ast_token(name), name);
				Ast *stmt = parse_stmt(f);
			#define _SET_LABEL(Kind_, label_) case GB_JOIN2(Ast_, Kind_): (stmt->Kind_).label = label_; break
				switch (stmt->kind) {
				_SET_LABEL(BlockStmt, label);
				_SET_LABEL(IfStmt, label);
				_SET_LABEL(ForStmt, label);
				_SET_LABEL(RangeStmt, label);
				_SET_LABEL(SwitchStmt, label);
				_SET_LABEL(TypeSwitchStmt, label);
				default:
					syntax_error(token, "Labels can only be applied to a loop or switch statement");
					break;
				}
			#undef _SET_LABEL

				if (is_partial) {
					switch (stmt->kind) {
					case Ast_SwitchStmt:
						stmt->SwitchStmt.partial = true;
						break;
					case Ast_TypeSwitchStmt:
						stmt->TypeSwitchStmt.partial = true;
						break;
					}
					syntax_error(partial_token, "Incorrect use of directive, use '#partial %.*s: switch'", LIT(ast_token(name).string));
				} else if (is_reverse) {
					switch (stmt->kind) {
					case Ast_RangeStmt:
						if (stmt->RangeStmt.reverse) {
							syntax_error(token, "#reverse already applied to a 'for in' statement");
						}
						stmt->RangeStmt.reverse = true;
						break;
					default:
						syntax_error(token, "#reverse can only be applied to a 'for in' statement");
						break;
					}
				}

				return stmt;
			} break;
			}
		}
		return parse_value_decl(f, lhs, docs);
	}

	if (lhs.count > 1) {
		syntax_error(token, "Expected 1 expression");
		return ast_bad_stmt(f, token, f->curr_token);
	}

	switch (token.kind) {
	case Token_Increment:
	case Token_Decrement:
		advance_token(f);
		syntax_error(token, "Postfix '%.*s' statement is not supported", LIT(token.string));
		break;
	}


	#if 0
	switch (token.kind) {
	case Token_Inc:
	case Token_Dec:
		advance_token(f);
		return ast_inc_dec_stmt(f, token, lhs[0]);
	}
	#endif

	return ast_expr_stmt(f, lhs[0]);
}



gb_internal Ast *parse_block_stmt(AstFile *f, b32 is_when) {
	skip_possible_newline_for_literal(f);
	if (!is_when && f->curr_proc == nullptr) {
		syntax_error(f->curr_token, "You cannot use a block statement in the file scope");
		return ast_bad_stmt(f, f->curr_token, f->curr_token);
	}
	return parse_body(f);
}



gb_internal Ast *parse_results(AstFile *f, bool *diverging) {
	if (!allow_token(f, Token_ArrowRight)) {
		return nullptr;
	}

	if (allow_token(f, Token_Not)) {
		if (diverging) *diverging = true;
		return nullptr;
	}

	isize prev_level = f->expr_level;
	defer (f->expr_level = prev_level);

	if (f->curr_token.kind != Token_OpenParen) {
		Token begin_token = f->curr_token;
		Array<Ast *> empty_names = {};
		auto list = array_make<Ast *>(ast_allocator(f), 0, 1);
		Ast *type = parse_type(f);
		Token tag = {};
		array_add(&list, ast_field(f, empty_names, type, nullptr, 0, tag, nullptr, nullptr));
		return ast_field_list(f, begin_token, list);
	}

	Ast *list = nullptr;
	expect_token(f, Token_OpenParen);
	list = parse_field_list(f, nullptr, FieldFlag_Results, Token_CloseParen, true, false);
	if (file_allow_newline(f)) {
		skip_possible_newline(f);
	}
	expect_token_after(f, Token_CloseParen, "parameter list");
	return list;
}


gb_internal ProcCallingConvention string_to_calling_convention(String const &s) {
	if (s == "odin")        return ProcCC_Odin;
	if (s == "contextless") return ProcCC_Contextless;
	if (s == "cdecl")       return ProcCC_CDecl;
	if (s == "c")           return ProcCC_CDecl;
	if (s == "stdcall")     return ProcCC_StdCall;
	if (s == "std")         return ProcCC_StdCall;
	if (s == "fastcall")    return ProcCC_FastCall;
	if (s == "fast")        return ProcCC_FastCall;
	if (s == "none")        return ProcCC_None;
	if (s == "naked")       return ProcCC_Naked;

	if (s == "win64")	return ProcCC_Win64;
	if (s == "sysv")        return ProcCC_SysV;

	if (s == "system") {
		if (build_context.metrics.os == TargetOs_windows) {
			return ProcCC_StdCall;
		}
		return ProcCC_CDecl;
	}


	return ProcCC_Invalid;
}

gb_internal Ast *parse_proc_type(AstFile *f, Token proc_token) {
	Ast *params = nullptr;
	Ast *results = nullptr;
	bool diverging = false;

	ProcCallingConvention cc = ProcCC_Invalid;
	if (f->curr_token.kind == Token_String) {
		Token token = expect_token(f, Token_String);
		auto c = string_to_calling_convention(string_value_from_token(f, token));
		if (c == ProcCC_Invalid) {
			syntax_error(token, "Unknown procedure calling convention: '%.*s'", LIT(token.string));
		} else {
			cc = c;
		}
	}
	if (cc == ProcCC_Invalid) {
		if (f->in_foreign_block) {
			cc = ProcCC_ForeignBlockDefault;
		} else {
			cc = default_calling_convention();
		}
	}


	expect_token(f, Token_OpenParen);
	params = parse_field_list(f, nullptr, FieldFlag_Signature, Token_CloseParen, true, true);
	if (file_allow_newline(f)) {
		skip_possible_newline(f);
	}
	expect_token_after(f, Token_CloseParen, "parameter list");
	results = parse_results(f, &diverging);

	u64 tags = 0;
	bool is_generic = false;

	for (Ast *param : params->FieldList.list) {
		ast_node(field, Field, param);
		if (field->type != nullptr) {
		    if (field->type->kind == Ast_PolyType) {
				is_generic = true;
				goto end;
			}
			for (Ast *name : field->names) {
				if (name->kind == Ast_PolyType) {
					is_generic = true;
					goto end;
				}
			}
		}
	}
end:
	return ast_proc_type(f, proc_token, params, results, tags, cc, is_generic, diverging);
}

gb_internal Ast *parse_var_type(AstFile *f, bool allow_ellipsis, bool allow_typeid_token) {
	if (allow_ellipsis && f->curr_token.kind == Token_Ellipsis) {
		Token tok = advance_token(f);
		Ast *type = parse_type_or_ident(f);
		if (type == nullptr) {
			syntax_error(tok, "variadic field missing type after '..'");
			type = ast_bad_expr(f, tok, f->curr_token);
		}
		return ast_ellipsis(f, tok, type);
	}
	Ast *type = nullptr;
	if (allow_typeid_token &&
	    f->curr_token.kind == Token_typeid) {
		Token token = expect_token(f, Token_typeid);
		Ast *specialization = nullptr;
		if (allow_token(f, Token_Quo)) {
			specialization = parse_type(f);
		}
		type = ast_typeid_type(f, token, specialization);
	} else {
		type = parse_type(f);
	}
	return type;
}


struct ParseFieldPrefixMapping {
	String          name;
	TokenKind       token_kind;
	FieldFlag       flag;
};

gb_global ParseFieldPrefixMapping const parse_field_prefix_mappings[] = {
	{str_lit("using"),        Token_using,     FieldFlag_using},
	{str_lit("no_alias"),     Token_Hash,      FieldFlag_no_alias},
	{str_lit("c_vararg"),     Token_Hash,      FieldFlag_c_vararg},
	{str_lit("const"),        Token_Hash,      FieldFlag_const},
	{str_lit("any_int"),      Token_Hash,      FieldFlag_any_int},
	{str_lit("subtype"),      Token_Hash,      FieldFlag_subtype},
	{str_lit("by_ptr"),       Token_Hash,      FieldFlag_by_ptr},
	{str_lit("no_broadcast"), Token_Hash,      FieldFlag_no_broadcast},
};


gb_internal FieldFlag is_token_field_prefix(AstFile *f) {
	switch (f->curr_token.kind) {
	case Token_EOF:
		return FieldFlag_Invalid;

	case Token_using:
		return FieldFlag_using;

	case Token_Hash:
		advance_token(f);
		switch (f->curr_token.kind) {
		case Token_Ident:
			for (i32 i = 0; i < gb_count_of(parse_field_prefix_mappings); i++) {
				auto const &mapping = parse_field_prefix_mappings[i];
				if (mapping.token_kind == Token_Hash) {
					if (f->curr_token.string == mapping.name) {
						return mapping.flag;
					}
				}
			}
			break;
		}
		return FieldFlag_Unknown;
	}
	return FieldFlag_Invalid;
}

gb_internal u32 parse_field_prefixes(AstFile *f) {
	i32 counts[gb_count_of(parse_field_prefix_mappings)] = {};

	for (;;) {
		FieldFlag flag = is_token_field_prefix(f);
		if (flag & FieldFlag_Invalid) {
			break;
		}
		if (flag & FieldFlag_Unknown) {
			syntax_error(f->curr_token, "Unknown prefix kind '#%.*s'", LIT(f->curr_token.string));
			advance_token(f);
			continue;
		}

		for (i32 i = 0; i < gb_count_of(parse_field_prefix_mappings); i++) {
			if (parse_field_prefix_mappings[i].flag == flag) {
				counts[i] += 1;
				advance_token(f);
				break;
			}
		}
	}

	u32 field_flags = 0;
	for (i32 i = 0; i < gb_count_of(parse_field_prefix_mappings); i++) {
		if (counts[i] > 0) {
			field_flags |= parse_field_prefix_mappings[i].flag;

			if (counts[i] != 1) {
				auto const &mapping = parse_field_prefix_mappings[i];
				String name = mapping.name;
				char const *prefix = "";
				if (mapping.token_kind == Token_Hash) {
					prefix = "#";
				}
				syntax_error(f->curr_token, "Multiple '%s%.*s' in this field list", prefix, LIT(name));
			}
		}
	}
	return field_flags;
}

gb_internal u32 check_field_prefixes(AstFile *f, isize name_count, u32 allowed_flags, u32 set_flags) {
	for (i32 i = 0; i < gb_count_of(parse_field_prefix_mappings); i++) {
		bool err = false;
		auto const &m = parse_field_prefix_mappings[i];

		if ((set_flags & m.flag) != 0) {
			if (m.flag == FieldFlag_using && name_count > 1) {
				err = true;
				syntax_error(f->curr_token, "Cannot apply 'using' to more than one of the same type");
			}

			if ((allowed_flags & m.flag) == 0) {
				err = true;
				char const *prefix = "";
				if (m.token_kind == Token_Hash) {
					prefix = "#";
				}
				syntax_error(f->curr_token, "'%s%.*s' in not allowed within this field list", prefix, LIT(m.name));
			}
		}

		if (err) {
			set_flags &= ~m.flag;
		}
	}
	return set_flags;
}

struct AstAndFlags {
	Ast *node;
	u32      flags;
};

gb_internal Array<Ast *> convert_to_ident_list(AstFile *f, Array<AstAndFlags> list, bool ignore_flags, bool allow_poly_names) {
	auto idents = array_make<Ast *>(ast_allocator(f), 0, list.count);
	// Convert to ident list
	isize i = 0;
	for (AstAndFlags const &item : list) {
		Ast *ident = item.node;

		if (!ignore_flags) {
			if (i != 0) {
				syntax_error(ident, "Illegal use of prefixes in parameter list");
			}
		}

		switch (ident->kind) {
		case Ast_Ident:
		case Ast_BadExpr:
			break;
		case Ast_Implicit:
			begin_error_block();
			syntax_error(ident, "Expected an identifier, '%.*s' which is a keyword", LIT(ident->Implicit.string));
			if (ident->Implicit.kind == Token_context) {
				error_line("\tSuggestion: Would 'ctx' suffice as an alternative name?\n");
			}
			end_error_block();
			ident = ast_ident(f, blank_token);
			break;

		case Ast_PolyType:
			if (allow_poly_names) {
				if (ident->PolyType.specialization == nullptr) {
					break;
				} else {
					syntax_error(ident, "Expected a polymorphic identifier without any specialization");
				}
			} else {
				syntax_error(ident, "Expected a non-polymorphic identifier");
			}
			/*fallthrough*/


		default:
			syntax_error(ident, "Expected an identifier");
			ident = ast_ident(f, blank_token);
			break;
		}
		array_add(&idents, ident);
		i += 1;
	}
	return idents;
}


gb_internal bool allow_field_separator(AstFile *f) {
	Token token = f->curr_token;
	if (allow_token(f, Token_Comma)) {
		return true;
	}
	if (token.kind == Token_Semicolon) {
		bool ok = false;
		if (file_allow_newline(f) && token_is_newline(token)) {
			TokenKind next = peek_token(f).kind;
			switch (next) {
			case Token_CloseBrace:
			case Token_CloseParen:
				ok = true;
				break;
			}
		}
		if (!ok) {
			String p = token_to_string(token);
			syntax_error(token_end_of_line(f, f->prev_token), "Expected a comma, got a %.*s", LIT(p));
		}
		advance_token(f);
		return true;
	}
	return false;
}

gb_internal Ast *parse_struct_field_list(AstFile *f, isize *name_count_) {
	Token start_token = f->curr_token;

	auto decls = array_make<Ast *>(ast_allocator(f));

	isize total_name_count = 0;

	Ast *params = parse_field_list(f, &total_name_count, FieldFlag_Struct, Token_CloseBrace, false, false);
	if (name_count_) *name_count_ = total_name_count;
	return params;
}


// Returns true if any are polymorphic names
gb_internal bool check_procedure_name_list(Array<Ast *> const &names) {
	if (names.count == 0) {
		return false;
	}
	bool first_is_polymorphic = names[0]->kind == Ast_PolyType;
	bool any_polymorphic_names = first_is_polymorphic;
	for (isize i = 1; i < names.count; i++) {
		Ast *name = names[i];
		if (first_is_polymorphic) {
			if (name->kind == Ast_PolyType) {
				any_polymorphic_names = true;
			} else {
				syntax_error(name, "Mixture of polymorphic and non-polymorphic identifiers");
				return any_polymorphic_names;
			}
		} else {
			if (name->kind == Ast_PolyType) {
				any_polymorphic_names = true;
				syntax_error(name, "Mixture of polymorphic and non-polymorphic identifiers");
				return any_polymorphic_names;
			} else {
				// Okay
			}
		}
	}
	return any_polymorphic_names;
}

gb_internal Ast *parse_field_list(AstFile *f, isize *name_count_, u32 allowed_flags, TokenKind follow, bool allow_default_parameters, bool allow_typeid_token) {
	bool prev_allow_newline = f->allow_newline;
	defer (f->allow_newline = prev_allow_newline);
	f->allow_newline = file_allow_newline(f);

	Token start_token = f->curr_token;

	CommentGroup *docs = f->lead_comment;

	auto params = array_make<Ast *>(ast_allocator(f));

	auto list = array_make<AstAndFlags>(temporary_allocator());

	bool allow_poly_names = allow_typeid_token;

	isize total_name_count = 0;
	bool allow_ellipsis = allowed_flags&FieldFlag_ellipsis;
	bool seen_ellipsis = false;
	bool is_signature = (allowed_flags & FieldFlag_Signature) == FieldFlag_Signature;

	while (f->curr_token.kind != follow &&
	       f->curr_token.kind != Token_Colon &&
	       f->curr_token.kind != Token_EOF) {
		u32 flags = parse_field_prefixes(f);
		Ast *param = parse_var_type(f, allow_ellipsis, allow_typeid_token);
		if (param->kind == Ast_Ellipsis) {
			if (seen_ellipsis) syntax_error(param, "Extra variadic parameter after ellipsis");
			seen_ellipsis = true;
		} else if (seen_ellipsis) {
			syntax_error(param, "Extra parameter after ellipsis");
		}
		AstAndFlags naf = {param, flags};
		array_add(&list, naf);
		if (!allow_field_separator(f)) {
			break;
		}
	}


	if (f->curr_token.kind == Token_Colon) {
		Array<Ast *> names = convert_to_ident_list(f, list, true, allow_poly_names); // Copy for semantic reasons
		if (names.count == 0) {
			syntax_error(f->curr_token, "Empty field declaration");
		}
		bool any_polymorphic_names = check_procedure_name_list(names);
		u32 set_flags = 0;
		if (list.count > 0) {
			set_flags = list[0].flags;
		}
		set_flags = check_field_prefixes(f, names.count, allowed_flags, set_flags);
		total_name_count += names.count;

		Ast *type = nullptr;
		Ast *default_value = nullptr;
		Token tag = {};

		expect_token_after(f, Token_Colon, "field list");
		if (f->curr_token.kind != Token_Eq) {
			type = parse_var_type(f, allow_ellipsis, allow_typeid_token);
			Ast *tt = unparen_expr(type);
			if (tt == nullptr) {
				syntax_error(f->prev_token, "Invalid type expression in field list");
			} else if (is_signature && !any_polymorphic_names && tt->kind == Ast_TypeidType && tt->TypeidType.specialization != nullptr) {
				syntax_error(type, "Specialization of typeid is not allowed without polymorphic names");
			}
		}

		if (allow_token(f, Token_Eq)) {
			default_value = parse_expr(f, false);
			if (!allow_default_parameters) {
				syntax_error(f->curr_token, "Default parameters are only allowed for procedures");
				default_value = nullptr;
			}
		}

		if (default_value != nullptr && names.count > 1) {
			syntax_error(f->curr_token, "Default parameters can only be applied to single values");
		}

		if (allowed_flags == FieldFlag_Struct && default_value != nullptr) {
			syntax_error(default_value, "Default parameters are not allowed for structs");
			default_value = nullptr;
		}

		if (type != nullptr && type->kind == Ast_Ellipsis) {
			if (seen_ellipsis) syntax_error(type, "Extra variadic parameter after ellipsis");
			seen_ellipsis = true;
			if (names.count != 1) {
				syntax_error(type, "Variadic parameters can only have one field name");
			}
		} else if (seen_ellipsis && default_value == nullptr) {
			syntax_error(f->curr_token, "Extra parameter after ellipsis without a default value");
		}

		if (type != nullptr && default_value == nullptr) {
			if (f->curr_token.kind == Token_String) {
				tag = expect_token(f, Token_String);
				if ((allowed_flags & FieldFlag_Tags) == 0) {
					syntax_error(tag, "Field tags are only allowed within structures");
				}
			}
		}

		allow_field_separator(f);
		Ast *param = ast_field(f, names, type, default_value, set_flags, tag, docs, f->line_comment);
		array_add(&params, param);


		while (f->curr_token.kind != follow &&
		       f->curr_token.kind != Token_EOF &&
		       f->curr_token.kind != Token_Semicolon) {
			CommentGroup *docs = f->lead_comment;
			u32 set_flags = parse_field_prefixes(f);
			Token tag = {};
			Array<Ast *> names = parse_ident_list(f, allow_poly_names);
			if (names.count == 0) {
				syntax_error(f->curr_token, "Empty field declaration");
				break;
			}
			bool any_polymorphic_names = check_procedure_name_list(names);
			set_flags = check_field_prefixes(f, names.count, allowed_flags, set_flags);
			total_name_count += names.count;

			Ast *type = nullptr;
			Ast *default_value = nullptr;
			expect_token_after(f, Token_Colon, "field list");
			if (f->curr_token.kind != Token_Eq) {
				type = parse_var_type(f, allow_ellipsis, allow_typeid_token);
				Ast *tt = unparen_expr(type);
				if (is_signature && !any_polymorphic_names &&
				    tt != nullptr &&
				    tt->kind == Ast_TypeidType && tt->TypeidType.specialization != nullptr) {
					syntax_error(type, "Specialization of typeid is not allowed without polymorphic names");
				}
			}

			if (allow_token(f, Token_Eq)) {
				default_value = parse_expr(f, false);
				if (!allow_default_parameters) {
					syntax_error(f->curr_token, "Default parameters are only allowed for procedures");
					default_value = nullptr;
				}
			}

			if (default_value != nullptr && names.count > 1) {
				syntax_error(f->curr_token, "Default parameters can only be applied to single values");
			}

			if (type != nullptr && type->kind == Ast_Ellipsis) {
				if (seen_ellipsis) syntax_error(type, "Extra variadic parameter after ellipsis");
				seen_ellipsis = true;
				if (names.count != 1) {
					syntax_error(type, "Variadic parameters can only have one field name");
				}
			} else if (seen_ellipsis && default_value == nullptr) {
				syntax_error(f->curr_token, "Extra parameter after ellipsis without a default value");
			}

			if (type != nullptr && default_value == nullptr) {
				if (f->curr_token.kind == Token_String) {
					tag = expect_token(f, Token_String);
					if ((allowed_flags & FieldFlag_Tags) == 0) {
						syntax_error(tag, "Field tags are only allowed within structures");
					}
				}
			}


			bool ok = allow_field_separator(f);
			Ast *param = ast_field(f, names, type, default_value, set_flags, tag, docs, f->line_comment);
			array_add(&params, param);

			if (!ok) {
				break;
			}
		}

		if (name_count_) *name_count_ = total_name_count;
		return ast_field_list(f, start_token, params);
	}

	for (AstAndFlags const &item : list) {
		Ast *type = item.node;
		Token token = blank_token;
		if (allowed_flags&FieldFlag_Results) {
			// NOTE(bill): Make this nothing and not `_`
			token.string = str_lit("");
		}

		auto names = array_make<Ast *>(ast_allocator(f), 1);
		token.pos = ast_token(type).pos;
		names[0] = ast_ident(f, token);
		u32 flags = check_field_prefixes(f, list.count, allowed_flags, item.flags);
		Token tag = {};
		Ast *param = ast_field(f, names, item.node, nullptr, flags, tag, docs, f->line_comment);
		array_add(&params, param);
	}

	if (name_count_) *name_count_ = total_name_count;
	return ast_field_list(f, start_token, params);
}

gb_internal Ast *parse_type_or_ident(AstFile *f) {
	bool prev_allow_type = f->allow_type;
	isize prev_expr_level = f->expr_level;
	defer ({
		f->allow_type = prev_allow_type;
		f->expr_level = prev_expr_level;
	});

	f->allow_type = true;
	f->expr_level = -1;

	bool lhs = true;
	Ast *operand = parse_operand(f, lhs);
	Ast *type = parse_atom_expr(f, operand, lhs);
	return type;
}



gb_internal Ast *parse_body(AstFile *f) {
	Array<Ast *> stmts = {};
	Token open, close;
	isize prev_expr_level = f->expr_level;
	bool prev_allow_newline = f->allow_newline;

	// NOTE(bill): The body may be within an expression so reset to zero
	f->expr_level = 0;
	// f->allow_newline = false;
	open = expect_token(f, Token_OpenBrace);
	stmts = parse_stmt_list(f);
	close = expect_token(f, Token_CloseBrace);
	f->expr_level = prev_expr_level;
	f->allow_newline = prev_allow_newline;

	return ast_block_stmt(f, stmts, open, close);
}

gb_internal Ast *parse_do_body(AstFile *f, Token const &token, char const *msg) {
	Token open, close;
	isize prev_expr_level = f->expr_level;
	bool prev_allow_newline = f->allow_newline;

	// NOTE(bill): The body may be within an expression so reset to zero
	f->expr_level = 0;
	f->allow_newline = false;

	Ast *body = convert_stmt_to_body(f, parse_stmt(f));
	if (build_context.disallow_do) {
		syntax_error(body, "'do' has been disallowed");
	} else if (token.pos.file_id != 0 && !ast_on_same_line(token, body)) {
		syntax_error(body, "The body of a 'do' must be on the same line as %s", msg);
	}
	f->expr_level = prev_expr_level;
	f->allow_newline = prev_allow_newline;

	return body;
}

gb_internal bool parse_control_statement_semicolon_separator(AstFile *f) {
	Token tok = peek_token(f);
	if (tok.kind != Token_OpenBrace) {
		return allow_token(f, Token_Semicolon);
	}
	if (f->curr_token.string == ";") {
		return allow_token(f, Token_Semicolon);
	}
	return false;
}


gb_internal Ast *parse_if_stmt(AstFile *f) {
	if (f->curr_proc == nullptr) {
		syntax_error(f->curr_token, "You cannot use an if statement in the file scope");
		return ast_bad_stmt(f, f->curr_token, f->curr_token);
	}

	Token token = expect_token(f, Token_if);
	Ast *init = nullptr;
	Ast *cond = nullptr;
	Ast *body = nullptr;
	Ast *else_stmt = nullptr;

	isize prev_level = f->expr_level;
	f->expr_level = -1;
	bool prev_allow_in_expr = f->allow_in_expr;
	f->allow_in_expr = true;

	if (allow_token(f, Token_Semicolon)) {
		cond = parse_expr(f, false);
	} else {
		init = parse_simple_stmt(f, StmtAllowFlag_None);
		if (parse_control_statement_semicolon_separator(f)) {
			cond = parse_expr(f, false);
		} else {
			cond = convert_stmt_to_expr(f, init, str_lit("boolean expression"));
			init = nullptr;
		}
	}

	f->expr_level = prev_level;
	f->allow_in_expr = prev_allow_in_expr;

	if (cond == nullptr) {
		syntax_error(f->curr_token, "Expected condition for if statement");
	}

	if (allow_token(f, Token_do)) {
		body = parse_do_body(f, cond ? ast_token(cond) : token, "the if statement");
	} else {
		body = parse_block_stmt(f, false);
	}

	skip_possible_newline_for_literal(f);
	if (f->curr_token.kind == Token_else) {
		Token else_token = expect_token(f, Token_else);
		switch (f->curr_token.kind) {
		case Token_if:
			else_stmt = parse_if_stmt(f);
			break;
		case Token_OpenBrace:
			else_stmt = parse_block_stmt(f, false);
			break;
		case Token_do:
			expect_token(f, Token_do);
			else_stmt = parse_do_body(f, else_token, "'else'");
			break;
		default:
			syntax_error(f->curr_token, "Expected if statement block statement");
			else_stmt = ast_bad_stmt(f, f->curr_token, f->tokens[f->curr_token_index+1]);
			break;
		}
	}

	return ast_if_stmt(f, token, init, cond, body, else_stmt);
}

gb_internal Ast *parse_when_stmt(AstFile *f) {
	Token token = expect_token(f, Token_when);
	Ast *cond = nullptr;
	Ast *body = nullptr;
	Ast *else_stmt = nullptr;

	isize prev_level = f->expr_level;
	f->expr_level = -1;

	cond = parse_expr(f, false);

	f->expr_level = prev_level;

	if (cond == nullptr) {
		syntax_error(f->curr_token, "Expected condition for when statement");
	}

	bool was_in_when_statement = f->in_when_statement;
	f->in_when_statement = true;
	if (allow_token(f, Token_do)) {
		body = parse_do_body(f, cond ? ast_token(cond) : token, "then when statement");
	} else {
		body = parse_block_stmt(f, true);
	}

	skip_possible_newline_for_literal(f);
	if (f->curr_token.kind == Token_else) {
		Token else_token = expect_token(f, Token_else);
		switch (f->curr_token.kind) {
		case Token_when:
			else_stmt = parse_when_stmt(f);
			break;
		case Token_OpenBrace:
			else_stmt = parse_block_stmt(f, true);
			break;
		case Token_do: {
			expect_token(f, Token_do);
			else_stmt = parse_do_body(f, else_token, "'else'");
		} break;
		default:
			syntax_error(f->curr_token, "Expected when statement block statement");
			else_stmt = ast_bad_stmt(f, f->curr_token, f->tokens[f->curr_token_index+1]);
			break;
		}
	}
	f->in_when_statement = was_in_when_statement;

	return ast_when_stmt(f, token, cond, body, else_stmt);
}


gb_internal Ast *parse_return_stmt(AstFile *f) {
	Token token = expect_token(f, Token_return);

	if (f->curr_proc == nullptr) {
		syntax_error(f->curr_token, "You cannot use a return statement in the file scope");
		return ast_bad_stmt(f, token, f->curr_token);
	}
	if (f->expr_level > 0) {
		syntax_error(f->curr_token, "You cannot use a return statement within an expression");
		return ast_bad_stmt(f, token, f->curr_token);
	}

	auto results = array_make<Ast *>(ast_allocator(f));

	while (f->curr_token.kind != Token_Semicolon && f->curr_token.kind != Token_CloseBrace) {
		Ast *arg = parse_expr(f, false);
		array_add(&results, arg);
		if (f->curr_token.kind != Token_Comma ||
		    f->curr_token.kind == Token_EOF) {
		    break;
		}
		advance_token(f);
	}

	expect_semicolon(f);
	return ast_return_stmt(f, token, results);
}

gb_internal Ast *parse_for_stmt(AstFile *f) {
	if (f->curr_proc == nullptr) {
		syntax_error(f->curr_token, "You cannot use a for statement in the file scope");
		return ast_bad_stmt(f, f->curr_token, f->curr_token);
	}

	Token token = expect_token(f, Token_for);

	Ast *init = nullptr;
	Ast *cond = nullptr;
	Ast *post = nullptr;
	Ast *body = nullptr;
	bool is_range = false;

	if (f->curr_token.kind != Token_OpenBrace &&
	    f->curr_token.kind != Token_do) {
		isize prev_level = f->expr_level;
		defer (f->expr_level = prev_level);
		f->expr_level = -1;

		if (f->curr_token.kind == Token_in) {
			Token in_token = expect_token(f, Token_in);
			syntax_error(in_token, "Prefer 'for _ in' over 'for in'");

			Ast *rhs = nullptr;
			bool prev_allow_range = f->allow_range;
			f->allow_range = true;
			rhs = parse_expr(f, false);
			f->allow_range = prev_allow_range;

			if (allow_token(f, Token_do)) {
				body = parse_do_body(f, token, "the for statement");
			} else {
				body = parse_block_stmt(f, false);
			}

			return ast_range_stmt(f, token, {}, in_token, rhs, body);
		}

		if (f->curr_token.kind != Token_Semicolon) {
			cond = parse_simple_stmt(f, StmtAllowFlag_In);
			if (cond->kind == Ast_AssignStmt && cond->AssignStmt.op.kind == Token_in) {
				is_range = true;
			}
		}

		if (!is_range && parse_control_statement_semicolon_separator(f)) {
			init = cond;
			cond = nullptr;

			if (f->curr_token.kind == Token_OpenBrace || f->curr_token.kind == Token_do) {
				syntax_error(f->curr_token, "Expected ';', followed by a condition expression and post statement, got %.*s", LIT(token_strings[f->curr_token.kind]));
			} else {
				if (f->curr_token.kind != Token_Semicolon) {
					cond = parse_simple_stmt(f, StmtAllowFlag_None);
				}

				if (f->curr_token.string != ";") {
					syntax_error(f->curr_token, "Expected ';', got %.*s", LIT(token_to_string(f->curr_token)));
				} else {
					expect_token(f, Token_Semicolon);
				}

				if (f->curr_token.kind != Token_OpenBrace &&
				    f->curr_token.kind != Token_do) {
					post = parse_simple_stmt(f, StmtAllowFlag_None);
				}
			}
		}
	}


	if (allow_token(f, Token_do)) {
		body = parse_do_body(f, token, "the for statement");
	} else {
		body = parse_block_stmt(f, false);
	}

	if (is_range) {
		GB_ASSERT(cond->kind == Ast_AssignStmt);
		Token in_token = cond->AssignStmt.op;
		Slice<Ast *> vals = cond->AssignStmt.lhs;
		Ast *rhs = nullptr;
		if (cond->AssignStmt.rhs.count > 0) {
			rhs = cond->AssignStmt.rhs[0];
		}
		return ast_range_stmt(f, token, vals, in_token, rhs, body);
	}

	cond = convert_stmt_to_expr(f, cond, str_lit("boolean expression"));
	if (init != nullptr &&
	    cond == nullptr &&
	    post == nullptr) {
		syntax_error(init, "'for init; ; {' without an explicit condition nor post statement is not allowed, please prefer something like 'for init; true; /**/{'");
	}


	return ast_for_stmt(f, token, init, cond, post, body);
}


gb_internal Ast *parse_case_clause(AstFile *f, bool is_type) {
	Token token = f->curr_token;
	Array<Ast *> list = {};
	expect_token(f, Token_case);
	bool prev_allow_range = f->allow_range;
	bool prev_allow_in_expr = f->allow_in_expr;
	f->allow_range = !is_type;
	f->allow_in_expr = !is_type;
	if (f->curr_token.kind != Token_Colon) {
		list = parse_rhs_expr_list(f);
	}
	f->allow_range = prev_allow_range;
	f->allow_in_expr = prev_allow_in_expr;
	expect_token(f, Token_Colon);
	Array<Ast *> stmts = parse_stmt_list(f);

	return ast_case_clause(f, token, list, stmts);
}


gb_internal Ast *parse_switch_stmt(AstFile *f) {
	if (f->curr_proc == nullptr) {
		syntax_error(f->curr_token, "You cannot use a switch statement in the file scope");
		return ast_bad_stmt(f, f->curr_token, f->curr_token);
	}

	Token token = expect_token(f, Token_switch);
	Ast *init = nullptr;
	Ast *tag  = nullptr;
	Ast *body = nullptr;
	Token open, close;
	bool is_type_switch = false;
	auto list = array_make<Ast *>(ast_allocator(f));

	if (f->curr_token.kind != Token_OpenBrace) {
		isize prev_level = f->expr_level;
		f->expr_level = -1;
		defer (f->expr_level = prev_level);

		if (f->curr_token.kind == Token_in) {
			Token in_token = expect_token(f, Token_in);
			syntax_error(in_token, "Prefer 'switch _ in' over 'switch in'");

			auto lhs = array_make<Ast *>(ast_allocator(f), 0, 1);
			auto rhs = array_make<Ast *>(ast_allocator(f), 0, 1);
			Token blank_ident = token;
			blank_ident.kind = Token_Ident;
			blank_ident.string = str_lit("_");
			Ast *blank = ast_ident(f, blank_ident);
			array_add(&lhs, blank);
			array_add(&rhs, parse_expr(f, true));

			tag = ast_assign_stmt(f, token, lhs, rhs);
			is_type_switch = true;
		} else {
			tag = parse_simple_stmt(f, StmtAllowFlag_In);
			if (tag->kind == Ast_AssignStmt && tag->AssignStmt.op.kind == Token_in) {
				is_type_switch = true;
			} else if (parse_control_statement_semicolon_separator(f)) {
				init = tag;
				tag = nullptr;
				if (f->curr_token.kind != Token_OpenBrace) {
					tag = parse_simple_stmt(f, StmtAllowFlag_None);
				}
			}
		}
	}
	skip_possible_newline(f);
	open = expect_token(f, Token_OpenBrace);

	while (f->curr_token.kind == Token_case) {
		array_add(&list, parse_case_clause(f, is_type_switch));
	}

	close = expect_token(f, Token_CloseBrace);

	body = ast_block_stmt(f, list, open, close);

	if (is_type_switch) {
		return ast_type_switch_stmt(f, token, tag, body);
	}
	tag = convert_stmt_to_expr(f, tag, str_lit("switch expression"));
	return ast_switch_stmt(f, token, init, tag, body);
}

gb_internal Ast *parse_defer_stmt(AstFile *f) {
	if (f->curr_proc == nullptr) {
		syntax_error(f->curr_token, "You cannot use a defer statement in the file scope");
		return ast_bad_stmt(f, f->curr_token, f->curr_token);
	}

	Token token = expect_token(f, Token_defer);
	Ast *stmt = parse_stmt(f);
	switch (stmt->kind) {
	case Ast_EmptyStmt:
		syntax_error(token, "Empty statement after defer (e.g. ';')");
		break;
	case Ast_DeferStmt:
		syntax_error(token, "You cannot defer a defer statement");
		stmt = stmt->DeferStmt.stmt;
		break;
	case Ast_ReturnStmt:
		syntax_error(token, "You cannot defer a return statement");
		break;
	}

	return ast_defer_stmt(f, token, stmt);
}


enum ImportDeclKind {
	ImportDecl_Standard,
	ImportDecl_Using,
};

gb_internal Ast *parse_import_decl(AstFile *f, ImportDeclKind kind) {
	CommentGroup *docs = f->lead_comment;
	Token token = expect_token(f, Token_import);
	Token import_name = {};

	switch (f->curr_token.kind) {
	case Token_Ident:
		import_name = advance_token(f);
		break;
	default:
		import_name.pos = f->curr_token.pos;
		break;
	}

	Token file_path = expect_token_after(f, Token_String, "import");

	Ast *s = nullptr;
	if (f->curr_proc != nullptr) {
		syntax_error(import_name, "Cannot use 'import' within a procedure. This must be done at the file scope");
		s = ast_bad_decl(f, import_name, file_path);
	} else {
		s = ast_import_decl(f, token, file_path, import_name, docs, f->line_comment);
		array_add(&f->imports, s);
	}

	if (f->in_when_statement) {
		syntax_error(import_name, "Cannot use 'import' within a 'when' statement. Prefer using the file suffixes (e.g. foo_windows.odin) or '//+build' tags");
	}

	if (kind != ImportDecl_Standard) {
		syntax_error(import_name, "'using import' is not allowed, please use the import name explicitly");
	}

	expect_semicolon(f);
	return s;
}

gb_internal Ast *parse_foreign_decl(AstFile *f) {
	CommentGroup *docs = f->lead_comment;
	Token token = expect_token(f, Token_foreign);

	switch (f->curr_token.kind) {
	case Token_Ident:
	case Token_OpenBrace:
		return parse_foreign_block(f, token);

	case Token_import: {
		Token import_token = expect_token(f, Token_import);
		Token lib_name = {};
		switch (f->curr_token.kind) {
		case Token_Ident:
			lib_name = advance_token(f);
			break;
		default:
			lib_name.pos = token.pos;
			break;
		}
		if (is_blank_ident(lib_name)) {
			syntax_error(lib_name, "Illegal foreign import name: '_'");
		}
		Array<Token> filepaths = {};
		if (allow_token(f, Token_OpenBrace)) {
			array_init(&filepaths, ast_allocator(f));

			while (f->curr_token.kind != Token_CloseBrace &&
			       f->curr_token.kind != Token_EOF) {

				Token path = expect_token(f, Token_String);
				array_add(&filepaths, path);

				if (!allow_field_separator(f)) {
					break;
				}
			}
			expect_closing_brace_of_field_list(f);
		} else {
			filepaths = array_make<Token>(ast_allocator(f), 0, 1);
			Token path = expect_token(f, Token_String);
			array_add(&filepaths, path);
		}

		Ast *s = nullptr;
		if (filepaths.count == 0) {
			syntax_error(lib_name, "foreign import without any paths");
			s = ast_bad_decl(f, lib_name, f->curr_token);
		} else if (f->curr_proc != nullptr) {
			syntax_error(lib_name, "You cannot use foreign import within a procedure. This must be done at the file scope");
			s = ast_bad_decl(f, lib_name, filepaths[0]);
		} else {
			s = ast_foreign_import_decl(f, token, filepaths, lib_name, docs, f->line_comment);
		}
		expect_semicolon(f);
		return s;
	}
	}

	syntax_error(token, "Invalid foreign declaration");
	return ast_bad_decl(f, token, f->curr_token);
}

gb_internal Ast *parse_attribute(AstFile *f, Token token, TokenKind open_kind, TokenKind close_kind, CommentGroup *docs) {
	Array<Ast *> elems = {};
	Token open = {};
	Token close = {};

	if (f->curr_token.kind == Token_Ident) {
		elems = array_make<Ast *>(ast_allocator(f), 0, 1);
		Ast *elem = parse_ident(f);
		array_add(&elems, elem);
	} else {
		open = expect_token(f, open_kind);
		f->expr_level++;
		if (f->curr_token.kind != close_kind) {
			elems = array_make<Ast *>(ast_allocator(f));
			while (f->curr_token.kind != close_kind &&
			       f->curr_token.kind != Token_EOF) {
				Ast *elem = nullptr;
				elem = parse_ident(f);

				if (f->curr_token.kind == Token_Eq) {
					Token eq = expect_token(f, Token_Eq);
					Ast *value = parse_value(f);
					elem = ast_field_value(f, elem, value, eq);
				}

				array_add(&elems, elem);

				if (!allow_field_separator(f)) {
					break;
				}
			}
		}
		f->expr_level--;
		close = expect_closing(f, close_kind, str_lit("attribute"));
	}
	Ast *attribute = ast_attribute(f, token, open, close, elems);

	skip_possible_newline(f);

	Ast *decl = parse_stmt(f);
	if (decl->kind == Ast_ValueDecl) {
		if (decl->ValueDecl.docs == nullptr && docs != nullptr) {
			decl->ValueDecl.docs = docs;
		}
		array_add(&decl->ValueDecl.attributes, attribute);
	} else if (decl->kind == Ast_ForeignBlockDecl) {
		array_add(&decl->ForeignBlockDecl.attributes, attribute);
	} else if (decl->kind == Ast_ForeignImportDecl) {
		array_add(&decl->ForeignImportDecl.attributes, attribute);
	} else if (decl->kind == Ast_ImportDecl) {
		array_add(&decl->ImportDecl.attributes, attribute);
	} else {
		syntax_error(decl, "Expected a value or foreign declaration after an attribute, got %.*s", LIT(ast_strings[decl->kind]));
		return ast_bad_stmt(f, token, f->curr_token);
	}

	return decl;
}


gb_internal Ast *parse_unrolled_for_loop(AstFile *f, Token unroll_token) {
	Token for_token = expect_token(f, Token_for);
	Ast *val0 = nullptr;
	Ast *val1 = nullptr;
	Token in_token = {};
	Ast *expr = nullptr;
	Ast *body = nullptr;

	bool bad_stmt = false;

	if (f->curr_token.kind != Token_in) {
		Array<Ast *> idents = parse_ident_list(f, false);
		switch (idents.count) {
		case 1:
			val0 = idents[0];
			break;
		case 2:
			val0 = idents[0];
			val1 = idents[1];
			break;
		default:
			syntax_error(for_token, "Expected either 1 or 2 identifiers");
			bad_stmt = true;
			break;
		}
	}
	in_token = expect_token(f, Token_in);

	bool prev_allow_range = f->allow_range;
	isize prev_level = f->expr_level;
	f->allow_range = true;
	f->expr_level = -1;
	expr = parse_expr(f, false);
	f->expr_level = prev_level;
	f->allow_range = prev_allow_range;

	if (allow_token(f, Token_do)) {
		body = parse_do_body(f, for_token, "the for statement");
	} else {
		body = parse_block_stmt(f, false);
	}
	if (bad_stmt) {
		return ast_bad_stmt(f, unroll_token, f->curr_token);
	}
	return ast_unroll_range_stmt(f, unroll_token, for_token, val0, val1, in_token, expr, body);
}

gb_internal Ast *parse_stmt(AstFile *f) {
	Ast *s = nullptr;
	Token token = f->curr_token;
	switch (token.kind) {
	// Operands
	case Token_context: // Also allows for `context =`
	case Token_proc:
	case Token_Ident:
	case Token_Integer:
	case Token_Float:
	case Token_Imag:
	case Token_Rune:
	case Token_String:
	case Token_OpenParen:
	case Token_Pointer:
	case Token_asm: // Inline assembly
	// Unary Operators
	case Token_Add:
	case Token_Sub:
	case Token_Xor:
	case Token_Not:
	case Token_And:
	case Token_Mul: // Used for error handling when people do C-like things
		s = parse_simple_stmt(f, StmtAllowFlag_Label);
		expect_semicolon(f);
		return s;


	case Token_foreign:
		return parse_foreign_decl(f);

	case Token_import:
		return parse_import_decl(f, ImportDecl_Standard);


	case Token_if:     return parse_if_stmt(f);
	case Token_when:   return parse_when_stmt(f);
	case Token_for:    return parse_for_stmt(f);
	case Token_switch: return parse_switch_stmt(f);
	case Token_defer:  return parse_defer_stmt(f);
	case Token_return: return parse_return_stmt(f);

	case Token_break:
	case Token_continue:
	case Token_fallthrough: {
		Token token = advance_token(f);
		Ast *label = nullptr;
		if (token.kind != Token_fallthrough &&
		    f->curr_token.kind == Token_Ident) {
			label = parse_ident(f);
		}
		s = ast_branch_stmt(f, token, label);
		expect_semicolon(f);
		return s;
	}

	case Token_using: {
		CommentGroup *docs = f->lead_comment;
		Token token = expect_token(f, Token_using);
		if (f->curr_token.kind == Token_import) {
			return parse_import_decl(f, ImportDecl_Using);
		}

		Ast *decl = nullptr;
		Array<Ast *> list = parse_lhs_expr_list(f);
		if (list.count == 0) {
			syntax_error(token, "Illegal use of 'using' statement");
			expect_semicolon(f);
			return ast_bad_stmt(f, token, f->curr_token);
		}

		if (f->curr_token.kind != Token_Colon) {
			expect_semicolon(f);
			return ast_using_stmt(f, token, list);
		}
		expect_token_after(f, Token_Colon, "identifier list");
		decl = parse_value_decl(f, list, docs);

		if (decl != nullptr && decl->kind == Ast_ValueDecl) {
			decl->ValueDecl.is_using = true;
			return decl;
		}

		syntax_error(token, "Illegal use of 'using' statement");
		return ast_bad_stmt(f, token, f->curr_token);
	} break;

	case Token_At: {
		CommentGroup *docs = f->lead_comment;
		Token token = expect_token(f, Token_At);
		return parse_attribute(f, token, Token_OpenParen, Token_CloseParen, docs);
	}

	case Token_Hash: {
		Ast *s = nullptr;
		Token hash_token = expect_token(f, Token_Hash);
		Token name = expect_token(f, Token_Ident);
		String tag = name.string;

		if (tag == "bounds_check") {
			s = parse_stmt(f);
			return parse_check_directive_for_statement(s, name, StateFlag_bounds_check);
		} else if (tag == "no_bounds_check") {
			s = parse_stmt(f);
			return parse_check_directive_for_statement(s, name, StateFlag_no_bounds_check);
		} else if (tag == "type_assert") {
			s = parse_stmt(f);
			return parse_check_directive_for_statement(s, name, StateFlag_type_assert);
		} else if (tag == "no_type_assert") {
			s = parse_stmt(f);
			return parse_check_directive_for_statement(s, name, StateFlag_no_type_assert);
		} else if (tag == "partial") {
			s = parse_stmt(f);
			switch (s->kind) {
			case Ast_SwitchStmt:
				s->SwitchStmt.partial = true;
				break;
			case Ast_TypeSwitchStmt:
				s->TypeSwitchStmt.partial = true;
				break;
			case Ast_EmptyStmt:
				return parse_check_directive_for_statement(s, name, 0);
			default:
				syntax_error(token, "#partial can only be applied to a switch statement");
				break;
			}
			return s;
		} else if (tag == "assert" || tag == "panic") {
			Ast *t = ast_basic_directive(f, hash_token, name);
			Ast *stmt = ast_expr_stmt(f, parse_call_expr(f, t));
			expect_semicolon(f);
			return stmt;
		} else if (name.string == "force_inline" ||
		           name.string == "force_no_inline") {
			Ast *expr = parse_force_inlining_operand(f, name);
			Ast *stmt =  ast_expr_stmt(f, expr);
			expect_semicolon(f);
			return stmt;
		} else if (tag == "unroll") {
			return parse_unrolled_for_loop(f, name);
		} else if (tag == "reverse") {
			Ast *for_stmt = parse_for_stmt(f);
			if (for_stmt->kind == Ast_RangeStmt) {
				if (for_stmt->RangeStmt.reverse) {
					syntax_error(token, "#reverse already applied to a 'for in' statement");
				}
				for_stmt->RangeStmt.reverse = true;
			} else {
				syntax_error(token, "#reverse can only be applied to a 'for in' statement");
			}
			return for_stmt;
		} else if (tag == "include") {
			syntax_error(token, "#include is not a valid import declaration kind. Did you mean 'import'?");
			s = ast_bad_stmt(f, token, f->curr_token);
		} else {
			syntax_error(token, "Unknown tag directive used: '%.*s'", LIT(tag));
			s = ast_bad_stmt(f, token, f->curr_token);
		}

		fix_advance_to_next_stmt(f);

		return s;
	} break;

	case Token_OpenBrace:
		return parse_block_stmt(f, false);

	case Token_Semicolon:
		s = ast_empty_stmt(f, token);
		expect_semicolon(f);
		return s;
	}

	// Error correction statements
	switch (token.kind) {
	case Token_else:
		expect_token(f, Token_else);
		syntax_error(token, "'else' unattached to an 'if' statement");
		switch (f->curr_token.kind) {
		case Token_if:
			return parse_if_stmt(f);
		case Token_when:
			return parse_when_stmt(f);
		case Token_OpenBrace:
			return parse_block_stmt(f, true);
		case Token_do: {
			expect_token(f, Token_do);
			Ast *stmt = parse_do_body(f, {}, "the for statement");
			if (build_context.disallow_do) {
				syntax_error(stmt, "'do' has been disallowed");
			}
			return stmt;
		} break;
		default:
			fix_advance_to_next_stmt(f);
			return ast_bad_stmt(f, token, f->curr_token);
		}
	}


	syntax_error(token, "Expected a statement, got '%.*s'", LIT(token_strings[token.kind]));
	fix_advance_to_next_stmt(f);
	return ast_bad_stmt(f, token, f->curr_token);
}

gb_internal Array<Ast *> parse_stmt_list(AstFile *f) {
	auto list = array_make<Ast *>(ast_allocator(f));

	while (f->curr_token.kind != Token_case &&
	       f->curr_token.kind != Token_CloseBrace &&
	       f->curr_token.kind != Token_EOF) {
		Ast *stmt = parse_stmt(f);
		if (stmt && stmt->kind != Ast_EmptyStmt) {
			array_add(&list, stmt);
			if (stmt->kind == Ast_ExprStmt &&
			    stmt->ExprStmt.expr != nullptr &&
			    stmt->ExprStmt.expr->kind == Ast_ProcLit) {
				syntax_error(stmt, "Procedure literal evaluated but not used");
			}
		}
	}

	return list;
}


gb_internal ParseFileError init_ast_file(AstFile *f, String const &fullpath, TokenPos *err_pos) {
	GB_ASSERT(f != nullptr);
	f->fullpath  = string_trim_whitespace(fullpath); // Just in case
	f->filename  = remove_directory_from_path(f->fullpath);
	f->directory = directory_from_path(f->fullpath);
	set_file_path_string(f->id, f->fullpath);
	thread_safe_set_ast_file_from_id(f->id, f);
	if (!string_ends_with(f->fullpath, str_lit(".odin"))) {
		return ParseFile_WrongExtension;
	}
	zero_item(&f->tokenizer);
	f->tokenizer.curr_file_id = f->id;

	TokenizerInitError err = init_tokenizer_from_fullpath(&f->tokenizer, f->fullpath, build_context.copy_file_contents);
	if (err != TokenizerInit_None) {
		switch (err) {
		case TokenizerInit_Empty:
			break;
		case TokenizerInit_NotExists:
			return ParseFile_NotFound;
		case TokenizerInit_Permission:
			return ParseFile_Permission;
		case TokenizerInit_FileTooLarge:
			return ParseFile_FileTooLarge;
		default:
			return ParseFile_InvalidFile;
		}

	}

	isize file_size = f->tokenizer.end - f->tokenizer.start;

	// NOTE(bill): Determine allocation size required for tokens
	isize token_cap = file_size/3ll;
	isize pow2_cap = gb_max(cast(isize)prev_pow2(cast(i64)token_cap)/2, 16);
	token_cap = ((token_cap + pow2_cap-1)/pow2_cap) * pow2_cap;

	isize init_token_cap = gb_max(token_cap, 16);
	array_init(&f->tokens, ast_allocator(f), 0, gb_max(init_token_cap, 16));

	if (err == TokenizerInit_Empty) {
		Token token = {Token_EOF};
		token.pos.file_id = f->id;
		token.pos.line    = 1;
		token.pos.column  = 1;
		array_add(&f->tokens, token);
		return ParseFile_None;
	}

	u64 start = time_stamp_time_now();

	for (;;) {
		Token *token = array_add_and_get(&f->tokens);
		tokenizer_get_token(&f->tokenizer, token);
		if (token->kind == Token_Invalid) {
			err_pos->line   = token->pos.line;
			err_pos->column = token->pos.column;
			return ParseFile_InvalidToken;
		}

		if (token->kind == Token_EOF) {
			break;
		}
	}

	u64 end = time_stamp_time_now();
	f->time_to_tokenize = cast(f64)(end-start)/cast(f64)time_stamp__freq();

	f->prev_token_index = 0;
	f->curr_token_index = 0;
	f->prev_token = f->tokens[f->prev_token_index];
	f->curr_token = f->tokens[f->curr_token_index];

	array_init(&f->comments, ast_allocator(f), 0, 0);
	array_init(&f->imports,  ast_allocator(f), 0, 0);

	f->curr_proc = nullptr;

	return ParseFile_None;
}

gb_internal void destroy_ast_file(AstFile *f) {
	GB_ASSERT(f != nullptr);
	array_free(&f->tokens);
	array_free(&f->comments);
	array_free(&f->imports);
}

gb_internal bool init_parser(Parser *p) {
	GB_ASSERT(p != nullptr);
	string_set_init(&p->imported_files);
	array_init(&p->packages, permanent_allocator());
	return true;
}

gb_internal void destroy_parser(Parser *p) {
	GB_ASSERT(p != nullptr);
	for (AstPackage *pkg : p->packages) {
		for (AstFile *file : pkg->files) {
			destroy_ast_file(file);
		}
		array_free(&pkg->files);
		array_free(&pkg->foreign_files);
	}
	array_free(&p->packages);
	string_set_destroy(&p->imported_files);
}


gb_internal void parser_add_package(Parser *p, AstPackage *pkg) {
	MUTEX_GUARD_BLOCK(&p->packages_mutex) {
		pkg->id = p->packages.count+1;
		array_add(&p->packages, pkg);
	}
}

gb_internal ParseFileError process_imported_file(Parser *p, ImportedFile imported_file);

gb_internal WORKER_TASK_PROC(parser_worker_proc) {
	ParserWorkerData *wd = cast(ParserWorkerData *)data;
	ParseFileError err = process_imported_file(wd->parser, wd->imported_file);
	if (err != ParseFile_None) {
		auto *node = gb_alloc_item(permanent_allocator(), ParseFileErrorNode);
		node->err = err;

		MUTEX_GUARD_BLOCK(&wd->parser->file_error_mutex) {
			if (wd->parser->file_error_tail != nullptr) {
				wd->parser->file_error_tail->next = node;
			}
			wd->parser->file_error_tail = node;
			if (wd->parser->file_error_head == nullptr) {
				wd->parser->file_error_head = node;
			}
		}
	}
	return cast(isize)err;
}


gb_internal void parser_add_file_to_process(Parser *p, AstPackage *pkg, FileInfo fi, TokenPos pos) {
	ImportedFile f = {pkg, fi, pos, p->file_to_process_count++};
	auto wd = gb_alloc_item(permanent_allocator(), ParserWorkerData);
	wd->parser = p;
	wd->imported_file = f;
	thread_pool_add_task(parser_worker_proc, wd);
}

gb_internal WORKER_TASK_PROC(foreign_file_worker_proc) {
	ForeignFileWorkerData *wd = cast(ForeignFileWorkerData *)data;
	ImportedFile *imp = &wd->imported_file;
	AstPackage *pkg = imp->pkg;

	AstForeignFile foreign_file = {wd->foreign_kind};

	String fullpath = string_trim_whitespace(imp->fi.fullpath); // Just in case

	char *c_str = alloc_cstring(temporary_allocator(), fullpath);

	gbFileContents fc = gb_file_read_contents(permanent_allocator(), true, c_str);
	foreign_file.source.text = (u8 *)fc.data;
	foreign_file.source.len = fc.size;

	switch (wd->foreign_kind) {
	case AstForeignFile_S:
		// TODO(bill): Actually do something with it
		break;
	}
	MUTEX_GUARD_BLOCK(&pkg->foreign_files_mutex) {
		array_add(&pkg->foreign_files, foreign_file);
	}
	return 0;
}


gb_internal void parser_add_foreign_file_to_process(Parser *p, AstPackage *pkg, AstForeignFileKind kind, FileInfo fi, TokenPos pos) {
	// TODO(bill): Use a better allocator
	ImportedFile f = {pkg, fi, pos, p->file_to_process_count++};
	auto wd = gb_alloc_item(permanent_allocator(), ForeignFileWorkerData);
	wd->parser = p;
	wd->imported_file = f;
	wd->foreign_kind = kind;
	thread_pool_add_task(foreign_file_worker_proc, wd);
}


// NOTE(bill): Returns true if it's added
gb_internal AstPackage *try_add_import_path(Parser *p, String path, String const &rel_path, TokenPos pos, PackageKind kind = Package_Normal) {
	String const FILE_EXT = str_lit(".odin");

	MUTEX_GUARD_BLOCK(&p->imported_files_mutex) {
		if (string_set_update(&p->imported_files, path)) {
			return nullptr;
		}
	}

	path = copy_string(permanent_allocator(), path);

	AstPackage *pkg = gb_alloc_item(permanent_allocator(), AstPackage);
	pkg->kind = kind;
	pkg->fullpath = path;
	array_init(&pkg->files, permanent_allocator());
	pkg->foreign_files.allocator = permanent_allocator();

	// NOTE(bill): Single file initial package
	if (kind == Package_Init && string_ends_with(path, FILE_EXT)) {
		FileInfo fi = {};
		fi.name = filename_from_path(path);
		fi.fullpath = path;
		fi.size = get_file_size(path);
		fi.is_dir = false;

		array_reserve(&pkg->files, 1);
		pkg->is_single_file = true;
		parser_add_package(p, pkg);
		parser_add_file_to_process(p, pkg, fi, pos);
		return pkg;
	}


	Array<FileInfo> list = {};
	ReadDirectoryError rd_err = read_directory(path, &list);
	defer (array_free(&list));

	if (list.count == 1) {
		GB_ASSERT(path != list[0].fullpath);
	}


	switch (rd_err) {
	case ReadDirectory_InvalidPath:
		syntax_error(pos, "Invalid path: %.*s", LIT(rel_path));
		return nullptr;
	case ReadDirectory_NotExists:
		syntax_error(pos, "Path does not exist: %.*s", LIT(rel_path));
		return nullptr;
	case ReadDirectory_Permission:
		syntax_error(pos, "Unknown error whilst reading path %.*s", LIT(rel_path));
		return nullptr;
	case ReadDirectory_NotDir:
		syntax_error(pos, "Expected a directory for a package, got a file: %.*s", LIT(rel_path));
		return nullptr;
	case ReadDirectory_Empty:
		syntax_error(pos, "Empty directory: %.*s", LIT(rel_path));
		return nullptr;
	case ReadDirectory_Unknown:
		syntax_error(pos, "Unknown error whilst reading path %.*s", LIT(rel_path));
		return nullptr;
	}

	isize files_with_ext = 0;
	isize files_to_reserve = 1; // always reserve 1
	for (FileInfo fi : list) {
		String name = fi.name;
		String ext = path_extension(name);
		if (ext == FILE_EXT) {
			files_with_ext += 1;
		}
		if (ext == FILE_EXT && !is_excluded_target_filename(name)) {
			files_to_reserve += 1;
		}
	}
	if (files_with_ext == 0 || files_to_reserve == 1) {
		if (files_with_ext != 0) {
			syntax_error(pos, "Directory contains no .odin files for the specified platform: %.*s", LIT(rel_path));
		} else {
			syntax_error(pos, "Empty directory that contains no .odin files: %.*s", LIT(rel_path));
		}
		return nullptr;
	}


	array_reserve(&pkg->files, files_to_reserve);
	for (FileInfo fi : list) {
		String name = fi.name;
		String ext = path_extension(name);
		if (ext == FILE_EXT) {
			if (is_excluded_target_filename(name)) {
				continue;
			}
			parser_add_file_to_process(p, pkg, fi, pos);
		} else if (ext == ".S" || ext ==".s") {
			if (is_excluded_target_filename(name)) {
				continue;
			}
			parser_add_foreign_file_to_process(p, pkg, AstForeignFile_S, fi, pos);
		}
	}

	parser_add_package(p, pkg);

	return pkg;
}

gb_global Rune illegal_import_runes[] = {
	'"', '\'', '`',
	'\t', '\r', '\n', '\v', '\f',
	'\\', // NOTE(bill): Disallow windows style filepaths
	'!', '$', '%', '^', '&', '*', '(', ')', '=',
	'[', ']', '{', '}',
	';',
	':', // NOTE(bill): Disallow windows style absolute filepaths
	'#',
	'|', ',',  '<', '>', '?',
};

gb_internal bool is_import_path_valid(String const &path) {
	if (path.len > 0) {
		u8 *start = path.text;
		u8 *end = path.text + path.len;
		u8 *curr = start;
		while (curr < end) {
			isize width = 1;
			Rune r = *curr;
			if (r >= 0x80) {
				width = utf8_decode(curr, end-curr, &r);
				if (r == GB_RUNE_INVALID && width == 1) {
					return false;
				}
				else if (r == GB_RUNE_BOM && curr-start > 0) {
					return false;
				}
			}

			for (isize i = 0; i < gb_count_of(illegal_import_runes); i++) {
				if (r == illegal_import_runes[i]) {
					return false;
				}
			}

			curr += width;
		}

		return true;
	}
	return false;
}

gb_internal bool is_build_flag_path_valid(String const &path) {
	if (path.len > 0) {
		u8 *start = path.text;
		u8 *end = path.text + path.len;
		u8 *curr = start;
		isize index = 0;
		while (curr < end) {
			isize width = 1;
			Rune r = *curr;
			if (r >= 0x80) {
				width = utf8_decode(curr, end-curr, &r);
				if (r == GB_RUNE_INVALID && width == 1) {
					return false;
				}
				else if (r == GB_RUNE_BOM && curr-start > 0) {
					return false;
				}
			}

			for (isize i = 0; i < gb_count_of(illegal_import_runes); i++) {
#if defined(GB_SYSTEM_WINDOWS)
				if (r == '\\') {
					break;
				} else if (r == ':') {
					break;
				}
#endif
				if (r == illegal_import_runes[i]) {
					return false;
				}
			}

			curr += width;
			index += 1;
		}

		return true;
	}
	return false;
}


gb_internal bool is_package_name_reserved(String const &name) {
	if (name == "builtin") {
		return true;
	} else if (name == "intrinsics") {
		return true;
	}
	return false;
}


gb_internal bool determine_path_from_string(BlockingMutex *file_mutex, Ast *node, String base_dir, String const &original_string, String *path) {
	GB_ASSERT(path != nullptr);

	// NOTE(bill): if file_mutex == nullptr, this means that the code is used within the semantics stage

	String collection_name = {};

	isize colon_pos = -1;
	for (isize j = 0; j < original_string.len; j++) {
		if (original_string[j] == ':') {
			colon_pos = j;
			break;
		}
	}

	bool has_windows_drive = false;
#if defined(GB_SYSTEM_WINDOWS)
	if (file_mutex == nullptr) {
		if (colon_pos == 1 && original_string.len > 2) {
			if (original_string[2] == '/' || original_string[2] == '\\') {
				colon_pos = -1;
				has_windows_drive = true;
			}
		}
	}
#endif

	String file_str = {};
	if (colon_pos == 0) {
		syntax_error(node, "Expected a collection name");
		return false;
	}

	if (original_string.len > 0 && colon_pos > 0) {
		collection_name = substring(original_string, 0, colon_pos);
		file_str = substring(original_string, colon_pos+1, original_string.len);
	} else {
		file_str = original_string;
	}


	if (has_windows_drive) {
		String sub_file_path = substring(file_str, 3, file_str.len);
		if (!is_import_path_valid(sub_file_path)) {
			syntax_error(node, "Invalid import path: '%.*s'", LIT(file_str));
			return false;
		}
	} else if (!is_import_path_valid(file_str)) {
		syntax_error(node, "Invalid import path: '%.*s'", LIT(file_str));
		return false;
	}


	if (collection_name.len > 0) {
		// NOTE(bill): `base:runtime` == `core:runtime`
		if (collection_name == "core" && string_starts_with(file_str, str_lit("runtime"))) {
			collection_name = str_lit("base");
		}

		if (collection_name == "system") {
			if (node->kind != Ast_ForeignImportDecl) {
				syntax_error(node, "The library collection 'system' is restrict for 'foreign_library'");
				return false;
			} else {
				*path = file_str;
				return true;
			}
		} else if (!find_library_collection_path(collection_name, &base_dir)) {
			// NOTE(bill): It's a naughty name
			syntax_error(node, "Unknown library collection: '%.*s'", LIT(collection_name));
			return false;
		}
	} else {
#if !defined(GB_SYSTEM_WINDOWS)
		// @NOTE(vassvik): foreign imports of shared libraries that are not in the system collection on
		//                 linux/mac have to be local to the executable for consistency with shared libraries.
		//                 Unix does not have a concept of "import library" for shared/dynamic libraries,
		//                 so we need to pass the relative path to the linker, and add the current
		//                 working directory of the exe to the library search paths.
		//                 Static libraries can be linked directly with the full pathname
		//
		if (node->kind == Ast_ForeignImportDecl && (string_ends_with(file_str, str_lit(".so")) || string_contains_string(file_str, str_lit(".so.")))) {
			*path = file_str;
			return true;
		}
#endif
	}

	if (is_package_name_reserved(file_str)) {
		*path = file_str;
		if (collection_name == "core" || collection_name == "base") {
			return true;
		} else {
			syntax_error(node, "The package '%.*s' must be imported with the 'base' library collection: 'base:%.*s'", LIT(file_str), LIT(file_str));
			return false;
		}
	}

	if (file_mutex) mutex_lock(file_mutex);
	defer (if (file_mutex) mutex_unlock(file_mutex));


	if (node->kind == Ast_ForeignImportDecl) {
		node->ForeignImportDecl.collection_name = collection_name;
	}

	if (has_windows_drive) {
		*path = file_str;
	} else {
		bool ok = false;
		String fullpath = string_trim_whitespace(get_fullpath_relative(permanent_allocator(), base_dir, file_str, &ok));
		*path = fullpath;
	}
	return true;
}



gb_internal void parse_setup_file_decls(Parser *p, AstFile *f, String const &base_dir, Slice<Ast *> &decls);

gb_internal void parse_setup_file_when_stmt(Parser *p, AstFile *f, String const &base_dir, AstWhenStmt *ws) {
	if (ws->body != nullptr) {
		auto stmts = ws->body->BlockStmt.stmts;
		parse_setup_file_decls(p, f, base_dir, stmts);
	}

	if (ws->else_stmt != nullptr) {
		switch (ws->else_stmt->kind) {
		case Ast_BlockStmt: {
			auto stmts = ws->else_stmt->BlockStmt.stmts;
			parse_setup_file_decls(p, f, base_dir, stmts);
		} break;
		case Ast_WhenStmt:
			parse_setup_file_when_stmt(p, f, base_dir, &ws->else_stmt->WhenStmt);
			break;
		}
	}
}

gb_internal void parse_setup_file_decls(Parser *p, AstFile *f, String const &base_dir, Slice<Ast *> &decls) {
	for_array(i, decls) {
		Ast *node = decls[i];
		if (!is_ast_decl(node) &&
		    node->kind != Ast_WhenStmt &&
		    node->kind != Ast_BadStmt &&
		    node->kind != Ast_EmptyStmt) {
			// NOTE(bill): Sanity check

			if (node->kind == Ast_ExprStmt) {
				Ast *expr = node->ExprStmt.expr;
				if (expr->kind == Ast_CallExpr &&
				    expr->CallExpr.proc->kind == Ast_BasicDirective) {
					f->directive_count += 1;
					continue;
				}
			}

			syntax_error(node, "Only declarations are allowed at file scope, got %.*s", LIT(ast_strings[node->kind]));
		} else if (node->kind == Ast_ImportDecl) {
			ast_node(id, ImportDecl, node);

			String original_string = string_trim_whitespace(string_value_from_token(f, id->relpath));
			String import_path = {};
			bool ok = determine_path_from_string(&p->file_decl_mutex, node, base_dir, original_string, &import_path);
			if (!ok) {
				decls[i] = ast_bad_decl(f, id->relpath, id->relpath);
				continue;
			}
			import_path = string_trim_whitespace(import_path);

			id->fullpath = import_path;
			if (is_package_name_reserved(import_path)) {
				continue;
			}
			try_add_import_path(p, import_path, original_string, ast_token(node).pos);
		} else if (node->kind == Ast_ForeignImportDecl) {
			ast_node(fl, ForeignImportDecl, node);

			auto fullpaths = array_make<String>(permanent_allocator(), 0, fl->filepaths.count);

			for (Token const &fp : fl->filepaths) {
				String file_str = string_trim_whitespace(string_value_from_token(f, fp));
				String fullpath = file_str;
				if (allow_check_foreign_filepath()) {
					String foreign_path = {};
					bool ok = determine_path_from_string(&p->file_decl_mutex, node, base_dir, file_str, &foreign_path);
					if (!ok) {
						decls[i] = ast_bad_decl(f, fp, fl->filepaths[fl->filepaths.count-1]);
						goto end;
					}
					fullpath = foreign_path;
				}
				array_add(&fullpaths, fullpath);
			}
			if (fullpaths.count == 0) {
				syntax_error(decls[i], "No foreign paths found");
				decls[i] = ast_bad_decl(f, fl->filepaths[0], fl->filepaths[fl->filepaths.count-1]);
				goto end;
			}

			fl->fullpaths = slice_from_array(fullpaths);


		} else if (node->kind == Ast_WhenStmt) {
			ast_node(ws, WhenStmt, node);
			parse_setup_file_when_stmt(p, f, base_dir, ws);
		}

	end:;
	}
}

gb_internal String build_tag_get_token(String s, String *out) {
	s = string_trim_whitespace(s);
	isize n = 0;
	while (n < s.len) {
		Rune rune = 0;
		isize width = utf8_decode(&s[n], s.len-n, &rune);
		if (n == 0 && rune == '!') {

		} else if (!rune_is_letter(rune) && !rune_is_digit(rune)) {
			isize k = gb_max(gb_max(n, width), 1);
			*out = substring(s, k, s.len);
			return substring(s, 0, k);
		}
		n += width;
	}
	out->len = 0;
	return s;
}

gb_internal bool parse_build_tag(Token token_for_pos, String s) {
	String const prefix = str_lit("+build");
	GB_ASSERT(string_starts_with(s, prefix));
	s = string_trim_whitespace(substring(s, prefix.len, s.len));

	if (s.len == 0) {
		return true;
	}

	bool any_correct = false;

	while (s.len > 0) {
		bool this_kind_correct = true;

		do {
			String p = string_trim_whitespace(build_tag_get_token(s, &s));
			if (p.len == 0) break;
			if (p == ",") break;

			bool is_notted = false;
			if (p[0] == '!') {
				is_notted = true;
				p = substring(p, 1, p.len);
				if (p.len == 0) {
					syntax_error(token_for_pos, "Expected a build platform after '!'");
					break;
				}
			}

			if (p.len == 0) {
				continue;
			}
			if (p == "ignore") {
				this_kind_correct = false;
				continue;
			}

			TargetOsKind   os   = get_target_os_from_string(p);
			TargetArchKind arch = get_target_arch_from_string(p);
			if (os != TargetOs_Invalid) {
				GB_ASSERT(arch == TargetArch_Invalid);
				if (is_notted) {
					this_kind_correct = this_kind_correct && (os != build_context.metrics.os);
				} else {
					this_kind_correct = this_kind_correct && (os == build_context.metrics.os);
				}
			} else if (arch != TargetArch_Invalid) {
				if (is_notted) {
					this_kind_correct = this_kind_correct && (arch != build_context.metrics.arch);
				} else {
					this_kind_correct = this_kind_correct && (arch == build_context.metrics.arch);
				}
			}
			if (os == TargetOs_Invalid && arch == TargetArch_Invalid) {
				syntax_error(token_for_pos, "Invalid build tag platform: %.*s", LIT(p));
				break;
			}
		} while (s.len > 0);

		any_correct = any_correct || this_kind_correct;
	}

	return any_correct;
}

gb_internal String vet_tag_get_token(String s, String *out) {
	s = string_trim_whitespace(s);
	isize n = 0;
	while (n < s.len) {
		Rune rune = 0;
		isize width = utf8_decode(&s[n], s.len-n, &rune);
		if (n == 0 && rune == '!') {

		} else if (!rune_is_letter(rune) && !rune_is_digit(rune) && rune != '-') {
			isize k = gb_max(gb_max(n, width), 1);
			*out = substring(s, k, s.len);
			return substring(s, 0, k);
		}
		n += width;
	}
	out->len = 0;
	return s;
}


gb_internal u64 parse_vet_tag(Token token_for_pos, String s) {
	String const prefix = str_lit("+vet");
	GB_ASSERT(string_starts_with(s, prefix));
	s = string_trim_whitespace(substring(s, prefix.len, s.len));

	if (s.len == 0) {
		return VetFlag_All;
	}


	u64 vet_flags = 0;
	u64 vet_not_flags = 0;

	while (s.len > 0) {
		String p = string_trim_whitespace(vet_tag_get_token(s, &s));
		if (p.len == 0) {
			break;
		}

		bool is_notted = false;
		if (p[0] == '!') {
			is_notted = true;
			p = substring(p, 1, p.len);
			if (p.len == 0) {
				syntax_error(token_for_pos, "Expected a vet flag name after '!'");
				return build_context.vet_flags;
			}
		}

		u64 flag = get_vet_flag_from_name(p);
		if (flag != VetFlag_NONE) {
			if (is_notted) {
				vet_not_flags |= flag;
			} else {
				vet_flags     |= flag;
			}
		} else {
			ERROR_BLOCK();
			syntax_error(token_for_pos, "Invalid vet flag name: %.*s", LIT(p));
			error_line("\tExpected one of the following\n");
			error_line("\tunused\n");
			error_line("\tshadowing\n");
			error_line("\tusing-stmt\n");
			error_line("\tusing-param\n");
			error_line("\textra\n");
			return build_context.vet_flags;
		}
	}

	if (vet_flags == 0 && vet_not_flags == 0) {
		return build_context.vet_flags;
	}
	if (vet_flags == 0 && vet_not_flags != 0) {
		return build_context.vet_flags &~ vet_not_flags;
	}
	if (vet_flags != 0 && vet_not_flags == 0) {
		return vet_flags;
	}
	GB_ASSERT(vet_flags != 0 && vet_not_flags != 0);
	return vet_flags &~ vet_not_flags;
}

gb_internal String dir_from_path(String path) {
	String base_dir = path;
	for (isize i = path.len-1; i >= 0; i--) {
		if (base_dir[i] == '\\' ||
		    base_dir[i] == '/') {
			break;
		}
		base_dir.len--;
	}
	return base_dir;
}

gb_internal isize calc_decl_count(Ast *decl) {
	isize count = 0;
	switch (decl->kind) {
	case Ast_BlockStmt:
		for (Ast *stmt : decl->BlockStmt.stmts) {
			count += calc_decl_count(stmt);
		}
		break;
	case Ast_WhenStmt:
		{
			isize inner_count = calc_decl_count(decl->WhenStmt.body);
			if (decl->WhenStmt.else_stmt) {
				inner_count = gb_max(inner_count, calc_decl_count(decl->WhenStmt.else_stmt));
			}
			count += inner_count;
		}
		break;
	case Ast_ValueDecl:
		count = decl->ValueDecl.names.count;
		break;
	case Ast_ForeignBlockDecl:
		count = calc_decl_count(decl->ForeignBlockDecl.body);
		break;
	case Ast_ImportDecl:
	case Ast_ForeignImportDecl:
		count = 1;
		break;
	}
	return count;
}

gb_internal bool parse_build_project_directory_tag(Token token_for_pos, String s) {
	String const prefix = str_lit("+build-project-name");
	GB_ASSERT(string_starts_with(s, prefix));
	s = string_trim_whitespace(substring(s, prefix.len, s.len));
	if (s.len == 0) {
		return true;
	}

	bool any_correct = false;

	while (s.len > 0) {
		bool this_kind_correct = true;

		do {
			String p = string_trim_whitespace(build_tag_get_token(s, &s));
			if (p.len == 0) break;
			if (p == ",") break;

			bool is_notted = false;
			if (p[0] == '!') {
				is_notted = true;
				p = substring(p, 1, p.len);
				if (p.len == 0) {
					syntax_error(token_for_pos, "Expected a build-project-name after '!'");
					break;
				}
			}

			if (p.len == 0) {
				continue;
			}

			if (is_notted) {
				this_kind_correct = this_kind_correct && (p != build_context.ODIN_BUILD_PROJECT_NAME);
			} else {
				this_kind_correct = this_kind_correct && (p == build_context.ODIN_BUILD_PROJECT_NAME);
			}
		} while (s.len > 0);

		any_correct = any_correct || this_kind_correct;
	}

	return any_correct;
}

gb_internal bool parse_file(Parser *p, AstFile *f) {
	if (f->tokens.count == 0) {
		return true;
	}
	if (f->tokens.count > 0 && f->tokens[0].kind == Token_EOF) {
		return true;
	}

	u64 start = time_stamp_time_now();

	String filepath = f->tokenizer.fullpath;
	String base_dir = dir_from_path(filepath);
	if (f->curr_token.kind == Token_Comment) {
		consume_comment_groups(f, f->prev_token);
	}

	CommentGroup *docs = f->lead_comment;

	if (f->curr_token.kind != Token_package) {
		ERROR_BLOCK();
		syntax_error(f->curr_token, "Expected a package declaration at the beginning of the file");
		// IMPORTANT NOTE(bill): this is technically a race condition with the suggestion, but it's ony a suggession
		// so in practice is should be "fine"
		if (f->pkg && f->pkg->name != "") {
			error_line("\tSuggestion: Add 'package %.*s' to the top of the file\n", LIT(f->pkg->name));
		}
		return false;
	}

	f->package_token = expect_token(f, Token_package);
	if (f->package_token.kind != Token_package) {
		return false;
	}
	if (docs != nullptr) {
		TokenPos end = token_pos_end(docs->list[docs->list.count-1]);
		if (end.line == f->package_token.pos.line || end.line+1 == f->package_token.pos.line) {
			// Okay
		} else {
			docs = nullptr;
		}
	}

	Token package_name = expect_token_after(f, Token_Ident, "package");
	if (package_name.kind == Token_Ident) {
		if (package_name.string == "_") {
			syntax_error(package_name, "Invalid package name '_'");
		} else if (f->pkg->kind != Package_Runtime && package_name.string == "runtime") {
			syntax_error(package_name, "Use of reserved package name '%.*s'", LIT(package_name.string));
		} else if (is_package_name_reserved(package_name.string)) {
			syntax_error(package_name, "Use of reserved package name '%.*s'", LIT(package_name.string));
		}
	}
	f->package_name = package_name.string;

	if (!f->pkg->is_single_file && docs != nullptr && docs->list.count > 0) {
		for (Token const &tok : docs->list) {
			GB_ASSERT(tok.kind == Token_Comment);
			String str = tok.string;
			if (string_starts_with(str, str_lit("//"))) {
				String lc = string_trim_whitespace(substring(str, 2, str.len));
				if (lc.len > 0 && lc[0] == '+') {
					 if (string_starts_with(lc, str_lit("+build-project-name"))) {
						if (!parse_build_project_directory_tag(tok, lc)) {
							return false;
						}
					} else if (string_starts_with(lc, str_lit("+build"))) {
						if (!parse_build_tag(tok, lc)) {
							return false;
						}
					} else if (string_starts_with(lc, str_lit("+vet"))) {
						f->vet_flags = parse_vet_tag(tok, lc);
						f->vet_flags_set = true;
					} else if (string_starts_with(lc, str_lit("+ignore"))) {
						return false;
					} else if (string_starts_with(lc, str_lit("+private"))) {
						f->flags |= AstFile_IsPrivatePkg;
						String command = string_trim_starts_with(lc, str_lit("+private "));
						command = string_trim_whitespace(command);
						if (lc == "+private") {
							f->flags |= AstFile_IsPrivatePkg;
						} else if (command == "package") {
							f->flags |= AstFile_IsPrivatePkg;
						} else if (command == "file") {
							f->flags |= AstFile_IsPrivateFile;
						}
					} else if (lc == "+lazy") {
						if (build_context.ignore_lazy) {
							// Ignore
						} else if (f->flags & AstFile_IsTest) {
							// Ignore
						} else if (f->pkg->kind == Package_Init && build_context.command_kind == Command_doc) {
							// Ignore
						} else {
							f->flags |= AstFile_IsLazy;
						}
					} else if (lc == "+no-instrumentation") {
						f->flags |= AstFile_NoInstrumentation;
					} else {
						warning(tok, "Ignoring unknown tag '%.*s'", LIT(lc));
					}
				}
			}
		}
	}

	Ast *pd = ast_package_decl(f, f->package_token, package_name, docs, f->line_comment);
	expect_semicolon(f);
	f->pkg_decl = pd;

	if (f->error_count == 0) {
		auto decls = array_make<Ast *>(ast_allocator(f));

		while (f->curr_token.kind != Token_EOF) {
			Ast *stmt = parse_stmt(f);
			if (stmt && stmt->kind != Ast_EmptyStmt) {
				array_add(&decls, stmt);
				if (stmt->kind == Ast_ExprStmt &&
				    stmt->ExprStmt.expr != nullptr &&
				    stmt->ExprStmt.expr->kind == Ast_ProcLit) {
					syntax_error(stmt, "Procedure literal evaluated but not used");
				}

				f->total_file_decl_count += calc_decl_count(stmt);
				if (stmt->kind == Ast_WhenStmt || stmt->kind == Ast_ExprStmt || stmt->kind == Ast_ImportDecl) {
					f->delayed_decl_count += 1;
				}
			}
		}

		f->decls = slice_from_array(decls);

		parse_setup_file_decls(p, f, base_dir, f->decls);
	}

	u64 end = time_stamp_time_now();
	f->time_to_parse = cast(f64)(end-start)/cast(f64)time_stamp__freq();

	for (int i = 0; i < AstDelayQueue_COUNT; i++) {
		array_init(f->delayed_decls_queues+i, ast_allocator(f), 0, f->delayed_decl_count);
	}


	return f->error_count == 0;
}


gb_internal ParseFileError process_imported_file(Parser *p, ImportedFile imported_file) {
	AstPackage *pkg = imported_file.pkg;
	FileInfo    fi  = imported_file.fi;
	TokenPos    pos = imported_file.pos;

	AstFile *file = gb_alloc_item(permanent_allocator(), AstFile);
	file->pkg = pkg;
	file->id = cast(i32)(imported_file.index+1);
	TokenPos err_pos = {0};
	ParseFileError err = init_ast_file(file, fi.fullpath, &err_pos);
	err_pos.file_id = file->id;
	file->last_error = err;

	if (err != ParseFile_None) {
		if (err == ParseFile_EmptyFile) {
			if (fi.fullpath == p->init_fullpath) {
				syntax_error(pos, "Initial file is empty - %.*s\n", LIT(p->init_fullpath));
				exit_with_errors();
			}
		} else {
			switch (err) {
			case ParseFile_WrongExtension:
				syntax_error(pos, "Failed to parse file: %.*s; invalid file extension: File must have the extension '.odin'", LIT(fi.name));
				break;
			case ParseFile_InvalidFile:
				syntax_error(pos, "Failed to parse file: %.*s; invalid file or cannot be found", LIT(fi.name));
				break;
			case ParseFile_Permission:
				syntax_error(pos, "Failed to parse file: %.*s; file permissions problem", LIT(fi.name));
				break;
			case ParseFile_NotFound:
				syntax_error(pos, "Failed to parse file: %.*s; file cannot be found ('%.*s')", LIT(fi.name), LIT(fi.fullpath));
				break;
			case ParseFile_InvalidToken:
				syntax_error(err_pos, "Failed to parse file: %.*s; invalid token found in file", LIT(fi.name));
				break;
			case ParseFile_EmptyFile:
				syntax_error(pos, "Failed to parse file: %.*s; file contains no tokens", LIT(fi.name));
				break;
			case ParseFile_FileTooLarge:
				syntax_error(pos, "Failed to parse file: %.*s; file is too large, exceeds maximum file size of 2 GiB", LIT(fi.name));
				break;
			}

			return err;
		}
	}

	{
		String name = file->fullpath;
		name = remove_directory_from_path(name);
		name = remove_extension_from_path(name);

		if (string_starts_with(name, str_lit("_"))) {
			syntax_error(pos, "Files cannot start with '_', got '%.*s'", LIT(file->fullpath));
		}
	}

	if (build_context.command_kind == Command_test) {
		String name = file->fullpath;
		name = remove_extension_from_path(name);

		String test_suffix = str_lit("_test");
		if (string_ends_with(name, test_suffix) && name != test_suffix) {
			file->flags |= AstFile_IsTest;
		}
	}


	if (parse_file(p, file)) {
		MUTEX_GUARD_BLOCK(&pkg->files_mutex) {
			array_add(&pkg->files, file);
		}

		mutex_lock(&pkg->name_mutex);
		if (pkg->name.len == 0) {
			pkg->name = file->package_name;
		} else if (pkg->name != file->package_name) {
			if (file->tokens.count > 0 && file->tokens[0].kind != Token_EOF) {
				Token tok = file->package_token;
				tok.pos.file_id = file->id;
				tok.pos.line = gb_max(tok.pos.line, 1);
				tok.pos.column = gb_max(tok.pos.column, 1);
				syntax_error(tok, "Different package name, expected '%.*s', got '%.*s'", LIT(pkg->name), LIT(file->package_name));
			}
		}
		mutex_unlock(&pkg->name_mutex);

		p->total_line_count.fetch_add(file->tokenizer.line_count);
		p->total_token_count.fetch_add(file->tokens.count);
	}

	return ParseFile_None;
}


gb_internal ParseFileError parse_packages(Parser *p, String init_filename) {
	GB_ASSERT(init_filename.text[init_filename.len] == 0);

	String init_fullpath = path_to_full_path(permanent_allocator(), init_filename);
	if (!path_is_directory(init_fullpath)) {
		String const ext = str_lit(".odin");
		if (!string_ends_with(init_fullpath, ext)) {
			error({}, "Expected either a directory or a .odin file, got '%.*s'\n", LIT(init_filename));
			return ParseFile_WrongExtension;
		}
	} else if (init_fullpath.len != 0) {
		String path = init_fullpath;
		if (path[path.len-1] == '/') {
			path.len -= 1;
		}
		if ((build_context.command_kind & Command__does_build) &&
		    build_context.build_mode == BuildMode_Executable) {
			String short_path = filename_from_path(path);
			char *cpath = alloc_cstring(temporary_allocator(), short_path);
			if (gb_file_exists(cpath)) {
			    	error({}, "Please specify the executable name with -out:<string> as a directory exists with the same name in the current working directory");
			    	return ParseFile_DirectoryAlreadyExists;
			}
		}
	}


	{ // Add these packages serially and then process them parallel
		TokenPos init_pos = {};
		{
			bool ok = false;
			String s = get_fullpath_base_collection(permanent_allocator(), str_lit("runtime"), &ok);
			if (!ok) {
				compiler_error("Unable to find The 'base:runtime' package. Is the ODIN_ROOT set up correctly?");
			}
			try_add_import_path(p, s, s, init_pos, Package_Runtime);
		}

		try_add_import_path(p, init_fullpath, init_fullpath, init_pos, Package_Init);
		p->init_fullpath = init_fullpath;

		if (build_context.command_kind == Command_test) {
			bool ok = false;
			String s = get_fullpath_core_collection(permanent_allocator(), str_lit("testing"), &ok);
			if (!ok) {
				compiler_error("Unable to find The 'core:testing' package. Is the ODIN_ROOT set up correctly?");
			}
			try_add_import_path(p, s, s, init_pos, Package_Normal);
		}
		

		for (String const &path : build_context.extra_packages) {
			String fullpath = path_to_full_path(permanent_allocator(), path); // LEAK?
			if (!path_is_directory(fullpath)) {
				String const ext = str_lit(".odin");
				if (!string_ends_with(fullpath, ext)) {
					error({}, "Expected either a directory or a .odin file, got '%.*s'\n", LIT(fullpath));
					return ParseFile_WrongExtension;
				}
			}
			AstPackage *pkg = try_add_import_path(p, fullpath, fullpath, init_pos, Package_Normal);
			if (pkg) {
				pkg->is_extra = true;
			}
		}
	}
	
	thread_pool_wait();

	for (ParseFileErrorNode *node = p->file_error_head; node != nullptr; node = node->next) {
		if (node->err != ParseFile_None) {
			return node->err;
		}
	}

	for (isize i = p->packages.count-1; i >= 0; i--) {
		AstPackage *pkg = p->packages[i];
		for (isize j = pkg->files.count-1; j >= 0; j--) {
			AstFile *file = pkg->files[j];
			if (file->error_count != 0) {
				if (file->last_error != ParseFile_None) {
					return file->last_error;
				}
				return ParseFile_GeneralError;
			}
		}
	}
	return ParseFile_None;
}