aboutsummaryrefslogtreecommitdiff
path: root/compiler/parser.c
blob: c614e9044a29c0fbe40f58d49f4178b828da1259 (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

/*

  parser.c -- Builds an AST from a token stream.

  Copyright © 2011-2016 Samuel Lidén Borell <samuel@kodafritt.se>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

#include <string.h>

#include "parser.h"
#include "context_private.h"
#include "misc.h"
#include "string.h"


typedef enum {
    RE_TERMINAL, /* no arguments follow because it's a terminal symbol */
    RE_OP,       /* number of arguments depends on the operator type */
    RE_UNARY,    /* a single argument follows (used for unary +/-) */
    RE_ARGLIST,  /* function call or array index access */
    RE_GROUPING, /* grouping, e.g. (x+x)*2 */
    RE_ELEMLIST  /* structs and arrays */
} REContext;

typedef struct {
    const LRLToken *token;
    REContext context;
    size_t num_args;
} RPNEntry;


static LRLASTExpr *parse_expr(LRLCtx *ctx, LRLIdent *scope,
                              const LRLToken **tokens);

static LRLASTType *parse_type(LRLCtx *ctx, LRLIdent *scope,
                              const LRLToken **tokens);
static LRLASTExpr *rpn_to_ast(LRLCtx *ctx, const LRLToken *operator,
                              LRLIdent *scope,
                              const RPNEntry *out_stack, size_t *out_size);
static int is_declaration(LRLCtx *ctx, const LRLToken *tokens,
                          const LRLToken *start);

#define set_def_node(ident, def) do { \
        if ((ident) && !(ident)->def_node) { \
            (ident)->def_node = (def); \
        } \
    } while (0)


static int expected(LRLCtx *ctx, const LRLToken **tokens,
                    LRLTokenType expected_token)
{
    if ((*tokens)->type != expected_token)
    {
        const char *tokstr;
        
        lrl_err_set_token(ctx, *tokens, 0);
        switch ((int)expected_token) {
        case LRL_Sym_LParen:        tokstr = "("; break;
        case LRL_Sym_RParen:        tokstr = ")"; break;
        case LRL_Sym_LSquare:       tokstr = "["; break;
        case LRL_Sym_RSquare:       tokstr = "]"; break;
        case LRL_Sym_LCurly:        tokstr = "{"; break;
        case LRL_Sym_RCurly:        tokstr = "}"; break;
        case LRL_Sym_Semicolon:     tokstr = ";"; break;
        case LRL_Sym_Comma:         tokstr = ","; break;
        case LRL_Sym_NamespaceSep:  tokstr = ":"; break;
        case LRL_Op_Assign:         tokstr = "="; break;
        case LRL_KW_Enum:           tokstr = "enum"; break;
        case LRL_KW_Bits:           tokstr = "bits"; break;
        case LRL_KW_While:          tokstr = "while"; break;
        case LRL_KW_In:             tokstr = "in"; break;
        case LRL_TT_String:         tokstr = "(a string)"; break;
        default: tokstr = NULL;
        }
        if (tokstr) {
            lrl_err_set_char_range(ctx, tokstr, strlen(tokstr), 1);
        }
        lrl_err_finish(ctx, LRL_Err_UnexpectedToken);
        return 0;
    }
    
    (*tokens)++;
    return 1;
}

/* The "skip_" functions are mainly used for error recovery, but also for
   looking ahead during parsing. The token pointer is placed after the final
   closing parenthesis/semicolon. */

/**
 * Skips through a parenthesis. The token pointer should point to the token
 * right after the opening parenthesis. Returns 1 if OK, 0 if an error was
 * displayed.
 */
static int skip_parens(LRLCtx *ctx, const LRLToken **tokens)
{
    const LRLToken *token = *tokens + 1;
    size_t depth = 1;
    
    do {
        const LRLTokenType type = token->type;
        if (!type) {
            lrl_err_set_token(ctx, token, 0);
            lrl_err_set_token(ctx, *tokens, 1);
            lrl_err_finish(ctx, LRL_Err_UnclosedParenthesis);
            *tokens = token;
            return 0;
        }
        
        if (lrl_is_paren(type)) {
            if (lrl_is_start_paren(type)) { depth++; }
            else { depth--; }
        } else if (type == LRL_KW_Typedef) {
            /* Break and continue parsing at top level */
            lrl_err_token(ctx, LRL_Err_UnexpectedTokenInDefOrStmt, token);
            *tokens = token;
            return 0;
        }
        
        token++;
    } while (depth);
    
    *tokens = token;
    return 1;
}

#define skip_statement_skip_paren(ctx, t) skip_statement(ctx, t, 0)

/**
 * Skips all tokens until the next semicolon, end of open parenthesis or
 * something that cannot appear inside a statement (e.g. a code block or
 * a typedef). Tokens in parentheses are also skipped.
 *
 * Returns 0 if we should try to break out to the top level.
 */
static int skip_statement(LRLCtx *ctx, const LRLToken **tokens,
                                 LRLTokenType dont_skip_type)
{
    const LRLToken *token = *tokens;
    int ret = 1;
    
    while (token->type && token->type != LRL_Sym_Semicolon &&
           token->type != LRL_Sym_Comma)
    {
        const LRLTokenType type = token->type;
        
        if (lrl_is_paren(type)) {
            /* Parentheses are handled specially */
            if (!lrl_is_start_paren(type)) {
                if (type != dont_skip_type) {
                    token++;
                }
                break;
            }
            
            skip_parens(ctx, &token);
            
            /* Stop if we reached a code block, and it's not an "else" block */
            if (type == LRL_Sym_LCurly && token->type &&
                                          token->type != LRL_KW_Else) {
                ret = 0;
                break;
            }
        } else if (type == LRL_KW_Typedef) {
            ret = 0;
            break;
        } else {
            token++;
        }
    }
    
    if ((token->type == LRL_Sym_Semicolon || token->type == LRL_Sym_Comma) &&
        token->type != dont_skip_type) {
        token++;
    }
    
    *tokens = token;
    return ret;
}

static int expect_end_of_statement(LRLCtx *ctx, const LRLToken **tokens)
{
    if (expected(ctx, tokens, LRL_Sym_Semicolon)) {
        return 1;
    } else {
        skip_statement_skip_paren(ctx, tokens);
        return 0;
    }
}

static int skip_ident(LRLCtx *ctx, const LRLToken **tokens)
{
    const LRLToken *token = *tokens;
    int ok = 0;
    
    /* "here" is also a valid identifier */
    if (token->type == LRL_KW_Here) {
        token++;
        if (token->type != LRL_Sym_NamespaceSep) {
            ok = 1;
            goto end;
        }
        token++;
    }
    
    /* Process sequence of namespace and identifier tokens: aaa:bbb:ccc ... */
    for (;;) {
        /* First (and odd) tokens must be identifiers */
        if (token->type != LRL_TT_Ident) {
            if (*tokens == token) {
                lrl_err_token(ctx, LRL_Err_ExpectedIdentifier, *tokens);
            } else {
                lrl_err_token(ctx, LRL_Err_ColonWithoutSubident, token-1);
            }
            goto end;
        }
        
        token++;
        
        /* Second (and even) tokens must be separators */
        if (token->type != LRL_Sym_NamespaceSep) break;
        
        token++;
    }
    ok = 1;
    
  end:
    *tokens = token;
    return ok;
}

static int is_valid_ident(LRLCtx *ctx, const LRLToken *tokens)
{
    return skip_ident(ctx, &tokens);
}

#define is_ident(token) ((token)->type == LRL_TT_Ident || \
                         (token)->type == LRL_KW_Here)

/** "do nothing" scope */
static const LRLIdent discarding_scope;

/**
 * Parses an identifier and moves the *tokens pointer forward.
 * newident may optionally point to a pre-allocated identifier to use,
 * otherwise it's allocated.
 */
static LRLIdent *parse_ident(LRLCtx *ctx, LRLIdent *scope,
                             const LRLToken **tokens,
                             LRLIdentOperation op, LRLIdent *newident)
{
    const LRLToken *first = *tokens;

    if (op == LRL_Ident_CreateMember) {
        /* May only contain a plain identifier, without any namespaces */
        if (first->type != LRL_TT_Ident) {
            lrl_err_token(ctx, LRL_Err_ExpectedIdentifier, first);
            return NULL;
        } else if (first[1].type == LRL_Sym_NamespaceSep) {
            lrl_err_token(ctx, LRL_Err_NamespaceNotAllowed, first+1);
            /* most likely the user meant ";". continue */
        }
        ++*tokens;
    } else if (!skip_ident(ctx, tokens)) {
        return NULL;
    }
    
    return scope == &discarding_scope ? scope :
        lrl_ident_get(ctx, scope, first, op, newident);
}

static void defer_ident(LRLCtx *ctx, LRLIdent *scope, LRLIdentRef *identref,
                        const LRLToken **tokens)
{
    const LRLToken *first = *tokens;
    identref->ident = NULL; /* Deferred */
    identref->first_token = first;
    identref->scope = scope;
    identref->next = LRL_IDENTREF_NEW;
    
    if (skip_ident(ctx, tokens) && scope != &discarding_scope) {
        lrl_ident_defer(ctx, identref);
    } else {
        identref->ident = LRL_IDENT_MISSING;
    }
}

static void defer_uses(LRLCtx *ctx, LRLIdent *scope, LRLIdentRef *identref,
                       const LRLToken **tokens)
{
    const LRLToken *first = *tokens;
    identref->ident = NULL; /* Deferred */
    identref->first_token = first;
    identref->scope = scope;
    identref->next = LRL_IDENTREF_NEW;
    
    if (skip_ident(ctx, tokens)) {
        lrl_ident_defer_uses(ctx, identref);
    } else {
        identref->ident = LRL_IDENT_MISSING;
    }
}

/**
 * Returns the scope for the function body that the given scope is inside of.
 */
static LRLIdent *get_function_scope(LRLIdent *scope) {
    while (scope->scope && (scope->scope->flags & LRL_IdFl_FunctionBody) == 0) {
        scope = (LRLIdent*)scope->scope;
    }
    return scope;
}


static LRLASTExpr *make_undef_expr(const LRLToken *token)
{
    LRLASTExpr *expr = malloc(sizeof(LRLASTExpr));
    expr->ast_type = LRL_AST_Value_Undefined;
    expr->from = expr->to = token;
    memset(&expr->typeref, 0, sizeof(LRLTypeRef));
    return expr;
}

static LRLASTType *make_private_type(const LRLToken *from, const LRLToken *to)
{
    LRLASTType *type = malloc(sizeof(LRLASTType));
    type->ast_type = LRL_AST_Type_Private;
    type->from = from;
    type->to = to;
    type->quals = 0;
    type->unique_id = LRL_UNIQUEID_UNSET;
    return type;
}


static LRLTypeQualifiers parse_qualifiers(LRLCtx *ctx, const LRLToken **tokens)
{
    const LRLToken *token = *tokens;
    LRLTypeQualifiers quals = 0;
    
    for (;; token++) {
        LRLTypeQualifiers addquals;
        
        if (!token->type) {
            lrl_err_token(ctx, LRL_Err_ExpectedType, token);
            break;
        }
        
        if (token->type == LRL_KW_Incomplete) {
            lrl_err_token(ctx, LRL_Err_IncompleteKeywordNotOnTypedef, token);
            continue;
        }
        
        if (token->type < LRL_FirstQual || token->type > LRL_LastQual) break;
        
        /* Convert and add to bitmask */
        addquals = 1 << (token->type - LRL_FirstQual);
        if (quals & addquals) {
            lrl_err_token(ctx, LRL_Err_RepeatedKeyword, token);
        }
        quals |= addquals;
    }
    
    *tokens = token;
    return quals;
}

/**
 * If the given scope is the hidden scope of a typedef (used for type params
 * and struct members), this function returns the visible typedef scope
 * (used for enum members).
 */
static LRLIdent *typedef_get_visible_scope(LRLIdent *scope)
{
    if (scope->flags & LRL_IdFl_TypedefAnon) {
        return (LRLIdent*)scope->scope;
    } else if (scope->flags & LRL_IdFl_Statement) {
        /* Do not add enum identifiers directly in statement scopes */
        return lrl_ident_create_priv_scope(scope);
    }
    return scope;
}

static LRLASTType *parse_enum(LRLCtx *ctx, LRLIdent *scope,
                              LRLASTType *base_type, const LRLToken **tokens)
{
    const LRLToken *token = *tokens;
    LRLIdent *defscope;
    LRLASTType *type = NULL;
    LRLASTDefList *list_first = NULL, *list_last = NULL;
    
    if (!expected(ctx, &token, LRL_KW_Enum)) return NULL;
    
    defscope = typedef_get_visible_scope(scope);
    type = malloc(sizeof(LRLASTType));
    type->ast_type = LRL_AST_Type_Enum;
    type->kind.enu.scope = defscope;
    type->from = token-1;
    type->kind.enu.base_type = base_type;
    type->unique_id = 0;
    
    /* Read values */
    if (!expected(ctx, &token, LRL_Sym_LParen)) goto end;
    
    while (token->type && token->type != LRL_Sym_RParen) {
        LRLASTDefList *entry;
        LRLIdent *ident;
        
        /* Read identifier */
        ident = parse_ident(ctx, defscope, &token,
                            LRL_Ident_CreateMember, NULL);
        if (!ident) goto recover;
        if (ident != &discarding_scope) {
            ident->flags |= LRL_IdFl_EnumValue;
        }
        
        /* Add to list */
        linked_append(&entry, &list_first, &list_last);
        entry->def.ast_type = LRL_AST_Def_Data;
        entry->def.kind.data.type = type; /* e.g. type of "false" is "bool" */
        entry->def.kind.data.flags = 0;
        entry->def.kind.data.ident = ident;
        entry->def.kind.data.value = NULL;
        if (ident != &discarding_scope) {
            set_def_node(ident, (LRLASTDefOrStmt*)&entry->def);
        }
        
        /* Read value (if any) */
        if (token->type == LRL_Op_Assign) {
            LRLASTExpr *value;
            token++;
            
            value = parse_expr(ctx, scope, &token);
            if (!value) goto recover;
            entry->def.kind.data.value = value;
        } else {
            /* Auto increment. Computed later */
        }
        
        /* Check for end of enum */
        if (token->type == LRL_Sym_RParen) break; /* (a, b) */
        
        expected(ctx, &token, LRL_Sym_Comma);
        
        continue;
        
      recover:
        if (!skip_statement(ctx, &token, LRL_Sym_RParen)) break;
    }
    
    expected(ctx, &token, LRL_Sym_RParen);
    
  end:
    type->to = token-1;
    type->kind.enu.values = list_first;
    
    *tokens = token;
    return type;
}

/**
 * Parses a struct type. If is_funcparams is set, then the struct is
 * allowed to end with "...*" to indicate a variadic function
 */
static LRLASTType *parse_struct(LRLCtx *ctx, LRLIdent *scope,
                                const LRLToken **tokens,
                                int is_funcparams)
{
    const LRLToken *token = *tokens;
    LRLASTType *type = NULL;
    LRLASTDefList *list_first = NULL, *list_last = NULL;
    
    if (!expected(ctx, &token, LRL_Sym_LParen)) return NULL;
    
    type = malloc(sizeof(LRLASTType));
    type->ast_type = LRL_AST_Type_Struct;
    type->kind.struc.scope = scope;
    type->kind.struc.flags = 0;
    type->from = token-1;
    type->unique_id = LRL_UNIQUEID_UNSET;
    
    while (token->type && token->type != LRL_Sym_RParen) {
        LRLASTDefList *entry;
        LRLASTType *member_type;
        LRLIdent *ident;
        
        if (scope != &discarding_scope) {
            ident = calloc(1, sizeof(LRLIdent));
            ident->scope = scope;
            ident->flags |= LRL_IdFl_StructMember;
        } else {
            ident = (LRLIdent*)&discarding_scope;
        }
        
        /* Read type */
        member_type = parse_type(ctx, ident, &token);
        if (!member_type) goto recover;
        if (member_type->quals & LRL_Qual_Var) {
            lrl_err_type(ctx, LRL_Err_VarInsideType, member_type);
        }
        
        /* Add to list */
        linked_append(&entry, &list_first, &list_last);
        entry->def.ast_type = LRL_AST_Def_Data;
        entry->def.kind.data.ident = NULL;
        entry->def.kind.data.flags = 0;
        entry->def.kind.data.type = member_type;
        entry->def.kind.data.value = NULL;
        
        if (is_ident(token)) {
            /* Read identifier */
            ident = parse_ident(ctx, scope, &token,
                                LRL_Ident_CreateMember, ident);
            if (ident != &discarding_scope) {
                entry->def.kind.data.ident = ident;
                set_def_node(ident, (LRLASTDefOrStmt*)&entry->def);
            }
        }
        
        /* Check for end of struct */
        if (token->type == LRL_Sym_RParen) break; /* (int a, int b) */
        
        expected(ctx, &token, LRL_Sym_Comma);
        
        /* "...*" = C-style varargs */
        if (is_funcparams && token->type == LRL_Sym_CVarArg) {
            type->kind.struc.flags |= LRL_SF_CVarArg;
            token++;
            if (token->type != LRL_Sym_RParen) {
                lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
            }
        }
        
        continue;
        
      recover:
        if (!skip_statement(ctx, &token, LRL_Sym_RParen)) break;
    }
    
    expected(ctx, &token, LRL_Sym_RParen);
    
    type->to = token-1;
    type->kind.struc.members = list_first;
    
    *tokens = token;
    return type;
}

static LRLASTType *parse_bitfield(LRLCtx *ctx, LRLIdent *scope,
                                  LRLASTType *base_type,
                                  const LRLToken **tokens)
{
    const LRLToken *token = *tokens;
    LRLASTType *type = NULL;
    LRLASTDefList *list_first = NULL, *list_last = NULL;
    
    if (!expected(ctx, &token, LRL_KW_Bits)) return NULL;
    if (!expected(ctx, &token, LRL_Sym_LParen)) return NULL;
    
    scope = lrl_ident_create_priv_scope(scope);
    
    type = malloc(sizeof(LRLASTType));
    type->ast_type = LRL_AST_Type_Bitfield;
    type->kind.bitfield.scope = scope;
    type->from = token-1;
    type->kind.bitfield.base_type = base_type;
    type->unique_id = 0;
    
    /* Read values */
    while (token->type && token->type != LRL_Sym_RParen) {
        LRLASTDefList *entry;
        LRLASTExpr *num_bits;
        LRLASTType *member_type;
        LRLIdent *ident;
        
        if (scope != &discarding_scope) {
            ident = calloc(1, sizeof(LRLIdent));
            ident->scope = scope;
        } else {
            ident = (LRLIdent*)&discarding_scope;
        }
        
        /*
            Syntaxes:
            
                x,            => 1 bits boolean x,
                2 bits x,     => 2 bits base_type x,
                2 bits int x, => 2 bits int x,
        
        */
        if (token->type == LRL_TT_Ident && (token[1].type == LRL_Sym_Comma || token[1].type == LRL_Sym_RParen)) {
            /* x, --> Bits = 1, Type = bool (defaults) */
            num_bits = NULL;
            member_type = NULL;
        } else {
            /* X bits [type] y,  --> Bits = X, Type = type or NULL */
            num_bits = parse_expr(ctx, ident, &token);
            if (!num_bits) goto recover;
            
            if (!expected(ctx, &token, LRL_KW_Bits)) goto recover;
            
            member_type = (is_declaration(ctx, token, token) > 0 ?
                parse_type(ctx, ident, &token) : NULL);
            if (member_type && member_type->quals & LRL_Qual_Var) {
                lrl_err_type(ctx, LRL_Err_VarInsideType, member_type);
            }
        }
        
        ident = parse_ident(ctx, scope, &token, LRL_Ident_CreateMember, ident);
        
        /* Add to list */
        linked_append(&entry, &list_first, &list_last);
        entry->def.ast_type = LRL_AST_Def_Data;
        entry->def.kind.data.ident = ident;
        entry->def.kind.data.flags = 0;
        entry->def.kind.data.type = member_type;
        entry->def.kind.data.value = num_bits;
        
        if (ident != &discarding_scope) {
            entry->def.kind.data.ident = ident;
            set_def_node(ident, (LRLASTDefOrStmt*)&entry->def);
        }
        
        /* Check for end */
        if (token->type == LRL_Sym_RParen) break;
        
        expected(ctx, &token, LRL_Sym_Comma);
        
        continue;
        
      recover:
        if (!skip_statement(ctx, &token, LRL_Sym_RParen)) break;
    }
    
    expected(ctx, &token, LRL_Sym_RParen);
    
    type->to = token-1;
    type->kind.bitfield.members = list_first;
    
    *tokens = token;
    return type;
}

/**
 * Parses the #[] part of an array type. The array element type should
 * be passed in the elemtype parameter.
 */
static LRLASTType *parse_array_type(LRLCtx *ctx, LRLIdent *scope,
                                    const LRLToken **tokens,
                                    LRLASTType *elemtype)
{
    const LRLToken *token = *tokens;
    LRLASTType *root = NULL; /* leftmost dimension (row) */
    LRLASTType *leaf = NULL; /* rightmost dimension (column) */
    
    if (!expected(ctx, &token, LRL_Sym_LSquare)) return NULL;
    
    for (;;) {
        LRLASTType *array;
        LRLASTExpr *length = NULL;
        const LRLToken *first_token = token;
        
        if (!token->type || token->type == LRL_Sym_Semicolon) {
            lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
            break;
        } else if (token->type == LRL_Sym_RSquare || token->type == LRL_Sym_Comma) {
            /* No array length specified, like [] or [,]
               (should be [undefined] or [undefined,undefined]) */
            lrl_err_token(ctx, LRL_Err_EmptyArrayLength, token);
            length = make_undef_expr(token);
        } else {
            /* Read array length */
            length = parse_expr(ctx, scope, &token);
        }
        
        /* Add array dimension (in reverse order) */
        array = malloc(sizeof(LRLASTType));
        array->ast_type = LRL_AST_Type_Array;
        array->from = first_token-2; /* including surrounding #[ , and ] */
        array->to = token;
        array->quals = elemtype->quals;
        array->unique_id = 0;
        array->kind.array.type = elemtype;
        array->kind.array.length = length;
        if (leaf) leaf->kind.array.type = array;
        
        leaf = array;
        if (!root) root = array;
        
        /* Check for end */
        if (token->type == LRL_Sym_RSquare) break;
        
        if (!expected(ctx, &token, LRL_Sym_Comma)) break;
    }
    
    expected(ctx, &token, LRL_Sym_RSquare);
    
    *tokens = token;
    return root;
}

static LRLASTTypeList *parse_type_params(LRLCtx *ctx, LRLIdent *scope,
                                         const LRLToken **tokens)
{
    const LRLToken *token = *tokens;
    LRLASTTypeList *list_first = NULL, *list_last = NULL;
    
    if (!expected(ctx, &token, LRL_Sym_LSquare)) return NULL;
    
    if (token->type == LRL_Sym_RSquare) {
        lrl_err_token(ctx, LRL_Err_EmptyTypeParamList, token);
    }
    
    while (token->type && token->type != LRL_Sym_RSquare) {
        LRLASTTypeList *entry;
        
        /* Read type */
        LRLASTType *parameter = parse_type(ctx, scope, &token);
        if (!parameter) goto recover;
        /* TODO only type parameters that are used inside pointers etc.
                 may have a "var" qualifier. Otherwise it isn't meaningful
                 (and could likely be used to circumvent var/const checks) */
        
        /* Add to list */
        linked_append(&entry, &list_first, &list_last);
        entry->type = parameter;
        
        /* Check for end of type params */
        if (token->type == LRL_Sym_RSquare) break; /* [a] as opposed to [a,] */
        
        expected(ctx, &token, LRL_Sym_Comma);
        
        continue;
        
      recover:
        if (!skip_statement(ctx, &token, LRL_Sym_RSquare)) break;
    }
    
    expected(ctx, &token, LRL_Sym_RSquare);
    
    *tokens = token;
    return list_first;
}


static LRLASTDefList *parse_type_names(LRLCtx *ctx, LRLIdent *scope,
                                       const LRLToken **tokens)
{
    const LRLToken *token = *tokens;
    LRLASTDefList *list_first = NULL, *list_last = NULL;
    
    if (!expected(ctx, &token, LRL_Sym_LSquare)) return NULL;
    
    if (token->type == LRL_Sym_RSquare) {
        lrl_err_token(ctx, LRL_Err_EmptyTypeParamList, token);
    }
    
    while (token->type && token->type != LRL_Sym_RSquare) {
        LRLASTDefList *entry;
        LRLASTType *type = NULL;
        const LRLToken *first_token = token;
        
        /* TODO covariance/contravariance? */
        
        /* Read type identifier */
        /* TODO can reuse typedef parsing */
        LRLIdent *ident = parse_ident(ctx, scope, &token,
                                      LRL_Ident_CreateMember, NULL);
        if (!ident) goto recover;
        ident->flags |= LRL_IdFl_TypedefParam;
        
        if (token->type == LRL_Op_Assign) {
            token++;
            
            type = parse_type(ctx, ident, &token);
            /* TODO should have a type qualifier check */
        }
        
        if (!type) {
            type = make_private_type(first_token, token-1);
        }
        type->quals |= LRL_InternQual_TypeParam;
        
        /* Add to list */
        linked_append(&entry, &list_first, &list_last);
        entry->def.ast_type = LRL_AST_Def_Type;
        entry->def.kind.type.ident = ident;
        entry->def.kind.type.flags = 0;
        entry->def.kind.type.typenames = NULL;
        entry->def.kind.type.type = type;
        if (ident != &discarding_scope) {
            set_def_node(ident, (LRLASTDefOrStmt*)&entry->def);
        }
        
        /* Check for end of typename list */
        if (token->type == LRL_Sym_RSquare) break; /* [a] as opposed to [a,] */
        
        expected(ctx, &token, LRL_Sym_Comma);
        
        continue;
        
      recover:
        if (!skip_statement(ctx, &token, LRL_Sym_RSquare)) break;
    }
    
    expected(ctx, &token, LRL_Sym_RSquare);
    
    *tokens = token;
    return list_first;
}


static LRLASTType *parse_type(LRLCtx *ctx, LRLIdent *scope,
                              const LRLToken **tokens)
{
    const LRLToken *token = *tokens;
    LRLASTType *type = NULL;
    const LRLToken *outer_first_token = token;
    LRLTypeQualifiers quals;
    LRLPointerFlags pointerflags;
    int noreturn_kw;
    
    /* Read type qualifiers */
    quals = parse_qualifiers(ctx, &token);
    if (!token->type) goto reported_error;
    
    if (token->type == LRL_Sym_LParen) {
        /* Struct type */
        LRLIdent *memberscope = (scope != &discarding_scope ?
            lrl_ident_create_priv_scope(scope) :
            (LRLIdent*)&discarding_scope);
        type = parse_struct(ctx, memberscope, &token, 0);
    } else if (token->type == LRL_KW_Union) {
        /* Union type */
        LRLIdent *memberscope = (scope != &discarding_scope ?
            lrl_ident_create_priv_scope(scope) :
            (LRLIdent*)&discarding_scope);
        token++; /* skip keyword */
        type = parse_struct(ctx, memberscope, &token, 0);
        if (!type) goto reported_error; /* missing "(" */
        type->ast_type = LRL_AST_Type_Union;
    } else if (token->type == LRL_KW_Enum) {
        /* Enum with default base type (i.e. count) */
        type = parse_enum(ctx, scope, lrl_builtin_get_type(LRL_BT_count),
                          &token);
        if (!type) goto reported_error;
    } else if (token->type == LRL_KW_Bits) {
        /* Bitfield type without type (=unaligned bitfield) */
        type = parse_bitfield(ctx, scope, NULL, &token);
        if (!type) goto reported_error;
    } else if (is_ident(token)) {
        /* Reference to a type */
        type = malloc(sizeof(LRLASTType));
        type->ast_type = LRL_AST_Type_Ident;
        defer_ident(ctx, scope, &type->kind.identref, &token);
    } else if (token->type == LRL_KW_Private) {
        /* Private type (= nothing is known about it) */
        type = malloc(sizeof(LRLASTType));
        type->ast_type = LRL_AST_Type_Private;
        token++;
    } else if (token->type == LRL_KW_Any) {
        /* Wildcard type */
        type = malloc(sizeof(LRLASTType));
        type->ast_type = LRL_AST_Type_Any;
        token++;
    } else if (token->type == LRL_KW_NoReturn) {
        /* noreturn function */
        if (token[1].type != LRL_Sym_LParen) {
            token++;
            lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
            goto reported_error;
        }
        type = malloc(sizeof(LRLASTType));
        type->ast_type = LRL_AST_Type_Struct;
        type->from = outer_first_token;
        type->to = token;
        type->quals = 0;
        type->unique_id = 0;
        type->kind.struc.members = NULL;
        type->kind.struc.scope = NULL;
        type->kind.struc.flags = 0;
        if (quals != 0) {
            lrl_err_token(ctx, LRL_Err_QualifierOnNoReturn, token);
        }
        noreturn_kw = 1;
        token++;
        goto function_type;
    } else {
        /* Invalid type */
        lrl_err_token(ctx, LRL_Err_ExpectedType, token);
        goto reported_error;
    }
    
    type->from = outer_first_token;
    type->to = token-1;
    type->quals = quals;
    type->unique_id = 0;
    
    /* Check pointers, arrays, optional modifiers... */
    for (;;) {
        const LRLToken *first_token = token;
        if (!token->type) goto end;
        
        /* Pointers can have type qualifiers before them */
        quals = parse_qualifiers(ctx, &token);
        if (!token->type) goto reported_error;
        
        switch ((int)token->type) {
            case LRL_Op_Deref:
                pointerflags = 0;
                goto has_ptrflags;
            case LRL_Sym_FlexiPointer:
                pointerflags = LRL_PF_Flexible;
                goto has_ptrflags;
            case LRL_Sym_RawPointer:
                pointerflags = LRL_PF_Raw;
                goto has_ptrflags;
            case LRL_Sym_RawFlexiPointer:
                pointerflags = LRL_PF_Flexible | LRL_PF_Raw;
                goto has_ptrflags;
                
              has_ptrflags:
                /* Pointer type */
                if (type->quals & LRL_Qual_Const) {
                    lrl_err_token(ctx, LRL_Err_ConstOnPointer, token);
                }
                {
                    LRLASTType *ptrtype = malloc(sizeof(LRLASTType));
                    ptrtype->ast_type = LRL_AST_Type_Pointer;
                    ptrtype->from = first_token;
                    ptrtype->to = token;
                    ptrtype->unique_id = 0;
                    ptrtype->kind.pointer.type = type;
                    ptrtype->kind.pointer.flags = pointerflags;
                    type = ptrtype;
                    
                    token++;
                    break;
                }
            case LRL_Op_OptionalValue:
                /* Optional value */
                {
                    LRLASTType *optional = malloc(sizeof(LRLASTType));
                    optional->ast_type = LRL_AST_Type_Optional;
                    optional->from = first_token;
                    optional->to = token;
                    optional->unique_id = 0;
                    optional->kind.pointer.type = type;
                    
                    /* Qualifiers are inherited from the element type */
                    if (quals != 0) {
                        lrl_err_token(ctx, LRL_Err_QualifierOnOptional, token);
                    }
                    quals = type->quals;
                    
                    type = optional;
                    
                    token++;
                    break;
                }
            case LRL_Sym_ArrayIndex:
                /* Array type */
                {
                    LRLASTType *array;
                    
                    /* Qualifiers are inherited from the element type */
                    if (quals != 0) {
                        lrl_err_token(ctx, LRL_Err_QualifierOnArray, token);
                    }
                    quals = type->quals;
                    
                    token++;
                    
                    array = parse_array_type(ctx, scope, &token, type);
                    if (!array) goto reported_error;
                    type = array;
                    break;
                }
            case LRL_Sym_LSquare:
                /* Type parameter */
                {
                    LRLASTType *parametric;
                    
                    /* The preceding type must be an identifier */
                    if (type->ast_type != LRL_AST_Type_Ident) {
                        lrl_err_token(ctx, LRL_Err_TypeParameterNotOnIdent, token);
                        goto reported_error;
                    }
                    
                    /* Qualifiers are inherited from the unparametrized type */
                    if (quals != 0) {
                        lrl_err_token(ctx, LRL_Err_QualifierOnTypeParamList, token);
                    }
                    quals = type->quals;
                    
                    parametric = malloc(sizeof(LRLASTType));
                    parametric->ast_type = LRL_AST_Type_Parametric;
                    parametric->from = first_token;
                    parametric->unique_id = 0;
                    parametric->kind.parametric.type = type;
                    parametric->kind.parametric.params = parse_type_params(
                        ctx, scope, &token);
                    parametric->to = token-1;
                    type = parametric;
                    break;
                }
            case LRL_Sym_LParen:
                /* Function type */
                noreturn_kw = 0;
              function_type:
                {
                    LRLASTType *functype;
                    LRLIdent *argscope = (scope != &discarding_scope ?
                            lrl_ident_create_priv_scope(scope) :
                            (LRLIdent*)&discarding_scope);
                    
                    /* Qualifiers are not allowed on the input parameter or
                       return parameter lists. */
                    if (quals != 0 || type->quals != 0) {
                        lrl_err_token(ctx, LRL_Err_QualifierOnFunction, token);
                        quals = 0;
                        type->quals = 0;
                    }
                    
                    functype = malloc(sizeof(LRLASTType));
                    functype->ast_type = LRL_AST_Type_Function;
                    functype->from = outer_first_token;
                    functype->unique_id = 0;
                    functype->kind.function.flags = noreturn_kw ?
                        LRL_FF_NoReturn : 0;
                    functype->kind.function.ret = type;
                    functype->kind.function.args = parse_struct(
                        ctx, argscope, &token, 1);
                    functype->kind.function.args->quals =
                        LRL_InternQual_NotApplicable;
                    functype->to = token-1;
                    type = functype;
                    break;
                }
            case LRL_KW_Enum:
                /* Enumeration type */
                if (quals != 0) {
                    lrl_err_token(ctx, LRL_Err_QualifierOnEnumList, token);
                }
                quals = type->quals;
                
                type = parse_enum(ctx, scope, type, &token);
                break;
            case LRL_KW_Bits:
                /* Bitfield type */
                if (quals != 0) {
                    lrl_err_token(ctx, LRL_Err_QualifierOnBitsList, token);
                }
                quals = type->quals;
                
                type = parse_bitfield(ctx, scope, type, &token);
                break;
            default:
                /* Reached the end */
                if (quals != 0) {
                    lrl_err_token(ctx, LRL_Err_NoTypeAfterQualifier, token);
                }
                goto end;
        }
        
        if (!type) goto reported_error;
        type->quals = quals;
    }
    
  reported_error:
    /* Free the type and return NULL */
    /* TODO */
    type = NULL;
    
  end:
    if (type) {
        type->to = token-1;
    }
    
    *tokens = token;
    return type;
}

static int skip_type(LRLCtx *ctx, const LRLToken **tokens)
{
    return parse_type(ctx, (LRLIdent*)&discarding_scope, tokens) != NULL;
}


typedef struct {
    unsigned char precedence;
    unsigned char right_assoc;
    enum { Binary, Ternary, Postfix, Prefix } type;
} OpInfo;
#define LRL_CALL_AND_ARRIND_PRECEDENCE 17

static OpInfo get_opinfo(LRLTokenType type, REContext context)
{
/*
    operator precedence:
    
    highest  . -> ^ ? []
             () #[]
             @ enumbase makeopt sizeof etc.
             + - compl (unary)
             * / mod
             + - (binary)
             << >>
             bitand
             bitxor
             bitor
             as makeopt
             == != < <= > >=
             not
             and
             or xor
             then-else
             += -= /= *= <<= >>=
    lowest   =
 */
    OpInfo info;
    switch (type) {
        /* function calls, type parameters and array indices
           are handled in rpn_to_ast() */
        case LRL_Op_Member:
        case LRL_Op_FunctionMember:
            info.precedence = 18;
            info.right_assoc = 0;
            info.type = Binary;
            break;
        case LRL_Op_Deref:
        case LRL_Op_OptionalValue:
            info.precedence = 18;
            info.right_assoc = 0;
            info.type = Postfix;
            break;
        /* #[] (LRL_Sym_ArrayIndex) is 17 */
        case LRL_Op_AddrOf:
        case LRL_Op_EnumBase:
        case LRL_Op_SizeOf:
        case LRL_Op_MinSizeOf:
        case LRL_Op_OffsetOf:
        case LRL_Op_AlignOf:
            /* TODO add a "type x" operator so these operations can
               be used on types and not only on expressions */
            info.precedence = 16;
            info.right_assoc = 1;
            info.type = Prefix;
            break;
        case LRL_Op_Compl:
            info.precedence = 15;
            info.right_assoc = 1;
            info.type = Prefix;
            break;
        case LRL_Op_Times:
        case LRL_Op_Divide:
        case LRL_Op_Modulo:
            info.precedence = 14;
            info.right_assoc = 0;
            info.type = Binary;
            break;
        case LRL_Op_Plus:
        case LRL_Op_Minus:
            if (context == RE_UNARY) {
                info.precedence = 15;
                info.right_assoc = 1;
                info.type = Prefix;
            } else {
                info.precedence = 13;
                info.right_assoc = 0;
                info.type = Binary;
            }
            break;
        case LRL_Op_ShiftL:
        case LRL_Op_ShiftR:
            info.precedence = 12;
            info.right_assoc = 0;
            info.type = Binary;
            break;
        case LRL_Op_BitAnd:
            info.precedence = 11;
            info.right_assoc = 0;
            info.type = Binary;
            break;
        case LRL_Op_BitXor:
            info.precedence = 10;
            info.right_assoc = 0;
            info.type = Binary;
            break;
        case LRL_Op_BitOr:
            info.precedence = 9;
            info.right_assoc = 0;
            info.type = Binary;
            break;
        case LRL_Op_MakeOpt:
            info.precedence = 8;
            info.right_assoc = 1;
            info.type = Prefix;
            break;
        case LRL_KW_As:
        case LRL_KW_TypeAssert:
            info.precedence = 7;
            info.right_assoc = 0;
            info.type = Postfix;
            break;
        case LRL_Op_Equal:
        case LRL_Op_NotEqual:
        case LRL_Op_Less:
        case LRL_Op_LessEqual:
        case LRL_Op_Greater:
        case LRL_Op_GreaterEqual:
            info.precedence = 6;
            info.right_assoc = 0;
            info.type = Binary;
            break;
        case LRL_Op_LNot:
            info.precedence = 5;
            info.right_assoc = 0;
            info.type = Prefix;
            break;
        case LRL_Op_LAnd:
            info.precedence = 4;
            info.right_assoc = 0;
            info.type = Binary;
            break;
        case LRL_Op_LOr:
        case LRL_Op_LXor:
            info.precedence = 3;
            info.right_assoc = 0;
            info.type = Binary;
            break;
        case LRL_Op_Then:
        case LRL_KW_Else:
            info.precedence = 2;
            info.right_assoc = 1;
            info.type = Ternary;
            break;
        case LRL_Op_Assign:
        case LRL_Op_PlusAssign:
        case LRL_Op_MinusAssign:
        case LRL_Op_TimesAssign:
        case LRL_Op_DivideAssign:
        case LRL_Op_ShiftLAssign:
        case LRL_Op_ShiftRAssign:
            info.precedence = 1;
            info.right_assoc = 1;
            info.type = Binary;
            break;
        case LRL_Sym_ArrayIndex:
        LRL_case_except_tt_ops default:
            /* Not parsed using the Shunting-yard algorithm */
            info.precedence = 0;
            info.right_assoc = 0;
            info.type = Binary;
    }
    return info;
}

/**
 * Like rpn_to_ast() but handles .member operands.
 */
static const LRLToken *rpn_member_to_ast(LRLCtx *ctx,
                                         const RPNEntry *out_stack,
                                         size_t *out_size)
{
    const RPNEntry *entry;
    const LRLToken *token;
    
    if (*out_size == 0) return NULL;
    
    /* Pop last token */
    entry = &out_stack[--*out_size];
    token = entry->token;
    
    if (token->type != LRL_TT_Ident) {
        lrl_err_token(ctx, LRL_Err_MemberIsNotAnIdent, token);
        return NULL;
    }
    
    return token;
}

/**
 * Reads argument and element lists from an RPN stack.
 *
 * entry is the start bracket, with the argument count.
 */
static void rpn_read_exprlist(LRLCtx *ctx, LRLIdent *scope,
                              const RPNEntry *entry,
                              const RPNEntry *out_stack, size_t *out_size,
                              LRLASTExprList *list)
{
    size_t argcount = entry->num_args, i;
    list->num_args = argcount;
    list->values = malloc(argcount*sizeof(LRLASTExpr*));
    
    for (i = argcount; i > 0; i--) {
        list->values[i-1] = rpn_to_ast(ctx, NULL, scope, out_stack, out_size);
    }
}

/**
 * Sets the from/to tokens on an expr
 */
static void set_expr_range(LRLASTExpr *expr, const LRLASTExpr *fromexpr,
                           const LRLASTExpr *toexpr)
{
    if (fromexpr && fromexpr->from < expr->from) expr->from = fromexpr->from;
    if (toexpr && toexpr->to > expr->to) expr->to = toexpr->to;
}

/**
 * Converts a stack of tokens in Reverse Polish Notation to an AST substree
 */
static LRLASTExpr *rpn_to_ast(LRLCtx *ctx, const LRLToken *operator,
                              LRLIdent *scope,
                              const RPNEntry *out_stack, size_t *out_size)
{
    LRLASTExpr *expr;
    const RPNEntry *entry;
    const LRLToken *token;
    LRLTokenType toktype;
    OpInfo op;
    
    if (*out_size == 0) {
        if (operator) {
            lrl_err_token(ctx, LRL_Err_MissingOperand, operator);
        }
        return NULL;
    }
    
    /* Pop last token */
    entry = &out_stack[--*out_size];
    token = entry->token;
    toktype = token->type;
    op = get_opinfo(toktype, entry->context);
    
    expr = malloc(sizeof(LRLASTExpr));
    /* from/to are used when displaying the expr, e.g. in error messages */
    expr->from = token;
    expr->to = token;
    memset(&expr->typeref, 0, sizeof(LRLTypeRef));
    
    if (!op.precedence) {
        /* Values */
        switch ((int)toktype) {
            case LRL_TT_Ident:
            case LRL_KW_Here:
                expr->ast_type = LRL_AST_Value_Ident;
                
                /* Parse identifier */
                defer_ident(ctx, scope, &expr->kind.ident.identref, &token);
                
                /* Parse type parameters */
                expr->kind.ident.type_params =
                    (token->type == LRL_Sym_LSquare ?
                        parse_type_params(ctx, scope, &token) : NULL);
                
                expr->to = token-1;
                break;
            case LRL_Sym_NamespaceSep:
                expr->ast_type = LRL_AST_Value_TypeIdent;
                expr->kind.typeident.identref.ident = NULL; /* looked up later */
                expr->kind.typeident.identref.first_token = token+1;
                expr->kind.typeident.identref.scope = NULL; /* of type. assigned later */
                expr->kind.typeident.identref.next = LRL_IDENTREF_NEW;
                
                token++;
                if (!skip_ident(ctx, &token)) {
                    expr->kind.typeident.identref.ident = LRL_IDENT_MISSING;
                }
                
                /* Parse type parameters */
                expr->kind.typeident.type_params =
                    (token->type == LRL_Sym_LSquare ?
                        parse_type_params(ctx, scope, &token) : NULL);
                
                expr->to = token-1;
                break;
            case LRL_TT_Undefined:
                expr->ast_type = LRL_AST_Value_Undefined;
                break;
            case LRL_TT_None:
                expr->ast_type = LRL_AST_Value_None;
                break;
            case LRL_TT_NaN:
                expr->ast_type = LRL_AST_Value_NaN;
                break;
            case LRL_TT_Inf:
                expr->ast_type = LRL_AST_Value_Inf;
                break;
            case LRL_TT_Integer:
            case LRL_TT_Real:
            case LRL_TT_String:
                expr->ast_type = LRL_AST_Value_Scalar;
                expr->kind.scalar.token = token;
                expr->kind.scalar.is_negative = 0; /* it's set from unary op */
                break;
            case LRL_Sym_LSquare:
            case LRL_Sym_LParen: {
                /* Function call, array index, array value or struct value */
                LRLASTExpr **values;
                size_t numargs;
                
                /* Read arguments */
                rpn_read_exprlist(ctx, scope, entry, out_stack, out_size,
                                  &expr->kind.call.args);
                values = expr->kind.call.args.values;
                numargs = expr->kind.call.args.num_args;
                
                /* Include function or array also */
                if (entry->context == RE_ARGLIST) expr->from--;
                if (numargs && values[numargs-1] && values[numargs-1]->to) {
                    /* Include elements up to the end parenthesis */
                    expr->to = values[numargs-1]->to+1;
                    if (expr->to->type == LRL_Sym_Comma) expr->to++;
                } else {
                    /* Include end parenthesis */
                    expr->to++;
                }
                
                
                if (entry->context == RE_ARGLIST) {
                    if (toktype == LRL_Sym_LParen) {
                        expr->ast_type = LRL_AST_Expr_Call;
                        expr->kind.call.function =
                            rpn_to_ast(ctx, token, scope, out_stack, out_size);
                    } else {
                        /* Array index */
                        /* Convert the exprlist into multiple exprs */
                        size_t i;
                        
                        expr->kind.index.array =
                            rpn_to_ast(ctx, token, scope, out_stack, out_size);
                        
                        if (!numargs) {
                            lrl_err_token(ctx, LRL_Err_MissingArrayIndex,
                                          token);
                            
                            expr->ast_type = LRL_AST_Expr_ArrayIndex;
                            expr->kind.index.index = NULL;
                        } else {
                            for (i = 0; i < numargs; i++) {
                                if (i != 0) {
                                    LRLASTExpr *inner = expr;
                                    expr = malloc(sizeof(LRLASTExpr));
                                    expr->from = token;
                                    expr->to = token;
                                    memset(&expr->typeref, 0, sizeof(LRLTypeRef));
                                    expr->kind.index.array = inner;
                                }
                                
                                expr->ast_type = LRL_AST_Expr_ArrayIndex;
                                expr->kind.index.index = values[i];
                            }
                        }
                        free(values);
                    }
                } else {
                    if (toktype == LRL_Sym_LParen) {
                        expr->ast_type = LRL_AST_Value_Struct;
                    } else {
                        expr->ast_type = LRL_AST_Value_Array;
                    }
                }
                
                break; }
            default:
                lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
                goto error;
        }
    } else if (op.type == Binary) {
        /* Binary operators */
        if (toktype == LRL_Op_Member) {
            expr->ast_type = LRL_AST_Expr_Member;
            expr->kind.member.token = rpn_member_to_ast(ctx, out_stack, out_size);
            expr->kind.member.struc = rpn_to_ast(ctx, token, scope, out_stack, out_size);
            expr->kind.member.ident = NULL;
            
            set_expr_range(expr, expr->kind.member.struc, NULL);
            if (expr->kind.member.token) {
                expr->to = expr->kind.member.token;
            }
        } else if (toktype == LRL_Op_FunctionMember) {
            expr->ast_type = LRL_AST_Expr_FuncMember;
            expr->kind.member.token = rpn_member_to_ast(ctx, out_stack, out_size);
            expr->kind.member.struc = rpn_to_ast(ctx, token, scope, out_stack, out_size);
            expr->kind.member.ident = NULL;
            
            set_expr_range(expr, expr->kind.member.struc, NULL);
            if (expr->kind.member.token) {
                expr->to = expr->kind.member.token;
            }
        } else {
            expr->ast_type = LRL_AST_Expr_BinaryOp;
            expr->kind.binary_op.token_type = toktype;
            expr->kind.binary_op.operand2 = rpn_to_ast(ctx, token, scope, out_stack, out_size);
            expr->kind.binary_op.operand1 = rpn_to_ast(ctx, token, scope, out_stack, out_size);
            
            set_expr_range(expr, expr->kind.binary_op.operand1, expr->kind.binary_op.operand2);
        }
    } else if (op.type == Ternary) {
        /* "then-else" operator */
        expr->ast_type = LRL_AST_Expr_Conditional;
        expr->kind.conditional.falseexpr = rpn_to_ast(ctx, token, scope, out_stack, out_size);
        expr->kind.conditional.trueexpr = rpn_to_ast(ctx, token, scope, out_stack, out_size);
        expr->kind.conditional.condexpr = rpn_to_ast(ctx, token, scope, out_stack, out_size);
        
        set_expr_range(expr, expr->kind.conditional.condexpr, expr->kind.conditional.falseexpr);
    } else {
        /* Unary operators */
        if (toktype == LRL_KW_As) {
            const LRLToken *typetok = entry->token+1;
            LRLASTType *type;
            expr->ast_type = LRL_AST_Expr_As;
            
            type = parse_type(ctx, scope, &typetok);
            if (!type) {
                /* Recover from error */
                type = make_private_type(typetok, typetok);
            } else if (type->quals & LRL_NonInternal_Quals) {
                lrl_err_type(ctx, LRL_Err_QualifierNotAllowed, type);
            }
            expr->kind.asexpr.type = type;
            expr->kind.asexpr.expr = rpn_to_ast(ctx, token, scope, out_stack, out_size);
            
            set_expr_range(expr, expr->kind.asexpr.expr, NULL);
            if (expr->kind.asexpr.type) { /* FIXME never true. and expr->to should = expr->from (or the given token? does that work in rpn_to_ast?) on parse error */
                expr->to = expr->kind.asexpr.type->to;
            }
        } else if (toktype == LRL_KW_TypeAssert) {
            const LRLToken *typetok = entry->token+1;
            LRLASTType *type;
            expr->ast_type = LRL_AST_Expr_TypeAssert;
            
            type = parse_type(ctx, scope, &typetok);
            if (!type) {
                /* This is an error, but it will be handled by the verifier */
            } else if (type->quals & LRL_NonInternal_Quals) {
                lrl_err_type(ctx, LRL_Err_QualifierNotAllowed, type);
            }
            expr->kind.typeassert.type = type;
            expr->kind.typeassert.expr = rpn_to_ast(ctx, token, scope, out_stack, out_size);
            
            set_expr_range(expr, expr->kind.typeassert.expr, NULL);
            if (expr->kind.typeassert.type) {
                expr->to = expr->kind.typeassert.type->to;
            }
        } else {
            expr->ast_type = LRL_AST_Expr_UnaryOp; /* prefix or postfix */
            expr->kind.unary_op.token_type = toktype;
            expr->kind.unary_op.operand = rpn_to_ast(ctx, token, scope, out_stack, out_size);
            
            /* Special handling of negative literals, e.g. -128 */
            if (toktype == LRL_Op_Minus && expr->kind.unary_op.operand &&
                expr->kind.unary_op.operand->ast_type == LRL_AST_Value_Scalar) {
                expr->kind.unary_op.operand->kind.scalar.is_negative = 1;
            }
            
            /* Extend the range of tokens, either to the left or to the right */
            set_expr_range(expr, expr->kind.unary_op.operand, expr->kind.unary_op.operand);
        }
    }
    
    return expr;
    
  error:
    free(expr);
    return NULL;
}

/**
 * Modified version of the "Shunting-yard algorithm" by Edsger Dijkstra.
 * https://en.wikipedia.org/wiki/Shunting-yard_algorithm
 */
static LRLASTExpr *parse_expr(LRLCtx *ctx, LRLIdent *scope,
                              const LRLToken **tokens)
{
    const LRLToken *token = *tokens;
    LRLASTExpr *expr;
    RPNEntry entry;
    int operator_expected = 0;
    
    /* Operator stack */
    size_t op_size, op_capacity;
    RPNEntry *op_stack;
    
    /* Output stack */
    size_t out_size, out_capacity;
    RPNEntry *out_stack;
    
    init_list(&op_stack, &op_size, &op_capacity, 16);
    init_list(&out_stack, &out_size, &out_capacity, 16);
    
    while (token->type) {
        int found;
        LRLTokenType type = token->type;
        OpInfo op;
        
        switch ((int)type) {
            case LRL_TT_Ident:
            case LRL_KW_Here:
            case LRL_Sym_NamespaceSep: /* :typeident */
            case LRL_TT_Integer:
            case LRL_TT_Real:
            case LRL_TT_String:
            case LRL_TT_Undefined:
            case LRL_TT_None:
            case LRL_TT_NaN:
            case LRL_TT_Inf:
                if (operator_expected) {
                    lrl_err_token(ctx, LRL_Err_OperatorExpected, token);
                    break;
                }
                
                /* Terminal tokens are pushed directly to the output stack */
                entry.token = token;
                entry.context = RE_TERMINAL;
                list_push(&out_stack, &out_size, &out_capacity, entry);
                
                operator_expected = 1;
                
                if (type == LRL_Sym_NamespaceSep) {
                    token++;
                    if (token->type != LRL_TT_Ident) {
                        lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
                        expr = NULL;
                        goto cleanup;
                    }
                }
                
                if (type == LRL_TT_Ident || type == LRL_KW_Here ||
                    type == LRL_Sym_NamespaceSep) {
                    /* Skip any following subidentifiers */
                    while (token[1].type == LRL_Sym_NamespaceSep) {
                        token++;
                        
                        if (token[1].type != LRL_TT_Ident) {
                            lrl_err_token(ctx, LRL_Err_UnexpectedToken, &token[1]);
                            break;
                        }
                        
                        token++;
                    }
                    
                    if (token[1].type == LRL_Sym_LSquare) {
                        /* Skip type parameters (re-parsed later) */
                        token++;
                        parse_type_params(ctx, scope, &token);
                        goto no_add;
                    }
                }
                
                break;
            
            /*
               Argument and element list (exprlist) parsing.
               
               exprlists are stored like this on the out stack:
               
                    identifier value1 value2 value3    (
                       TERM     TERM   TERM   TERM    CALL
                        --       --     --     --      3
             */
            case LRL_Sym_ArrayIndex:
                if (!operator_expected) {
                    lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
                    break;
                }
                
                if (token[1].type != LRL_Sym_LSquare) {
                    lrl_err_token(ctx, LRL_Err_UnexpectedToken, &token[1]);
                    break;
                }
                
                token++;
                /* fall through */
            case LRL_Sym_LParen:
            case LRL_Sym_LSquare: {
                LRLTokenType next_type = token[1].type;
                
                if (operator_expected && type == LRL_Sym_LSquare) {
                    /* Type parameters are allowed on identifiers only */
                    lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
                    break;
                }
                
                /* Pop operators with higher precedence,
                   e.g. member operator */
                while (op_size > 0) {
                    const RPNEntry *st_entry = &op_stack[op_size-1];
                    LRLTokenType st_type = st_entry->token->type;
                    OpInfo st = get_opinfo(st_type, st_entry->context);
                    
                    if (!st.precedence) break;
                    
                    if ((!st.right_assoc && LRL_CALL_AND_ARRIND_PRECEDENCE <= st.precedence) ||
                        (st.right_assoc  && LRL_CALL_AND_ARRIND_PRECEDENCE < st.precedence)) {
                        /* Move to the output stack */
                        list_push(&out_stack, &out_size, &out_capacity, *st_entry);
                        op_size--;
                        continue;
                    }
                    
                    break;
                }
                
                /* Check if the argument list is empty */
                entry.num_args = (lrl_is_paren(next_type) &&
                        !lrl_is_start_paren(next_type) ?
                        0 : 1);
                
                entry.context = (operator_expected ?
                    RE_ARGLIST : /* Function call or array index */
                    (type == LRL_Sym_LSquare ?
                        RE_ELEMLIST :  /* Array literal */
                        RE_GROUPING)); /* Grouping or struct literal
                                          (until a comma is parsed) */
                
                entry.token = token;
                list_push(&op_stack, &op_size, &op_capacity, entry);
                
                operator_expected = 0;
                break; }
            
            case LRL_Sym_Comma:
            case LRL_Sym_RParen:
            case LRL_Sym_RSquare: {
                LRLTokenType next_type = token[1].type;
                int popped_ops = 0;
                
                /* Pop everything off the stack until a ( or [ is found */
                found = 0;
                while (op_size > 0) {
                    const RPNEntry *st_entry = &op_stack[op_size-1];
                    LRLTokenType st_type = st_entry->token->type;
                    
                    if (lrl_is_paren(st_type) && lrl_is_start_paren(st_type)) {
                        found = 1;
                        break;
                    }
                    
                    list_push(&out_stack, &out_size, &out_capacity, *st_entry);
                    op_size--;
                    popped_ops = 1;
                }
                
                /* This check is equivalent to checking if this is
                   neither an empty list nor a completed operation. */
                if (!operator_expected && popped_ops) {
                    /* Missing right operand */
                    lrl_err_token(ctx, LRL_Err_MissingOperand, token);
                }
                
                /* Check for end of expression */
                if (!found) goto finished;
                
                operator_expected = (type != LRL_Sym_Comma);
                
                if (type != LRL_Sym_Comma) {
                    /* Pop the left parenthesis of the stack */
                    op_size--;
                    
                    /* Check that this wasn't just a grouping parenthesis */
                    if (op_stack[op_size].context != RE_GROUPING ||
                        op_stack[op_size].token->type != LRL_Sym_LParen ||
                        op_stack[op_size].num_args != 1) {
                        /* Push the start parenthesis to the out stack */
                        list_push(&out_stack, &out_size, &out_capacity,
                                  op_stack[op_size]);
                    }
                } else {
                    /* Comma */
                    LRLTokenType prev_type = token[-1].type;
                    if (prev_type == LRL_Sym_Comma ||
                        (lrl_is_paren(prev_type) &&
                         lrl_is_start_paren(prev_type))) {
                        lrl_err_token(ctx, LRL_Err_EmptyExprInList, token);
                        break;
                    }
                    
                    if (op_stack[op_size-1].context == RE_GROUPING) {
                        op_stack[op_size-1].context = RE_ELEMLIST;
                    }
                    
                    if (!lrl_is_paren(next_type) || lrl_is_start_paren(next_type)) {
                        /* Comma, but not a trailing one */
                        op_stack[op_size-1].num_args++;
                    } else if (op_stack[op_size-1].context == RE_ARGLIST) {
                        /* Trailing commas are not allowed in arglists or array
                           index expressions */
                        lrl_err_token(ctx, LRL_Err_TrailingCommaInArgList, token);
                        break;
                    }
                }
                
                break; }
                
            case LRL_KW_Else:
                /* Last part of conditional "then-else" operator */
                if (!operator_expected) {
                    lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
                    break;
                }
                operator_expected = 0;
                
                /* Pop everything off the stack up to and including "then" */
                found = 0;
                while (op_size > 0) {
                    const RPNEntry *st_entry = &op_stack[op_size-1];
                    LRLTokenType st_type = st_entry->token->type;
                    op_size--;
                    
                    if (st_type == LRL_Op_Then) { /* deleted from stack */
                        found = 1;
                        break;
                    }
                    
                    list_push(&out_stack, &out_size, &out_capacity, *st_entry);
                }
                
                /* Check for end of expression */
                if (!found) goto finished;
                
                /* Push ternary "else" operator to the operator stack */
                entry.token = token;
                entry.context = RE_OP;
                list_push(&op_stack, &op_size, &op_capacity, entry);
                break;
                
            case LRL_Sym_Semicolon:
            case LRL_Sym_LCurly:
            case LRL_KW_Bits:
            case LRL_KW_Break:
            case LRL_KW_Continue:
            case LRL_KW_Goto:
            case LRL_KW_SkipTo:
            case LRL_KW_RepeatFrom:
            case LRL_KW_Return:
            case LRL_KW_Case:
            case LRL_KW_Unreachable:
            case LRL_KW_With:
                goto finished;
            
            default:
                op = get_opinfo(type, operator_expected ? RE_OP : RE_UNARY);
                
                if (!op.precedence) {
                    /* Error */
                    lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
                    break;
                }
                
                /* Prefix operator? */
                if (op.type == Prefix) {
                    entry.token = token;
                    entry.context = RE_UNARY;
                    list_push(&op_stack, &op_size, &op_capacity, entry);
                    operator_expected = 0;
                    break;
                }
                
                if (!operator_expected) {
                    lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
                    break;
                }
                
                /* Binary or postfix operator */
                while (op_size > 0) {
                    const RPNEntry *st_entry = &op_stack[op_size-1];
                    LRLTokenType st_type = st_entry->token->type;
                    OpInfo st = get_opinfo(st_type, st_entry->context);
                    
                    if (!st.precedence) break;
                    
                    if ((!st.right_assoc && op.precedence <= st.precedence) ||
                        (st.right_assoc  && op.precedence < st.precedence)) {
                        /* Move to the output stack */
                        list_push(&out_stack, &out_size, &out_capacity, *st_entry);
                        op_size--;
                        continue;
                    }
                    
                    break;
                }
                
                if (op.type == Postfix) {
                    entry.token = token;
                    entry.context = RE_UNARY;
                    list_push(&out_stack, &out_size, &out_capacity, entry);
                    operator_expected = 1;
                    
                    if (type == LRL_KW_As || type == LRL_KW_TypeAssert) {
                        /* Skip through the following type */
                        token++;
                        skip_type(ctx, &token);
                        continue; /* we are at the next token now */
                    }
                    break;
                }
                
                /* Push to the operator stack */
                entry.token = token;
                entry.context = RE_OP;
                list_push(&op_stack, &op_size, &op_capacity, entry);
                operator_expected = 0;
        }
        
        token++;
      no_add: ;
    }
    
  finished:
    /* Move remaining tokens on the operator stack to the output stack */
    while (op_size > 0) {
        const RPNEntry *st_entry = &op_stack[op_size-1];
        LRLTokenType st_type = st_entry->token->type;
        
        if (lrl_is_paren(st_type)) {
            /* Error - Mismatched parenthesis */
            lrl_err_token(ctx, LRL_Err_UnexpectedToken, st_entry->token);
            break;
        }
        
        list_push(&out_stack, &out_size, &out_capacity, *st_entry);
        op_size--;
    }
    
    if (out_size == 0 || !operator_expected) {
        lrl_err_token(ctx, LRL_Err_IncompleteExpression, token);
        expr = NULL;
        goto cleanup;
    }
    
    /* Read from stack in reverse order, and build the ASTExpr */
    expr = rpn_to_ast(ctx, NULL, scope, out_stack, &out_size);
    
    if (out_size != 0) {
        lrl_err_token(ctx, LRL_Err_IncompleteExpression,
                      out_stack[out_size-1].token);
    }
    
  cleanup:
    free(out_stack);
    free(op_stack);
    
    *tokens = token;
    return expr;
}

/**
 * Looks ahead at the token sequence, and returns:
 *    -1  on error
 *     0  if it should be parsed as a normal expression
 *     1  if it should be parsed as a variable declaration
 */
static int is_declaration(LRLCtx *ctx, const LRLToken *tokens,
                          const LRLToken *start)
{
    /* An expression cannot contain two operands followed by each other.
       Declarations always consist of a type (an operand) and an identifier
       (also and operand). By determining if the first operand could be a
       type, and whether the second operand is an identifier, we can check
       if a statement is a declaration. */

    /* Skip type qualifiers */
    int expected_decl = parse_qualifiers(ctx, &tokens);
    
    /* The "leaf" type comes first and is either an identifier, a struct
       or an enumeration. */
    if (is_ident(tokens)) {
        /* Possibly identifier type */
        skip_ident(ctx, &tokens);
    } else if (tokens->type == LRL_Sym_LParen) {
        /* Possibly struct type */
        if (!skip_parens(ctx, &tokens)) return -1;
    } else if (tokens->type == LRL_KW_Union || tokens->type == LRL_KW_Enum ||
               tokens->type == LRL_KW_Bits) {
        /* Union/Enum type */
        return 1;
    } else if (tokens->type == LRL_KW_Private || tokens->type == LRL_KW_Any) {
        return 1;
    } else if (tokens->type == LRL_KW_NoReturn) {
        /* Function type */
        return 1;
    } else {
        /* Doesn't start with a type */
        goto is_expression;
    }
    
    /* Go through pointer/optional specifiers, function parameters, etc. */
    for (;;) {
        LRLTokenType ttype;
        if (!tokens->type) break;
        
        /* Only types can have qualifiers */
        if (parse_qualifiers(ctx, &tokens)) {
            expected_decl = 1;
        }
        
        ttype = tokens->type;
        if (!tokens->type) break;
        
        /* Only types can be used as a base for enumerations/bitfields */
        if (ttype == LRL_KW_Enum || ttype == LRL_KW_Bits) return 1;
        
        /* Check if we found the name of the variable */
        if (is_ident(tokens)) return 1;
        
        /* Skip "#" in array index */
        if (ttype == LRL_Sym_ArrayIndex && tokens[1].type == LRL_Sym_LSquare) {
            tokens++;
            ttype = tokens->type;
        }
        
        if (ttype == LRL_Sym_LParen || ttype == LRL_Sym_LSquare) {
            /* Skip brackets (function, type parameters or array) */
            if (!skip_parens(ctx, &tokens)) return -1;
        } else if (ttype == LRL_Op_Deref || ttype == LRL_Op_OptionalValue ||
                   (ttype >= LRL_Sym_FlexiPointer && ttype <= LRL_Sym_RawFlexiPointer)) {
            /* Skip pointer or optional type */
            tokens++;
        } else {
            /* Not a type */
            break;
        }
    }
    
  is_expression:
    
    if (expected_decl) {
        /* Error */
        lrl_err_set_token_range(ctx, start, tokens, 0);
        lrl_err_finish(ctx, LRL_Err_InvalidDeclaration);
        return -1;
    }
    return 0;
}


static void check_no_semicolon_before_body(LRLCtx *ctx,
                                           const LRLToken **tokens)
{
    if ((*tokens)->type == LRL_Sym_Semicolon) {
        /* Should not have a semicolon before the if body! */
        lrl_err_token(ctx, LRL_Err_SemicolonBeforeBody, *tokens);
        ++*tokens;
    }
}

static LRLDefFlags parse_typedef_flags(LRLCtx *ctx, const LRLToken **tokens)
{
    LRLDefFlags flags = 0;
    const LRLToken *token = *tokens;
    for (;;) {
        LRLDefFlags addflag;
        if (token->type == LRL_KW_Incomplete) {
            addflag = LRL_DeFl_Incomplete;
        } else if (token->type == LRL_KW_Alias) {
            addflag = LRL_DeFl_Alias;
        } else {
            break;
        }
        
        if (flags & addflag) {
            lrl_err_token(ctx, LRL_Err_RepeatedKeyword, token);
        }
        flags |= addflag;
        token++;
    }
    *tokens = token;
    return flags;
}

static int parse_typedef(LRLCtx *ctx, LRLIdent *scope,
                         const LRLToken **tokens, LRLASTDefOrStmt *defstmt)
{
    LRLASTDefType *deftype = &defstmt->def.kind.type;
    LRLIdent *ident, *anon;
    if (!defstmt) fail("parsetypedef_nostmt");
    
    ++*tokens;
    deftype->flags = parse_typedef_flags(ctx, tokens);
    
    /* Read identifier */
    ident = parse_ident(ctx, scope, tokens, LRL_Ident_Create, NULL);
    if (!ident) return 0;
    ident->flags |= LRL_IdFl_Typedef |
                    (scope->flags & LRL_IdFl_Statement);
    deftype->ident = ident;
    set_def_node(ident, defstmt);
    
    /* Create anonymous namespace */
    anon = lrl_ident_create_priv_scope(ident);
    anon->flags |= LRL_IdFl_TypedefAnon;
    
    /* Read type parameter definitions (if any) */
    deftype->typenames = ((*tokens)->type == LRL_Sym_LSquare ?
        parse_type_names(ctx, ident, tokens) : NULL);
    
    if (!expected(ctx, tokens, LRL_Op_Assign))
        return 0;
    
    /* Read definition */
    deftype->type = parse_type(ctx, anon, tokens);
    if (!deftype->type) return 0;
    
    if (deftype->type->quals & LRL_Qual_Var) {
        lrl_err_type(ctx, LRL_Err_TypedefVarIsDefault, deftype->type);
    }
    
    expected(ctx, tokens, LRL_Sym_Semicolon);
    return 1;
}

typedef enum {
    STF_NoSemicolonEnd = 0x1
} StmtFlags;

static LRLASTStmt *parse_statement(LRLCtx *ctx, const LRLIdent *outer_scope,
                                   LRLASTStmt *last_loop, StmtFlags flags,
                                   const LRLToken **tokens)
{
    const LRLToken *token = *tokens;
    const LRLToken *start = token;
    LRLTokenType toktype = token->type;
    LRLIdent *scope;
    
    LRLASTStmt *stmt = malloc(sizeof(LRLASTStmt));
    stmt->token = token;
    
    /* Prune empty statement scopes (except "{...}") in the identifier tree */
    if (!outer_scope->contents.size &&
        (outer_scope->flags & LRL_IdFl_Statement) != 0) {
        if (outer_scope->scope) outer_scope = outer_scope->scope;
    }
    
    /* Statement scopes are nested */
    memset(&stmt->scope, 0, sizeof(stmt->scope));
    stmt->scope.flags = LRL_IdFl_Statement; /* except in {} */
    stmt->scope.scope = outer_scope;
    scope = &stmt->scope;
    
    switch ((int)toktype) {
        case LRL_Sym_LCurly: {
            /* Multiple statements grouped by { } */
            LRLASTStmtList *list_first = NULL, *list_last = NULL;
            stmt->scope.flags = 0;
            token++;
            
            while (token->type && token->type != LRL_Sym_RCurly) {
                LRLASTStmt *inner = parse_statement(ctx, scope, last_loop,
                                                    0, &token);
                if (inner) {
                    /* Add to list */
                    LRLASTStmtList *entry;
                    linked_append(&entry, &list_first, &list_last);
                    entry->statement = inner;
                    
                    /* Make the scope of the last statement accessible to
                       subsequent statements */
                    scope = &inner->scope;
                    if (inner->scope.scope == NULL) fail("parsestmt_nullscope");
                }
            }
            
            stmt->ast_type = LRL_AST_Stmt_Compound;
            stmt->kind.compound = list_first;
            
            if (!token->type) {
                lrl_err_token(ctx, LRL_Err_UnclosedParenthesis, *tokens);
            } else {
                token++;
            }
            break;
        }
        case LRL_Sym_Semicolon:
            /* Error - Empty statements should be written as { }, not ; */
            lrl_err_token(ctx, LRL_Err_SemicolonWithoutStatement, token);
            
            stmt = NULL;
            token++;
            break;
        case LRL_KW_If:
            stmt->ast_type = LRL_AST_Stmt_If;
            token++;
            
            /* Parse boolean expression */
            stmt->kind.ifstm.boolexpr = parse_expr(ctx, scope, &token);
            check_no_semicolon_before_body(ctx, &token);
            
            /* Parse if bodies */
            stmt->kind.ifstm.body_true = parse_statement(ctx, scope, last_loop,
                                                         0, &token);
            stmt->kind.ifstm.body_false = NULL;
            
            if (token->type == LRL_KW_Else) {
                token++;
                check_no_semicolon_before_body(ctx, &token);
                
                stmt->kind.ifstm.body_false = parse_statement(ctx, scope,
                                                    last_loop, 0, &token);
            }
            break;
        case LRL_KW_Switch:
            stmt->ast_type = LRL_AST_Stmt_Switch;
            token++;
            
            /* Parse switch expression */
            stmt->kind.switchstm.switchexpr = parse_expr(ctx, scope, &token);
            
            /* Parse cases */
            stmt->kind.switchstm.num_cases = 0;
            stmt->kind.switchstm.cases = NULL;
            stmt->kind.switchstm.defaultstm = NULL;
            if (!expected(ctx, &token, LRL_Sym_LCurly)) break;
            while (token->type && token->type != LRL_Sym_RCurly &&
                   token->type != LRL_KW_Default) {
                
                LRLASTCase *casenode;
                
                stmt->kind.switchstm.cases = try_realloc(
                        stmt->kind.switchstm.cases,
                        sizeof(LRLASTCase)*++stmt->kind.switchstm.num_cases);
                
                casenode = &stmt->kind.switchstm.cases[stmt->kind.switchstm.num_cases-1];
                casenode->num_matchvalues = 0;
                casenode->matchvalues = NULL;
                casenode->stmt = NULL;
                
                /* Parse comparison values */
                if (token->type != LRL_KW_Case) {
                    lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
                    goto recover_case;
                }
                while (token->type == LRL_KW_Case) {
                    LRLASTCaseMatch *casematch;
                    token++;
                  recover_case:
                    if (!token || token->type == LRL_Sym_RCurly) {
                        break; /* Error */
                    }
                    
                    casenode->matchvalues = try_realloc(casenode->matchvalues,
                        sizeof(LRLASTCaseMatch)*++casenode->num_matchvalues);
                    casematch = &casenode->matchvalues[casenode->num_matchvalues-1];
                    casematch->expr = parse_expr(ctx, scope, &token);
                    
                    if (token->type == LRL_KW_With) {
                        token++;
                        casematch->withstm = parse_statement(ctx, scope,
                                     last_loop, STF_NoSemicolonEnd, &token);
                    } else {
                        casematch->withstm = NULL;
                    }
                }
                
                /* Parse code block */
                check_no_semicolon_before_body(ctx, &token);
                if (token->type == LRL_Sym_RCurly) {
                    lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
                    break;
                }
                casenode->stmt = parse_statement(ctx, scope, last_loop, 0, &token);
            }
            
            /* Parse default case */
            if (token->type == LRL_KW_Default) {
                token++;
                check_no_semicolon_before_body(ctx, &token);
                stmt->kind.switchstm.defaultstm =
                        parse_statement(ctx, scope, last_loop, 0, &token);
            }
            
            expected(ctx, &token, LRL_Sym_RCurly);
            break;
        case LRL_KW_While:
            stmt->ast_type = LRL_AST_Stmt_While;
            token++;
            
            /* Parse boolean expression */
            stmt->kind.whilestm.boolexpr = parse_expr(ctx, scope, &token);
            check_no_semicolon_before_body(ctx, &token);
            
            /* Parse while body */
            stmt->kind.whilestm.body = parse_statement(ctx, scope, stmt, 0,
                                                       &token);
            break;
        case LRL_KW_Do:
            stmt->ast_type = LRL_AST_Stmt_DoWhile;
            token++;
            
            /* Parse do/while body */
            if (token->type != LRL_Sym_LCurly) {
                lrl_err_token(ctx, LRL_Err_DoWhileWithoutBlock, token);
            }
            stmt->kind.whilestm.body = parse_statement(ctx, scope, stmt, 0,
                                                       &token);
            
            /* Parse boolean expression */
            if (expected(ctx, &token, LRL_KW_While)) {
                stmt->kind.whilestm.boolexpr = parse_expr(ctx, scope, &token);
                goto expect_semicolon;
            } else {
                stmt->kind.whilestm.boolexpr = NULL;
            }
            break;
        case LRL_KW_For: {
            LRLIdent *ident, *scope_endempty;
            LRLASTType *valuetype;
            
            stmt->ast_type = LRL_AST_Stmt_For;
            token++;
            
            /* Create a separate scope for the main loop body
               (which the end/empty bodies can't access) */
            scope_endempty = lrl_ident_create_priv_scope(scope);
            /* Create a private scope for the whole loop, to block access
               to the loop variable from statements after the loop */
            scope = lrl_ident_create_priv_scope(scope);
            
            /* Parse value variable */
            /* TODO allow nested loops to be written like this?
                    for int x y in [1,2,3], [1,2,3] { ... }
                    for int x, double f in [1,2,3], [1, 1.1, 1.2] { ... }    */
            valuetype = parse_type(ctx, scope, &token);
            stmt->kind.forstm.valuedef.ast_type = LRL_AST_Stmt_Decl;
            stmt->kind.forstm.valuedef.kind.data.flags = 0;
            stmt->kind.forstm.valuedef.kind.data.type = valuetype;
            if (valuetype) {
                if (valuetype->quals & LRL_Qual_Const) {
                    lrl_err_type(ctx, LRL_Err_DataConstIsDefault, valuetype);
                } else if (valuetype->quals & LRL_NonInternal_Quals) {
                    lrl_err_type(ctx, LRL_Err_QualifierNotAllowed, valuetype);
                }
            }
            
            ident = parse_ident(ctx, scope, &token, LRL_Ident_Create, NULL);
            set_def_node(ident, (LRLASTDefOrStmt*)&stmt->kind.forstm.valuedef);
            stmt->kind.forstm.valuedef.kind.data.ident = ident;
            stmt->kind.forstm.valuedef.kind.data.value = make_undef_expr(token);
            
            /* "in" */
            expected(ctx, &token, LRL_KW_In);
            
            /* Parse iterable expression */
            stmt->kind.forstm.iterexpr = parse_expr(ctx, scope, &token);
            check_no_semicolon_before_body(ctx, &token);
            stmt->kind.forstm.temp = NULL; /* used by the verifier */
            
            /* Parse for body */
            stmt->kind.forstm.body = parse_statement(ctx, scope, stmt, 0, &token);
            
            /* "loopend" body is executed if no "break" was executed */
            if (token->type == LRL_KW_LoopEnd) {
                token++;
                check_no_semicolon_before_body(ctx, &token);
                stmt->kind.forstm.body_end = parse_statement(ctx,
                                        scope_endempty, last_loop, 0, &token);
            } else {
                stmt->kind.forstm.body_end = NULL;
            }
            /* "loopempty" body is executed if the loop was empty */
            if (token->type == LRL_KW_LoopEmpty) {
                token++;
                check_no_semicolon_before_body(ctx, &token);
                stmt->kind.forstm.body_empty = parse_statement(ctx,
                                        scope_endempty, last_loop, 0, &token);
            } else {
                stmt->kind.forstm.body_empty = NULL;
            }
            
            break; }
        case LRL_KW_Goto:
            stmt->ast_type = LRL_AST_Stmt_Goto;
            goto parse_goto;
        case LRL_KW_SkipTo:
            stmt->ast_type = LRL_AST_Stmt_SkipTo;
            goto parse_goto;
        case LRL_KW_RepeatFrom:
            stmt->ast_type = LRL_AST_Stmt_RepeatFrom;
          parse_goto: {
            LRLIdent *funcscope;
            token++;
            
            /* Parse identifier */
            if (token->type != LRL_TT_Ident) {
                lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
                goto recover;
            }
            funcscope = get_function_scope(scope);
            defer_ident(ctx, funcscope, &stmt->kind.gotostm.identref, &token);
            
            goto expect_semicolon; }
        case LRL_KW_Label: {
            LRLIdent *ident, *funcscope, *dup;
            char *name;
            stmt->ast_type = LRL_AST_Stmt_Label;
            token++;
            
            /* Read name token */
            if (token->type != LRL_TT_Ident) {
                lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
                goto recover;
            }
            name = lrl_strndup(token->loc.start, token->loc.length);
            if (!name) goto recover;
            
            /* Check for duplicate */
            funcscope = get_function_scope(scope);
            dup = lrl_ident_get_string(funcscope, name);
            if (dup) {
                lrl_err_set_token(ctx, token, 0);
                if (dup->def_token) {
                    lrl_err_set_token(ctx, dup->def_token, 1);
                }
                lrl_err_finish(ctx, LRL_Err_DuplicateIdentifier);
            }
            
            /* Insert label into scope */
            ident = lrl_ident_insert_string(ctx, funcscope, name);
            set_def_node(ident, (LRLASTDefOrStmt*)stmt);
            stmt->kind.labelstm.ident = ident;
            token++;
            
            /* Expect a colon */
            /* TODO should require a non-identifier character after the colon, to prevent confusing code e.g. "label a:b;"
                    perhaps we can just check that there's at least one character between the : and the first character
                    in the next token if it's an identifier token? */
            expected(ctx, &token, LRL_Sym_NamespaceSep);
            break; }
        case LRL_KW_Break:
            stmt->ast_type = LRL_AST_Stmt_Break;
            goto breakcont_stmt;
        case LRL_KW_Continue:
            stmt->ast_type = LRL_AST_Stmt_Continue;
          breakcont_stmt:
            stmt->kind.breakstm.outer_stmt = last_loop;
            if (!last_loop) {
                lrl_err_token(ctx, LRL_Err_BreakContinueOutsideLoop, token);
            }
            token++;
            goto expect_semicolon;
        case LRL_KW_Return:
            stmt->ast_type = LRL_AST_Stmt_Return;
            token++;
            
            stmt->kind.retstm.retexpr = (token->type != LRL_Sym_Semicolon ?
                parse_expr(ctx, scope, &token) : NULL);
            
            goto expect_semicolon;
        case LRL_KW_Unreachable:
            stmt->ast_type = LRL_AST_Stmt_Unreachable;
            token++;
            goto expect_semicolon;
        case LRL_KW_TypeAssert: {
            LRLIdent *targetscope = calloc(1, sizeof(LRLIdent));
            int has_do_body = 0;
            stmt->ast_type = LRL_AST_Stmt_TypeAssert;
            stmt->kind.typeassertstm.asserts = NULL;
            stmt->kind.typeassertstm.body_do = NULL;
            stmt->kind.typeassertstm.body_else = NULL;
            
            targetscope->flags = LRL_IdFl_Statement; /* except in {} */
            targetscope->scope = scope;
            
            do {
                LRLTypeAssert *ta = calloc(1, sizeof(LRLTypeAssert));
                const LRLToken *identstart;
                LRLIdent *ident;
                
                ta->next = stmt->kind.typeassertstm.asserts;
                ta->def.ast_type = LRL_AST_Def_Data;
                
                identstart = ++token;
                /* Add identref in parent scope */
                ta->refexpr.ast_type = LRL_AST_Value_Ident;
                ta->refexpr.from = token;
                defer_ident(ctx, (LRLIdent*)outer_scope,
                            &ta->refexpr.kind.ident.identref, &token);
                ta->refexpr.to = token-1;
                
                /* Create identifier in this scope */
                token = identstart;
                ident = parse_ident(ctx, targetscope, &token,
                                    LRL_Ident_Create, NULL);
                set_def_node(ident, (LRLASTDefOrStmt*)&ta->def);
                ta->def.kind.data.ident = ident;
                ta->def.kind.data.flags = LRL_DeFl_Internal_TypeAssert;
                ta->def.kind.data.value = &ta->refexpr;
                
                if (token->type != LRL_KW_Is && token->type != LRL_KW_In) {
                    lrl_err_token(ctx, LRL_Err_TypeAssertIsOrInExpected, token);
                    continue;
                }
                
                if (token->type == LRL_KW_Is) {
                    LRLASTType *type;
                    token++;
                    /* Parse type to cast to */
                    type = parse_type(ctx, scope, &token);
                    if (type && type->quals & LRL_NonInternal_Quals) {
                        lrl_err_type(ctx, LRL_Err_QualifierNotAllowed, type);
                    }
                    ta->def.kind.data.type = type;
                    /* TODO should be able to cast e.g. (int,int) into (byte,byte) */
                }
                
                /* TODO change this into a generic condition?
                        e.g. "typeassert x is byte cond (value >= 0 and value <= 15) and y is ..." */
                if (token->type == LRL_KW_In) {
                    token++;
                    /* Parse range */
                    /* TODO */
                    fail("parsestmt_typeassert_ranges_notimpl");
                }
                
                if (!ta->def.kind.data.type) continue;
                
                stmt->kind.typeassertstm.asserts = ta;
            } while (token->type == LRL_Op_LAnd);
            
            /* Read do and/or else blocks (if any) */
            if (token->type != LRL_KW_Do && token->type != LRL_KW_Else) {
                if ((flags & STF_NoSemicolonEnd) == 0) {
                    expect_end_of_statement(ctx, &token);
                }
            } else {
                if (token->type == LRL_KW_Do) {
                    token++;
                    check_no_semicolon_before_body(ctx, &token);
                    stmt->kind.typeassertstm.body_do = parse_statement(
                                    ctx, targetscope, last_loop, 0, &token);
                    has_do_body = 1;
                }
                if (token->type == LRL_KW_Else) {
                    token++;
                    check_no_semicolon_before_body(ctx, &token);
                    stmt->kind.typeassertstm.body_else = parse_statement(
                                    ctx, scope->scope, last_loop, 0, &token);
                }
            }
            
            if (!has_do_body) {
                size_t bi;
                /* Make target identifiers visible to statements after the
                   typeassert stmt by moving them to the statement scope */
                for (bi = 0; bi < targetscope->contents.num_buckets; bi++) {
                    LRLIdent *subident = targetscope->contents.buckets[bi];
                    for (; subident; subident = subident->next) {
                        subident->scope = &stmt->scope;
                    }
                }
                targetscope->scope = outer_scope;
                stmt->scope = *targetscope;
                free(targetscope);
            }
            break; }
        case LRL_KW_Assert:
            stmt->ast_type = LRL_AST_Stmt_Assert;
            token++;
            stmt->kind.assertstm.exprstart = token->loc.start;
            stmt->kind.assertstm.boolexpr = parse_expr(ctx, scope, &token);
            stmt->kind.assertstm.exprlength = token->loc.start -
                    stmt->kind.assertstm.exprstart;
            goto expect_semicolon;
        case LRL_Sym_RParen:
        case LRL_Sym_RSquare:
        case LRL_Sym_RCurly:
            lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
            
            stmt = NULL;
            if (token->type != LRL_Sym_RCurly) token++;
            break;
        case LRL_KW_Typedef: {
            /* Type definition */
            stmt->ast_type = LRL_AST_Stmt_DefType;
            stmt->kind.deftype.ident = NULL;
            stmt->kind.deftype.flags = 0;
            stmt->kind.deftype.type = NULL;
            stmt->kind.deftype.typenames = NULL;
            
            if (!parse_typedef(ctx, scope, &token, (LRLASTDefOrStmt*)stmt))
                goto recover;
            
            break; }
        default: {
            /* An expression or variable declaration */
            int is_decl = is_declaration(ctx, token, start);
            if (is_decl > 0) {
                /* This is a variable declaration */
                /* Type */
                LRLIdent *ident;
                stmt->ast_type = LRL_AST_Stmt_Decl;
                stmt->kind.data.flags = 0;
                stmt->kind.data.type = parse_type(ctx, scope, &token);
                if (!stmt->kind.data.type) goto recover;
                if (stmt->kind.data.type->quals & LRL_Qual_Const) {
                    lrl_err_type(ctx, LRL_Err_DataConstIsDefault, stmt->kind.data.type);
                } else if ((stmt->kind.data.type->quals & (LRL_Qual_Var|LRL_Qual_Shared)) == LRL_Qual_Shared) {
                    lrl_err_type(ctx, LRL_Err_LocalSharedWithoutVar, stmt->kind.data.type);
                }
                
                /* Identifier */
                if (is_valid_ident(ctx, token)) {
                    lrl_ident_check_duplicates(ctx, scope, token);
                    ident = parse_ident(ctx, scope, &token,
                                        LRL_Ident_Create, NULL);
                    set_def_node(ident, (LRLASTDefOrStmt*)stmt);
                    stmt->kind.data.ident = ident;
                } else {
                    /* Error recovery */
                    skip_ident(ctx, &token);
                    stmt->kind.data.ident = NULL;
                    ident = NULL;
                    if (token->type != LRL_Op_Assign) {
                        stmt->kind.data.value = make_undef_expr(token);
                        skip_statement_skip_paren(ctx, &token);
                        break;
                    }
                }
                
                if (token->type == LRL_Sym_LSquare) {
                    lrl_err_token(ctx, LRL_Err_DataWithTypeParameters, token);
                    stmt->kind.data.value = make_undef_expr(token);
                    skip_statement_skip_paren(ctx, &token);
                    break;
                }
                
                if (token->type == LRL_Op_Assign) {
                    /* Parse initial value */
                    token++;
                    stmt->kind.data.value = parse_expr(ctx, ident, &token);
                } else {
                    /* Use default (undefined) */
                    stmt->kind.data.value = make_undef_expr(token);
                }

                goto expect_semicolon;
                
            } else if (!is_decl) {
                /* This is an expression */
                stmt->ast_type = LRL_AST_Stmt_Expr;
                stmt->kind.expr = parse_expr(ctx, scope, &token);
                goto expect_semicolon;
            } else {
                /* Error (already reported by is_declaration()) */
                goto recover;
            }
            break;
        }
    }
    
  end:
    *tokens = token;
    return stmt;
    
  expect_semicolon:
    if ((flags & STF_NoSemicolonEnd) == 0) {
        expect_end_of_statement(ctx, &token);
    }
    goto end;

  recover:
    skip_statement_skip_paren(ctx, &token);
    *tokens = token;
    return NULL;
}


static void try_add_linkname(LRLCtx *ctx, LRLIdent *ident,
                             const LRLToken *linkname)
{
    if (!linkname) return;
    
    if (ident->linkname &&
        !lrl_strings_equal(&ident->linkname->loc, &linkname->loc)) {
        
        lrl_err_set_token(ctx, linkname, 0);
        lrl_err_set_token(ctx, ident->linkname, 1);
        lrl_err_finish(ctx, LRL_Err_MultipleDifferentLinknames);
        return;
    }
    
    ident->linkname = linkname;
}

/**
 * Parses the top level definitions in a file: Functions, types,
 * uses statements, static variables, etc.
 */
static void parse_deflist(LRLCtx *ctx, LRLIdent *scope,
                          const LRLToken **tokens, LRLASTDefList **parsed)
{
    LRLASTDefList *list_first = NULL, *list_last = NULL;
    const LRLToken *token = *tokens;
    
    while (token->type && token->type != LRL_Sym_RCurly) {
        LRLIdent *ident;
        LRLASTType *type;
        LRLASTDefList *def;
        LRLDefFlags defflags = 0;
        LRLASTDefList *typenames = NULL;
        const LRLToken *first_token = token;
        const LRLToken *linkname = NULL;
        const LRLToken *type_start;
        int noreturn_kw;
        
        if (token->type == LRL_KW_Deprecated) {
            defflags |= LRL_DeFl_Deprecated;
            token++;
        }
        
        /* Parse linkname qualifier (if any) */
        if (token->type == LRL_KW_Local) {
            defflags |= LRL_DeFl_Local;
            token++;
        } else if (token->type == LRL_KW_DeclOnly) {
            /* TODO should be the default in headers
                    should be required if there's no function body/variable value */
            defflags |= LRL_DeFl_DeclOnly;
            token++;
        } else if (token->type == LRL_KW_Export) {
            defflags |= LRL_DeFl_Export;
            token++;
        } else if (token->type == LRL_KW_Import) {
            defflags |= LRL_DeFl_Import;
            token++;
        }
        
        if (token->type == LRL_KW_Linkname) {
            token++;
            if (token->type == LRL_TT_String) {
                linkname = token;
                token++;
            } else {
                lrl_err_token(ctx, LRL_Err_ExpectedLinknameString, token);
            }
            
            /* If there's nothing after it, add the linkname to the current namespace */
            if (token->type == LRL_Sym_Semicolon || token->type == LRL_TT_EOF) {
                try_add_linkname(ctx, scope, linkname);
                expected(ctx, &token, LRL_Sym_Semicolon);
                continue;
            }
        }
        
        /* Type definition? */
        if (token->type == LRL_KW_Typedef) {
            /*
             * Syntax:
             *
             *   typedef = "typedef", [ flags ], identifier, "=",
             *             type, ";" ;
             */
            LRLASTDefList *saved = list_last;
            
            if (defflags & LRL_LinkageFlags) {
                lrl_err_token(ctx, LRL_Err_LinkageFlagsNotAllowedHere, token);
                defflags = 0;
            }
            
            linked_append(&def, &list_first, &list_last);
            def->def.ast_type = LRL_AST_Def_Type;
            def->def.kind.type.ident = NULL;
            def->def.kind.type.flags = 0;
            def->def.kind.type.type = NULL;
            def->def.kind.type.typenames = NULL;
            
            if (!parse_typedef(ctx, scope, &token, (LRLASTDefOrStmt*)&def->def)) {
                if (!def->def.kind.type.ident) {
                    /* Remove def it the identifier couldn't be parsed */
                    if (list_first == list_last) list_first = NULL;
                    free(list_last);
                    list_last = saved;
                    if (saved) saved->next = NULL;
                    goto recover;
                }
                if (token->type == LRL_Sym_Semicolon) {
                    token++; /* don't show "extranous semicolon" error also */
                }
            }
            
            try_add_linkname(ctx, def->def.kind.type.ident, linkname);
            continue;
        }
        
        /* Uses statement? */
        if (token->type == LRL_KW_Uses) {
            /*
             * Syntax:
             *
             *   typedef = "uses", identifier, [ "as", identifier ], ";" ;
             */
            if (linkname) {
                lrl_err_token(ctx, LRL_Err_LinknameNotAllowedHere, token);
            }
            
            if (defflags & LRL_LinkageFlags) {
                lrl_err_token(ctx, LRL_Err_LinkageFlagsNotAllowedHere, token);
                defflags = 0;
            }
            
            token++;
            if (token->type != LRL_TT_Ident) {
                lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
                goto recover;
            }
            
            linked_append(&def, &list_first, &list_last);
            def->def.ast_type = LRL_AST_Uses;
            defer_uses(ctx, NULL, &def->def.kind.uses.identref, &token);
            
            if (token->type == LRL_KW_As) {
                token++;
                
                if (token->type == LRL_KW_Here) {
                    lrl_err_token(ctx, LRL_Err_HereNotAllowedHere, token);
                    ident = calloc(1, sizeof(LRLIdent)); /* throwaway */
                } else {
                    ident = parse_ident(ctx, scope, &token,
                                        LRL_Ident_Create, NULL);
                    if (!ident) {
                        ident = calloc(1, sizeof(LRLIdent)); /* throwaway */
                    } else {
                        ident->flags = LRL_IdFl_Link;
                        set_def_node(ident, (LRLASTDefOrStmt*)&def->def);
                    }
                }
            } else {
                ident = scope;
            }
            
            def->def.kind.uses.identref.scope = ident;
            
            
            expected(ctx, &token, LRL_Sym_Semicolon);
            continue;
        }
        
        /* Namespace? */
        if (token->type == LRL_KW_Namespace) {
            /*
             * Syntax:
             *
             *   namespace = "namespace", identifier, "{", def-list, "}";
             */
            token++;
            if (token->type == LRL_KW_Here) {
                lrl_err_token(ctx, LRL_Err_HereNotAllowedHere, token);
            }
            
            if (defflags & LRL_LinkageFlags) {
                lrl_err_token(ctx, LRL_Err_LinkageFlagsNotAllowedHere, token);
                defflags = 0;
            }
            
            ident = parse_ident(ctx, scope, &token, LRL_Ident_Extend, NULL);
            if (!ident) goto recover;
            ident->flags |= LRL_IdFl_HasHere;
            try_add_linkname(ctx, ident, linkname);
            
            if (!expected(ctx, &token, LRL_Sym_LCurly)) goto recover;
            linked_append(&def, &list_first, &list_last);
            def->def.ast_type = LRL_AST_Namespace;
            def->def.kind.namespac = calloc(1, sizeof(LRLASTNamespace));
            def->def.kind.namespac->ident = ident;
            parse_deflist(ctx, ident, &token,
                          &def->def.kind.namespac->list);
            expected(ctx, &token, LRL_Sym_RCurly);
            continue;
        }
        
        /* Interop (e.g. inclusion of C header file) */
        if (token->type == LRL_KW_Interop) {
            /*
             * Syntax:
             *
             *   interop = "interop", identifier, "=",
             *             interop-name-string, interop-config-expr, ";" ;
             */
            if (defflags & LRL_LinkageFlags) {
                lrl_err_token(ctx, LRL_Err_LinkageFlagsNotAllowedHere, token);
                defflags = 0;
            }
            
            token++;
            ident = parse_ident(ctx, scope, &token, LRL_Ident_Extend, NULL);
            if (!ident) goto recover;
            ident->flags |= LRL_IdFl_HasHere | LRL_IdFl_Uninitialized;
            try_add_linkname(ctx, ident, linkname);
            
            if (!expected(ctx, &token, LRL_Op_Assign)) goto recover;
            
            linked_append(&def, &list_first, &list_last);
            def->def.ast_type = LRL_AST_Interop;
            def->def.kind.interop.ident = ident;
            
            def->def.kind.interop.name = token;
            if (!expected(ctx, &token, LRL_TT_String)) {
                def->def.kind.interop.name = NULL;
            }
            
            def->def.kind.interop.options_expr = parse_expr(ctx, scope, &token);
            def->def.kind.interop.options_type = NULL;
            
            def->def.kind.interop.translated = NULL;
            
            set_def_node(ident, (LRLASTDefOrStmt*)&def->def);
            def->def.kind.interop.next = ctx->interop_list;
            ctx->interop_list = &def->def.kind.interop;
            expected(ctx, &token, LRL_Sym_Semicolon);
            continue;
        }
        
        /* Common error */
        if (token->type == LRL_Sym_Semicolon) {
            lrl_err_token(ctx, LRL_Err_ExtraneousSemicolonInDefList, token);
            token++;
            continue;
        }
        
        /* It must be a variable or function */
        
        /*
         * syntax:
         *
         *   data = [ "alias" ], type, identifier, [ "=", expression ], ";" ;
         *   function = [ "alias" ], type, identifier, struct-type,
         *            ( ";" | "{", code, "}" ) ;
         */
        if (token->type == LRL_KW_Alias) {
            defflags |= LRL_DeFl_Alias;
            token++;
        }
        
        type_start = token;
        if (type_start->type == LRL_KW_NoReturn) {
            /* noreturn function */
            token++;
        } else {
            /* Normal data or function definition */
            if (!skip_type(ctx, &token)) goto recover;
        }
        
        ident = parse_ident(ctx, scope, &token, LRL_Ident_Create, NULL);
        if (!ident) goto recover;
        try_add_linkname(ctx, ident, linkname);
        
        if (!token->type) {
            lrl_err_token(ctx, LRL_Err_UnexpectedToken, token);
            break;
        }
        
        noreturn_kw = 0;
        if (type_start->type == LRL_KW_NoReturn) {
            /* noreturn function */
            type = malloc(sizeof(LRLASTType));
            type->ast_type = LRL_AST_Type_Struct;
            type->from = type_start;
            type->to = type_start;
            type->quals = 0;
            type->unique_id = 0;
            type->kind.struc.members = NULL;
            type->kind.struc.scope = NULL;
            type->kind.struc.flags = 0;
            noreturn_kw = 1;
        } else {
            /* Normal data or function definition */
            type = parse_type(ctx, ident, &type_start);
            if (!type) goto recover;
        }
        
        if (type->quals & LRL_Qual_Const) {
            lrl_err_type(ctx, LRL_Err_DataConstIsDefault, type);
        }
        
        /* Read type parameter definitions (if any) */
        if (token->type == LRL_Sym_LSquare) {
            typenames = parse_type_names(ctx, ident, &token);
        }
        
        if (token->type == LRL_Sym_LParen)  {
            /* Function */
            LRLASTType *args_type;
            LRLASTStmt *code;
            const LRLToken *last_token;
            int error = 0;
            
            /* Parse argument list */
            args_type = parse_struct(ctx, ident, &token, 1);
            args_type->quals = LRL_InternQual_NotApplicable;
            
            /* Parse constraints */
            /* TODO */
            
            last_token = token-1;
            
            if (token->type == LRL_Sym_LCurly) {
                /* Parse code block */
                if (defflags & (LRL_DeFl_Import|LRL_DeFl_DeclOnly)) {
                    lrl_err_token(ctx, LRL_Err_ImportWithBody, token);
                }
                code = parse_statement(ctx, ident, NULL, 0, &token);
                if (code) {
                    code->scope.flags |= LRL_IdFl_FunctionBody;
                }
            } else if (token->type == LRL_Sym_Semicolon) {
                /* It's a function prototype */
                code = NULL;
                token++;
            } else {
                /* Error */
                lrl_err_token(ctx, LRL_Err_ExpectedFunctionBody, token);
                code = NULL;
                error = 1;
            }
            
            /* Put in definition list */
            linked_append(&def, &list_first, &list_last);
            def->def.ast_type = LRL_AST_Def_Function;
            def->def.kind.function.flags = defflags;
            def->def.kind.function.ident = ident;
            def->def.kind.function.type.ast_type = LRL_AST_Type_Function;
            def->def.kind.function.type.from = first_token;
            def->def.kind.function.type.to = last_token;
            def->def.kind.function.type.quals = LRL_InternQual_NotApplicable;
            def->def.kind.function.type.kind.function.ret = type;
            def->def.kind.function.type.kind.function.args = args_type;
            def->def.kind.function.type.kind.function.flags = noreturn_kw ?
                LRL_FF_NoReturn : 0;
            def->def.kind.function.typenames = typenames;
            def->def.kind.function.code = code;
            set_def_node(ident, (LRLASTDefOrStmt*)&def->def);
            
            if (error) goto recover;
            else continue;
            
        } else if (token->type == LRL_Op_Assign ||
                   token->type == LRL_Sym_Semicolon) {
            /* Data */
            LRLASTExpr *expr;
            
            if (typenames != NULL) {
                lrl_err_token(ctx, LRL_Err_DataWithTypeParameters, token);
                skip_statement(ctx, &token, LRL_Sym_Semicolon);
                goto recover_datadef;
            }
            
            if (noreturn_kw) {
                lrl_err_token(ctx, LRL_Err_DataWithNoReturn, token);
                skip_statement(ctx, &token, LRL_Sym_Semicolon);
                goto recover_datadef;
            }
            
            if ((defflags & LRL_DeFl_Alias) != 0 &&
                (type->quals & LRL_Qual_Var) != 0) {
                lrl_err_token(ctx, LRL_Err_VarAlias, first_token);
                defflags &= ~LRL_DeFl_Alias;
            }
            
            /* Parse constraints */
            /* TODO */
            
            /* Check initial value */
            if (token->type == LRL_Op_Assign) {
                /* Parse expression */
                if (defflags & (LRL_DeFl_Import|LRL_DeFl_DeclOnly)) {
                    lrl_err_token(ctx, LRL_Err_ImportWithValue, token);
                }
                token++;
                expr = parse_expr(ctx, scope, &token);
            } else {
              recover_datadef:
                /* Use default (undefined) */
                expr = make_undef_expr(token);
            }
            
            /* Put in definition list */
            linked_append(&def, &list_first, &list_last);
            def->def.ast_type = LRL_AST_Def_Data;
            def->def.kind.data.flags = defflags;
            def->def.kind.data.ident = ident;
            def->def.kind.data.type = type;
            def->def.kind.data.value = expr;
            set_def_node(ident, (LRLASTDefOrStmt*)&def->def);
            
            expected(ctx, &token, LRL_Sym_Semicolon);
            continue;
        }
        
        /* Parse error */
        lrl_err_token(ctx, LRL_Err_NotADeclaration, token);
        
        /* Fall through */
      recover:
        skip_statement_skip_paren(ctx, &token);
    }
    
    *tokens = token;
    *parsed = list_first;
}

LRLASTNamespace *lrl_parse(LRLCtx *ctx, LRLIdent *scope,
                           const LRLToken *tokens)
{
    LRLASTNamespace *root;
    
    /* Create root namespace for this file */
    root = malloc(sizeof(LRLASTNamespace));
    root->ident = scope;
    root->list = NULL;
    
    for (;;) {
        parse_deflist(ctx, scope, &tokens, &root->list);
        ctx->has_parsed = 1;
        
        if (!tokens->type) break;
        
        /* Invalid } detected */
        lrl_err_token(ctx, LRL_Err_MismatchedRCurly, tokens);
        tokens++;
    }
    
    return root;
}