pluto-src 0.1.1+0.10.4

Sources of Pluto (Lua 5.4 dialect) and logic to build it.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
/*
** $Id: lparser.c $
** Lua Parser
** See Copyright Notice in lua.h
*/

#define lparser_c
#define LUA_CORE

#include "lprefix.h"


#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>

#include <functional>
#include <string>
#include <vector>

#include "lua.h"
#include "lualib.h" // Pluto::all_preloaded
#include "lapi.h" // api_incr_top
#include "lcode.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "llex.h"
#include "lmem.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lparser.h"
#include "lstate.h"
#include "lstring.h"
#include "lsuggestions.hpp"
#include "ltable.h"

#include "lerrormessage.hpp"

#include "vendor/Soup/soup/version_compare.hpp"



#define hasmultret(k)		((k) == VCALL || (k) == VVARARG)


/*
** Invokes the lua_writestring macro with a std::string.
*/
#define write_std_string(std_string) lua_writestring(std_string.data(), std_string.size())


/* because all strings are unified by the scanner, the parser
   can use pointer equality for string equality */
#define eqstr(a,b)	((a) == (b))


#define luaO_fmt luaO_pushfstring


//#define PLUTO_ALLOW_FUNCTION_INJECTION_REASSIGNMENT


std::string TypeDesc::toString() const {
  std::string str = vtToString(type);
  if (type == VT_FUNC &&
      retn &&
      !retn->empty()) {
    str.push_back('(');
    str.append(retn->toString());
    str.push_back(')');
  }
  return str;
}

enum class BlockType : lu_byte {
  BT_DEFAULT,
  BT_BREAK,
  BT_CONTINUE
};

/*
** nodes for block list (list of active blocks)
*/
typedef struct BlockCnt {
  struct BlockCnt *previous;  /* chain */
  int firstlabel;  /* index of first label in this block */
  int firstgoto;  /* index of first pending goto in this block */
  int nactvar;  /* # active locals outside the block */
  lu_byte upval;  /* true if some variable in the block is an upvalue */
  BlockType type;  /* one of block types */
  lu_byte insidetbc;  /* true if inside the scope of a to-be-closed var. */
  std::vector<TString*> export_symbols{};
  ValType var_overide = VT_NONE;
  unsigned short var_overide_vidx;
} BlockCnt;



/*
** prototypes for recursive non-terminal functions
*/
static void statement (LexState *ls, TypeHint *prop = nullptr);
static void expr (LexState *ls, expdesc *v, TypeHint *prop = nullptr, int flags = 0);


/*
** Throws an exception into Lua, which will promptly close the program.
** This is only called for vital errors, like lexer and/or syntax problems.
*/
static l_noret throwerr (LexState *ls, const char *err, const char *here, int line, const char *note = nullptr) {
  err = luaG_addinfo(ls->L, err, ls->source, line);
  auto msg = new Pluto::ErrorMessage{ ls, HRED "syntax error: " BWHT }; // We'll only throw syntax errors if 'throwerr' is called
  msg->addMsg(err);
  if (ls->t.token == TK_EOS && strstr(err, "near '<eof>'") == nullptr) {  /* for 'incomplete' in REPL */
    msg->addMsg(" near ")
       .addMsg(luaX_token2str(ls, ls->t));
  }
  msg->addSrcLine(line)
     .addGenericHere(here);

  if (note != nullptr) {
    msg->addNote(note);
  }

  msg->finalizeAndThrow();
}

static l_noret throwerr (LexState *ls, const char *err, const char *here, const char *note = nullptr) {
  throwerr(ls, err, here, ls->getLineNumber(), note);
}


// No note.
static void throw_warn (LexState *ls, const char *err, const char *here, int line, WarningType warningType) {
  if (ls->shouldEmitWarning(line, warningType)) {
    auto msg = new Pluto::ErrorMessage{ ls, luaG_addinfo(ls->L, YEL "warning: " BWHT, ls->source, line) };
    msg->addMsg(err)
      .addMsg(" [")
      .addMsg(ls->getWarningConfig().getWarningName(warningType))
      .addMsg("]")
      .addSrcLine(line)
      .addGenericHere(here)
      .finalize();
    if (ls->getWarningConfig().isFatal(warningType)) {
      delete msg;
      luaD_throw(ls->L, LUA_ERRSYNTAX);
    }
    lua_warning(ls->L, msg->content.c_str(), 0);
    delete msg;
    ls->L->top.p -= 2; // Pluto::ErrorMessage::finalize & luaG_addinfo
  }
}

// Note.
static void throw_warn(LexState* ls, const char* err, const char* here, const char* note, int line, WarningType warningType) {
  if (ls->shouldEmitWarning(line, warningType)) {
    auto msg = new Pluto::ErrorMessage{ ls, luaG_addinfo(ls->L, YEL "warning: " BWHT, ls->source, line) };
    msg->addMsg(err)
      .addMsg(" [")
      .addMsg(ls->getWarningConfig().getWarningName(warningType))
      .addMsg("]")
      .addSrcLine(line)
      .addGenericHere(here)
      .addNote(note)
      .finalize();
    if (ls->getWarningConfig().isFatal(warningType)) {
      delete msg;
      luaD_throw(ls->L, LUA_ERRSYNTAX);
    }
    lua_warning(ls->L, msg->content.c_str(), 0);
    delete msg;
    ls->L->top.p -= 2; // Pluto::ErrorMessage::finalize & luaG_addinfo
  }
}

static void throw_warn(LexState *ls, const char* err, const char *here, WarningType warningType) {
  return throw_warn(ls, err, here, ls->getLineNumber(), warningType);
}

static void throw_warn(LexState *ls, const char *err, int line, WarningType warningType) {
  return throw_warn(ls, err, "", line, warningType);
}

#pragma warning(disable : 4068) // unknown pragma
#pragma clang diagnostic ignored "-Wunused-function"
static void throw_warn(LexState* ls, const char* err, WarningType warningType) {
  throw_warn(ls, err, ls->getLineNumber(), warningType);
}


static void disablekeyword (LexState *ls, int token) {
  auto i = ls->tokens.begin();
  if (ls->tidx != -1)
    i += ls->tidx;  /* don't apply retroactively */
  for (; i != ls->tokens.end(); ++i)
    if (i->token == token)
      i->token = TK_NAME;
}

/*
** Responsible for the following:
**   - Non-portable keyword usage. (class, switch, etc)
*/
static void check_for_non_portable_code (LexState *ls) {
  if (ls->t.IsNonCompatible() && !ls->t.IsOverridable()) {
    if (ls->getKeywordState(ls->t.token) == KS_ENABLED_BY_PLUTO_UNINFORMED) {
      const auto next = luaX_lookahead(ls);
      if (next == '=' || next == '.' || next == ':' || next == '['  /* attempting to create or use a global? */
#ifdef PLUTO_PARANOID_KEYWORD_DETECTION
          || next == '(' || next == '{' || next == TK_STRING
#endif
        ) {
        disablekeyword(ls, ls->t.token);
        ls->uninformed_reserved.emplace(ls->t.token, ls->getLineNumber());
        ls->setKeywordState(ls->t.token, KS_DISABLED_BY_PLUTO_INFORMED);
        luaX_setpos(ls, luaX_getpos(ls));  /* update ls->t */
      }
      else
        ls->setKeywordState(ls->t.token, KS_ENABLED_BY_PLUTO_INFORMED);
    }
    if (ls->getKeywordState(ls->t.token) == KS_ENABLED_BY_PLUTO_INFORMED || ls->getKeywordState(ls->t.token) == KS_ENABLED_BY_ENV) {  /* enabled by a means other than 'pluto_use'? */
      throw_warn(ls, "non-portable keyword usage", luaO_fmt(ls->L, "use 'pluto_%s' instead, or 'pluto_use' this keyword: https://pluto.do/compat", luaX_token2str_noq(ls, ls->t)), WT_NON_PORTABLE_CODE);
      ls->L->top.p--;
    }
  }
}


/*
** This function will throw an exception and terminate the program.
*/
static l_noret error_expected (LexState *ls, int token) {
  switch (token) {
    case TK_ARROW: {
      if (luaX_lookahead(ls) == '>') {
        throwerr(ls,
          "impromper lambda definition",
          "expected '->' arrow syntax for lambda expression.");
      }
      goto _default; // Run-through default case, no more work to be done.
    }
    case TK_IN: {
      throwerr(ls,
        "expected 'in' to delimit loop iterator.", "expected 'in' symbol.");
    }
    case TK_DO: {
      throwerr(ls,
        "expected 'do' to establish block.", "you need to append this with the 'do' symbol.");
    }
    case TK_END: {
      throwerr(ls,
        "expected 'end' to terminate block.", "expected 'end' symbol after or on this line.");
    }
    case TK_NAME: {
      throwerr(ls,
        "expected an identifier.", "this needs a name.");
    }
    case TK_PCONTINUE: {
      throwerr(ls,
        "expected 'continue' inside a loop.", "this is not within a loop.");
    }
    default: {
      _default:
      throwerr(ls, luaO_fmt(ls->L, "%s expected near %s", luaX_token2str(ls, token), luaX_token2str(ls, ls->t)), "this is invalid syntax.");
    }
  }
}


static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
  lua_State *L = fs->ls->L;
  const char *msg;
  int line = fs->f->linedefined;
  const char *where = (line == 0)
                      ? "main function"
                      : luaO_pushfstring(L, "function at line %d", line);
  msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
                             what, limit, where);
  luaX_syntaxerror(fs->ls, msg);
}


static void checklimit (FuncState *fs, int v, int l, const char *what) {
  if (v > l) errorlimit(fs, l, what);
}


/*
** Test whether next token is 'c'; if so, skip it.
*/
static int testnext (LexState *ls, int c) {
  if (ls->t.token == c) {
    luaX_next(ls);
    return 1;
  }
  else return 0;
}


// Test the next token to see if it's either 'token1' or 'token2'.
static bool testnext2 (LexState *ls, int token1, int token2) {
  return testnext(ls, token1) || testnext(ls, token2);
}


/*
** Check that next token is 'c'.
*/
static void check (LexState *ls, int c) {
#ifdef PLUTO_PARSER_SUGGESTIONS
  if (ls->shouldSuggest()) {
    SuggestionsState ss(ls);
    ss.push("stat", luaX_token2str_noq(ls, c));
  }
#endif
  if (ls->t.token != c) {
    error_expected(ls, c);
  }
}


/*
** Check that next token is 'c' and skip it.
*/
static void checknext (LexState *ls, int c) {
  check(ls, c);
  luaX_next(ls);
}


#define check_condition(ls,c,msg)	{ if (!(c)) luaX_syntaxerror(ls, msg); }


/*
** Check that next token is 'what' and skip it. In case of error,
** raise an error that the expected 'what' should match a 'who'
** in line 'where' (if that is not the current line).
*/
static void check_match (LexState *ls, int what, int who, int where, const char* note = nullptr) {
  if (l_unlikely(!testnext(ls, what))) {
    if (where == ls->getLineNumber())  /* all in the same line? */
      error_expected(ls, what);  /* do not need a complex message */
    else {
      if (what == TK_END) {
        if (ls->else_if)
          throw_warn(ls, "'else if' is not the same as 'elseif' in Lua/Pluto", "did you mean 'elseif'?", ls->else_if, WT_POSSIBLE_TYPO);
        const char *msg;
        if (who == TK_ARROW) {
          msg = luaO_fmt(ls->L, "missing 'end' to terminate lambda starting on line %d", where);
        }
        else {
          msg = luaO_fmt(ls->L, "missing 'end' to terminate %s on line %d", luaX_token2str(ls, who), where);
        }
        throwerr(ls, msg, "this was the last statement.", ls->getLineNumberOfLastNonEmptyLine());
      }
      else {
        auto err = new Pluto::ErrorMessage{ ls, RED "syntax error: " BWHT };
        err->addMsg(luaX_token2str(ls, what))
          .addMsg(" expected (to close ")
          .addMsg(luaX_token2str(ls, who))
          .addMsg(" on line ")
          .addMsg(luaO_fmt(ls->L, "%d", where))
          .addMsg(")")
          .addSrcLine(ls->getLineNumberOfLastNonEmptyLine())
          .addGenericHere();

        if (note != nullptr) {
          err->addNote(note);
        }

        err->finalizeAndThrow();
      }
    }
  }
}


enum NameFlags {
  N_RESERVED_NON_VALUE = (1 << 0),
  N_RESERVED = (1 << 1),
  N_OVERRIDABLE = (1 << 2),
};

[[nodiscard]] static bool isnametkn (LexState *ls, int flags = 0) {
  return ls->t.token == TK_NAME || ls->t.IsNarrow()
      || ((flags & N_RESERVED_NON_VALUE) && ls->t.IsReservedNonValue())
      || ((flags & N_RESERVED) && ls->t.IsReserved())
      || ((flags & N_OVERRIDABLE) && ls->t.IsOverridable())
      ;
}

[[nodiscard]] static int find_non_compat_tkn_by_name (LexState *ls, const char *str) {
  for (int i = FIRST_NON_COMPAT; i != END_NON_COMPAT; ++i) {
    if (strcmp(luaX_token2str_noq(ls, i), str) == 0) {
      return i;
    }
  }
  return 0;
}

static bool trydisablekeyword (LexState *ls) {
  if (ls->getKeywordState(ls->t.token) == KS_ENABLED_BY_PLUTO_UNINFORMED) {
    disablekeyword(ls, ls->t.token);
    ls->uninformed_reserved.emplace(ls->t.token, ls->getLineNumber());
    ls->setKeywordState(ls->t.token, KS_DISABLED_BY_PLUTO_INFORMED);
    luaX_setpos(ls, luaX_getpos(ls));  /* update ls->t */
    return true;
  }
  return false;
}

static TString *str_checkname (LexState *ls, int flags = 0) {
#ifdef PLUTO_PARSER_SUGGESTIONS
  if (ls->shouldSuggest()) {
    SuggestionsState ss(ls);
    ss.pushLocals();
  }
#endif
  if (!isnametkn(ls, flags)) {
    if (ls->t.IsNonCompatible()) {
      if (trydisablekeyword(ls))  /* see if we can fix it */
        return str_checkname(ls, flags);  /* then try again */
      throwerr(ls, luaO_fmt(ls->L, "expected a name, found %s", luaX_token2str(ls, ls->t)), luaO_fmt(ls->L, "%s has a different meaning in Pluto, but you can disable this: https://pluto.do/compat", luaX_token2str(ls, ls->t)));
    }
    error_expected(ls, TK_NAME);
  }
  TString *ts = ls->t.seminfo.ts;
  lua_assert(ts != nullptr);
  if (!(flags & N_RESERVED) && !(flags & N_RESERVED_NON_VALUE)) {
    if (auto t = find_non_compat_tkn_by_name(ls, getstr(ts)); t != 0 && t != TK_PARENT) {
      if (ls->getKeywordState(t) != KS_DISABLED_BY_SCRIPTER) {
        throw_warn(
          ls,
          luaO_fmt(ls->L, "'%s' is a non-portable name", getstr(ts)),
          "use a different name, or use 'pluto_use' to disable this keyword: https://pluto.do/compat",
          WT_NON_PORTABLE_NAME
        );
        ls->L->top.p--;
      }
    }
  }
  luaX_next(ls);
  return ts;
}


static void init_exp (expdesc *e, expkind k, int i) {
  e->f = e->t = NO_JUMP;
  e->k = k;
  e->u.info = e->u.pc = e->u.reg = i;
  e->code_primitive = VT_NONE;
}


static void codestring (expdesc *e, TString *s) {
  e->f = e->t = NO_JUMP;
  e->k = VKSTR;
  e->u.strval = s;
  e->code_primitive = VT_STR;
}


static void codename (LexState *ls, expdesc *e, int flags = 0) {
  codestring(e, str_checkname(ls, flags));
}


/*
** Register a new local variable in the active 'Proto' (for debug
** information).
*/
static int registerlocalvar (LexState *ls, FuncState *fs, TString *varname) {
  Proto *f = fs->f;
  int oldsize = f->sizelocvars;
  luaM_growvector(ls->L, f->locvars, fs->ndebugvars, f->sizelocvars,
                  LocVar, SHRT_MAX, "local variables");
  while (oldsize < f->sizelocvars)
    f->locvars[oldsize++].varname = NULL;
  f->locvars[fs->ndebugvars].varname = varname;
  f->locvars[fs->ndebugvars].startpc = fs->pc;
  luaC_objbarrier(ls->L, f, varname);
  return fs->ndebugvars++;
}


#define new_localvarliteral(ls,v) \
    new_localvar(ls,  \
      luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char)) - 1));


[[nodiscard]] static TypeHint* new_typehint (LexState *ls) {
  return ::new (ls->parse_time_allocations.emplace_back(malloc(sizeof(TypeHint)))) TypeHint();
}


[[nodiscard]] static TypeHint gettypehint (LexState *ls, bool funcret = false) {
  /* TYPEHINT -> [':' TYPEDESC { '|' TYPEDESC } ] */
  TypeHint th;
  if (testnext(ls, ':')) {
    if (testnext(ls, '?'))
      th.emplaceTypeDesc(VT_NIL);
    do {
      TString *ts = str_checkname(ls, N_RESERVED);
      const char *tname = getstr(ts);
      if (strcmp(tname, "number") == 0)
        th.emplaceTypeDesc(VT_NUMBER);
      else if (strcmp(tname, "int") == 0)
        th.emplaceTypeDesc(VT_INT);
      else if (strcmp(tname, "float") == 0)
        th.emplaceTypeDesc(VT_FLT);
      else if (strcmp(tname, "table") == 0)
        th.emplaceTypeDesc(VT_TABLE);
      else if (strcmp(tname, "string") == 0)
        th.emplaceTypeDesc(VT_STR);
      else if (strcmp(tname, "boolean") == 0 || strcmp(tname, "bool") == 0)
        th.emplaceTypeDesc(VT_BOOL);
      else if (strcmp(tname, "function") == 0)
        th.emplaceTypeDesc(VT_FUNC);
      else if (strcmp(tname, "void") == 0) {
        if (funcret) {
          if (!th.empty()) { /* already had a hinted type? */
            luaX_prev(ls);
            throw_warn(ls, "'void' must be the only return type if used", "invalid type hint", WT_TYPE_MISMATCH);
            luaX_next(ls);
          }
          th.emplaceTypeDesc(VT_VOID);
          if (testnext(ls, '|'))
            throw_warn(ls, "'void' must be the only return type if used", "invalid type hint", WT_TYPE_MISMATCH);
          break; /* no further type hints allowed */
        }
        throw_warn(ls, "'void' is not a valid type hint in this context", "invalid type hint", WT_TYPE_MISMATCH);
      }
      else if (strcmp(tname, "userdata") != 0) {
        luaX_prev(ls);
        throw_warn(ls, luaO_fmt(ls->L, "'%s' is not a type known to the parser", tname), "unknown type hint", WT_TYPE_MISMATCH);
        ls->L->top.p--;
        luaX_next(ls);
      }
    } while (testnext(ls, '|'));
    if (!th.contains(VT_NIL) && testnext(ls, '?'))
      th.emplaceTypeDesc(VT_NIL);
  }
  return th;
}


/*
** Propgates type from 'e' into 't'.
*/
static void exp_propagate(LexState* ls, const expdesc& e, TypeHint& t) noexcept {
  if (e.k == VLOCAL) {
    if (ls->fs->bl->var_overide != VT_NONE && ls->fs->bl->var_overide_vidx == e.u.var.vidx) {
      t.merge(ls->fs->bl->var_overide);
    }
    else {
      t.merge(*getlocalvardesc(ls->fs, e.u.var.vidx)->vd.prop);
    }
  }
  else if (e.k == VCONST) {
    TValue* val = &ls->dyd->actvar.arr[e.u.info].k;
    switch (ttype(val))
    {
    case LUA_TNIL: t.emplaceTypeDesc(VT_NIL); break;
    case LUA_TBOOLEAN: t.emplaceTypeDesc(VT_BOOL); break;
    case LUA_TNUMBER: t.emplaceTypeDesc((ttypetag(val) == LUA_VNUMINT) ? VT_INT : VT_FLT); break;
    case LUA_TSTRING: t.emplaceTypeDesc(VT_STR); break;
    case LUA_TTABLE: t.emplaceTypeDesc(VT_TABLE); break;
    case LUA_TFUNCTION: t.emplaceTypeDesc(VT_FUNC); break;
    }
  }
}


static void process_assign (LexState *ls, int vidx, const TypeHint& t, int line) {
  Vardesc *var = getlocalvardesc(ls->fs, vidx);
  auto hinted = !var->vd.hint->empty();
  auto knownvalue = !t.empty();
  auto incompatible = !var->vd.hint->isCompatibleWith(t);
  if (hinted && knownvalue && incompatible) {
    const auto hint = var->vd.hint->toString();
    std::string err = var->vd.name->toCpp();
    err.insert(0, "'");
    err.append("' type-hinted as '" + hint);
    err.append("', but provided with ");
    err.append(t.toString());
    err.append(" value.");
    if (t.toPrimitive() == VT_NIL) {  /* Specialize warnings for nullable state incompatibility. */
      throw_warn(ls, "variable type mismatch", err.c_str(), luaO_fmt(ls->L, "try a nilable type hint: '?%s'", hint.c_str()), line, WT_TYPE_MISMATCH);
      ls->L->top.p--; // luaO_fmt
    }
    else {  /* Throw a generic mismatch warning. */
      throw_warn(ls, "variable type mismatch", err.c_str(), line, WT_TYPE_MISMATCH);
    }
  }
  var->vd.prop->merge(t); /* propagate type */
  if (ls->fs->bl->var_overide != VT_NONE && ls->fs->bl->var_overide_vidx == vidx) {
    ls->fs->bl->var_overide = t.toPrimitive();
  }
}


static TypeHint& get_global_prop(LexState* ls, const TString* name) {
  if (auto e = ls->global_props.find(name); e != ls->global_props.end()) {
    return *reinterpret_cast<TypeHint*>(e->second);
  }
  auto th = new_typehint(ls);
  ls->global_props.emplace(name, th);
  return *th;
}


/*
** Convert 'nvar', a compiler index level, to its corresponding
** register. For that, search for the highest variable below that level
** that is in a register and uses its register index ('ridx') plus one.
*/
static int reglevel (FuncState *fs, int nvar) {
  while (nvar-- > 0) {
    Vardesc *vd = getlocalvardesc(fs, nvar);  /* get previous variable */
    if (vd->vd.kind != RDKCTC && vd->vd.kind != RDKENUM)  /* is in a register? */
      return vd->vd.ridx + 1;
  }
  return 0;  /* no variables in registers */
}


/*
** Return the number of variables in the register stack for the given
** function.
*/
int luaY_nvarstack (FuncState *fs) {
  return reglevel(fs, fs->nactvar);
}


/*
** Get the debug-information entry for current variable 'vidx'.
*/
static LocVar *localdebuginfo (FuncState *fs, int vidx) {
  Vardesc *vd = getlocalvardesc(fs, vidx);
  if (vd->vd.kind == RDKCTC || vd->vd.kind == RDKENUM)
    return NULL;  /* no debug info. for constants [Pluto] and named enums */
  else {
    int idx = vd->vd.pidx;
    lua_assert(idx < fs->ndebugvars);
    return &fs->f->locvars[idx];
  }
}


/*
** Arbitrary selection. Based on probability to cause a confusing error (i.e, something that can be more deep than 'attempt to call a string value')
** For example, shadowing 'arg' with a function makes an obvious error. But, shadowing with string or table can cause confusing bugs because they can both be indexed and won't raise an error.
*/
static const char* const common_global_names[] = { PLUTO_COMMON_GLOBAL_NAMES };


static int searchvar (FuncState *fs, TString *n, expdesc *var);
static void checkforshadowing (LexState *ls, FuncState *fs, TString *name, int line, bool check_globals = true, bool check_locals = true) {
  std::string n = name->toCpp();
  if (n == "(for state)" || n == "(switch control value)" || n == "(try results)")
    return;
  FuncState *current_fs = fs;
  while (current_fs != nullptr) {
    if (check_locals) {
      expdesc var;
      if (searchvar(current_fs, name, &var) != -1) {
        Vardesc* desc = getlocalvardesc(current_fs, var.u.var.vidx);
        LocVar* local = localdebuginfo(current_fs, var.u.var.vidx);
        if (local && local->varname == name) { // Got a match.
          throw_warn(ls,
            "duplicate local declaration",
              luaO_fmt(ls->L, "this shadows the initial declaration of '%s' on line %d.", getstr(name), desc->vd.line), line, WT_VAR_SHADOW);
          ls->L->top.p--; /* pop result of luaO_fmt */
          return;
        }
      }
    }
    if (check_globals) {
      for (const auto& global_name : common_global_names) {
        if (n == global_name) {
          throw_warn(ls,
            "duplicate global declaration",
              luaO_fmt(ls->L, "this shadows the initial global definition of '%s'", getstr(name)), line, WT_GLOBAL_SHADOW);
          ls->L->top.p--;
          return;
        }
      }
    }
    current_fs = current_fs->prev;
  }
}


static void checkforshadowing (LexState *ls, FuncState *fs, const std::unordered_set<TString*>& names, int line) {
  for (auto variable_name : names) {
    checkforshadowing(ls, fs, variable_name, line, true, false);
  }
}


/*
** Create a new local variable with the given 'name'. Return its index
** in the function.
*/
static int new_localvar (LexState *ls, TString *name, int line, TypeHint hint = {}, bool check_globals = true) {
  lua_State *L = ls->L;
  FuncState *fs = ls->fs;
  Dyndata *dyd = ls->dyd;
  Vardesc *var;
  checkforshadowing(ls, fs, name, line, check_globals, true);
  luaM_growvector(L, dyd->actvar.arr, dyd->actvar.n + 1,
                  dyd->actvar.size, Vardesc, SHRT_MAX, "local variables");
  var = &dyd->actvar.arr[dyd->actvar.n++];
  var->vd.kind = VDKREG;  /* default */
  var->vd.hint = new_typehint(ls);
  var->vd.prop = new_typehint(ls);
  if (!hint.empty())
    *var->vd.hint = std::move(hint);
  var->vd.name = name;
  var->vd.line = line;
  return dyd->actvar.n - 1 - fs->firstlocal;
}

static int new_localvar (LexState *ls, TString *name, TypeHint hint = {}) {
  return new_localvar(ls, name, ls->getLineNumber(), std::move(hint));
}


/*
** Create an expression representing variable 'vidx'
*/
static void init_var (FuncState *fs, expdesc *e, int vidx) {
  e->f = e->t = NO_JUMP;
  e->k = VLOCAL;
  e->u.var.vidx = vidx;
  e->u.var.ridx = getlocalvardesc(fs, vidx)->vd.ridx;
}


/*
** Raises an error if variable described by 'e' is read only
*/
static void check_readonly (LexState *ls, expdesc *e) {
  FuncState *fs = ls->fs;
  TString *varname = NULL;  /* to be set if variable is const */
  switch (e->k) {
    case VCONST: {
      varname = ls->dyd->actvar.arr[e->u.info].vd.name;
      break;
    }
    case VLOCAL: {
      Vardesc *vardesc = getlocalvardesc(fs, e->u.var.vidx);
      if (vardesc->vd.kind != VDKREG)  /* not a regular variable? */
        varname = vardesc->vd.name;
      break;
    }
    case VUPVAL: {
      Upvaldesc *up = &fs->f->upvalues[e->u.info];
      if (up->kind != VDKREG)
        varname = up->name;
      break;
    }
    default:
      return;  /* other cases cannot be read-only */
  }
  if (varname) {
    const char *msg = luaO_fmt(ls->L, "attempt to reassign constant '%s'", getstr(varname));
    const char *here = "this variable is constant, and cannot be reassigned.";
    throwerr(ls, luaO_fmt(ls->L, msg, getstr(varname)), here);
  }
}


/*
** Start the scope for the last 'nvars' created variables.
*/
static void adjustlocalvars (LexState *ls, int nvars) {
  FuncState *fs = ls->fs;
  int reglevel = luaY_nvarstack(fs);
  int i;
  for (i = 0; i < nvars; i++) {
    int vidx = fs->nactvar++;
    Vardesc *var = getlocalvardesc(fs, vidx);
    var->vd.ridx = reglevel++;
    var->vd.pidx = registerlocalvar(ls, fs, var->vd.name);
  }
}


/*
** Close the scope for all variables up to level 'tolevel'.
** (debug info.)
*/
static void removevars (FuncState *fs, int tolevel) {
  fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
  while (fs->nactvar > tolevel) {
    LocVar *var = localdebuginfo(fs, --fs->nactvar);
    if (var)  /* does it have debug information? */
      var->endpc = fs->pc;
  }
}


/*
** Search the upvalues of the function 'fs' for one
** with the given 'name'.
*/
static int searchupvalue (FuncState *fs, TString *name) {
  int i;
  Upvaldesc *up = fs->f->upvalues;
  for (i = 0; i < fs->nups; i++) {
    if (eqstr(up[i].name, name)) return i;
  }
  return -1;  /* not found */
}


static Upvaldesc *allocupvalue (FuncState *fs) {
  Proto *f = fs->f;
  int oldsize = f->sizeupvalues;
  checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
  luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
                  Upvaldesc, MAXUPVAL, "upvalues");
  while (oldsize < f->sizeupvalues)
    f->upvalues[oldsize++].name = NULL;
  return &f->upvalues[fs->nups++];
}


static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
  Upvaldesc *up = allocupvalue(fs);
  FuncState *prev = fs->prev;
  if (v->k == VLOCAL) {
    up->instack = 1;
    up->idx = v->u.var.ridx;
    up->kind = getlocalvardesc(prev, v->u.var.vidx)->vd.kind;
    lua_assert(eqstr(name, getlocalvardesc(prev, v->u.var.vidx)->vd.name));
  }
  else {
    lua_assert(v->k == VUPVAL);
    up->instack = 0;
    up->idx = cast_byte(v->u.info);
    up->kind = prev->f->upvalues[v->u.info].kind;
    lua_assert(eqstr(name, prev->f->upvalues[v->u.info].name));
  }
  up->name = name;
  luaC_objbarrier(fs->ls->L, fs->f, name);
  return fs->nups - 1;
}


/*
** Look for an active local variable with the name 'n' in the
** function 'fs'. If found, initialize 'var' with it and return
** its expression kind; otherwise return -1.
*/
static int searchvar (FuncState *fs, TString *n, expdesc *var) {
  int i;
  for (i = fs->nactvar - 1; i >= 0; i--) {
    Vardesc *vd = getlocalvardesc(fs, i);
    if (eqstr(n, vd->vd.name)) {  /* found? */
      if (vd->vd.kind == RDKCTC)  /* compile-time constant? */
        init_exp(var, VCONST, fs->firstlocal + i);
      else if (vd->vd.kind == RDKENUM) {
        init_exp(var, VENUM, 0);
        var->u.ival = ivalue(&vd->k);
      }
      else  /* real variable */
        init_var(fs, var, i);
      return var->k;
    }
  }
  return -1;  /* not found */
}


/*
** Mark block where variable at given level was defined
** (to emit close instructions later).
*/
static void markupval (FuncState *fs, int level) {
  BlockCnt *bl = fs->bl;
  while (bl->nactvar > level)
    bl = bl->previous;
  bl->upval = 1;
  fs->needclose = 1;
}


/*
** Mark that current block has a to-be-closed variable.
*/
static void marktobeclosed (FuncState *fs) {
  BlockCnt *bl = fs->bl;
  bl->upval = 1;
  bl->insidetbc = 1;
  fs->needclose = 1;
}


/*
** Find a variable with the given name 'n'. If it is an upvalue, add
** this upvalue into all intermediate functions. If it is a global, set
** 'var' as 'void' as a flag.
*/
static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
  if (fs == NULL)  /* no more levels? */
    init_exp(var, VVOID, 0);  /* default is global */
  else {
    int v = searchvar(fs, n, var);  /* look up locals at current level */
    if (v >= 0) {  /* found? */
      if (v == VLOCAL && !base)
        markupval(fs, var->u.var.vidx);  /* local will be used as an upval */
    }
    else {  /* not found as local at current level; try upvalues */
      int idx = searchupvalue(fs, n);  /* try existing upvalues */
      if (idx < 0) {  /* not found? */
        singlevaraux(fs->prev, n, var, 0);  /* try upper levels */
        if (var->k == VLOCAL || var->k == VUPVAL)  /* local or upvalue? */
          idx  = newupvalue(fs, n, var);  /* will be a new upvalue */
        else  /* it is a global or a constant */
          return;  /* don't need to do anything at this level */
      }
      init_exp(var, VUPVAL, idx);  /* new or old upvalue */
    }
  }
}


inline int gett(LexState *ls) {
  return ls->t.token;
}


/*
** Adjust the number of results from an expression list 'e' with 'nexps'
** expressions to 'nvars' values.
*/
static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
  FuncState *fs = ls->fs;
  int needed = nvars - nexps;  /* extra values needed */
  if (hasmultret(e->k) || e->k == VSAFECALL) {  /* last expression has multiple returns? */
    int extra = needed + 1;  /* discount last expression itself */
    if (extra < 0)
      extra = 0;
    luaK_setreturns(fs, e, extra);  /* last exp. provides the difference */
  }
  else {
    if (e->k != VVOID)  /* at least one expression? */
      luaK_exp2nextreg(fs, e);  /* close last expression */
    if (needed > 0)  /* missing values? */
      luaK_nil(fs, fs->freereg, needed);  /* complete with nils */
  }
  if (needed > 0)
    luaK_reserveregs(fs, needed);  /* registers for extra values */
  else  /* adding 'needed' is actually a subtraction */
    fs->freereg += needed;  /* remove extra values */
}


/*
** Find a variable with the given name 'n', handling global variables
** too.
*/
static void singlevarinner (LexState *ls, TString *varname, expdesc *var, bool localonly = false) {
  FuncState *fs = ls->fs;
  singlevaraux(fs, varname, var, 1);
  if (var->k == VVOID && !localonly) {  /* global name? */
    expdesc key;
    singlevaraux(fs, ls->envn, var, 1);  /* get environment variable */
    lua_assert(var->k != VVOID);  /* this one must exist */
    luaK_exp2anyregup(fs, var);  /* but could be a constant */
    codestring(&key, varname);  /* key is variable name */
    luaK_indexed(fs, var, &key);  /* env[varname] */
  }
}

static void singlevar (LexState *ls, expdesc *var, TString *varname, bool localonly = false) {
  singlevarinner(ls, varname, var, localonly);
}

static void singlevar (LexState *ls, expdesc *var) {
  TString *varname = str_checkname(ls);
  singlevar(ls, var, varname);
}


#define enterlevel(ls)	luaE_incCstack(ls->L)


#define leavelevel(ls) ((ls)->L->nCcalls--)


/*
** Generates an error that a goto jumps into the scope of some
** local variable.
*/
static l_noret jumpscopeerror (LexState *ls, Labeldesc *gt) {
  const char *varname = getstr(getlocalvardesc(ls->fs, gt->nactvar)->vd.name);
  const char *msg;
  if (!gt->special) {
    msg = luaO_pushfstring(ls->L, "<goto %s> at line %d jumps into the scope of local '%s'", getstr((TString*)gt->name), gt->line, varname);
  } else {
    BlockCnt* bt = (BlockCnt*)gt->name;
    const char *type = bt->type == BlockType::BT_BREAK ? "break" : bt->type == BlockType::BT_CONTINUE ? "continue" : "?";
    msg = luaO_pushfstring(ls->L, "%s at line %d jumps into the scope of local '%s'", type, gt->line, varname);
  }
  luaK_semerror(ls, msg);  /* raise the error */
}

static bool samelabelnames(Labeldesc* l1, Labeldesc* l2) {
  return l1->special==l2->special && (l1->special ? l1->name == l2->name : eqstr((TString*)l1->name, (TString*)l2->name));
}

/*
** Solves the goto at index 'g' to given 'label' and removes it
** from the list of pending gotos.
** If it jumps into the scope of some variable, raises an error.
*/
static void solvegoto (LexState *ls, int g, Labeldesc *label) {
  int i;
  Labellist *gl = &ls->dyd->gt;  /* list of gotos */
  Labeldesc *gt = &gl->arr[g];  /* goto to be resolved */
  lua_assert(samelabelnames(gt, label));
  if (l_unlikely(gt->nactvar < label->nactvar))  /* enter some scope? */
    jumpscopeerror(ls, gt);
  luaK_patchlist(ls->fs, gt->pc, label->pc);
  for (i = g; i < gl->n - 1; i++)  /* remove goto from pending list */
    gl->arr[i] = gl->arr[i + 1];
  gl->n--;
}


/*
** Search for an active label with the given name.
*/
static Labeldesc *findlabel (LexState *ls, TString *name) {
  int i;
  Dyndata *dyd = ls->dyd;
  /* check labels in current function for a match */
  for (i = ls->fs->firstlabel; i < dyd->label.n; i++) {
    Labeldesc *lb = &dyd->label.arr[i];
    if (!lb->special && eqstr((TString*)lb->name, name))  /* correct label? */
      return lb;
  }
  return NULL;  /* label not found */
}


/*
** Adds a new label/goto in the corresponding list.
*/
static int newlabelentry (LexState *ls, Labellist *l, void *name,
                          int line, int pc, bool special) {
  int n = l->n;
  luaM_growvector(ls->L, l->arr, n, l->size,
                  Labeldesc, SHRT_MAX, "labels/gotos");
  l->arr[n].name = name;
  l->arr[n].line = line;
  l->arr[n].nactvar = ls->fs->nactvar;
  l->arr[n].close = 0;
  l->arr[n].special = special;
  l->arr[n].pc = pc;
  l->n = n + 1;
  return n;
}


static int newgotoentry (LexState *ls, void *name, int line, int pc, bool special) {
  return newlabelentry(ls, &ls->dyd->gt, name, line, pc, special);
}


/*
** Solves forward jumps. Check whether new label 'lb' matches any
** pending gotos in current block and solves them. Return true
** if any of the gotos need to close upvalues.
*/
static int solvegotos (LexState *ls, Labeldesc *lb) {
  Labellist *gl = &ls->dyd->gt;
  int i = ls->fs->bl->firstgoto;
  int needsclose = 0;
  while (i < gl->n) {
    if (samelabelnames(&gl->arr[i], lb)) {
      needsclose |= gl->arr[i].close;
      solvegoto(ls, i, lb);  /* will remove 'i' from the list */
    }
    else
      i++;
  }
  return needsclose;
}


/*
** Create a new label with the given 'name' at the given 'line'.
** 'last' tells whether label is the last non-op statement in its
** block. Solves all pending gotos to this new label and adds
** a close instruction if necessary.
** Returns true iff it added a close instruction.
*/
static int createlabel (LexState *ls, void *name, int line,
                        int last, bool special) {
  FuncState *fs = ls->fs;
  Labellist *ll = &ls->dyd->label;
  int l = newlabelentry(ls, ll, name, line, luaK_getlabel(fs), special);
  if (last) {  /* label is last no-op statement in the block? */
    /* assume that locals are already out of scope */
    ll->arr[l].nactvar = fs->bl->nactvar;
  }
  if (solvegotos(ls, &ll->arr[l])) {  /* need close? */
    luaK_codeABC(fs, OP_CLOSE, luaY_nvarstack(fs), 0, 0);
    return 1;
  }
  return 0;
}


/*
** Adjust pending gotos to outer level of a block.
*/
static void movegotosout (FuncState *fs, BlockCnt *bl) {
  int i;
  Labellist *gl = &fs->ls->dyd->gt;
  /* correct pending gotos to current block */
  for (i = bl->firstgoto; i < gl->n; i++) {  /* for each pending goto */
    Labeldesc *gt = &gl->arr[i];
    /* leaving a variable scope? */
    if (reglevel(fs, gt->nactvar) > reglevel(fs, bl->nactvar))
      gt->close |= bl->upval;  /* jump may need a close */
    gt->nactvar = bl->nactvar;  /* update goto level */
  }
}


static void enterblock (FuncState *fs, BlockCnt *bl, BlockType type) {
  bl->type = type;
  bl->nactvar = fs->nactvar;
  bl->firstlabel = fs->ls->dyd->label.n;
  bl->firstgoto = fs->ls->dyd->gt.n;
  bl->upval = 0;
  bl->insidetbc = static_cast<lu_byte>(fs->bl != NULL && fs->bl->insidetbc);
  bl->previous = fs->bl;
  fs->bl = bl;
  lua_assert(fs->freereg == luaY_nvarstack(fs));
}


/*
** generates an error for an undefined 'goto'.
*/
static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
  lua_assert(!gt->special); // Should be checked by lbreak & continuestat before creating the label
  const char *msg = "no visible label '%s' for <goto> at line %d";
  msg = luaO_pushfstring(ls->L, msg, getstr((TString*)gt->name), gt->line);
  ls->setLineNumber(gt->line);
  luaK_semerror(ls, msg);
}


static void leaveblock (FuncState *fs) {
  BlockCnt *bl = fs->bl;
  LexState *ls = fs->ls;
  int hasclose = 0;
  int stklevel = reglevel(fs, bl->nactvar);  /* level outside the block */
  removevars(fs, bl->nactvar);  /* remove block locals */
  lua_assert(bl->nactvar == fs->nactvar);  /* back to level on entry */
  if (bl->type != BlockType::BT_DEFAULT)  /* has to fix pending breaks / continues? */
    hasclose = createlabel(ls, bl, 0, 0, true);
  if (!hasclose && bl->previous && bl->upval)  /* still need a 'close'? */
    luaK_codeABC(fs, OP_CLOSE, stklevel, 0, 0);
  fs->freereg = stklevel;  /* free registers */
  ls->dyd->label.n = bl->firstlabel;  /* remove local labels */
  fs->bl = bl->previous;  /* current block now is previous one */
  if (bl->previous)  /* was it a nested block? */
    movegotosout(fs, bl);  /* update pending gotos to enclosing block */
  else {
    if (bl->firstgoto < ls->dyd->gt.n)  /* still pending gotos? */
      undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]);  /* error */
  }
  ls->laststat.token = TK_EOS;  /* Prevent unreachable code warnings on blocks that don't explicitly check for TK_END. */
}


/*
** adds a new prototype into list of prototypes
*/
static Proto *addprototype (LexState *ls) {
  Proto *clp;
  lua_State *L = ls->L;
  FuncState *fs = ls->fs;
  Proto *f = fs->f;  /* prototype of current function */
  if (fs->np >= f->sizep) {
    int oldsize = f->sizep;
    luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions");
    while (oldsize < f->sizep)
      f->p[oldsize++] = NULL;
  }
  f->p[fs->np++] = clp = luaF_newproto(L);
  luaC_objbarrier(L, f, clp);
  return clp;
}


/*
** codes instruction to create new closure in parent function.
** The OP_CLOSURE instruction uses the last available register,
** so that, if it invokes the GC, the GC knows which registers
** are in use at that time.

*/
static void codeclosure (LexState *ls, expdesc *v) {
  FuncState *fs = ls->fs->prev;
  init_exp(v, VRELOC, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));
  luaK_exp2nextreg(fs, v);  /* fix it at the last register */
}


static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
  Proto *f = fs->f;
  fs->prev = ls->fs;  /* linked list of funcstates */
  fs->ls = ls;
  ls->fs = fs;
  fs->pc = 0;
  fs->previousline = f->linedefined;
  fs->iwthabs = 0;
  fs->lasttarget = 0;
  fs->freereg = 0;
  fs->nk = 0;
  fs->nabslineinfo = 0;
  fs->np = 0;
  fs->nups = 0;
  fs->ndebugvars = 0;
  fs->nactvar = 0;
  fs->needclose = 0;
  fs->istrybody = 0;
  fs->seenrets = 0;
  fs->firstlocal = ls->dyd->actvar.n;
  fs->firstlabel = ls->dyd->label.n;
  fs->bl = NULL;
  fs->pinnedreg = -1;
  f->source = ls->source;
  luaC_objbarrier(ls->L, f, f->source);
  f->maxstacksize = 2;  /* registers 0/1 are always valid */
  enterblock(fs, bl, BlockType::BT_DEFAULT);
}


static void close_func (LexState *ls) {
  lua_State *L = ls->L;
  FuncState *fs = ls->fs;
  Proto *f = fs->f;
  luaK_ret(fs, luaY_nvarstack(fs), 0);  /* final return */
  leaveblock(fs);
  lua_assert(fs->bl == NULL);
  luaK_finish(fs);
  luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction);
  luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte);
  luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo,
                       fs->nabslineinfo, AbsLineInfo);
  luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue);
  luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *);
  luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->ndebugvars, LocVar);
  luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
  ls->fs = fs->prev;
  luaC_checkGC(L);
}



/*============================================================*/
/* GRAMMAR RULES */
/*============================================================*/


/*
** check whether current token is in the follow set of a block.
** 'until' closes syntactical blocks, but do not close scope,
** so it is handled in separate.
*/
static int block_follow (LexState *ls, int withuntil) {
  switch (ls->t.token) {
    case '$': {
      int ret;
      luaX_next(ls);
      ret = block_follow(ls, withuntil);
      luaX_prev(ls);
      return ret;
    }
    case TK_ELSE: case TK_ELSEIF:
    case TK_END: case TK_EOS:
      return 1;
    case TK_CATCH: case TK_PCATCH:
      return ls->used_try;
    case TK_UNTIL: return withuntil;
    default: return 0;
  }
}


static void newtable (LexState *ls, expdesc *v, const std::function<bool(expdesc *key, expdesc *val)>& gen);
static void statlist (LexState *ls, TypeHint *prop = nullptr, bool no_ret_implies_void = false) {
  /* statlist -> { stat [';'] } */
  bool ret = false;
  while (!block_follow(ls, 1)) {
    ret = (ls->t.token == TK_RETURN);
    TypeHint p{};
#if defined LUAI_ASSERT
    const auto levels = ls->L->nCcalls;
#endif
    statement(ls, &p);
    lua_assert(levels == ls->L->nCcalls);
    if (prop && /* do we need to propagate the return type? */
        !p.empty()) { /* is there a return path here? */
      prop->merge(p);
    }
    if (ret) break;
  }
  if (prop) { /* do we need to propagate the return type? */
    if (!ret && /* had no return statement? */
        no_ret_implies_void) { /* does that imply a void return? */
      prop->emplaceTypeDesc(VT_VOID); /* propagate */
    }
    prop->fixTypes();
  }
  if (!ls->fs->bl->export_symbols.empty()) {
    if (ret) {
      luaX_prev(ls);
      luaX_syntaxerror(ls, "'export' used but body already returns something");
    }
    enterlevel(ls);
    size_t i = 0;
    expdesc t;
    if (ls->fs->istrybody) {
      init_exp(&t, VKINT, 0);
      t.u.ival = 1;
      luaK_exp2nextreg(ls->fs, &t);
    }
    newtable(ls, &t, [ls, &i](expdesc *k, expdesc *v) {
      if (i == ls->fs->bl->export_symbols.size())
        return false;
      codestring(k, ls->fs->bl->export_symbols.at(i));
      singlevar(ls, v, ls->fs->bl->export_symbols.at(i));
      ++i;
      return true;
    });
    ls->fs->seenrets = 1<<1;
    luaK_ret(ls->fs, luaK_exp2anyreg(ls->fs, &t)-ls->fs->istrybody, 1+ls->fs->istrybody);
    leavelevel(ls);
    ls->fs->bl->export_symbols.clear();
  }
}

static BlockCnt* searchloop(FuncState* fs, BlockType type, lua_Integer depth) {
  for(;;) {
    BlockCnt* bl = fs->bl;
    while (bl) {
      if (bl->type == type && --depth == 0) return bl;
      bl = bl->previous;
    }
    if (!fs->istrybody)
      return 0;
    fs = fs->prev;
  }
}

static int countdepth(FuncState* fs, BlockType type) {
  int depth = 0;
  for(;;) {
    BlockCnt* bl = fs->bl;
    while (bl) {
      if (bl->type == type) depth++;
      bl = bl->previous;
    }
    if (!fs->istrybody)
      return depth;
    fs = fs->prev;
  }
}

/*
** Continue statement. Semantically similar to "goto continue".
** Unlike break, this doesn't use labels. It tracks where to jump via BlockCnt.scopeend;
*/
static void continuestat (LexState *ls) {
  auto line = ls->getLineNumber();
  FuncState *fs = ls->fs;
  luaX_next(ls);  /* skip 'continue' */
  lua_Integer backwards = 1;
  if (ls->t.token == TK_INT) {
    backwards = ls->t.seminfo.i;
    if (backwards == 0) {
      throwerr(ls, "expected number of blocks to skip, found '0'", "unexpected '0'", line);
    }
    luaX_next(ls);
  }
  BlockCnt* l = searchloop(fs, BlockType::BT_CONTINUE, backwards);
  if (l) {
    newgotoentry(ls, l, line, luaK_jump(fs), true);
  }
  else {
    int foundloops = countdepth(fs, BlockType::BT_CONTINUE);
    if (foundloops == 0)
      throwerr(ls, "'continue' outside of a loop","'continue' can only be used inside the context of a loop.", line);
    else {
      if (foundloops == 1) {
        throwerr(ls,
          "'continue' argument exceeds the amount of enclosing loops",
            luaO_fmt(ls->L, "there is only 1 enclosing loop.", foundloops));
      }
      else {
        throwerr(ls,
          "'continue' argument exceeds the amount of enclosing loops",
            luaO_fmt(ls->L, "there are only %d enclosing loops.", foundloops));
      }
    }
  }
}


static void lbreak (LexState *ls, lua_Integer backwards, int line, int jump) {
  BlockCnt* l = searchloop(ls->fs, BlockType::BT_BREAK, backwards);
  if (l) {
    newgotoentry(ls, l, line, jump, true);
  }
  else {
    throwerr(ls, "break can't skip that many blocks", "try a smaller number", line);
  }
}


/*
** Break statement. Very similiar to `continue` usage, but it jumps slightly more forward.
**
** Implementation Detail:
**   Unlike normal Lua, it has been reverted from a label implementation back into a mix between a label & patchlist implementation.
**   This allows reusage of the existing "continue" implementation, which has been time-tested extensively by now.
*/
static void breakstat (LexState *ls) {
  const auto line = ls->getLineNumber();
  luaX_next(ls); /* skip TK_BREAK */
  lua_Integer backwards = 1;
  if (ls->t.token == TK_INT) {
    backwards = ls->t.seminfo.i;
    if (backwards == 0) {
      throwerr(ls, "expected number of blocks to skip, found '0'", "unexpected '0'", line);
    }
    luaX_next(ls);
  }
  lbreak(ls, backwards, line, luaK_jump(ls->fs));
}


static void fieldsel (LexState *ls, expdesc *v) {
  /* fieldsel -> ['.' | ':'] NAME */
  FuncState *fs = ls->fs;
  expdesc key;
  luaK_exp2anyregup(fs, v);
  luaX_next(ls);  /* skip the dot or colon */
  codename(ls, &key, N_RESERVED);
  luaK_indexed(fs, v, &key);
}


static void yindex (LexState *ls, expdesc *v) {
  /* index -> '[' expr ']' */
  luaX_next(ls);  /* skip the '[' */
  expr(ls, v);
  luaK_exp2val(ls->fs, v);
  checknext(ls, ']');
}


/*
** {======================================================================
** Rules for Constructors
** =======================================================================
*/


typedef struct ConsControl {
  expdesc v;  /* last list item read */
  expdesc *t;  /* table descriptor */
  int nh;  /* total number of 'record' elements */
  int na;  /* number of array elements already stored */
  int tostore;  /* number of array elements pending to be stored */
} ConsControl;


static void preassignfield (LexState *ls, expdesc& key) {
  if (key.k == VKSTR) {
    if (ls->constructorfieldsets.top().count(key.u.strval)) {
      throw_warn(ls, "duplicate table field", luaO_fmt(ls->L, "this overwrites the value assigned to '%s' field earlier", getstr(key.u.strval)), WT_FIELD_SHADOW);
      lua_pop(ls->L, 1);
    }
    else
      ls->constructorfieldsets.top().emplace(key.u.strval);
  }
}

static void recfield (LexState *ls, ConsControl *cc, bool for_class) {
  /* recfield -> (NAME | '['exp']') = exp */
  FuncState *fs = ls->fs;
  int reg = ls->fs->freereg;
  expdesc tab, key, val;
  if (ls->t.token == TK_NAME) {
    checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
    TString *name = str_checkname(ls, N_RESERVED);  /* we already know this is a TK_NAME, but don't wanna raise non-portable-name, so passing N_RESERVED */
    if (for_class) {
      if (strcmp(getstr(name), "public") == 0) {
        name = str_checkname(ls);
      }
      else if (strcmp(getstr(name), "protected") == 0) {
        luaX_syntaxerror(ls, "'protected' is reserved in this context");
        name = str_checkname(ls);
      }
      else if (strcmp(getstr(name), "private") == 0) {
        const auto field_name = ls->classes.top().addPrefix(str_checkname(ls)->toCpp());
        name = luaX_newstring(ls, field_name.c_str());
      }
    }
    codestring(&key, name);
  }
  else  /* ls->t.token == '[' */
    yindex(ls, &key);
  if (for_class)
    UNUSED(gettypehint(ls));
  cc->nh++;
  tab = *cc->t;
  preassignfield(ls, key);
  luaK_indexed(fs, &tab, &key);
  if (for_class) {
    if (testnext(ls, '='))
      expr(ls, &val);
    else
      init_exp(&val, VNIL, 0);
  }
  else {
    checknext(ls, '=');
    expr(ls, &val);
  }
  luaK_storevar(fs, &tab, &val);
  fs->freereg = reg;  /* free registers */
}

static void prenamedfield (LexState *ls, ConsControl *cc, const char *name) {
  FuncState* fs = ls->fs;
  int reg = ls->fs->freereg;
  expdesc tab, key, val;
  codestring(&key, luaX_newstring(ls, name));
  cc->nh++;
  luaX_next(ls); /* skip name token */
  checknext(ls, '=');
  tab = *cc->t;
  preassignfield(ls, key);
  luaK_indexed(fs, &tab, &key);
  expr(ls, &val);
  luaK_storevar(fs, &tab, &val);
  fs->freereg = reg;  /* free registers */
}

static void closelistfield (FuncState *fs, ConsControl *cc) {
  if (cc->v.k == VVOID) return;  /* there is no list item */
  luaK_exp2nextreg(fs, &cc->v);
  cc->v.k = VVOID;
  if (cc->tostore == LFIELDS_PER_FLUSH) {
    luaK_setlist(fs, cc->t->u.reg, cc->na, cc->tostore);  /* flush */
    cc->na += cc->tostore;
    cc->tostore = 0;  /* no more items pending */
  }
}


static void lastlistfield (FuncState *fs, ConsControl *cc) {
  if (cc->tostore == 0) return;
  if (hasmultret(cc->v.k)) {
    luaK_setmultret(fs, &cc->v);
    luaK_setlist(fs, cc->t->u.reg, cc->na, LUA_MULTRET);
    cc->na--;  /* do not count last expression (unknown number of elements) */
  }
  else {
    if (cc->v.k != VVOID)
      luaK_exp2nextreg(fs, &cc->v);
    luaK_setlist(fs, cc->t->u.reg, cc->na, cc->tostore);
  }
  cc->na += cc->tostore;
}


static void listfield (LexState *ls, ConsControl *cc) {
  /* listfield -> exp */
  expr(ls, &cc->v);
  cc->tostore++;
}


static void body (LexState *ls, expdesc *e, int ismethod, int line, TypeDesc *funcdesc = nullptr);
static void funcfield (LexState *ls, struct ConsControl *cc, int ismethod, bool isprivate = false) {
  /* funcfield -> function NAME funcargs */
  FuncState *fs = ls->fs;
  int reg = ls->fs->freereg;
  expdesc tab, key, val;
  cc->nh++;
  luaX_next(ls); /* skip TK_FUNCTION */
  codename(ls, &key);
  if (isprivate) {
    const auto new_name = ls->classes.top().addPrefix(getstr(key.u.strval));
    codestring(&key, luaX_newstring(ls, new_name.c_str()));
  }
  if (ismethod)
    ismethod += (strcmp(getstr(key.u.strval), "__construct") == 0);
  tab = *cc->t;
  luaK_indexed(fs, &tab, &key);
  body(ls, &val, ismethod, ls->getLineNumber());
  luaK_storevar(fs, &tab, &val);
  fs->freereg = reg;  /* free registers */
}


static void field (LexState *ls, ConsControl *cc, bool for_class = false) {
  /* field -> listfield | recfield | funcfield */
#ifdef PLUTO_PARSER_SUGGESTIONS
  if (ls->shouldSuggest()) {
    SuggestionsState ss(ls);
    ss.push("stat", "function");
    ss.push("stat", "static");
  }
#endif
  if (ls->t.IsReserved() && luaX_lookahead(ls) == '=') {
    prenamedfield(ls, cc, luaX_reserved2str(ls->t.token));
  }
  else switch(ls->t.token) {
    case TK_NAME: {  /* may be 'listfield', 'recfield' or static 'funcfield' */
      if (strcmp(getstr(ls->t.seminfo.ts), "static") == 0) {
        luaX_next(ls);
        check(ls, TK_FUNCTION);
        funcfield(ls, cc, false);
      }
      else if (for_class && luaX_lookahead(ls) == TK_FUNCTION && strcmp(getstr(ls->t.seminfo.ts), "public") == 0) {
        luaX_next(ls);
        funcfield(ls, cc, true);
      }
      else if (for_class && luaX_lookahead(ls) == TK_FUNCTION && strcmp(getstr(ls->t.seminfo.ts), "private") == 0) {
        luaX_next(ls);
        funcfield(ls, cc, true, true);
      }
      else {
        if (!for_class && luaX_lookahead(ls) != '=')  /* expression? */
          listfield(ls, cc);
        else
          recfield(ls, cc, for_class);
      }
      break;
    }
    case '[': {
      recfield(ls, cc, for_class);
      break;
    }
    case TK_FUNCTION: {
      if (luaX_lookahead(ls) == '(') {
        listfield(ls, cc);
      }
      else {
        funcfield(ls, cc, true);
      }
      break;
    }
    default: {
      if (for_class)
        throwerr(ls, luaO_fmt(ls->L, "unexpected token: %s", luaX_token2str(ls, ls->t)), "expected a class member");
      listfield(ls, cc);
      break;
    }
  }
}


static void constructor (LexState *ls, expdesc *t) {
  /* constructor -> '{' [ field { sep field } [sep] ] '}'
     sep -> ',' | ';' */
  FuncState *fs = ls->fs;
  int line = ls->getLineNumber();
  int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
  ls->constructorfieldsets.emplace();
  ConsControl cc;
  luaK_code(fs, 0);  /* space for extra arg. */
  cc.na = cc.nh = cc.tostore = 0;
  cc.t = t;
  init_exp(t, VNONRELOC, fs->freereg);  /* table will be at stack top */
  luaK_reserveregs(fs, 1);
  init_exp(&cc.v, VVOID, 0);  /* no value (yet) */
  checknext(ls, '{');
  do {
    lua_assert(cc.v.k == VVOID || cc.tostore > 0);
    if (ls->t.token == '}') break;
    closelistfield(fs, &cc);
    field(ls, &cc);
  } while (testnext(ls, ',') || testnext(ls, ';'));
  if (ls->t.token == TK_NAME || ls->t.token == TK_FUNCTION || ls->t.token == '[' || ls->t.isSimple()) {
    check_match(ls, '}', '{', line, "Ensure that you've delimited the previous field with ',' or ';'.");
  }
  else {
    check_match(ls, '}', '{', line);
  }
  lastlistfield(fs, &cc);
  luaK_settablesize(fs, pc, t->u.reg, cc.na, cc.nh);
  ls->constructorfieldsets.pop();
}


static void newtable (LexState *ls, expdesc *v, const std::function<bool(expdesc*)>& gen) {
  FuncState* fs = ls->fs;
  int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
  ConsControl cc;
  luaK_code(fs, 0);  /* space for extra arg. */
  cc.na = cc.nh = cc.tostore = 0;
  cc.t = v;
  init_exp(v, VNONRELOC, fs->freereg);  /* table will be at stack top */
  luaK_reserveregs(fs, 1);
  while (gen(&cc.v)) {
    ++cc.tostore;
    closelistfield(fs, &cc);
  }
  lastlistfield(fs, &cc);
  luaK_settablesize(fs, pc, v->u.reg, cc.na, cc.nh);
}

static void newtable (LexState *ls, expdesc *v, const std::function<bool(expdesc *key, expdesc *val)>& gen) {
  FuncState* fs = ls->fs;
  int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
  ConsControl cc;
  luaK_code(fs, 0);  /* space for extra arg. */
  cc.na = cc.nh = cc.tostore = 0;
  cc.t = v;
  init_exp(v, VNONRELOC, fs->freereg);  /* table will be at stack top */
  luaK_reserveregs(fs, 1);
  init_exp(&cc.v, VVOID, 0);
  while (true) {
    closelistfield(fs, &cc);
    int reg = ls->fs->freereg;
    expdesc tab, key, val;
    if (!gen(&key, &val))
      break;
    luaK_exp2val(ls->fs, &key);
    cc.nh++;
    tab = *cc.t;
    luaK_indexed(fs, &tab, &key);
    luaK_storevar(fs, &tab, &val);
    fs->freereg = reg;
  }
  lastlistfield(fs, &cc);
  luaK_settablesize(fs, pc, v->u.reg, cc.na, cc.nh);
}


static void classname (LexState *ls, expdesc *v) {
  singlevarinner(ls, str_checkname(ls, 0), v);
  while (ls->t.token == '.')
    fieldsel(ls, v);
}

static void skip_classname (LexState *ls) {
  str_checkname(ls, 0);
  while (ls->t.token == '.') {
    luaX_next(ls);
    str_checkname(ls, N_RESERVED);
  }
}

static size_t checkextends (LexState *ls) {
  size_t pos = 0;
#ifdef PLUTO_PARSER_SUGGESTIONS
  if (ls->shouldSuggest()) {
    SuggestionsState ss(ls);
    ss.push("stat", "extends");
    ss.push("stat", "function");
    ss.push("stat", "static");
    ss.push("stat", "end");
  }
#endif
  if (ls->t.token == TK_EXTENDS) {
    luaX_next(ls);
    pos = luaX_getpos(ls);
    skip_classname(ls);
  }
  ls->classes.top().parent_name_pos = pos;
  return pos;
}

static void applyextends (LexState *ls, size_t name_pos, size_t parent_pos, int line) {
  FuncState *fs = ls->fs;

  expdesc f;
  singlevaraux(fs, luaS_newliteral(ls->L, "Pluto_operator_extends"), &f, 1);
  lua_assert(f.k != VVOID);
  luaK_exp2nextreg(fs, &f);

  expdesc args;
  auto pos = luaX_getpos(ls);
  luaX_setpos(ls, name_pos);
  classname(ls, &args);
  luaK_exp2nextreg(fs, &args);
  luaX_setpos(ls, parent_pos);
  classname(ls, &args);
  luaX_setpos(ls, pos);

  lua_assert(f.k == VNONRELOC);
  int base = f.u.reg;  /* base register for call */
  luaK_exp2nextreg(fs, &args);  /* close last argument */
  int nparams = fs->freereg - (base + 1);
  init_exp(&f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams + 1, 2));
  luaK_fixline(fs, line);
  fs->freereg = base + 1;
}

static size_t preprocessclass (LexState *ls) {
  int allowed_ends = 0;
  bool expect_block_opener = false;
  const auto start = luaX_getpos(ls);

  while (ls->t.token != TK_EOS) {
    if (ls->t.token == TK_END && allowed_ends-- <= 0) {
      // printf("Preprocessed class body ending at line %d.\n", ls->getLineNumber());
      break;
    }

    // This is only checking *inside* our current class body, the parser has already skipped the class declaration.
    switch (ls->t.normalizedToken()) {
    case TK_CLASS:  /* 'class' or 'enum class' */
    case TK_IF:
    case TK_CATCH:
      expect_block_opener = true;
      ++allowed_ends;
      break;

    case TK_FUNCTION:
      expect_block_opener = false;
      ++allowed_ends;
      break;

    case TK_THEN:
    case TK_BEGIN:
      expect_block_opener = false;
      break;

    case TK_DO:
      if (expect_block_opener)
        expect_block_opener = false;
      else
        ++allowed_ends;  /* forstat, whilestat, switchstat, dostat, '-> do' */
      break;

    case TK_ENUM:
      expect_block_opener = true;
      if (luaX_lookahead(ls) != TK_CLASS) {  /* 'enum class' would already be counted */
        ++allowed_ends;
      }
      break;
    }

    if (ls->t.token == TK_NAME && strcmp(getstr(ls->t.seminfo.ts), "private") == 0) {
      if (luaX_lookahead(ls) == TK_FUNCTION) {
        checknext(ls, TK_NAME);
        checknext(ls, TK_FUNCTION);
        ls->classes.top().addField(getstr(ls->t.seminfo.ts));
        ++allowed_ends; // For TK_FUNCTION
      }
      else if (luaX_lookahead(ls) == TK_NAME) {
        checknext(ls, TK_NAME);
        ls->classes.top().addField(getstr(ls->t.seminfo.ts));
      }
    }

    luaX_next(ls);
  }

  const auto finish = luaX_getpos(ls);
  luaX_setpos(ls, start);
  return finish;
}

static void classexpr (LexState *ls, expdesc *t) {
  FuncState *fs = ls->fs;
  int line = ls->getLineNumber();
  testnext2(ls, TK_BEGIN, TK_DO);
  int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
  ls->constructorfieldsets.emplace();
  ConsControl cc;
  luaK_code(fs, 0);  /* space for extra arg. */
  cc.na = cc.nh = cc.tostore = 0;
  cc.t = t;
  init_exp(t, VNONRELOC, fs->freereg);  /* table will be at stack top */
  luaK_reserveregs(fs, 1);
  init_exp(&cc.v, VVOID, 0);  /* no value (yet) */
  const auto finish = preprocessclass(ls);
  while (ls->t.token != TK_END) {
    lua_assert(cc.v.k == VVOID || cc.tostore > 0);
    closelistfield(fs, &cc);
    field(ls, &cc, true);
    (testnext(ls, ',') || testnext(ls, ';'));
  }
  if (finish != luaX_getpos(ls)) { // The preprocessor should've terminated at the same exact spot.
    throwerr(ls,
      "internal error: 'preprocessclass' failed to handle a block",
      "",
      "Report this at: https://github.com/PlutoLang/Pluto/issues"
    );
  }
  check_match(ls, TK_END, TK_CLASS, line);
  lastlistfield(fs, &cc);
  luaK_settablesize(fs, pc, t->u.reg, cc.na, cc.nh);
  ls->constructorfieldsets.pop();
}


static void check_assignment (LexState *ls, const expdesc *v) {
  if (v->k == VINDEXUP && ls->isKeywordEnabled(TK_GLOBAL)) {
    luaX_prev(ls);
    TString *name = str_checkname(ls, N_RESERVED_NON_VALUE | N_OVERRIDABLE);
    if (ls->explicit_globals.count(name) == 0) {
      throw_warn(ls, "implicit global creation", "prefix this with 'global' to be explicit", WT_IMPLICIT_GLOBAL);
    }
  }
}


static void classstat (LexState *ls, int line, const bool global) {
  ls->classes.emplace();

  size_t name_pos = luaX_getpos(ls);
  expdesc v;
  if (global) {
    singlevarinner(ls, str_checkname(ls, 0), &v);
  }
  else {
    classname(ls, &v);
    check_assignment(ls, &v);
  }

  size_t parent_pos = checkextends(ls);

  expdesc t;
  classexpr(ls, &t);
  check_readonly(ls, &v);
  luaK_storevar(ls->fs, &v, &t);
  luaK_fixline(ls->fs, line);

  lua_assert(ls->getParentClassPos() == parent_pos);
  ls->classes.pop();

  if (parent_pos)
    applyextends(ls, name_pos, parent_pos, line);
}


static void localclass (LexState *ls) {
  luaX_prev(ls);
  check_for_non_portable_code(ls);
  luaX_next(ls);
  auto line = ls->getLineNumber();

  ls->classes.emplace();

  size_t name_pos = luaX_getpos(ls);
  TString *name = str_checkname(ls, 0);
  size_t parent_pos = checkextends(ls);

  new_localvar(ls, name, line);

  expdesc t;
  classexpr(ls, &t);

  adjust_assign(ls, 1, 1, &t);
  adjustlocalvars(ls, 1);

  lua_assert(ls->getParentClassPos() == parent_pos);
  ls->classes.pop();

  if (parent_pos)
    applyextends(ls, name_pos, parent_pos, line);
}

/* }====================================================================== */


static void setvararg (FuncState *fs, int nparams) {
  fs->f->is_vararg = 1;
  luaK_codeABC(fs, OP_VARARGPREP, nparams, 0, 0);
}


enum expflags {
  E_NO_METHOD_CALL   = 1 << 0,  /* ':' may not be used to initiate a method call */
  E_NO_CALL          = 1 << 1,
  E_NO_BOR           = 1 << 2,
  E_PIPERHS          = 1 << 3,
  E_WALRUS           = 1 << 4,
  E_OR_KILLED_WALRUS = 1 << 5,
  E_NO_CONSUME_COLON = 1 << 6,  /* this expression must not consume a non-nested colon */
};

static void simpleexp (LexState *ls, expdesc *v, int flags = 0, TypeHint *prop = nullptr);


/* keep advancing until we hit `token` */
static void skip_until (LexState *ls, int token) {
  int parens = 0;
  int curlys = 0;
  while (ls->t.token != TK_EOS) {
    if (ls->t.token == '(') {
      parens++;
    }
    else if (ls->t.token == ')') {
      parens--;
    }
    else if (ls->t.token == '{') {
      curlys++;
    }
    else if (ls->t.token == '}') {
      curlys--;
    }
    else if (ls->t.token == token) {
      if (parens == 0 && curlys == 0) {
        break;
      }
    }
    luaX_next(ls);
  }
}

/* keep advancing until we hit ',' or non-nested ')' */
static void skip_over_simpleexp_within_parenlist (LexState *ls) {
  int parens = 0;
  int curlys = 0;
  while (ls->t.token != TK_EOS) {
    if (ls->t.token == '(') {
      parens++;
    }
    else if (ls->t.token == ')') {
      if (parens == 0 && curlys == 0) {
        break;
      }
      parens--;
    }
    else if (ls->t.token == '{') {
      curlys++;
    }
    else if (ls->t.token == '}') {
      curlys--;
    }
    else if (ls->t.token == ',') {
      if (parens == 0 && curlys == 0) {
        break;
      }
    }
    luaX_next(ls);
  }
}

/* keep advancing until we hit ',' or '|' */
static void skip_over_simpleexp_within_lambdaparlist (LexState *ls) {
  int parens = 0;
  int curlys = 0;
  while (ls->t.token != TK_EOS) {
    if (ls->t.token == '(') {
      parens++;
    }
    else if (ls->t.token == ')') {
      parens--;
    }
    else if (ls->t.token == '{') {
      curlys++;
    }
    else if (ls->t.token == '}') {
      curlys--;
    }
    else if (ls->t.token == ',' || ls->t.token == '|') {
      if (parens == 0 && curlys == 0) {
        break;
      }
    }
    luaX_next(ls);
  }
}

static void parlist (LexState *ls, std::vector<std::pair<TString*, TString*>>* promotions, std::vector<size_t>* fallbacks, TString** varargname, bool lambda) {
  /* parlist -> [ {NAME ','} (NAME | '...') ] */
  FuncState *fs = ls->fs;
  Proto *f = fs->f;
  int nparams = 0;
  int isvararg = 0;
  if (ls->t.token != ')' && ls->t.token != '|') {  /* is 'parlist' not empty? */
    do {
      if (isnametkn(ls, N_OVERRIDABLE) || (ls->t.IsNonCompatible() && trydisablekeyword(ls) && isnametkn(ls, N_OVERRIDABLE))) {
        auto parname = str_checkname(ls, N_OVERRIDABLE);
        if (promotions) {
          if (strcmp(getstr(parname), "public") == 0) {
            parname = str_checkname(ls, N_OVERRIDABLE);
            promotions->emplace_back(parname, parname);
          }
          else if (strcmp(getstr(parname), "protected") == 0) {
            luaX_syntaxerror(ls, "'protected' is reserved in this context");
          }
          else if (strcmp(getstr(parname), "private") == 0) {
            parname = str_checkname(ls, N_OVERRIDABLE);
            const auto field_name = ls->classes.top().addPrefix(parname->toCpp());
            promotions->emplace_back(parname, luaX_newstring(ls, field_name.c_str()));
          }
        }
        auto parhint = gettypehint(ls);
        auto vidx = new_localvar(ls, parname, parhint);
        *getlocalvardesc(fs, vidx)->vd.prop = parhint;  /* set hinted type as propagated type */
        if (fallbacks) {
          if (testnext(ls, '=')) {
            if (ls->t.token == TK_NIL) {
              throwerr(ls, "default argument expected", "nil is not a valid default argument");
            }
            fallbacks->emplace_back(luaX_getpos(ls));
            if (lambda)
              skip_over_simpleexp_within_lambdaparlist(ls);
            else
              skip_over_simpleexp_within_parenlist(ls);
          }
          else {
            fallbacks->emplace_back(0);
          }
        }
        nparams++;
      }
      else if (ls->t.token == TK_DOTS) {
        luaX_next(ls);
        isvararg = 1;
        if (varargname && ls->t.token == TK_NAME) {
          *varargname = ls->t.seminfo.ts;
          luaX_next(ls);
        }
      }
      else luaX_syntaxerror(ls, "<name> or '...' expected");
    } while (!isvararg && testnext(ls, ','));
  }
  adjustlocalvars(ls, nparams);
  f->numparams = cast_byte(fs->nactvar);
  if (isvararg)
    setvararg(fs, f->numparams);  /* declared vararg */
  luaK_reserveregs(fs, fs->nactvar);  /* reserve registers for parameters */
}


/* Returns true if the function is declared '<nodiscard>'. */
static bool getfunctionattribute (LexState *ls) {
  if (testnext(ls, '<')) {
    TString *ts = str_checkname(ls);
    const char *attr = getstr(ts);
    checknext(ls, '>');
    if (strcmp(attr, "nodiscard") == 0)
      return true;
    else {
      luaX_prev(ls); // back to '>'
      luaX_prev(ls); // back to attribute
      luaK_semerror(ls,
        luaO_pushfstring(ls->L, "unknown attribute '%s'", attr));
    }
  }
  return false;
}


static void defaultarguments (LexState *ls, int ismethod, const std::vector<size_t>& fallbacks, int flags = 0) {
  const auto saved_pos = luaX_getpos(ls);
  int fallback_idx = (ismethod ? 1 : 0);
  for (const auto& tidx : fallbacks) {
    if (tidx != 0) {
      enterlevel(ls);
      FuncState *fs = ls->fs;

      expdesc nilable;
      Vardesc *vd = getlocalvardesc(fs, fallback_idx);
      singlevaraux(fs, vd->vd.name, &nilable, 0);

      luaX_setpos(ls, tidx);
      expdesc nilexp;
      luaK_infix(fs, OPR_NE, &nilable);
      init_exp(&nilexp, VNIL, 0);
      luaK_posfix(fs, OPR_NE, &nilable, &nilexp, ls->getLineNumber());
      auto pc = nilable.u.pc;

      expdesc fallback;
      expr(ls, &fallback, nullptr, flags);
      luaK_setoneret(fs, &fallback);
      singlevaraux(fs, vd->vd.name, &nilable, 0);
      luaK_storevar(fs, &nilable, &fallback);

      luaK_patchtohere(fs, pc);
      leavelevel(ls);
    }
    ++fallback_idx;
  }
  luaX_setpos(ls, saved_pos);
}


static void namedvararg (LexState *ls, TString *varargname) {
  enterlevel(ls);
  luaX_prev(ls);  /* in case we need to raise a var-shadow warning, ensure we're on the right line */
  new_localvar(ls, varargname);
  luaX_next(ls);

  FuncState *fs = ls->fs;
  int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
  luaK_code(fs, 0);
  expdesc t;
  init_exp(&t, VNONRELOC, fs->freereg);
  ConsControl cc;
  cc.na = cc.nh = cc.tostore = 0;
  cc.t = &t;
  luaK_reserveregs(fs, 1);
  lua_assert(fs->f->is_vararg);
  init_exp(&cc.v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 0, 1));
  cc.tostore++;
  lastlistfield(fs, &cc);
  luaK_settablesize(fs, pc, t.u.reg, cc.na, cc.nh);

  adjust_assign(ls, 1, 1, &t);
  adjustlocalvars(ls, 1);
  leavelevel(ls);
}


static void checkrettype (LexState *ls, TypeHint& rethint, TypeHint& retprop, int line) {
  if (!rethint.empty() /* has type hint for return type? */
      && !retprop.empty() && retprop.descs[0].type != VT_DUNNO /* return type is known? */
      && !rethint.isCompatibleWith(retprop)) { /* incompatible? */
    std::string err = "function was hinted to return ";
    err.append(rethint.toString());
    err.append(" but actually returns ");
    err.append(retprop.toString());
    throw_warn(ls, err.c_str(), line, WT_TYPE_MISMATCH);
  }
}


static void propfuncdesc (LexState *ls, FuncState& new_fs, TypeHint& retprop, TypeDesc *funcdesc) {
  funcdesc->type = VT_FUNC;
  funcdesc->proto = new_fs.f;
  funcdesc->retn = new_typehint(ls);
  *funcdesc->retn = retprop;
  int vidx = new_fs.firstlocal;
  for (lu_byte i = 0; i != funcdesc->getNumTypedParams(); ++i) {
    funcdesc->params[i] = ls->dyd->actvar.arr[vidx].vd.hint;
    ++vidx;
  }
}


static void body (LexState *ls, expdesc *e, int ismethod, int line, TypeDesc *funcdesc) {
  /* body ->  '(' parlist ')' block END */
  ls->pushContext(PARCTX_BODY);
  FuncState new_fs;
  BlockCnt bl;
  new_fs.f = addprototype(ls);
  new_fs.f->linedefined = line;
  open_func(ls, &new_fs, &bl);
  checknext(ls, '(');
  if (ismethod) {
    new_localvarliteral(ls, "self");  /* create 'self' parameter */
    adjustlocalvars(ls, 1);
  }
  BodyState& bs = ls->bodystates.emplace();
  TString *varargname = nullptr;
  parlist(ls, (ismethod == 2 ? &bs.promotions : nullptr), &bs.fallbacks, &varargname, false);
  if (ls->t.token != ')' && ismethod != 2 && luaX_lookbehind(ls).token == TK_NAME) {
    const char *str = getstr(luaX_lookbehind(ls).seminfo.ts);
    if (strcmp(str, "private") == 0 || strcmp(str, "protected") == 0 || strcmp(str, "public") == 0) {
      throwerr(ls, luaO_fmt(ls->L, "attempt to use constructor promotion outside of '__construct' near %s", luaX_token2str(ls, ls->t)), "this is invalid syntax.");
    }
  }
  checknext(ls, ')');
  defaultarguments(ls, ismethod, bs.fallbacks);
  for (const auto& e : bs.promotions) {
    FuncState *fs = ls->fs;
    expdesc tab, key, val;

    /* self[field] */
    singlevaraux(fs, luaS_newliteral(ls->L, "self"), &tab, 0);
    init_exp(&key, VKSTR, 0);
    key.u.strval = e.second;
    luaK_indexed(fs, &tab, &key);

    /* ... = arg */
    singlevaraux(fs, e.first, &val, 0);
    luaK_storevar(fs, &tab, &val);
  }
  if (varargname)
    namedvararg(ls, varargname);
  TypeHint rethint = gettypehint(ls, true);
  const bool nodiscard = getfunctionattribute(ls);
  TypeHint retprop{};
  statlist(ls, &retprop, true);
  checkrettype(ls, rethint, retprop, line);
  if (funcdesc) {
    propfuncdesc(ls, new_fs, retprop, funcdesc);
    funcdesc->nodiscard = nodiscard;
  }
  new_fs.f->lastlinedefined = ls->getLineNumber();
  check_match(ls, TK_END, TK_FUNCTION, line);
  codeclosure(ls, e);
  close_func(ls);
  ls->popContext(PARCTX_BODY);
  ls->bodystates.pop();
}


/*
** Lambda implementation.
** Shorthands lambda expressions into `function (...) return ... end`.
** The '|' token was chosen because it's not commonly used as a unary operator in programming.
** The '->' arrow syntax looked more visually appealing than a colon. It also plays along with common lambda tokens.
*/
static void lambdabody (LexState *ls, expdesc *e, int line, TypeDesc *funcdesc = nullptr) {
  FuncState new_fs;
  BlockCnt bl;
  new_fs.f = addprototype(ls);
  new_fs.f->linedefined = line;
  open_func(ls, &new_fs, &bl);
  BodyState& bs = ls->bodystates.emplace();
  TString *varargname = nullptr;
  parlist(ls, nullptr, &bs.fallbacks, &varargname, true);
  checknext(ls, '|');
  TypeHint rethint = gettypehint(ls, true);
  const bool nodiscard = getfunctionattribute(ls);
  checknext(ls, TK_ARROW);
  defaultarguments(ls, 0, bs.fallbacks, E_NO_BOR);
  if (varargname)
    namedvararg(ls, varargname);
  TypeHint retprop{};
  if (testnext(ls, TK_DO)) {
    ls->pushContext(PARCTX_BODY);
    statlist(ls, &retprop, true);
    check_match(ls, TK_END, TK_ARROW, line);
    ls->popContext(PARCTX_BODY);
  }
  else {
    ls->pushContext(PARCTX_LAMBDA_BODY);
    expr(ls, e, &retprop);
    ls->fs->seenrets |= 1<<1;
    luaK_ret(&new_fs, luaK_exp2anyreg(&new_fs, e), 1);
    ls->popContext(PARCTX_LAMBDA_BODY);
  }
  checkrettype(ls, rethint, retprop, line);
  if (funcdesc) {
    propfuncdesc(ls, new_fs, retprop, funcdesc);
    funcdesc->nodiscard = nodiscard;
  }
  new_fs.f->lastlinedefined = ls->getLineNumber();
  codeclosure(ls, e);
  close_func(ls);
  ls->bodystates.pop();
}


static void expr_propagate (LexState *ls, expdesc *v, TypeHint& t) {
  expr(ls, v, &t);
  exp_propagate(ls, *v, t);
}


static void expr_propagate_warn (LexState *ls, expdesc *v, TypeHint& t, std::unordered_set<TString*>& names) {
  expr(ls, v, &t);
  exp_propagate(ls, *v, t);
  if (v->k == VINDEXUP) {
    TString *key = tsvalue(&ls->fs->f->k[v->u.ind.idx]);
    for (auto global : common_global_names) {
      if (strncmp(getstr(key), global, sizeof(global) - 1) == 0) {
        names.emplace(key);
        break;
      }
    }
  }
}


static void explist_nonlinear_arg (LexState *ls, expdesc *v, size_t tidx, TypeHint& t) {
  if (tidx == 0) {
    init_exp(v, VNIL, 0);
    t.emplaceTypeDesc(VT_NIL);
  }
  else {
    luaX_setpos(ls, tidx);
    expr_propagate(ls, v, t);
  }
}

static void explist_nonlinear (LexState *ls, expdesc *v, const std::vector<size_t>& argtis, std::vector<void*>& prop) {
  prop.reserve(argtis.size());
  explist_nonlinear_arg(ls, v, argtis.at(0), *(TypeHint*)prop.emplace_back(new_typehint(ls)));
  for (size_t i = 1; i != argtis.size(); ++i) {
    luaK_exp2nextreg(ls->fs, v);
    explist_nonlinear_arg(ls, v, argtis.at(i), *(TypeHint*)prop.emplace_back(new_typehint(ls)));
  }
}

static int explist (LexState *ls, expdesc *v, TypeHint *prop = nullptr) {
  /* explist -> expr { ',' expr } */
  int n = 1;  /* at least one expression */
  expr(ls, v, prop);
  if (prop)
    exp_propagate(ls, *v, *prop);
  while (testnext(ls, ',')) {
    luaK_exp2nextreg(ls->fs, v);
    expr(ls, v);
    n++;
  }
  return n;
}

static bool isnamedarg (LexState *ls) {
  return ls->t.token != TK_EOS && luaX_lookahead(ls) == '=';
}

static void funcargs (LexState *ls, expdesc *f, TypeDesc *funcdesc = nullptr) {
  FuncState *fs = ls->fs;
  expdesc args;
  FuncArgsState& fas = ls->funcargsstates.emplace();
  int base, nparams;
  const auto line = ls->getLineNumber();
  switch (ls->t.token) {
    case '(': {  /* funcargs -> '(' [ explist ] ')' */
      luaX_next(ls);
      if (ls->t.token == ')')  /* arg list is empty? */
        args.k = VVOID;
      else {
        int num_positional_args = 0;
        if (!isnamedarg(ls)) {
          num_positional_args++;
          expr_propagate(ls, &args, *(TypeHint*)fas.argdescs.emplace_back(new_typehint(ls)));
          while (testnext(ls, ',')) {
            luaK_exp2nextreg(ls->fs, &args);
            if (isnamedarg(ls))
              break;
            expr_propagate(ls, &args, *(TypeHint*)fas.argdescs.emplace_back(new_typehint(ls)));
            num_positional_args++;
          }
        }
        if (ls->t.token != ')') {
          if (!isnamedarg(ls)) {  /* is this not a named argument? */
            error_expected(ls, ')');  /* then raise syntax error similar to Lua */
          }
          if (!funcdesc) {
            luaX_syntaxerror(ls, "can't used named arguments here because the function was not found at parse-time");
          }
          std::vector<size_t> argtis{};
          argtis.resize(funcdesc->getNumParams() - num_positional_args);
          do {
            TString *pname = str_checkname(ls, 0);
            int pi = funcdesc->findParamByName(pname);
            if (pi == -1) {
              throwerr(ls, luaO_fmt(ls->L, "function does not have a %s parameter", getstr(pname)), "unknown parameter");
            }
            if (num_positional_args > pi) {
              throwerr(ls, luaO_fmt(ls->L, "%s parameter was already assigned to positionally", getstr(pname)), "double-assignment of parameter");
            }
            pi -= num_positional_args;
            checknext(ls, '=');
            argtis.at(pi) = luaX_getpos(ls);
            skip_over_simpleexp_within_parenlist(ls);
          } while (testnext(ls, ','));
          const auto tidx = luaX_getpos(ls);
          explist_nonlinear(ls, &args, argtis, fas.argdescs);
          luaX_setpos(ls, tidx);
        }
        if (hasmultret(args.k) && args.k != VSAFECALL)
          luaK_setmultret(fs, &args);
      }
      check_match(ls, ')', '(', line);
      break;
    }
    case '{': {  /* funcargs -> constructor */
      auto hint = new_typehint(ls);
      hint->emplaceTypeDesc(VT_TABLE);
      fas.argdescs = { hint };
      constructor(ls, &args);
      break;
    }
    case TK_STRING: {  /* funcargs -> STRING */
      auto hint = new_typehint(ls);
      hint->emplaceTypeDesc(VT_STR);
      fas.argdescs = { hint };
      codestring(&args, ls->t.seminfo.ts);
      luaX_next(ls);  /* must use 'seminfo' before 'next' */
      break;
    }
    default: {
      luaX_syntaxerror(ls, "function arguments expected");
    }
  }
  if (funcdesc) {
    for (lu_byte i = 0; i != funcdesc->getNumTypedParams(); ++i) {
      const TypeHint* param_hint = funcdesc->params[i];
      if (param_hint->empty())
        continue; /* skip parameters without type hint */
      TypeHint arg{};
      if (i < (int)fas.argdescs.size()) {
        arg = *(TypeHint*)fas.argdescs.at(i);
        if (arg.empty())
          continue; /* skip arguments without propagated type */
      }
      if (!param_hint->isCompatibleWith(arg)) {
        std::string err = "Function's '";;
        err.append(getstr(funcdesc->proto->locvars[i].varname), tsslen(funcdesc->proto->locvars[i].varname));
        err.append("' parameter was type-hinted as ");
        err.append(param_hint->toString());
        err.append(" but provided with ");
        err.append(arg.toString());
        throw_warn(ls, err.c_str(), "argument type mismatch", line, WT_TYPE_MISMATCH);
      }
    }
    const auto expected = funcdesc->getNumParams();
    const auto received = (int)fas.argdescs.size();
    if (!funcdesc->proto->is_vararg && expected < received) {  /* Too many arguments? */
      auto suffix = expected == 1 ? "" : "s"; // Omit plural suffixes when the noun is singular.
      throw_warn(ls,
        "too many arguments",
          luaO_fmt(ls->L, "expected %d argument%s, got %d.", expected, suffix, received), line, WT_EXCESSIVE_ARGUMENTS);
      --ls->L->top.p;
    }
    ls->nodiscard = funcdesc->nodiscard;
  }
  else {
    ls->nodiscard = false;
  }
  lua_assert(f->k == VNONRELOC);
  base = f->u.reg;  /* base register for call */
  if (hasmultret(args.k) && args.k != VSAFECALL)
    nparams = LUA_MULTRET;  /* open call */
  else {
    if (args.k != VVOID)
      luaK_exp2nextreg(fs, &args);  /* close last argument */
    nparams = fs->freereg - (base+1);
  }
  init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
  luaK_fixline(fs, line);
  fs->freereg = base+1;  /* call remove function and arguments and leaves
                            (unless changed) one result */
  ls->funcargsstates.pop();
}




/*
** {======================================================================
** Expression parsing
** =======================================================================
*/


static void method_call_funcargs (LexState *ls, expdesc *v) {
  if (testnext(ls, '?')) {
    FuncState *fs = ls->fs;
    luaK_codeABC(fs, OP_TEST, v->u.reg, NO_REG, 0);
    int jf = luaK_jump(fs);
    funcargs(ls, v);
    lua_assert(v->k == VCALL);
    const auto pc = v->u.pc;
    luaK_exp2nextreg(fs, v);
    lua_assert(v->k == VNONRELOC);
    v->k = VSAFECALL;
    v->u.pc = pc;  /* instruction pc */
    int jt = luaK_jump(fs);
    luaK_patchtohere(fs, jf);
    luaK_nil(fs, v->u.reg + 1, 1);  /* failed to call, push nil */
    luaK_patchtohere(fs, jt);
  }
  else
    funcargs(ls, v);
}

/*
** Safe navigation is based on a patch published by SvenOlsen.
** http://lua-users.org/wiki/SvenOlsen
*/
static void safe_navigation (LexState *ls, expdesc *v) {
  FuncState *fs = ls->fs;
  luaK_exp2nextreg(fs, v);
  luaK_codeABC(fs, OP_TEST, v->u.reg, NO_REG, 0);
  const bool is_method_call = (ls->t.token == ':');
  int jt;
  {
    int old_free = fs->freereg;
    int vreg = v->u.reg;
    int jf = luaK_jump(fs);
    expdesc key;
    switch (ls->t.token) {
      case '[': {
        luaX_next(ls);  /* skip the '[' */
        expr(ls, &key);
        checknext(ls, ']');
        luaK_indexed(fs, v, &key);
        break; 
      }       
      case '.': {
        luaX_next(ls);
        codename(ls, &key);
        luaK_indexed(fs, v, &key);
        break;
      }
      case ':': {
        luaX_next(ls);
        codename(ls, &key, N_RESERVED);
        luaK_self(fs, v, &key);
        method_call_funcargs(ls, v);
        break;
      }
      default: {
        luaX_syntaxerror(ls, "unexpected symbol");
      }
    }
    luaK_exp2nextreg(fs, v);
    fs->freereg = old_free;
    if (v->u.reg != vreg) {
      luaK_codeABC(fs, OP_MOVE, vreg, v->u.reg, 0);
      v->u.reg = vreg;
    }
    if (is_method_call) {
      jt = luaK_jump(fs);
    }
    luaK_patchtohere(fs, jf);
  }
  if (is_method_call) {
    v->k = VSAFECALL;
    luaK_nil(fs, v->u.reg + 1, 1);  /* failed to call, push nil */
    luaK_patchtohere(fs, jt);
  }
}


static void top_to_expdesc (LexState *ls, expdesc *v) {
  lua_State *L = ls->L;
  switch (lua_type(L, -1)) {
    case LUA_TNUMBER: {
      if (lua_isinteger(L, -1)) {
        init_exp(v, VKINT, 0);
        v->u.ival = lua_tointeger(L, -1);
      }
      else {
        init_exp(v, VKFLT, 0);
        v->u.nval = lua_tonumber(L, -1);
      }
      break;
    }
    case LUA_TSTRING: {
      size_t len;
      const char* str = lua_tolstring(L, -1, &len);
      codestring(v, luaS_newlstr(L, str, len));
      break;
    }
    case LUA_TTABLE: {
      lua_pushnil(L);
      newtable(ls, v, [ls](expdesc *key, expdesc *val) {
        if (lua_next(ls->L, -2)) {
          top_to_expdesc(ls, val);
          lua_pop(ls->L, 1);
          top_to_expdesc(ls, key);
          return true;
        }
        return false;
      });
      break;
    }
    default: {
      luaX_syntaxerror(ls, "unexpected return value in constexpr_call");
    }
  }
}

static void constexpr_call (LexState *ls, expdesc *v, lua_CFunction f) {
  auto line = ls->getLineNumber();
  checknext(ls, '(');
  lua_State *L = ls->L;
  lua_pushcfunction(L, f);
  int nargs = 0;
  if (ls->t.token != ')') {
    do {
      ++nargs;
      auto argline = ls->getLineNumber();
      expdesc argexp;
      simpleexp(ls, &argexp, E_NO_METHOD_CALL);
      switch (argexp.k) {
        case VKSTR:
          lua_pushlstring(L, getstr(argexp.u.strval), tsslen(argexp.u.strval));
          break;
        case VKINT:
          lua_pushinteger(L, argexp.u.ival);
          break;
        case VKFLT:
          lua_pushnumber(L, argexp.u.nval);
          break;
        case VTRUE:
          lua_pushboolean(L, true);
          break;
        case VFALSE:
          lua_pushboolean(L, false);
          break;
        case VNIL:
          lua_pushnil(L);
          break;
        case VCONST:
          lua_lock(L);
          *s2v(L->top.p) = ls->dyd->actvar.arr[argexp.u.info].k;
          api_incr_top(L);
          lua_unlock(L);
          break;
        default:
          throwerr(ls, "unexpected argument type in constexpr_call", "unexpected argument type", argline);
      }
    } while (testnext(ls, ','));
  }
  check_match(ls, ')', '(', line);
  int status = lua_pcall(L, nargs, 1, 0);
  if (status != LUA_OK) {
    throwerr(ls, lua_tostring(L, -1), "error in constexpr_call", line);
  }
  top_to_expdesc(ls, v);
  lua_pop(L, 1);
}


static bool check_constexpr_call (LexState *ls, expdesc *v, const char *name, lua_CFunction f) {
  if (strcmp(getstr(ls->t.seminfo.ts), name) == 0) {
    luaX_next(ls); /* skip TK_NAME */
    constexpr_call(ls, v, f);
    return true;
  }
  return false;
}

int luaB_tonumber (lua_State *L);
int luaB_utonumber (lua_State *L);
int luaB_tostring (lua_State *L);
int luaB_utostring (lua_State *L);
int luaB_type (lua_State *L);

static void const_expr (LexState *ls, expdesc *v) {
  switch (ls->t.token) {
    case TK_NAME: {
      const Pluto::ConstexprLibrary* lib = nullptr;
      for (const auto& library : Pluto::all_preloaded) {
        if (strcmp(library->name, getstr(ls->t.seminfo.ts)) == 0) {
          lib = library;
          break;
        }
      }
      if (lib == nullptr) {
        for (const auto& library : Pluto::all_constexpr) {
          if (strcmp(library->name, getstr(ls->t.seminfo.ts)) == 0) {
            lib = library;
            break;
          }
        }
      }
      if (lib != nullptr) {
        luaX_next(ls); /* skip TK_NAME */
        checknext(ls, '.');
        check(ls, TK_NAME);
        lua_CFunction f = NULL;
        for (auto reg = &lib->funcs[0]; reg->name; ++reg) {
          if (strcmp(reg->name, getstr(ls->t.seminfo.ts)) == 0) {
            f = reg->func;
            break;
          }
        }
        if (f == NULL) {
          throwerr(ls, luaO_fmt(ls->L, "%s is not a member of %s", getstr(ls->t.seminfo.ts), lib->name), "unknown function.");
        }
        else {
          luaX_next(ls); /* skip TK_NAME */
          constexpr_call(ls, v, f);
        }
      }
      else if (!check_constexpr_call(ls, v, "tonumber", luaB_tonumber)
          && !check_constexpr_call(ls, v, "utonumber", luaB_utonumber)
          && !check_constexpr_call(ls, v, "tostring", luaB_tostring)
          && !check_constexpr_call(ls, v, "utostring", luaB_utostring)
          && !check_constexpr_call(ls, v, "type", luaB_type)
        )
      {
        throwerr(ls, luaO_fmt(ls->L, "%s is not available in constant expression", getstr(ls->t.seminfo.ts)), "unrecognized name.");
      }
      return;
    }
    default: {
      const char *token = luaX_token2str(ls, ls->t);
      throwerr(ls, luaO_fmt(ls->L, "unexpected symbol near %s", token), "unexpected symbol.");
    }
  }
}


static void enumexp (LexState *ls, expdesc *v, TString *varname) {
  switch (ls->t.token) {
    case ':': {
      luaX_next(ls);
#ifdef PLUTO_PARSER_SUGGESTIONS
      if (ls->shouldSuggest()) {
        SuggestionsState ss(ls);
        ss.push("efunc", "values");
        ss.push("efunc", "names");
        ss.push("efunc", "kvmap");
        ss.push("efunc", "vkmap");
      }
#endif
      check(ls, TK_NAME);
      if (strcmp(getstr(ls->t.seminfo.ts), "values") == 0) {
        luaX_next(ls);
        checknext(ls, '('); checknext(ls, ')');
        const EnumDesc* ed = &ls->enums.at((size_t)v->u.ival);
        size_t i = 0;
        newtable(ls, v, [ed, &i](expdesc *e) {
          if (i == ed->enumerators.size())
            return false;
          init_exp(e, VKINT, 0);
          e->u.ival = ed->enumerators.at(i++).value;
          return true;
        });
      }
      else if (strcmp(getstr(ls->t.seminfo.ts), "names") == 0) {
        luaX_next(ls);
        checknext(ls, '('); checknext(ls, ')');
        const EnumDesc* ed = &ls->enums.at((size_t)v->u.ival);
        size_t i = 0;
        newtable(ls, v, [ed, &i](expdesc *e) {
          if (i == ed->enumerators.size())
            return false;
          init_exp(e, VKSTR, 0);
          e->u.strval = ed->enumerators.at(i++).name;
          return true;
        });
      }
      else if (strcmp(getstr(ls->t.seminfo.ts), "kvmap") == 0) {
        luaX_next(ls);
        checknext(ls, '('); checknext(ls, ')');
        const EnumDesc* ed = &ls->enums.at((size_t)v->u.ival);
        size_t i = 0;
        newtable(ls, v, [ed, &i](expdesc *key, expdesc *val) {
          if (i == ed->enumerators.size())
            return false;
          init_exp(key, VKSTR, 0);
          key->u.strval = ed->enumerators.at(i).name;
          init_exp(val, VKINT, 0);
          val->u.ival = ed->enumerators.at(i).value;
          i++;
          return true;
        });
      }
      else if (strcmp(getstr(ls->t.seminfo.ts), "vkmap") == 0) {
        luaX_next(ls);
        checknext(ls, '('); checknext(ls, ')');
        const EnumDesc* ed = &ls->enums.at((size_t)v->u.ival);
        size_t i = 0;
        newtable(ls, v, [ed, &i](expdesc *key, expdesc *val) {
          if (i == ed->enumerators.size())
            return false;
          init_exp(key, VKINT, 0);
          key->u.ival = ed->enumerators.at(i).value;
          init_exp(val, VKSTR, 0);
          val->u.strval = ed->enumerators.at(i).name;
          i++;
          return true;
        });
      }
      else {
        throwerr(ls, luaO_fmt(ls->L, "%s is not a member of enums", getstr(ls->t.seminfo.ts)), "unknown member.");
      }
      return;
    }
    case '.': {
      const EnumDesc* ed = &ls->enums.at((size_t)v->u.ival);
      luaX_next(ls);
#ifdef PLUTO_PARSER_SUGGESTIONS
      if (ls->shouldSuggest()) {
        SuggestionsState ss(ls);
        for (const auto& e : ed->enumerators) {
          ss.push("eprop", getstr(e.name), std::to_string(e.value));
        }
      }
#endif
      check(ls, TK_NAME);
      for (const auto& e : ed->enumerators) {
        if (eqstr(e.name, ls->t.seminfo.ts)) {
          init_exp(v, VKINT, 0);
          v->u.ival = e.value;
          luaX_next(ls);
          return;
        }
      }
      throwerr(ls, luaO_fmt(ls->L, "%s is not a member of %s", getstr(ls->t.seminfo.ts), getstr(varname)), "unknown member.");
      return;
    }
    default: {
      const char *token = luaX_token2str(ls, ls->t);
      throwerr(ls, luaO_fmt(ls->L, "unexpected symbol near %s", token), "unexpected symbol.");
    }
  }
}


static void selfexp (LexState *ls, expdesc *v) {
  bool ismethod = testnext(ls, ':');
  if (testnext(ls, '.') || ismethod) {
    if (!ismethod) {
      luaK_exp2anyregup(ls->fs, v);
    }
    expdesc key;
    TString *keystr = str_checkname(ls, N_RESERVED);

    if (auto special = ls->classes.top().getSpecialName(keystr); special.has_value()) {
      codestring(&key, luaX_newstring(ls, special.value().c_str()));
    }
    else {
      codestring(&key, keystr);
    }

    if (!ismethod) {
      luaK_indexed(ls->fs, v, &key);
    }
    else {
      luaK_self(ls->fs, v, &key);
      method_call_funcargs(ls, v);
    }
  }
}


static void parentexp (LexState *ls, expdesc *v) {
  if (const auto parent_pos = ls->getParentClassPos()) {
    if (testnext(ls, ':')) {
      auto pos = luaX_getpos(ls);
      luaX_setpos(ls, parent_pos);
      classname(ls, v);
      luaX_setpos(ls, pos);
      luaK_exp2nextreg(ls->fs, v);

      expdesc key;
      codename(ls, &key);
      luaK_indexed(ls->fs, v, &key);
      luaK_exp2nextreg(ls->fs, v);

      expdesc first_arg;
      singlevar(ls, &first_arg, luaS_newliteral(ls->L, "self"));
      luaK_exp2nextreg(ls->fs, &first_arg);

      funcargs(ls, v);
    }
    else {
      singlevar(ls, v, luaS_newliteral(ls->L, "self"));
      luaK_exp2anyregup(ls->fs, v);
      expdesc key;
      codestring(&key, luaS_newliteral(ls->L, "__parent"));
      luaK_indexed(ls->fs, v, &key);
    }
  }
  else {
    throw_warn(ls, "'parent' used outside of a child class, defering to global called 'parent'", WT_BAD_PRACTICE);
    singlevar(ls, v, luaS_newliteral(ls->L, "parent"), false);  /* defer to global 'parent' */
  }
}


static void expsuffix (LexState* ls, expdesc* v, int line, int flags, TypeHint *prop);

static void primaryexp (LexState *ls, expdesc *v, int flags = 0) {
  /* primaryexp -> NAME | '(' expr ')' */
  if (isnametkn(ls, N_OVERRIDABLE)) {
    const bool is_overridable = ls->t.IsOverridable();
    TString *varname = str_checkname(ls, N_OVERRIDABLE);
    if (gett(ls) == TK_WALRUS) {
      if (flags & E_OR_KILLED_WALRUS)
        throwerr(ls, "':=' is not allowed in this context", "due to the 'or', it is no longer guaranteed that the local will be initialized by the time it's in scope.");
      if (!(flags & E_WALRUS) || ls->fs->freereg != luaY_nvarstack(ls->fs))
        throwerr(ls, "':=' is only allowed in 'if' and 'while' statements", "unexpected ':='");
      luaX_next(ls);
      new_localvar(ls, varname);
      expr(ls, v);
      adjust_assign(ls, 1, 1, v);
      adjustlocalvars(ls, 1);
      ls->used_walrus = true;
    }
    else
      singlevar(ls, v, varname, is_overridable);
    if (!ls->classes.empty() && strcmp(getstr(varname), "self") == 0) {
      selfexp(ls, v);
      return;
    }
    if (v->k == VENUM) {
      enumexp(ls, v, varname);
    }
    if (is_overridable && v->k == VVOID)
      luaX_prev(ls);
    else
      return;
  }
  switch (ls->t.token) {
    case '(': {
      int line = ls->getLineNumber();
      luaX_next(ls);
      expr(ls, v, nullptr, flags & (E_WALRUS | E_OR_KILLED_WALRUS));
      check_match(ls, ')', '(', line);
      luaK_dischargevars(ls->fs, v);
      return;
    }
    case '$': {
      luaX_next(ls); /* skip '$' */
      const_expr(ls, v);
      return;
    }
    case TK_PARENT:
    case TK_PPARENT: {
      luaX_next(ls);
      parentexp(ls, v);
      return;
    }
    case TK_STRING: {
      codestring(v, ls->t.seminfo.ts);
      luaX_next(ls);
      expsuffix(ls, v, ls->getLineNumber(), flags, nullptr);
      return;
    }
    case '{': {
      throwerr(ls, "unexpected symbol near '{'", "if you meant to begin this statement with a table, wrap it in parentheses.");
    }
    default: {
      if (ls->t.token == ')' && ls->getContext() == PARCTX_BODY) {
        throwerr(ls, "unexpected ')', expected 'end' to close function.", "missing 'end' before ')'.");
      }
      const char *token = luaX_token2str(ls, ls->t);
      throwerr(ls, luaO_fmt(ls->L, "unexpected symbol near %s", token), "unexpected symbol.");
    }
  }
}


static void suffixedexp (LexState *ls, expdesc *v, int flags = 0, TypeHint *prop = nullptr) {
  /* suffixedexp ->
       primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
  int line = ls->getLineNumber();
  primaryexp(ls, v, flags);
  if (prop) {
    if (v->k == VINDEXUP) {
      TValue *key = &ls->fs->f->k[v->u.ind.idx];
      prop->merge(get_global_prop(ls, tsvalue(key)));
    }
  }
  expsuffix(ls, v, line, flags, prop);
}

static void expsuffix (LexState *ls, expdesc *v, int line, int flags, TypeHint *prop) {
  FuncState *fs = ls->fs;
  for (;;) {
    switch (ls->t.token) {
      case '?': {  /* safe navigation or ternary */
        auto t = luaX_lookahead(ls);
        if (t != '[' && t != '.' && t != ':') {
          /* it's a ternary but we have to deal with that later */
          return; /* back to primaryexp */
        }
        luaX_next(ls); /* skip '?' */
        safe_navigation(ls, v);
        break;
      }
      case '.': {  /* fieldsel */
        fieldsel(ls, v);
        break;
      }
      case '[': {  /* '[' exp ']' */
        expdesc key;
        luaK_exp2anyregup(fs, v);
        yindex(ls, &key);
        luaK_indexed(fs, v, &key);
        break;
      }
      case ':': {  /* ':' NAME funcargs */
        if ((flags & E_NO_METHOD_CALL) || (flags & E_NO_CONSUME_COLON)) {
          return;
        }
        expdesc key;
        const auto colon_line = ls->t.line;
        const auto colon_column = ls->t.column;
        luaX_next(ls);  /* skip ':' */
        if (l_unlikely(colon_line != ls->t.line)) {
          throw_warn(ls, "possibly unwanted function call", luaO_fmt(ls->L, "possibly unwanted continuation of the expression on line %d.", colon_line), WT_POSSIBLE_TYPO);
          ls->L->top.p--;
        }
        else if (l_unlikely(ls->t.column != (colon_column + 1) && ls->getContext() == PARCTX_TERNARY_C)) {
          throw_warn(ls, "possible confusion with colons", "the second colon is interpreted as a method call instead of the first colon", "wrap the method call in parentheses", ls->t.line, WT_POSSIBLE_TYPO);
        }
        codename(ls, &key, N_RESERVED);
        luaK_self(fs, v, &key);
        method_call_funcargs(ls, v);
        break;
      }
      case '(': case TK_STRING: case '{': {  /* funcargs */
        if (flags & E_NO_CALL) {
          return;
        }
        if ((flags & E_PIPERHS) && ls->t.token == '(') {
          if (luaX_lookbehind(ls).line == ls->t.line)
            throw_warn(ls, "possible syntax confusion", "'(' is ignored by the pipe operator. use '|' if you meant to pass additional arguments.", WT_POSSIBLE_TYPO);
          return;
        }
        if (luaX_lookbehind(ls).line != ls->t.line && (ls->getContext() == PARCTX_LAMBDA_BODY || v->k == VCALL)) {
          throw_warn(ls, "possibly unwanted function call", luaO_fmt(ls->L, "possibly unwanted continuation of the expression on line %d.", luaX_lookbehind(ls).line), WT_POSSIBLE_TYPO);
          ls->L->top.p--;
        }
        Vardesc *vd;
        TypeDesc *funcdesc = nullptr;
        if (v->k == VLOCAL) {
          vd = getlocalvardesc(ls->fs, v->u.var.vidx);
        _funcdesc_from_vd:
          if (vd->vd.prop->descs[0].type == VT_FUNC  /* just in case... */
            && vd->vd.prop->descs[0].proto != nullptr  /* real function/not just a hint? */
          ) {
            funcdesc = &vd->vd.prop->descs[0];
            if (prop) { /* propagate return type */
              *prop = *vd->vd.prop->descs[0].retn;
            }
          }
        }
        else if (v->k == VUPVAL) {
          Upvaldesc *uv = &ls->fs->f->upvalues[v->u.info];
          FuncState *efs = ls->fs->prev;
          int idx = uv->idx;
          while (efs) { /* efs == nullptr && instack if resolving _ENV */
            if (uv->instack) {
              for (int i = 0; i != efs->nactvar; ++i) {
                vd = getlocalvardesc(efs, i);
                if (vd->vd.kind != RDKCTC && vd->vd.kind != RDKENUM  /* is in a register? */
                  && vd->vd.ridx == idx) {
                  goto _funcdesc_from_vd;
                }
              }
              break;
            }
            lua_assert(idx < efs->nups);
            uv = &efs->f->upvalues[idx];
            efs = efs->prev;
            idx = uv->idx;
          }
        }
        luaK_exp2nextreg(fs, v);
        funcargs(ls, v, funcdesc);
        break;
      }
      case TK_PIPE: {  /* '|>' NAME */
        if ((flags & E_NO_CALL) || (flags & E_PIPERHS)) {
          return;
        }
        luaX_next(ls);
        int nparams = 1;
        if (!(flags & E_NO_METHOD_CALL) && !(flags & E_NO_CONSUME_COLON) && ls->t.token != TK_EOS && luaX_lookahead(ls) == ':') {
          luaK_reserveregs(fs, 2);
          luaK_exp2nextreg(fs, v);
          fs->freereg -= 3;
          primaryexp(ls, v);
          checknext(ls, ':');
          expdesc key;
          codename(ls, &key);
          luaK_self(fs, v, &key);
          ++nparams;
        }
        else {
          luaK_exp2nextreg(fs, v);
          expdesc func;
          simpleexp(ls, &func, flags | E_PIPERHS);
          luaK_prepcallfirstarg(fs, v, &func);
        }
        lua_assert(v->k == VNONRELOC);
        int base = v->u.reg;  /* base register for call */
        if (testnext(ls, '|')) {
          do {
            expdesc arg;
            expr(ls, &arg, nullptr, E_NO_BOR);
            luaK_exp2nextreg(fs, &arg);
            ++nparams;
          } while (testnext(ls, ','));
          checknext(ls, '|');
        }
        init_exp(v, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams + 1, 2));
        luaK_fixline(fs, line);
        fs->freereg = base + 1;
        if (ls->t.token == '(' || ls->t.token == TK_STRING || ls->t.token == '{')
          return;
        break;
      }
      default: return;
    }
  }
}


static int cond (LexState *ls, bool for_while_loop = false);
static void ifexpr (LexState *ls, expdesc *v) {
  /*
  ** 'if' expressions are based on a patch published by by Ryota Hirose.
  */
  FuncState *fs = ls->fs;
  int condition;
  int escape = NO_JUMP;
  int reg;
  luaX_next(ls);
  condition = cond(ls);
  checknext(ls, TK_THEN);
  expr(ls, v);
  reg = luaK_exp2anyreg(fs, v);
  luaK_concat(fs, &escape, luaK_jump(fs));
  luaK_patchtohere(fs, condition);
  checknext(ls, TK_ELSE);
  expr(ls, v);
  checknext(ls, TK_END);
  luaK_exp2reg(fs, v, reg);
  luaK_patchtohere(fs, escape);
}


static void newexpr (LexState *ls, expdesc *v) {
  FuncState *fs = ls->fs;

  luaX_next(ls);

  singlevaraux(fs, luaS_newliteral(ls->L, "Pluto_operator_new"), v, 1);
  lua_assert(v->k != VVOID);
  luaK_exp2nextreg(fs, v);

  expdesc first_arg;
  expr(ls, &first_arg, nullptr, E_NO_CALL);
  luaK_exp2nextreg(fs, &first_arg);

  funcargs(ls, v);
}


static BinOpr subexpr (LexState *ls, expdesc *v, int limit, TypeHint *prop = nullptr, int flags = 0);


static BinOpr custombinaryoperator (LexState *ls, expdesc *v, int flags, TString *impl) {
  FuncState *fs = ls->fs;
  int line = ls->getLineNumber();

  expdesc func;
  singlevaraux(fs, impl, &func, 1);
  lua_assert(v->k != VVOID);
  luaK_prepcallfirstarg(fs, v, &func);
  lua_assert(v->k == VNONRELOC);
  int base = v->u.reg;  /* base register for call */

  expdesc arg2;
  auto nextop = subexpr(ls, &arg2, 3, nullptr, flags);
  luaK_exp2nextreg(fs, &arg2);

  int nparams = fs->freereg - (base + 1);
  init_exp(v, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams + 1, 2));
  luaK_fixline(fs, line);
  fs->freereg = base + 1;

  return nextop;
}


static void lgoto (LexState *ls, TString *name, int line) {
  FuncState *fs = ls->fs;
  Labeldesc *lb = findlabel(ls, name);
  if (lb == NULL)  /* no label? */
    /* forward jump; will be resolved when the label is declared */
    newgotoentry(ls, name, line, luaK_jump(fs), false);
  else {  /* found a label */
    /* backward jump; will be resolved here */
    int lblevel = reglevel(fs, lb->nactvar);  /* label level */
    if (luaY_nvarstack(fs) > lblevel)  /* leaving the scope of a variable? */
      luaK_codeABC(fs, OP_CLOSE, lblevel, 0, 0);
    /* create jump and link it to the label */
    luaK_patchlist(fs, luaK_jump(fs), lb->pc);
  }
}


static std::vector<int> casecond (LexState *ls, const expdesc& ctrl, int tk) {
  std::vector<int> jumps{};
  FuncState *fs = ls->fs;
  const auto case_line = ls->getLineNumber();

  int expr_flags = 0;
  if (tk == ':') {
    expr_flags |= E_NO_CONSUME_COLON;
  }

  expdesc e, cmpval;
  e = ctrl;
  luaK_infix(fs, OPR_EQ, &e);
  expr(ls, &cmpval, nullptr, expr_flags);
  luaK_posfix(fs, OPR_EQ, &e, &cmpval, case_line);
  jumps.emplace_back(e.u.pc);
  while (testnext(ls, ',')) {
    e = ctrl;
    luaK_infix(fs, OPR_EQ, &e);
    expr(ls, &cmpval, nullptr, expr_flags);
    luaK_posfix(fs, OPR_EQ, &e, &cmpval, case_line);
    jumps.emplace_back(e.u.pc);
  }
  checknext(ls, tk);

  return jumps;
}

static void switchimpl (LexState *ls, int tk, void(*caselist)(LexState*,void*), void *ud = nullptr) {
  const auto line = ls->getLineNumber();
  const auto switchToken = gett(ls);
  luaX_next(ls); // Skip switch statement.

  ls->switchstates.emplace();
  FuncState *fs = ls->fs;
  BlockCnt sbl;

  lu_byte freereg = fs->freereg;
  if (tk == TK_ARROW)
    fs->freereg = luaY_nvarstack(fs); // To prevent assert in enterblock
  enterblock(fs, &sbl, BlockType::BT_BREAK);
  fs->freereg = freereg;

  int prevpinnedreg = -1;
  expdesc ctrl;
  expr(ls, &ctrl);
  checknext(ls, TK_DO);
  if (!vkhasregister(ctrl.k)
    || ctrl.t != ctrl.f  /* has jumps? */
  ) {
    luaK_exp2nextreg(ls->fs, &ctrl);
    if (tk == TK_ARROW) {
      prevpinnedreg = fs->pinnedreg;
      fs->pinnedreg = ctrl.u.reg;
    }
    else {
      new_localvarliteral(ls, "(switch control value)"); // Save control value into a local.
      adjustlocalvars(ls, 1);
    }
  }

  const auto nactvar = fs->nactvar;

  std::vector<int>& first = ls->switchstates.top().first;
  int default_pc = -1;
  int first_pc, goto_begin_pc;

  if (gett(ls) == TK_CASE) {
    luaX_next(ls); /* Skip 'case' */
    first = casecond(ls, ctrl, tk);
    first_pc = luaK_getlabel(fs);
    caselist(ls, ud);
  }
  else {
    goto_begin_pc = luaK_jump(fs);
  }

  std::vector<SwitchCase>& cases = ls->switchstates.top().cases;

  while (gett(ls) != TK_END) {
    auto case_line = ls->getLineNumber();
    if (fs->nactvar != nactvar) {
      Vardesc *var = getlocalvardesc(ls->fs, nactvar);
      const char *msg = "this case jumps into the scope of local '%s' defined on line %d";
      msg = luaO_pushfstring(ls->L, msg, getstr(var->vd.name), var->vd.line);
      luaK_semerror(ls, msg);  /* raise the error */
    }
    if (gett(ls) == TK_DEFAULT) {
      luaX_next(ls); /* Skip 'default' */
      checknext(ls, tk);
      if (default_pc != -1)
        throwerr(ls, "switch statement already has a default case", "second default case", case_line);
      default_pc = luaK_getlabel(fs);
    }
    else {
      checknext(ls, TK_CASE);
      cases.emplace_back(SwitchCase{ luaX_getpos(ls), luaK_getlabel(fs) });
      skip_until(ls, tk); /* skip over casecond */
      checknext(ls, tk);
    }
    ls->laststat.token = TK_EOS;  /* We don't want warnings for trailing control flow statements. */
    caselist(ls, ud);
  }

  if (ls->laststat.token != TK_BREAK) {  /* last block did not have 'break'? */
    if (tk == ':') {  /* switch statement? */
      /* jump to the end of switch as otherwise we would loop infinitely */
      lbreak(ls, 1, ls->getLineNumber(), luaK_jump(fs));
    }
  }

  /* if switch expression has no default case, generate one to guarantee nil in that case
     otherwise, the value returned by the expression would be whatever was in the register before */
  if (tk == TK_ARROW && default_pc == -1) {
    default_pc = luaK_getlabel(fs);
    const auto line = ls->getLineNumber();
    const auto reg = reinterpret_cast<expdesc*>(ud)->u.reg;
    expdesc cv;
    init_exp(&cv, VNIL, 0);
    luaK_exp2reg(ls->fs, &cv, reg);
    lbreak(ls, 1, line, luaK_jump(fs));
  }

  if (!first.empty()) {
    for (int i = 0; i != first.size() - 1; ++i) {
      luaK_patchlist(fs, first.at(i), first_pc);
    }
    luaK_invertcond(fs, first.back());
    luaK_patchtohere(fs, first.back());
  }
  else {
    luaK_patchtohere(fs, goto_begin_pc);
  }

  /* prune cases that lead to default case */
  if (default_pc != -1) {
    for (auto i = cases.begin(); i != cases.end(); ) {
      if (i->pc == default_pc) {
        i = cases.erase(i);
      }
      else {
        ++i;
      }
    }
  }

  int nactvarend = ls->fs->nactvar;
  ls->fs->nactvar = nactvar;  /* variables declared inside of switch body don't exist yet */
  for (auto& c : cases) {
    auto pos = luaX_getpos(ls);
    luaX_setpos(ls, c.tidx);
    for (const auto& j : casecond(ls, ctrl, tk)) {
      luaK_patchlist(fs, j, c.pc);
    }
    luaX_setpos(ls, pos);
  }
  ls->fs->nactvar = nactvarend;

  if (default_pc != -1)
    luaK_jumpto(fs, default_pc);

  if (tk == TK_ARROW && fs->pinnedreg != -1) {
    fs->pinnedreg = prevpinnedreg;
    luaK_freeexp(fs, &ctrl);
  }

  check_match(ls, TK_END, switchToken, line);
  leaveblock(fs);
  if (tk == TK_ARROW)
    fs->freereg = freereg;
  ls->switchstates.pop();
}

static void switchstat (LexState *ls) {
  switchimpl(ls, ':', [](LexState* ls, void*) {
    const int case_line = luaX_lookbehind(ls).line;
    if (gett(ls) == TK_CASE || gett(ls) == TK_DEFAULT || gett(ls) == TK_END) {
      /* this case is empty, nothing to do */
    }
    else if (gett(ls) == TK_FALLTHROUGH) {
      /* empty case explicitly declaring itself to be a fallthrough */
      luaX_next(ls);
    }
    else {
      do {
        statement(ls);
      }
      while (gett(ls) != TK_CASE && gett(ls) != TK_DEFAULT && gett(ls) != TK_END && gett(ls) != TK_FALLTHROUGH);
      if (ls->t.token == TK_CASE && ls->laststat.token != TK_BREAK && ls->laststat.token != TK_RETURN && ls->laststat.token != TK_GOTO) {
        throw_warn(ls, "possibly unwanted fallthrough", luaO_fmt(ls->L, "the case on line %d flows into this case", case_line), "place `--@fallthrough` before this case if this is intended", ls->getLineNumber(), WT_UNANNOTATED_FALLTHROUGH);
        ls->L->top.p--;
      }
      else testnext(ls, TK_FALLTHROUGH);
    }
  });
}

static void switchexpr (LexState *ls, expdesc *v) {
  init_exp(v, VNONRELOC, ls->fs->freereg);
  luaK_reserveregs(ls->fs, 1);
  switchimpl(ls, TK_ARROW, [](LexState *ls, void *ud) {
    const auto line = ls->getLineNumber();
    const auto reg = reinterpret_cast<expdesc*>(ud)->u.reg;
    expdesc cv;
    expr(ls, &cv);
    luaK_exp2reg(ls->fs, &cv, reg);
    lbreak(ls, 1, line, luaK_jump(ls->fs));
  }, v);
}


static void simpleexp (LexState *ls, expdesc *v, int flags, TypeHint *prop) {
  /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
                  constructor | FUNCTION body | suffixedexp */
  check_for_non_portable_code(ls);
  switch (ls->t.token) {
    case TK_FLT: {
      if (prop) prop->emplaceTypeDesc(VT_FLT);
      init_exp(v, VKFLT, 0);
      v->u.nval = ls->t.seminfo.r;
      luaX_next(ls);
      return;
    }
    case TK_INT: {
      if (prop) prop->emplaceTypeDesc(VT_INT);
      init_exp(v, VKINT, 0);
      v->u.ival = ls->t.seminfo.i;
      luaX_next(ls);
      return;
    }
    case TK_STRING: {
      if (prop) prop->emplaceTypeDesc(VT_STR);
      codestring(v, ls->t.seminfo.ts);
      luaX_next(ls);
      if (ls->t.token == '[' || ls->t.token == ':' || ls->t.token == TK_PIPE)
        break;
      return;
    }
    case TK_NIL: {
      if (prop) prop->emplaceTypeDesc(VT_NIL);
      init_exp(v, VNIL, 0);
      luaX_next(ls);
      return;
    }
    case TK_TRUE: {
      if (prop) prop->emplaceTypeDesc(VT_BOOL);
      init_exp(v, VTRUE, 0);
      luaX_next(ls);
      return;
    }
    case TK_FALSE: {
      if (prop) prop->emplaceTypeDesc(VT_BOOL);
      init_exp(v, VFALSE, 0);
      luaX_next(ls);
      return;
    }
    case TK_DOTS: {  /* vararg */
      FuncState *fs = ls->fs;
      check_condition(ls, fs->f->is_vararg,
                      "cannot use '...' outside a vararg function");
      init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 0, 1));
      luaX_next(ls);
      break;
    }
    case '{': {  /* constructor */
      if (prop) prop->emplaceTypeDesc(VT_TABLE);
      constructor(ls, v);
      if (ls->t.token == '[' || ls->t.token == ':' || ls->t.token == '.' || ls->t.token == TK_PIPE)
        break;
      return;
    }
    case TK_FUNCTION: {
      check_condition(ls, !(flags & E_NO_CONSUME_COLON), "cannot instantiate a function in this context");
      luaX_next(ls);
      if (prop) {
        TypeDesc funcdesc;
        body(ls, v, 0, ls->getLineNumber(), &funcdesc);
        prop->emplaceTypeDesc(std::move(funcdesc));
      }
      else {
        body(ls, v, 0, ls->getLineNumber());
      }
      return;
    }
    case '|': {
      check_condition(ls, !(flags & E_NO_CONSUME_COLON), "cannot instantiate a function in this context");
      luaX_next(ls);
      if (prop) {
        TypeDesc funcdesc;
        lambdabody(ls, v, ls->getLineNumber(), &funcdesc);
        prop->emplaceTypeDesc(std::move(funcdesc));
      }
      else {
        lambdabody(ls, v, ls->getLineNumber());
      }
      return;
    }
    case TK_NEW:
    case TK_PNEW: {
      if (prop) prop->emplaceTypeDesc(VT_TABLE);
      newexpr(ls, v);
      break;
    }
    case TK_CLASS:
    case TK_PCLASS: {
      if (prop) prop->emplaceTypeDesc(VT_TABLE);
      luaX_next(ls); /* skip 'class' */
      ls->classes.emplace();
      classexpr(ls, v);
      ls->classes.pop();
      return;
    }
    case TK_SWITCH:
    case TK_PSWITCH: {
      switchexpr(ls, v);
      return;
    }
    default: {
      suffixedexp(ls, v, flags, prop);
      return;
    }
  }
  expsuffix(ls, v, ls->getLineNumber(), flags, prop);
}


static void inexpr (LexState *ls, expdesc *v, int flags) {
  expdesc v2;
  checknext(ls, TK_IN);
  luaK_exp2nextreg(ls->fs, v);
  lua_assert(v->k == VNONRELOC);
  int base = v->u.reg;
  simpleexp(ls, &v2, flags);
  luaK_dischargevars(ls->fs, &v2);
  luaK_exp2nextreg(ls->fs, &v2);
  luaK_codeABC(ls->fs, OP_IN, v->u.reg, v2.u.reg, 0);
  ls->fs->f->onPlutoOpUsed(0);
  ls->fs->freereg = base + 1;
}


static UnOpr getunopr (int op) {
  switch (op) {
    case TK_NOT: return OPR_NOT;
    case '-': return OPR_MINUS;
    case '~': return OPR_BNOT;
    case '#': return OPR_LEN;
    default: return OPR_NOUNOPR;
  }
}


static BinOpr getbinopr (int op) {
  switch (op) {
    case '+': return OPR_ADD;
    case '-': return OPR_SUB;
    case '*': return OPR_MUL;
    case '%': return OPR_MOD;
    case '^': return OPR_POW;
    case '/': return OPR_DIV;
    case TK_IDIV: return OPR_IDIV;
    case '&': return OPR_BAND;
    case '|': return OPR_BOR;
    case '~': return OPR_BXOR;
    case TK_SHL: return OPR_SHL;
    case TK_SHR: return OPR_SHR;
    case TK_CONCAT: return OPR_CONCAT;
    case TK_NE: case TK_NE2: return OPR_NE;
    case TK_EQ: return OPR_EQ;
    case '<': return OPR_LT;
    case TK_LE: return OPR_LE;
    case '>': return OPR_GT;
    case TK_GE: return OPR_GE;
    case TK_SPACESHIP: return OPR_SPACESHIP;
    case TK_INSTANCEOF: return OPR_INSTANCEOF;
    case TK_AND: return OPR_AND;
    case TK_OR: return OPR_OR;
    case TK_COAL: return OPR_COAL;
    case TK_POW: return OPR_POW;  /* '**' operator support */
    default: return OPR_NOBINOPR;
  }
}


static void prefixplusplus (LexState *ls, expdesc *v, bool as_statement) {
  int line = ls->getLineNumber();
  luaX_next(ls); /* skip second '+' */
  if (as_statement)
    suffixedexp(ls, v);
  else
    singlevar(ls, v); /* variable name */
  FuncState *fs = ls->fs;
  expdesc e = *v, v2;
  if (v->k != VLOCAL) {  /* complex lvalue, use a temporary register. linear perf incr. with complexity of lvalue */
    const auto regs_to_reserve = fs->freereg-fs->nactvar;
    luaK_dischargevars(fs, &e);
    luaK_reserveregs(fs, regs_to_reserve);
    enterlevel(ls);
    luaK_infix(fs, OPR_ADD, &e);
    init_exp(&v2, VKINT, 0);
    v2.u.ival = 1;
    luaK_posfix(fs, OPR_ADD, &e, &v2, line);
    leavelevel(ls);
    luaK_exp2nextreg(fs, &e);
    luaK_setoneret(ls->fs, &e);
    luaK_storevar(ls->fs, v, &e);
  }
  else {  /* simple lvalue; a local. directly change value (~20% speedup vs temporary register) */
    enterlevel(ls);
    luaK_infix(fs, OPR_ADD, &e);
    init_exp(&v2, VKINT, 0);
    v2.u.ival = 1;
    luaK_posfix(fs, OPR_ADD, &e, &v2, line);
    leavelevel(ls);
    luaK_setoneret(ls->fs, &e);
    luaK_storevar(ls->fs, v, &e);
  }
}


/*
** Priority table for binary operators.
*/
static const struct {
  lu_byte left;  /* left priority for each binary operator */
  lu_byte right; /* right priority */
} priority[] = {  /* ORDER OPR */
   {10, 10}, {10, 10},           /* '+' '-' */
   {11, 11}, {11, 11},           /* '*' '%' */
   {14, 13},                  /* '^' (right associative) */
   {11, 11}, {11, 11},           /* '/' '//' */
   {6, 6}, {4, 4}, {5, 5},   /* '&' '|' '~' */
   {7, 7}, {7, 7},           /* '<<' '>>' */
   {9, 8},                   /* '..' (right associative) */
   {3, 3}, {3, 3}, {3, 3},   /* ==, <, <= */
   {3, 3}, {3, 3}, {3, 3},   /* ~=, >, >= */
   {3, 3}, {3, 3},           /* <=>, instanceof */
   {2, 2}, {1, 1}, {1, 1},   /* and, or, ?? */
};

#define UNARY_PRIORITY	12  /* priority for unary operators */


[[nodiscard]] static constexpr bool canchainopr (BinOpr opr) noexcept {
  return opr == OPR_LT || opr == OPR_LE || opr == OPR_GT || opr == OPR_GE;
}


/*
** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
** where 'binop' is any binary operator with a priority higher than 'limit'
*/
static BinOpr subexpr (LexState *ls, expdesc *v, int limit, TypeHint *prop, int flags) {
  BinOpr op;
  UnOpr uop;
  enterlevel(ls);
  uop = getunopr(ls->t.token);
  if (uop != OPR_NOUNOPR) {  /* prefix (unary) operator? */
    int line = ls->getLineNumber();
    luaX_next(ls);  /* skip operator */
    subexpr(ls, v, UNARY_PRIORITY, nullptr, flags);
    luaK_prefix(ls->fs, uop, v, line);
  }
  else if (ls->t.token == TK_IF) ifexpr(ls, v);
  else if (ls->t.token == '+') {
    int line = ls->getLineNumber();
    luaX_next(ls); /* skip '+' */
    if (ls->t.token == '+') { /* '++' ? */
      prefixplusplus(ls, v, false);
    }
    else {
      /* support pseudo-unary '+' by implying '0 + subexpr' */
      init_exp(v, VKINT, 0);
      v->u.ival = 0;
      luaK_infix(ls->fs, OPR_ADD, v);

      expdesc v2;
      subexpr(ls, &v2, priority[OPR_ADD].right, nullptr, flags);
      luaK_posfix(ls->fs, OPR_ADD, v, &v2, line);
    }
  }
  else {
    simpleexp(ls, v, flags, prop);
    if (ls->t.token == TK_IN) {
      throw_warn(ls, "non-portable operator usage", "this operator generates bytecode that is incompatible with Lua.", WT_NON_PORTABLE_BYTECODE);
      inexpr(ls, v, flags);
      if (prop) prop->emplaceTypeDesc(VT_BOOL);
    }
  }
  if (ls->t.token == '+' && luaX_lookahead(ls) == '+') { /* disambiguate '+' operator and '++' as next statement */
    leavelevel(ls);
    return OPR_NOBINOPR;
  }
  /* expand while operators have priorities higher than 'limit' */
  if (l_unlikely(ls->t.token == TK_POW))
    throw_warn(ls, "'**' is deprecated", "use '^' instead", WT_DEPRECATED);
  op = getbinopr(ls->t.token);
  if ((flags & E_NO_BOR) && op == OPR_BOR)
    op = OPR_NOBINOPR;
  while (op != OPR_NOBINOPR && priority[op].left > limit) {
    if (prop && op != OPR_COAL)
      prop->clear();
    expdesc v2;
    BinOpr nextop;
    int line = ls->getLineNumber();
    luaX_next(ls);  /* skip operator */
    if (op == OPR_INSTANCEOF) {
      custombinaryoperator(ls, v, flags, luaS_newliteral(ls->L, "Pluto_operator_instanceof"));
      nextop = getbinopr(ls->t.token);
    }
    else if (op == OPR_SPACESHIP) {
      custombinaryoperator(ls, v, flags, luaS_newliteral(ls->L, "Pluto_operator_spaceship"));
      nextop = getbinopr(ls->t.token);
    }
    else {
      TypeHint *subexpr_prop = nullptr;
      if (op == OPR_CONCAT) {
        if (prop)
          prop->emplaceTypeDesc(VT_STR);
        if (v->t == NO_JUMP && v->f == NO_JUMP) {
          TString *lhs = nullptr;
          if (v->k == VKSTR)
            lhs = v->u.strval;
          else if (v->k == VCONST && ttisstring(&ls->dyd->actvar.arr[v->u.info].k))
            lhs = tsvalue(&ls->dyd->actvar.arr[v->u.info].k);
          if (lhs && ls->t.token == TK_STRING) {
            const auto lhs_size = tsslen(lhs);
            const auto rhs_size = tsslen(ls->t.seminfo.ts);
            auto data = new char[lhs_size + rhs_size];
            memcpy(data, getstr(lhs), lhs_size);
            memcpy(data + lhs_size, getstr(ls->t.seminfo.ts), rhs_size);
            v->k = VKSTR;
            v->u.strval = luaX_newstring(ls, data, lhs_size + rhs_size);
            delete[] data;
            luaX_next(ls);
            op = getbinopr(ls->t.token);
            continue;
          }
        }
      }
      else if (op == OPR_COAL) {
        if (luaK_isalwaysnil(ls, v)) {
          /* weird, but nothing worth talking about... */
        }
        else {
          if (luaK_isalwaystrue(ls, v) || luaK_isalwaysfalse(ls, v))
            throw_warn(ls, "unreachable code", "the expression before the '?\?' is never nil, hence the expression after the '?\?' is never used.", WT_UNREACHABLE_CODE);
        }
        if (prop) {
          prop->erase(VT_NIL);
          subexpr_prop = prop;
        }
      }
      luaK_infix(ls->fs, op, v);
      /* read sub-expression with higher priority */
      if (op == OPR_OR && (flags & E_WALRUS)) {
        if (ls->used_walrus)
          throwerr(ls, "'or' invalidates previous usages of walrus operator", "due to the 'or', it is no longer guaranteed that the local will be initialized by the time it's in scope.");
        flags &= ~E_WALRUS;
        flags |= E_OR_KILLED_WALRUS;
      }
      nextop = subexpr(ls, &v2, priority[op].right, subexpr_prop, flags);
      luaK_posfix(ls->fs, op, v, &v2, line);
      if (canchainopr(op) && canchainopr(nextop)) {
        while (true) {
          op = nextop;
          if (v2.k == VNONRELOC && ls->fs->freereg == v2.u.reg) {
            ls->fs->freereg++;
          }
          luaX_next(ls);  /* skip operator */
          /* to generate 'a < b < c': 'a < b' is in `v`. 'b' is in `v2`. 'c' can be read from lexer state. */
          luaK_infix(ls->fs, OPR_AND, v);
          expdesc v3;
          luaK_infix(ls->fs, op, &v2);
          nextop = subexpr(ls, &v3, priority[op].right, subexpr_prop, flags);
          luaK_posfix(ls->fs, op, &v2, &v3, line);
          luaK_posfix(ls->fs, OPR_AND, v, &v2, line);
          if (!canchainopr(nextop))
            break;
          v2 = v3;
        }
      }
    }
    op = nextop;
  }
  leavelevel(ls);
  return op;  /* return first untreated operator */
}


static void expr (LexState *ls, expdesc *v, TypeHint *prop, int flags) {
#ifdef PLUTO_PARSER_SUGGESTIONS
  if (ls->shouldSuggest()) {
    SuggestionsState ss(ls);
    ss.pushLocals();
  }
#endif
  subexpr(ls, v, 0, prop, flags);
  if (testnext(ls, '?')) { /* ternary expression? */
    check_condition(ls, !(flags & E_NO_CONSUME_COLON), "cannot use a ternary expression in this context");
    if (prop) prop->clear(); /* we don't care what type the condition is/was */
    int escape = NO_JUMP;
    v->normalizeFalse();
    if (luaK_isalwaystrue(ls, v))
      throw_warn(ls, "unreachable code", "the condition before the '?' is always truthy, hence the expression after the ':' is never used.", WT_UNREACHABLE_CODE);
    else if (luaK_isalwaysfalse(ls, v))
      throw_warn(ls, "unreachable code", "the condition before the '?' is always falsy, hence the expression before the ':' is never used.", WT_UNREACHABLE_CODE);
    luaK_goiftrue(ls->fs, v);
    int condition = v->f;
    expr(ls, v, prop, E_NO_METHOD_CALL);
    auto fs = ls->fs;
    auto reg = luaK_exp2anyreg(fs, v);
    luaK_concat(fs, &escape, luaK_jump(fs));
    luaK_patchtohere(fs, condition);
    checknext(ls, ':');
    ls->pushContext(PARCTX_TERNARY_C);
    expr(ls, v, prop, flags & E_NO_METHOD_CALL);
    ls->popContext(PARCTX_TERNARY_C);
    luaK_exp2reg(fs, v, reg);
    luaK_patchtohere(fs, escape);
  }
}

/* }==================================================================== */



/*
** {======================================================================
** Rules for Statements
** =======================================================================
*/


static void block (LexState *ls, TypeHint *prop = nullptr) {
  /* block -> statlist */
  FuncState *fs = ls->fs;
  BlockCnt bl;
  enterblock(fs, &bl, BlockType::BT_DEFAULT);
  statlist(ls, prop);
  leaveblock(fs);
}


/*
** structure to chain all variables in the left-hand side of an
** assignment
*/
struct LHS_assign {
  struct LHS_assign *prev, *next; /* previous & next lhs objects */
  expdesc v;  /* variable (global, local, upvalue, or indexed) */
};


/*
** check whether, in an assignment to an upvalue/local variable, the
** upvalue/local variable is begin used in a previous assignment to a
** table. If so, save original upvalue/local value in a safe place and
** use this safe copy in the previous assignment.
*/
static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
  FuncState *fs = ls->fs;
  int extra = fs->freereg;  /* eventual position to save local variable */
  int conflict = 0;
  for (; lh; lh = lh->prev) {  /* check all previous assignments */
    if (vkisindexed(lh->v.k)) {  /* assignment to table field? */
      if (lh->v.k == VINDEXUP) {  /* is table an upvalue? */
        if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) {
          conflict = 1;  /* table is the upvalue being assigned now */
          lh->v.k = VINDEXSTR;
          lh->v.u.ind.t = extra;  /* assignment will use safe copy */
        }
      }
      else {  /* table is a register */
        if (v->k == VLOCAL && lh->v.u.ind.t == v->u.var.ridx) {
          conflict = 1;  /* table is the local being assigned now */
          lh->v.u.ind.t = extra;  /* assignment will use safe copy */
        }
        /* is index the local being assigned? */
        if (lh->v.k == VINDEXED && v->k == VLOCAL &&
            lh->v.u.ind.idx == v->u.var.ridx) {
          conflict = 1;
          lh->v.u.ind.idx = extra;  /* previous assignment will use safe copy */
        }
      }
    }
  }
  if (conflict) {
    /* copy upvalue/local value to a temporary (in position 'extra') */
    if (v->k == VLOCAL)
      luaK_codeABC(fs, OP_MOVE, extra, v->u.var.ridx, 0);
    else
      luaK_codeABC(fs, OP_GETUPVAL, extra, v->u.info, 0);
    luaK_reserveregs(fs, 1);
  }
}

/* 
  compound assignment function
  determines the binary operation to perform depending on lexer state tokens (ls->lasttoken)
  resets the lexer state token
  reserves N registers (where N = local variables on stack)
  preforms binary operation and assignment
*/ 
static void compoundassign (LexState *ls, expdesc *v, BinOpr op) {
  luaX_next(ls);
  int line = ls->getLineNumber();
  FuncState *fs = ls->fs;
  expdesc e = *v, v2;
  if (v->k != VLOCAL) {  /* complex lvalue, use a temporary register. linear perf incr. with complexity of lvalue */
    const auto regs_to_reserve = fs->freereg-fs->nactvar;
    luaK_dischargevars(fs, &e);
    luaK_reserveregs(fs, regs_to_reserve);
    enterlevel(ls);
    luaK_infix(fs, op, &e);
    expr(ls, &v2);
    luaK_posfix(fs, op, &e, &v2, line);
    leavelevel(ls);
    luaK_exp2nextreg(fs, &e);
    luaK_setoneret(ls->fs, &e);
    luaK_storevar(ls->fs, v, &e);
  }
  else {  /* simple lvalue; a local. directly change value (~20% speedup vs temporary register) */
    enterlevel(ls);
    luaK_infix(fs, op, &e);
    expr(ls, &v2);
    luaK_posfix(fs, op, &e, &v2, line);
    leavelevel(ls);
    luaK_setoneret(ls->fs, &e);
    luaK_storevar(ls->fs, v, &e);
  }
}

/*
  assignment function
  handles every Lua assignment
  special cases for compound operators via lexer state tokens (ls->t.seminfo.i)
*/
static void restassign (LexState *ls, struct LHS_assign *lh, int nvars) {
  int line = ls->getLineNumber(); /* in case we need to emit a warning */
  expdesc e;
  check_condition(ls, vkisvar(lh->v.k), "syntax error");
  check_readonly(ls, &lh->v);
  if (testnext(ls, ',')) {  /* restassign -> ',' suffixedexp restassign */
    struct LHS_assign nv;
    nv.prev = lh;
    nv.next = NULL;
    lh->next = &nv;
    suffixedexp(ls, &nv.v);
    if (!vkisindexed(nv.v.k))
      check_conflict(ls, lh, &nv.v);
    enterlevel(ls);  /* control recursion depth */
    restassign(ls, &nv, nvars+1);
    leavelevel(ls);
  }
  else {  /* restassign -> '=' explist */
    if (ls->t.token != TK_NE)
      check(ls, '=');
    BinOpr compound_op = (ls->t.token == TK_NE ? OPR_BXOR : getbinopr((int)ls->t.seminfo.i));
    if (compound_op != OPR_NOBINOPR) {  /* compound operator? */
      if (l_unlikely(ls->t.seminfo.i == TK_POW))
        throw_warn(ls, "'**' is deprecated", "use '^' instead", WT_DEPRECATED);
      check_condition(ls, nvars == 1, "unsupported tuple assignment");
      compoundassign(ls, &lh->v, compound_op);  /* perform binop & assignment */
      return;  /* avoid default */
    }
    luaX_next(ls);
    TypeHint prop{};
    ParserContext ctx = ((nvars == 1) ? PARCTX_CREATE_VAR : PARCTX_CREATE_VARS);
    ls->pushContext(ctx);
    int nexps = explist(ls, &e, &prop);
    ls->popContext(ctx);
    if (nexps != nvars)
      adjust_assign(ls, nvars, nexps, &e);
    else {
      luaK_setoneret(ls->fs, &e);  /* close last expression */
      if (lh->v.k == VINDEXUP) {
        TValue *key = &ls->fs->f->k[lh->v.u.ind.idx];
        lua_assert(ttype(key) == LUA_TSTRING);
        get_global_prop(ls, tsvalue(key)).merge(prop);
      }
      if (lh->v.k == VLOCAL) { /* assigning to a local variable? */
        exp_propagate(ls, e, prop);
        process_assign(ls, lh->v.u.var.vidx, prop, line);
      }
      luaK_storevar(ls->fs, &lh->v, &e);
      return;  /* avoid default */
    }
  }
  init_exp(&e, VNONRELOC, ls->fs->freereg-1);  /* default assignment */
  luaK_storevar(ls->fs, &lh->v, &e);
}

static int cond (LexState *ls, bool for_while_loop) {
  /* cond -> exp */
  expdesc v;
  ls->used_walrus = false;
  expr(ls, &v, nullptr, for_while_loop * E_WALRUS);  /* read condition */
  v.normalizeFalse();
  luaK_goiftrue(ls->fs, &v);
  return v.f;
}


static void gotostat (LexState *ls) {
  const auto line = ls->getLineNumber();
  lgoto(ls, str_checkname(ls, N_RESERVED), line);
}


static void enumstat (LexState *ls) {
  /* enumstat -> ENUM [[CLASS] NAME] BEGIN NAME ['=' INT] { ',' NAME ['=' INT] } END */

  luaX_next(ls); /* skip 'enum' */

  EnumDesc *ed = nullptr;
  bool is_enum_class = false;
  if (gett(ls) != TK_BEGIN && gett(ls) != TK_DO) { /* enum has name (and possibly modifier)? */
    if (ls->t.token == TK_CLASS
      || (ls->t.token == TK_NAME && strcmp(getstr(ls->t.seminfo.ts), "class") == 0)
      ) {
      is_enum_class = true;
      luaX_next(ls);
    }
    auto vidx = new_localvar(ls, str_checkname(ls, 0), ls->getLineNumber());
    auto var = getlocalvardesc(ls->fs, vidx);
    var->vd.kind = RDKENUM;
    setivalue(&var->k, ls->enums.size());
    ed = &ls->enums.emplace_back(EnumDesc{});
    ls->fs->nactvar++;
  }

  const auto line_begin = ls->getLineNumber();
  if (!testnext(ls, TK_DO))
    checknext(ls, TK_BEGIN);

  lua_Integer i = 1;
  while (gett(ls) != TK_END) {
    TString *name = str_checkname(ls, 0);
    int vidx;
    if (!is_enum_class) {
      vidx = new_localvar(ls, name, ls->getLineNumber());
    }
    if (testnext(ls, '=')) {
      expdesc v;
      expr(ls, &v);
      if (v.k == VCONST) { /* compile-time constant? */
        TValue *k = &ls->dyd->actvar.arr[v.u.info].k;
        if (ttype(k) == LUA_TNUMBER && ttisinteger(k)) { /* integer value? */
          init_exp(&v, VKINT, 0);
          v.u.ival = ivalue(k);
        }
      }
      if (v.k != VKINT) { /* assert expdesc kind */
        throwerr(ls, "expected integer constant", "unexpected expression type");
      }
      i = v.u.ival;
    }
    if (ed) {
      ed->enumerators.emplace_back(EnumDesc::Enumerator{ name, i });
    }
    if (!is_enum_class) {
      auto var = getlocalvardesc(ls->fs, vidx);
      var->vd.kind = RDKCTC;
      setivalue(&var->k, i);
      ls->fs->nactvar++;
    }
    i++;
    if (gett(ls) != ',') break;
    luaX_next(ls);
  }

  check_match(ls, TK_END, TK_ENUM, line_begin);
}


/*
** Check whether there is already a label with the given 'name'.
*/
static void checkrepeated (LexState *ls, TString *name) {
  Labeldesc *lb = findlabel(ls, name);
  if (l_unlikely(lb != NULL)) {  /* already defined? */
    const char *msg = "label '%s' already defined on line %d";
    msg = luaO_pushfstring(ls->L, msg, getstr(name), lb->line);
    luaK_semerror(ls, msg);  /* error */
  }
}


static void labelstat (LexState *ls, TString *name, int line) {
  /* label -> '::' NAME '::' */
  checknext(ls, TK_DBCOLON);  /* skip double colon */
  while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
    statement(ls);  /* skip other no-op statements */
  checkrepeated(ls, name);  /* check for repeated labels */
  createlabel(ls, name, line, block_follow(ls, 0), false);
}


static void whilestat (LexState *ls, int line) {
  /* whilestat -> WHILE cond DO block END */
  FuncState *fs = ls->fs;
  int whileinit;
  int condexit;
  BlockCnt bl;
  BlockCnt innerbl;

  luaX_next(ls);  /* skip WHILE */
  whileinit = luaK_getlabel(fs);
  enterblock(fs, &bl, BlockType::BT_BREAK);
  enterblock(fs, &innerbl, BlockType::BT_CONTINUE);
  condexit = cond(ls, true);
  checknext(ls, TK_DO);
  statlist(ls);
  leaveblock(fs);
  luaK_jumpto(fs, whileinit);
  check_match(ls, TK_END, TK_WHILE, line);
  leaveblock(fs);
  luaK_patchtohere(fs, condexit);  /* false conditions finish the loop */
}


static void repeatstat (LexState *ls) {
  /* repeatstat -> REPEAT block ( UNTIL | WHEN ) cond */
  int condexit;
  FuncState *fs = ls->fs;
  int repeat_init = luaK_getlabel(fs);
  BlockCnt bl1, bl2;
  enterblock(fs, &bl1, BlockType::BT_BREAK);  /* loop block */
  enterblock(fs, &bl2, BlockType::BT_CONTINUE);  /* scope block */
  luaX_next(ls);  /* skip REPEAT */
  statlist(ls);
  createlabel(ls, &bl2, 0, 0, true);
  bl2.type = BlockType::BT_DEFAULT;
  checknext(ls, TK_UNTIL);
  condexit = cond(ls);  /* read condition (inside scope block) */
  leaveblock(fs);  /* finish scope */
  if (bl2.upval) {  /* upvalues? */
    int exit = luaK_jump(fs);  /* normal exit must jump over fix */
    luaK_patchtohere(fs, condexit);  /* repetition must close upvalues */
    luaK_codeABC(fs, OP_CLOSE, reglevel(fs, bl2.nactvar), 0, 0);
    condexit = luaK_jump(fs);  /* repeat after closing upvalues */
    luaK_patchtohere(fs, exit);  /* normal exit comes to here */
  }
  luaK_patchlist(fs, condexit, repeat_init);  /* close the loop */
  leaveblock(fs);  /* finish loop */
}


/*
** Read an expression and generate code to put its results in next
** stack slot.
**
*/
static void exp1 (LexState *ls) {
  expdesc e;
  expr(ls, &e);
  luaK_exp2nextreg(ls->fs, &e);
  lua_assert(e.k == VNONRELOC);
}


/*
** Fix for instruction at position 'pc' to jump to 'dest'.
** (Jump addresses are relative in Lua). 'back' true means
** a back jump.
*/
static void fixforjump (FuncState *fs, int pc, int dest, int back) {
  Instruction *jmp = &fs->f->code[pc];
  int offset = dest - (pc + 1);
  if (back)
    offset = -offset;
  if (l_unlikely(offset > MAXARG_Bx))
    luaX_syntaxerror(fs->ls, "control structure too long");
  SETARG_Bx(*jmp, offset);
}


/*
** Generate code for a 'for' loop.
*/
static void forbody (LexState *ls, int base, int line, int nvars, int isgen, TypeHint *prop) {
  /* forbody -> DO block */
  static const OpCode forprep[2] = {OP_FORPREP, OP_TFORPREP};
  static const OpCode forloop[2] = {OP_FORLOOP, OP_TFORLOOP};
  BlockCnt bl;
  FuncState *fs = ls->fs;
  int prep, endfor;
  checknext(ls, TK_DO);
  prep = luaK_codeABx(fs, forprep[isgen], base, 0);
  enterblock(fs, &bl, BlockType::BT_CONTINUE);  /* scope for declared variables */
  adjustlocalvars(ls, nvars);
  luaK_reserveregs(fs, nvars);
  block(ls, prop);
  leaveblock(fs);  /* end of scope for declared variables */
  fixforjump(fs, prep, luaK_getlabel(fs), 0);
  if (isgen) {  /* generic for? */
    luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
    luaK_fixline(fs, line);
  }
  endfor = luaK_codeABx(fs, forloop[isgen], base, 0);
  fixforjump(fs, endfor, prep + 1, 1);
  luaK_fixline(fs, line);
}


static void fornum (LexState *ls, TString *varname, TypeHint *prop, int line) {
  /* fornum -> NAME = exp,exp[,exp] forbody */
  FuncState *fs = ls->fs;
  int base = fs->freereg;
  new_localvarliteral(ls, "(for state)");
  new_localvarliteral(ls, "(for state)");
  new_localvarliteral(ls, "(for state)");
  new_localvar(ls, varname);
  checknext(ls, '=');
  exp1(ls);  /* initial value */
  checknext(ls, ',');
  exp1(ls);  /* limit */
  if (testnext(ls, ','))
    exp1(ls);  /* optional step */
  else {  /* default step = 1 */
    luaK_int(fs, fs->freereg, 1);
    luaK_reserveregs(fs, 1);
  }
  adjustlocalvars(ls, 3);  /* control variables */
  forbody(ls, base, line, 1, 0, prop);
}


static void forlist (LexState *ls, TString *indexname, TypeHint *prop) {
  /* forlist -> NAME {,NAME} IN explist forbody */
  FuncState *fs = ls->fs;
  expdesc e;
  int nvars = 5;  /* gen, state, control, toclose, 'indexname' */
  int line;
  int base = fs->freereg;
  /* create control variables */
  new_localvarliteral(ls, "(for state)");
  new_localvarliteral(ls, "(for state)");
  new_localvarliteral(ls, "(for state)");
  new_localvarliteral(ls, "(for state)");
  /* create declared variables */
  new_localvar(ls, indexname);
  while (testnext(ls, ',')) {
    new_localvar(ls, str_checkname(ls));
    nvars++;
  }
  checknext(ls, TK_IN);
  line = ls->getLineNumber();
  adjust_assign(ls, 4, explist(ls, &e), &e);
  adjustlocalvars(ls, 4);  /* control variables */
  marktobeclosed(fs);  /* last control var. must be closed */
  luaK_checkstack(fs, 3);  /* extra space to call generator */
  forbody(ls, base, line, nvars - 4, 1, prop);
}


static void forvlist (LexState *ls, TypeHint *prop) {
  /* forvlist -> explist AS NAME forbody */
  FuncState *fs = ls->fs;
  expdesc e;
  int nvars = 5;  /* gen, state, control, toclose, 'indexname' */
  int line;
  int base = fs->freereg;
  /* create control variables */
  new_localvarliteral(ls, "(for state)");
  new_localvarliteral(ls, "(for state)");
  new_localvarliteral(ls, "(for state)");
  new_localvarliteral(ls, "(for state)");
  /* create variable for key */
  new_localvar(ls, luaS_newliteral(ls->L, "(for state)"));
  /* create variable for value */
  int vidx = new_localvar(ls, luaS_newliteral(ls->L, "(for state)"));
  nvars++;

  line = ls->getLineNumber();
  adjust_assign(ls, 4, explist(ls, &e), &e);
  adjustlocalvars(ls, 4);  /* control variables */
  marktobeclosed(fs);  /* last control var. must be closed */
  luaK_checkstack(fs, 3);  /* extra space to call generator */

  checknext(ls, TK_AS);
  TString *name = str_checkname(ls);
  checkforshadowing(ls, fs, name, line);
  getlocalvardesc(fs, vidx)->vd.name = name;

  forbody(ls, base, line, nvars - 4, 1, prop);
}


static void forstat (LexState *ls, int line, TypeHint *prop) {
  /* forstat -> FOR (fornum | forlist) END */
  FuncState *fs = ls->fs;
  BlockCnt bl;
  enterblock(fs, &bl, BlockType::BT_BREAK);  /* scope for loop and control variables */
  luaX_next(ls);  /* skip 'for' */

  if (luaX_lookahead(ls) == '=') {
    TString *varname = str_checkname(ls);  /* first variable name */
    fornum(ls, varname, prop, line);
  }
  else if (luaX_lookahead(ls) == ',' || luaX_lookahead(ls) == TK_IN) {
    TString *varname = str_checkname(ls);  /* first variable name */
    forlist(ls, varname, prop);
  }
  else {
    forvlist(ls, prop);
  }

  check_match(ls, TK_END, TK_FOR, line);
  leaveblock(fs);  /* loop scope ('break' jumps to this point) */
}


static void test_then_block (LexState *ls, int *escapelist, TypeHint *prop) {
  /* test_then_block -> [IF | ELSEIF] cond THEN block */
  BlockCnt bl;
  FuncState *fs = ls->fs;
  expdesc v;
  int jf;  /* instruction to skip 'then' code (if condition is false) */
  luaX_next(ls);  /* skip IF or ELSEIF */

  if (ls->t.token == TK_NAME && eqstr(ls->t.seminfo.ts, luaX_newliteral(ls, "type"))) {
    luaX_next(ls);
    if (testnext(ls, '(')) {
      if (isnametkn(ls)) {
        expdesc var;
        singlevar(ls, &var);
        if (var.k == VLOCAL && testnext(ls, ')')) {
          if (testnext(ls, TK_EQ)) {
            if (ls->t.token == TK_STRING) {
              bl.var_overide_vidx = var.u.var.vidx;
              if (eqstr(ls->t.seminfo.ts, luaX_newliteral(ls, "nil"))) {
                bl.var_overide = VT_NIL;
              }
              else if (eqstr(ls->t.seminfo.ts, luaX_newliteral(ls, "boolean"))) {
                bl.var_overide = VT_BOOL;
              }
              else if (eqstr(ls->t.seminfo.ts, luaX_newliteral(ls, "number"))) {
                bl.var_overide = VT_NUMBER;
              }
              else if (eqstr(ls->t.seminfo.ts, luaX_newliteral(ls, "string"))) {
                bl.var_overide = VT_STR;
              }
              else if (eqstr(ls->t.seminfo.ts, luaX_newliteral(ls, "table"))) {
                bl.var_overide = VT_TABLE;
              }
              else if (eqstr(ls->t.seminfo.ts, luaX_newliteral(ls, "function"))) {
                bl.var_overide = VT_FUNC;
              }
              else if (!eqstr(ls->t.seminfo.ts, luaX_newliteral(ls, "userdata"))
                && !eqstr(ls->t.seminfo.ts, luaX_newliteral(ls, "thread"))
                && !eqstr(ls->t.seminfo.ts, luaX_newliteral(ls, "no value"))
              ) {
                throw_warn(ls, luaO_fmt(ls->L, "'%s' is not a possible return value of 'type'", getstr(ls->t.seminfo.ts)), WT_POSSIBLE_TYPO);
                ls->L->top.p--;
              }
            }
            luaX_prev(ls);  /* back to '==' */
          }
          luaX_prev(ls);  /* back to ')' */
        }
        luaX_prev(ls);  /* back to nametkn */
      }
      luaX_prev(ls);  /* back to '(' */
    }
    luaX_prev(ls);  /* back to "type" */
  }

  ls->used_walrus = false;
  expr(ls, &v, nullptr, E_WALRUS);  /* read condition */
  const bool alwaystrue = luaK_isalwaystrue(ls, &v);
  if (luaK_isalwaysfalse(ls, &v))
    throw_warn(ls, "unreachable code", "this condition will never be truthy.", WT_UNREACHABLE_CODE);
  if (testnext(ls, TK_THEN)) {
    /* standard block opener for ifstat */
  }
  else if (testnext(ls, TK_DO)) {
    throw_warn(ls, "non-portable block opener", "using 'do' instead of 'then' is Pluto-specific", WT_NON_PORTABLE_CODE);
  }
  else {
    const char* token = luaX_token2str(ls, ls->t);
    throwerr(ls, luaO_fmt(ls->L, "unexpected symbol near %s", token), "expected 'then' or 'do' to open the block");
  }
  if (ls->t.token == TK_BREAK && luaX_lookahead(ls) != TK_INT) {  /* 'if x then break' and not 'if x then break int' ? */
    ls->laststat.token = TK_BREAK;
    int line = ls->getLineNumber();
    luaK_goiffalse(ls->fs, &v);  /* will jump if condition is true */
    luaX_next(ls);  /* skip 'break' */
    enterblock(fs, &bl, BlockType::BT_DEFAULT);  /* must enter block before 'goto' */
    lbreak(ls, 1, line, v.t);
    // TODO: Allow the integer level for break statements
    while (testnext(ls, ';')) {}  /* skip semicolons */
    if (block_follow(ls, 0)) {  /* jump is the entire block? */
      leaveblock(fs);
      return;  /* and that is it */
    }
    else  /* must skip over 'then' part if condition is false */
      jf = luaK_jump(fs);
  }
  else {  /* regular case (not a break) */
    luaK_goiftrue(ls->fs, &v);  /* skip over block if condition is false */
    enterblock(fs, &bl, BlockType::BT_DEFAULT);
    jf = v.f;
  }
  statlist(ls, prop);  /* 'then' part */
  leaveblock(fs);
  if (ls->t.token == TK_ELSE ||
      ls->t.token == TK_ELSEIF) {  /* followed by 'else'/'elseif'? */
    luaK_concat(fs, escapelist, luaK_jump(fs));  /* must jump over it */
    if (alwaystrue)
      throw_warn(ls, "unreachable code", "the condition in the if block is always truthy, hence this else block is unreachable.", WT_UNREACHABLE_CODE);
  }
  luaK_patchtohere(fs, jf);
}


static void ifstat (LexState *ls, int line, TypeHint *prop = nullptr) {
  /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  FuncState *fs = ls->fs;
  BlockCnt walrusbl;
  enterblock(fs, &walrusbl, BlockType::BT_DEFAULT);
  int escapelist = NO_JUMP;  /* exit list for finished parts */
  test_then_block(ls, &escapelist, prop);  /* IF cond THEN block */
  while (ls->t.token == TK_ELSEIF) {
    leaveblock(fs);
    enterblock(fs, &walrusbl, BlockType::BT_DEFAULT);
    test_then_block(ls, &escapelist, prop);  /* ELSEIF cond THEN block */
  }
  if (testnext(ls, TK_ELSE)) {
    leaveblock(fs);
    enterblock(fs, &walrusbl, BlockType::BT_DEFAULT);
    if (ls->t.token == TK_IF && ls->t.line == luaX_lookbehind(ls).line)
      ls->else_if = ls->getLineNumber();
    block(ls, prop);  /* 'else' part */
  }
  check_match(ls, TK_END, TK_IF, line);
  luaK_patchtohere(fs, escapelist);  /* patch escape list to 'if' end */
  leaveblock(fs);
}


/* keep advancing until we hit non-nested '$else', '$elseif' or '$end' */
static void skip_constexpr_block (LexState *ls) {
  int depth = 0;
  while (ls->t.token != TK_EOS) {
    if (ls->t.token == '$') {
      const auto la_tk = luaX_lookahead(ls);
      if (la_tk == TK_IF) {
        ++depth;
      }
      else if (la_tk == TK_ELSE || la_tk == TK_ELSEIF) {
        if (depth == 0) {
          break;
        }
      }
      else if (la_tk == TK_END) {
        if (depth == 0) {
          break;
        }
        depth--;
      }
      luaX_next(ls);
    }
    luaX_next(ls);
  }
}

static void constexprifstat (LexState *ls, int line) {
  bool hit = false;

  expdesc c;
  expr(ls, &c);
  if (!testnext(ls, TK_DO))
    checknext(ls, TK_THEN);
  if (luaK_isalwaystrue(ls, &c)) {
    hit = true;
    block(ls);
  }
  else {
    if (!luaK_isalwaysfalse(ls, &c))
      throwerr(ls, "this condition cannot be evaluated at compile-time", "");
    skip_constexpr_block(ls);
  }

  while (checknext(ls, '$'), testnext(ls, TK_ELSEIF)) {
    expr(ls, &c);
    if (!testnext(ls, TK_DO))
      checknext(ls, TK_THEN);
    if (luaK_isalwaystrue(ls, &c)) {
      if (hit) {
        skip_constexpr_block(ls);
      }
      else {
        hit = true;
        block(ls);
      }
    }
    else {
      if (!luaK_isalwaysfalse(ls, &c))
        throwerr(ls, "this condition cannot be evaluated at compile-time", "");
      skip_constexpr_block(ls);
    }
  }

  if (testnext(ls, TK_ELSE)) {
    if (!hit) {
      block(ls);
    }
    else {
      skip_constexpr_block(ls);
    }
    checknext(ls, '$');
  }

  check_match(ls, TK_END, TK_IF, line);
}


static void constexprdefinestat (LexState *ls, int line) {
  FuncState *fs = ls->fs;
  int vidx = new_localvar(ls, str_checkname(ls, N_OVERRIDABLE), line);
  TypeHint hint = gettypehint(ls);
  Vardesc *var = getlocalvardesc(fs, vidx);
  var->vd.kind = RDKCTC;
  *var->vd.hint = hint;

  expdesc e;
  checknext(ls, '=');
  ls->pushContext(PARCTX_CREATE_VAR);
  TypeHint t;
  expr_propagate(ls, &e, t);
  ls->popContext(PARCTX_CREATE_VAR);
  if (!luaK_exp2const(fs, &e, &var->k))
    throwerr(ls, "variable was not assigned a compile-time constant value", "expression not constant", line);

  fs->nactvar++;  /* don't adjustlocalvars, but count it */
}


static void constexprstat (LexState *ls, int line) {
  if (testnext(ls, TK_IF)) {
    constexprifstat(ls, line);
  }
  else if (ls->t.token == TK_NAME && strcmp(getstr(ls->t.seminfo.ts), "define") == 0) {
    luaX_next(ls);  /* skip 'define' */
    constexprdefinestat(ls, line);
  }
  else {
    const char *token = luaX_token2str(ls, ls->t);
    throwerr(ls, luaO_fmt(ls->L, "unexpected symbol near %s", token), "unexpected symbol.");
  }
}


static void localfunc (LexState *ls) {
  expdesc b;
  FuncState *fs = ls->fs;
  int fvar = fs->nactvar;  /* function's variable index */
  new_localvar(ls, str_checkname(ls, N_OVERRIDABLE));  /* new local variable */
  adjustlocalvars(ls, 1);  /* enter its scope */
  TypeDesc funcdesc;
  body(ls, &b, 0, ls->getLineNumber(), &funcdesc);  /* function created in next register */
  getlocalvardesc(fs, fvar)->vd.prop->emplaceTypeDesc(std::move(funcdesc));
  /* debug information will only see the variable after this point! */
  localdebuginfo(fs, fvar)->startpc = fs->pc;
}


static int getlocalattribute (LexState *ls) {
  /* ATTRIB -> ['<' Name '>'] */
  if (testnext(ls, '<')) {
    TString *ts = str_checkname(ls);
    const char *attr = getstr(ts);
    checknext(ls, '>');
    if (strcmp(attr, "const") == 0)
      return RDKCONST;  /* read-only variable */
    else if (strcmp(attr, "constexpr") == 0) {
      throw_warn(ls, "the 'constexpr' attribute will be removed in future versions of Pluto.", "use the 'const' attribute or '$define' statement, instead.", WT_DEPRECATED);
      return RDKCONSTEXP;  /* read-only variable */
    }
    else if (strcmp(attr, "close") == 0)
      return RDKTOCLOSE;  /* to-be-closed variable */
    else {
      luaX_prev(ls); // back to '>'
      luaX_prev(ls); // back to attribute
      luaK_semerror(ls,
        luaO_pushfstring(ls->L, "unknown attribute '%s'", attr));
    }
  }
  return VDKREG;  /* regular variable */
}


static void checktoclose (FuncState *fs, int level) {
  if (level != -1) {  /* is there a to-be-closed variable? */
    marktobeclosed(fs);
    luaK_codeABC(fs, OP_TBC, reglevel(fs, level), 0, 0);
  }
}


static void restdestructuring (LexState *ls, int line, std::vector<std::pair<TString*, expdesc>>& pairs) {
  checknext(ls, '=');

  /* begin scope of the locals we want to create */
  for (const auto& p : pairs) {
    new_localvar(ls, p.first, line);
  }
  expdesc e;
  e.k = VVOID;
  adjust_assign(ls, (int)pairs.size(), 0, &e);
  adjustlocalvars(ls, (int)pairs.size());

  /* get table */
  expdesc t;
  expr(ls, &t);

  /* ensure table has a place to stay */
  TString *temporary = nullptr;
  if (t.k != VLOCAL) {
    if (pairs.size() == 1) {
      luaK_exp2anyreg(ls->fs, &t);
    }
    else {
      temporary = luaS_newliteral(ls->L, "(temporary)");
      new_localvar(ls, temporary, line);
      adjust_assign(ls, 1, 1, &t);
      adjustlocalvars(ls, 1);
    }
  }

  /* assign locals */
  for (auto& p : pairs) {
    expdesc e, l;
    if (temporary)
      singlevar(ls, &e, temporary);
    else
      e = t;
    luaK_indexed(ls->fs, &e, &p.second);
    singlevar(ls, &l, p.first);
    luaK_storevar(ls->fs, &l, &e);
  }

  /* release table */
  if (temporary) {
    removevars(ls->fs, ls->fs->nactvar - 1);
  }
}

static void destructuring (LexState *ls) {
  auto line = ls->getLineNumber();
  std::vector<std::pair<TString*, expdesc>> pairs{};
  luaX_next(ls); /* skip '{' */
  do {
    TString* var = str_checkname(ls, N_OVERRIDABLE);
    TString* prop = var;
    if (testnext(ls, '='))
      prop = str_checkname(ls);
    expdesc propexp;
    codestring(&propexp, prop);
    pairs.emplace_back(var, std::move(propexp));
  } while (testnext(ls, ','));
  check_match(ls, '}', '{', line);
  restdestructuring(ls, line, pairs);
}

static void arraydestructuring (LexState *ls) {
  auto line = ls->getLineNumber();
  std::vector<std::pair<TString*, expdesc>> pairs{};
  luaX_next(ls); /* skip '[' */
  expdesc prop;
  init_exp(&prop, VKINT, 0);
  prop.u.ival = 1;
  do {
    pairs.emplace_back(str_checkname(ls, N_OVERRIDABLE), prop);
    prop.u.ival++;
  } while (testnext(ls, ','));
  check_match(ls, ']', '[', line);
  restdestructuring(ls, line, pairs);
}


static void localstat (LexState *ls) {
  if (ls->t.token == '{') {
    destructuring(ls);
    return;
  }
  if (ls->t.token == '[') {
    arraydestructuring(ls);
    return;
  }
  /* stat -> LOCAL NAME ATTRIB { ',' NAME ATTRIB } ['=' explist] */
  FuncState *fs = ls->fs;
  int toclose = -1;  /* index of to-be-closed variable (if any) */
  Vardesc *var;  /* last variable */
  int vidx, kind;  /* index and kind of last variable */
  int nvars = 0;
  int nexps;
  expdesc e;
  auto line = ls->getLineNumber(); /* in case we need to emit a warning */
  size_t starting_tidx = ls->tidx; /* code snippets on tuple assignments can have inaccurate line readings because the parser skips lines until it can close the statement */
  bool is_constexpr = false;
  ls->localstat_variable_names.clear();
  ls->localstat_expression_names.clear();
  do {
    if (is_constexpr)
      luaK_semerror(ls, "<constexpr> must only be used on the last variable in local list");
    TString* name = str_checkname(ls, N_OVERRIDABLE);
    vidx = new_localvar(ls, name, line, gettypehint(ls), false);
    ls->localstat_variable_names.emplace(name);
    kind = getlocalattribute(ls);
    var = getlocalvardesc(fs, vidx);
    var->vd.kind = kind;
    if (kind == RDKTOCLOSE) {  /* to-be-closed? */
      if (toclose != -1) { /* one already present? */
        luaX_setpos(ls, starting_tidx);
        luaK_semerror(ls, "multiple to-be-closed variables in local list");
      }
      toclose = fs->nactvar + nvars;
    }
    else if (kind == RDKCONSTEXP) {
      is_constexpr = true;
    }
    else if (kind == VDKREG) {
      if (line == ls->getLineNumber() && ls->t.token == TK_NAME) {
        if (strcmp(getstr(ls->t.seminfo.ts), "const") == 0
          || strcmp(getstr(ls->t.seminfo.ts), "constexpr") == 0
          || strcmp(getstr(ls->t.seminfo.ts), "close") == 0
          ) {
          throw_warn(ls, "possibly mistyped attribute", luaO_fmt(ls->L, "did you mean '<%s>'?", getstr(ls->t.seminfo.ts)), WT_POSSIBLE_TYPO);
          ls->L->top.p--;
        }
      }
    }
    nvars++;
  } while (testnext(ls, ','));
  ls->localstat_ts.clear();
  if (testnext(ls, '=')) {
    ParserContext ctx = ((nvars == 1) ? PARCTX_CREATE_VAR : PARCTX_CREATE_VARS);
    ls->pushContext(ctx);
    nexps = 1;
    expr_propagate_warn(ls, &e, *(TypeHint*)ls->localstat_ts.emplace_back(new_typehint(ls)), ls->localstat_expression_names);
    while (testnext(ls, ',')) {
      luaK_exp2nextreg(ls->fs, &e);
      expr_propagate_warn(ls, &e, *(TypeHint*)ls->localstat_ts.emplace_back(new_typehint(ls)), ls->localstat_expression_names);
      nexps++;
    }
    ls->popContext(ctx);
    for (auto variable_name : ls->localstat_variable_names) {
      if (ls->localstat_expression_names.find(variable_name) == ls->localstat_expression_names.end()) { // Not a localization optimization?
        checkforshadowing(ls, fs, variable_name, line, true, false); // new_localvar already checked for local duplication
      }
    }
    var = getlocalvardesc(fs, vidx);  /* actvar array may have been relocated */
  }
  else {
    e.k = VVOID;
    nexps = 0;
    process_assign(ls, vidx, TypeHint{ VT_NIL }, line);
    checkforshadowing(ls, fs, ls->localstat_variable_names, line);
  }
  if (is_constexpr) {
    if (nvars != nexps) {
      luaX_prev(ls);
      luaK_semerror(ls, "<constexpr> variable assignment needs adjustment");
    }
    if (!vkisconst(e.k))
      throwerr(ls, "<constexpr> variable was not assigned a compile-time constant value", "expression not constant", line);
    var->vd.kind = RDKCONST;
  }
  if (nvars == nexps) { /* no adjustments? */
    if (var->vd.kind == RDKCONST &&  /* last variable is const? */
        luaK_exp2const(fs, &e, &var->k)) {  /* compile-time constant? */
      var->vd.kind = RDKCTC;  /* variable is a compile-time constant */
      adjustlocalvars(ls, nvars - 1);  /* exclude last variable */
      fs->nactvar++;  /* but count it */
    }
    else {
      vidx = vidx - nvars + 1;
      for (void* t : ls->localstat_ts) {
        process_assign(ls, vidx, *(TypeHint*)t, line);
        ++vidx;
      }
      adjust_assign(ls, nvars, nexps, &e);
      adjustlocalvars(ls, nvars);
    }
  }
  else {
    adjust_assign(ls, nvars, nexps, &e);
    adjustlocalvars(ls, nvars);
  }
  checktoclose(fs, toclose);
}

static void conststat (LexState *ls) {
  FuncState *fs = ls->fs;
  auto line = ls->getLineNumber(); /* in case we need to emit a warning */
  int vidx = new_localvar(ls, str_checkname(ls, N_OVERRIDABLE), line);
  TypeHint hint = gettypehint(ls);
  Vardesc *var = getlocalvardesc(fs, vidx);
  var->vd.kind = RDKCONST;
  *var->vd.hint = hint;

  expdesc e;
  if (testnext(ls, '=')) {
    ls->pushContext(PARCTX_CREATE_VAR);
    TypeHint t;
    expr_propagate(ls, &e, t);
    ls->popContext(PARCTX_CREATE_VAR);
    if (luaK_exp2const(fs, &e, &var->k)) {  /* compile-time constant? */
      var->vd.kind = RDKCTC;  /* variable is a compile-time constant */
      fs->nactvar++;  /* don't adjustlocalvars, but count it */
    }
    else {
      exp_propagate(ls, e, t);
      process_assign(ls, vidx, t, line);
      adjust_assign(ls, 1, 1, &e);
      adjustlocalvars(ls, 1);
    }
  }
  else {
    e.k = VVOID;
    process_assign(ls, vidx, TypeHint{ VT_NIL }, line);
    adjust_assign(ls, 1, 0, &e);
    adjustlocalvars(ls, 1);
  }
}


static int funcname (LexState *ls, expdesc *v) {
  /* funcname -> NAME {fieldsel} [':' NAME] */
  int ismethod = 0;
  singlevar(ls, v);
  while (ls->t.token == '.')
    fieldsel(ls, v);
  if (ls->t.token == ':') {
    ismethod = 1;
    fieldsel(ls, v);
  }
  return ismethod;
}


static void funcstat (LexState *ls, int line, const bool global) {
  /* funcstat -> FUNCTION funcname body */
  int ismethod;
  expdesc v, b;
  ismethod = funcname(ls, &v);
  if (!global)
    check_assignment(ls, &v);
  body(ls, &b, ismethod, line);
  check_readonly(ls, &v);
  luaK_storevar(ls->fs, &v, &b);
  luaK_fixline(ls->fs, line);  /* definition "happens" in the first line */
}


static void exprstat (LexState *ls) {
  /* stat -> func | assignment */
  FuncState *fs = ls->fs;
  struct LHS_assign v;
  suffixedexp(ls, &v.v);
  if (ls->t.token == '=' || ls->t.token == ',' || ls->t.token == TK_NE) { /* stat -> assignment ? */
    v.prev = NULL;
    check_assignment(ls, &v.v);
    restassign(ls, &v, 1);
  }
  else {  /* stat -> func */
    Instruction *inst;
    if (l_unlikely(v.v.k != VCALL && v.v.k != VSAFECALL)) {
      if (luaX_lookbehind(ls).token == TK_NAME) {
        if (auto t = find_non_compat_tkn_by_name(ls, getstr(luaX_lookbehind(ls).seminfo.ts))) {
          if (ls->getKeywordState(t) == KS_DISABLED_BY_PLUTO_INFORMED) {
            const auto entry = ls->uninformed_reserved.find(t);
            const auto line = entry == ls->uninformed_reserved.end() ? -1 : entry->second;
            throwerr(ls,
              luaO_fmt(ls->L, "syntax error near %s", luaX_token2str(ls, ls->t)),
              luaO_fmt(ls->L, "%s was not recognized as a statement because it was used as an identifier on line %d", luaX_token2str(ls, t), line)
            );
          }
        }
      }
      luaX_syntaxerror(ls, "syntax error");
    }
    inst = &getinstruction(fs, &v.v);
    SETARG_C(*inst, 1);  /* call statement uses no results */
    if (ls->nodiscard) {
      luaX_prev(ls);
      throw_warn(ls, "discarding return value of function declared '<nodiscard>'", WT_DISCARDED_RETURN);
      luaX_next(ls);
    }
  }
}


static void retstat (LexState *ls, TypeHint *prop) {
  /* stat -> RETURN [explist] [';'] */
  FuncState *fs = ls->fs;
  expdesc e;
  int nret;  /* number of values being returned */
  int first = luaY_nvarstack(fs);  /* first slot to be returned */
  int startpc = fs->pc;
  int endpc = -1;
  if (block_follow(ls, 1) || ls->t.token == ';'
    || (!ls->switchstates.empty() && (ls->t.token == TK_CASE || ls->t.token == TK_DEFAULT || ls->t.token == TK_BREAK))
  ) {
    nret = 0;  /* return no values */
    if (prop) prop->emplaceTypeDesc(VT_VOID);
  }
  else {
    if (fs->istrybody) {
      singlevar(ls, &e, luaX_newliteral(ls, "table"));
      luaK_exp2anyregup(ls->fs, &e);
      expdesc key;
      codestring(&key, luaX_newliteral(ls, "pack"));
      luaK_indexed(ls->fs, &e, &key);
      luaK_exp2nextreg(ls->fs, &e);
      lua_assert(first == e.u.reg);
      endpc = fs->pc-1;
      lua_assert(endpc >= startpc);
    }
    nret = explist(ls, &e, prop);  /* optional return values */
    if (prop && prop->empty())
      prop->emplaceTypeDesc(VT_DUNNO);  /* we are returning something, but we don't know what. (this is needed for trystat.) */
    if (hasmultret(e.k)) {
      luaK_setmultret(fs, &e);
      if (e.k == VCALL && nret == 1 && !fs->bl->insidetbc && !fs->istrybody) {  /* tail call? */
        SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL);
        lua_assert(GETARG_A(getinstruction(fs,&e)) == luaY_nvarstack(fs));
      }
      nret = LUA_MULTRET;  /* return all values */
    }
    else {
      if (nret == 1 && !fs->istrybody) /* only one single value? */
        first = luaK_exp2anyreg(fs, &e);  /* can use original slot */
      else {  /* values must go to the top of the stack */
        luaK_exp2nextreg(fs, &e);
        lua_assert(nret + fs->istrybody == fs->freereg - first);
      }
    }
  }
  fs->seenrets |= 1 << (nret >= 0 && nret <= 3 ? nret : 3);
  if (fs->istrybody) {
    if (nret == 0) {
      init_exp(&e, VKINT, 0);
      e.u.ival = 0;
      first = luaK_exp2anyreg(fs, &e);  /* can use original slot */
      nret = 1;
    } else if (nret == 1 || nret == 2) {
      fs->f->code[endpc] = CREATE_ABx(OP_LOADI, first, nret + OFFSET_sBx);
      while (startpc<endpc) {
        fs->f->code[startpc] = CREATE_sJ(OP_JMP, (endpc-startpc-1) + OFFSET_sJ, 0);
        startpc++;
      }
      nret++;
    } else {
      luaK_codeABC(ls->fs, OP_CALL, first, nret + 1, 2);
      ls->fs->freereg = first + 1;
      nret = 1;
    }
  }
  luaK_ret(fs, first, nret);
  testnext(ls, ';');  /* skip optional semicolon */
}


static int checkkeyword (LexState *ls) {
  if (ls->t.token == TK_NAME) {
    for (int i = FIRST_NON_COMPAT; i != END_OPTIONAL; ++i) {
      if (strcmp(luaX_reserved2str(i), getstr(ls->t.seminfo.ts)) == 0) {
        luaX_next(ls);
        return i;
      }
    }
  }
  if (!ls->t.IsNonCompatible() && !ls->t.IsOptional()) {
    if (ls->t.IsCompatible())
      luaX_syntaxerror(ls, "expected non-compatible keyword");
    luaX_syntaxerror(ls, "expected keyword");
  }
  int token = ls->t.token;
  luaX_next(ls);
  return token;
}

static void enablekeyword (LexState *ls, int token) {
  const char* str = luaX_reserved2str(token);
  auto i = ls->tokens.begin() + ls->tidx;
  TString* ts = nullptr;
  /* find first instance of token */
  for (; i != ls->tokens.end(); ++i)
    if (i->token == TK_NAME && strcmp(str, getstr(i->seminfo.ts)) == 0) {
      ts = i->seminfo.ts;
      i->token = token;
      break;
    }
  /* find further instances of the token; faster now that we have TString */
  if (ts)
    for (; i != ls->tokens.end(); ++i)
      if (i->token == TK_NAME && eqstr(i->seminfo.ts, ts))
        i->token = token;
}

static void togglekeyword (LexState *ls, int token, bool enable) {
  if (ls->isKeywordEnabled(token) != enable) {
    ls->setKeywordState(token, enable ? KS_ENABLED_BY_SCRIPTER : KS_DISABLED_BY_SCRIPTER);
    if (enable)
      enablekeyword(ls, token);
    else
      disablekeyword(ls, token);
  }
}

static void usestat (LexState *ls) {
  const bool is_ann = ls->t.token == TK_USEANN;
  const auto line = ls->t.line;
  luaX_next(ls); /* skip 'pluto_use' */
  do {
    /* check affected tokens */
    bool is_all = false;
    bool is_version = false;
    std::vector<int> tokens{};
    if (ls->t.token == '*') {
      is_all = true;
      for (int i = FIRST_NON_COMPAT; i != END_OPTIONAL; ++i) {
        tokens.emplace_back(i);
      }
      luaX_next(ls);
    }
    else if (ls->t.token == TK_STRING) {
      is_version = true;
      if (soup::version_compare(getstr(ls->t.seminfo.ts), "0.8.0") >= 0) {
        tokens = { TK_SWITCH, TK_CONTINUE, TK_ENUM, TK_NEW, TK_CLASS, TK_PARENT, TK_EXPORT, TK_TRY, TK_CATCH };
      }
      else if (soup::version_compare(getstr(ls->t.seminfo.ts), "0.6.0") >= 0) {
        tokens = { TK_SWITCH, TK_CONTINUE, TK_ENUM, TK_NEW, TK_CLASS, TK_PARENT, TK_EXPORT };
      }
      else if (soup::version_compare(getstr(ls->t.seminfo.ts), "0.5.0") >= 0) {
        tokens = { TK_SWITCH, TK_CONTINUE, TK_ENUM };
      }
      else if (soup::version_compare(getstr(ls->t.seminfo.ts), "0.2.0") >= 0) {
        tokens = { TK_SWITCH, TK_CONTINUE };
      }
      else throwerr(ls, luaO_fmt(ls->L, "'pluto_use \"%s\"' is not valid", getstr(ls->t.seminfo.ts)), "did you mean \"0.8.0\", \"0.6.0\", \"0.5.0\" or \"0.2.0\"?");
      if (getstr(ls->t.seminfo.ts)[ls->t.seminfo.ts->size() - 1] == '+') {
        if (soup::version_compare(getstr(ls->t.seminfo.ts), "0.9.0") >= 0) {
          tokens.emplace_back(TK_GLOBAL);
          /* 'let' and 'const' are deprecated as of 0.9.0, so we don't wanna enable them with `pluto_use "0.9.0+"` */
        }
        else if (soup::version_compare(getstr(ls->t.seminfo.ts), "0.7.0") >= 0) {
          tokens.emplace_back(TK_LET);
          if (soup::version_compare(getstr(ls->t.seminfo.ts), "0.8.0") >= 0) {
            tokens.emplace_back(TK_CONST);
          }
        }
      }
      luaX_next(ls);
    }
    else {
      tokens = { checkkeyword(ls) };
    }

    /* check if enable or disable */
    bool enable = true;
    if (testnext(ls, '=')) {
      if (testnext(ls, TK_FALSE))
        enable = false;
      else checknext(ls, TK_TRUE);
    }

    /* catch stupid stuff */
    if (is_all && enable)
      throw_warn(ls, "'pluto_use *' is a bad idea because future Pluto versions may add keywords that will break your script", "consider using 'pluto_use \"0.8.0\"' instead", line, WT_BAD_PRACTICE);
    if (is_version && !enable)
      throwerr(ls, "'pluto_use <version>' is not valid for disabling tokens", "did you mean 'pluto_use * = false'?");

    /* apply change */
    if (is_all || is_version) {
      if (is_version) {
        /* disable all non-compatible keywords as of this Pluto version, then enable those from the elected Pluto version. */
        for (int i = FIRST_NON_COMPAT; i != END_OPTIONAL; ++i) {
          if (ls->isKeywordEnabled(i)) {
            ls->setKeywordState(i, KS_DISABLED_BY_SCRIPTER);
            disablekeyword(ls, i);
          }
        }
      }
      for (const auto& token : tokens) {
        togglekeyword(ls, token, enable);
      }
    }
    else {
      togglekeyword(ls, tokens.at(0), enable);
    }
  } while (testnext(ls, ','));

  /* update ls->t */
  luaX_setpos(ls, luaX_getpos(ls));

  if (is_ann) {
    /* skip remaining tokens in line */
    while (ls->t.line == line && ls->t.token != TK_EOS)
      luaX_next(ls);
  }
}

static void test_eqi (LexState *ls, expdesc* v, lua_Integer val, BinOpr op) {
  expdesc ival;
  luaK_infix(ls->fs, op, v);
  init_exp(&ival, VKINT, 0);
  ival.u.ival = val++;
  luaK_posfix(ls->fs, op, v, &ival, ls->getLineNumber());
}

static void ret_int(FuncState* fs, lua_Integer val) {
  expdesc v;
  init_exp(&v, VKINT, 0);
  v.u.ival = val;
  luaK_exp2anyreg(fs, &v);
  luaK_ret(fs, v.u.reg, 1);
}

static void trystat (LexState *ls) {
  BlockCnt trybl;
  expdesc ex;
  FuncState new_fs;
  BlockCnt bl;
  int exitjump = NO_JUMP;

  enterblock(ls->fs, &trybl, BlockType::BT_DEFAULT);

  ls->used_try = true;

  const auto line = ls->getLineNumber();
  luaX_next(ls);
  const bool vararg = ls->fs->f->is_vararg;

  /* temp (try status), (try result), (try result2), (try result3) = */
  const auto status_reg = ls->fs->freereg;
  const auto result_reg = ls->fs->freereg+1;

  /* temp (try status), (try result), (try result2), (try result3) = pcall */
  singlevar(ls, &ex, luaX_newliteral(ls, "pcall"));
  luaK_exp2nextreg(ls->fs, &ex);

  /* temp (try status), (try result), (try result2), (try result3) = pcall(function() */
  new_fs.f = addprototype(ls);
  new_fs.f->linedefined = ls->getLineNumber();
  open_func(ls, &new_fs, &bl);
  new_fs.istrybody = 1;
  if (vararg) {
    /* temp (try status), (try result), (try result2), (try result3) = pcall(function(...) */
    setvararg(&new_fs, 0);
  }

  /* temp (try status), (try result), (try result2), (try result3) = pcall(function(...) STATLIST */
  TypeHint prop{};
  statlist(ls, &prop);

  /* Move gotoes out of try/catch block */
  lua_assert(bl.firstgoto == trybl.firstgoto);
  Labellist *gl = &ls->dyd->gt;
  if (bl.firstgoto != gl->n) { /* There are some gotos that need to be moved out of the try/catch block */
    luaK_ret(&new_fs, luaY_nvarstack(&new_fs), 0);  /* Make sure the function body returns */
    removevars(&new_fs, bl.nactvar);  /* remove function locals */
    lua_assert(bl.nactvar == new_fs.nactvar);  /* no variables should remain */
    /* correct pending gotos to current block */
    int id = 3; // Next id of the goto return status
    for (int i = bl.firstgoto; i < gl->n; i++) {  /* for each pending goto */
      Labeldesc *gt = &gl->arr[i];
      int lab = luaK_getlabel(&new_fs);
      if (gt->pc != NO_JUMP) { /* Needs patching up */
        luaK_patchlist(&new_fs, gt->pc, lab);
        for (int j = i + 1; j < gl->n; j++) { /* Look for other gotos with the same name and patch them together */
          if (samelabelnames(&gl->arr[j], gt)) {
            luaK_patchlist(&new_fs, gl->arr[j].pc, lab);
            gl->arr[j].pc = NO_JUMP; /* This goto will also later be found, make sure it is later skipped but reamins in this list */
          }
        }
        ret_int(&new_fs, id++); /* Return the goto status */
      }
      gt->close = 0; /* Goto is moved out of the function, it is now new, so does for now not need closing. */
      gt->nactvar = bl.nactvar;  /* update goto level */
    }
    bl.firstgoto = gl->n; /* Prevent undefgoto errors here on the close_func */
  }

  /* temp (try status), (try result), (try result2), (try result3) = pcall(function(...) STATLIST end */
  new_fs.f->lastlinedefined = ls->getLineNumber();
  codeclosure(ls, &ex);
  close_func(ls);
  luaK_exp2nextreg(ls->fs, &ex);
  lua_assert(status_reg+1 == ex.u.reg);

  if (vararg) {
    /* temp (try status), (try result), (try result2), (try result3) = pcall(function(...) STATLIST end, ... */
    init_exp(&ex, VVARARG, luaK_codeABC(ls->fs, OP_VARARG, 0, 0, 1));
    luaK_setmultret(ls->fs, &ex);
  }

  /* temp (try status), (try result), (try result2), (try result3) = pcall(function(...) STATLIST end, ...) */
  init_exp(&ex, VCALL, luaK_codeABC(ls->fs, OP_CALL, status_reg, (vararg ? LUA_MULTRET : 1) + 1, 2));
  ls->fs->freereg = status_reg+1;

  int num_out = new_fs.seenrets & (1<<2) ? 4 : new_fs.seenrets & (1<<1) ? 3 : 2;
  adjust_assign(ls, num_out, 1, &ex);
  lua_assert(status_reg+num_out == ls->fs->freereg);

  if (!testnext(ls, TK_CATCH))
    check_match(ls, TK_PCATCH, TK_PTRY, line);

  auto old_pin = ls->fs->pinnedreg;

  /* if not (try status) then jump to catch block */
  ls->fs->pinnedreg = status_reg;
  init_exp(&ex, VNONRELOC, status_reg);

  if (trybl.firstgoto == gl->n && !new_fs.seenrets) {
    /* Simple case */
    /* Try body with only a falltrough case */
    /* Just jump over the catch block if there is no error */
    luaK_goiffalse(ls->fs, &ex);
    exitjump = ex.t;
  } else {
    /* Hard case */
    /* Try body had some special exits */
    /* Jump to catch if there was an error */
    luaK_goiftrue(ls->fs, &ex);
    int skip = ex.f;

    /* Jump to end of try/catch in case of falltrough */
    ls->fs->pinnedreg = result_reg;
    init_exp(&ex, VNONRELOC, result_reg);
    luaK_goiftrue(ls->fs, &ex);
    exitjump = ex.f;

    /* For every goto from the try body make a if case and update the jump */
    int id = 3;
    int j = trybl.firstgoto;
    for (int i = trybl.firstgoto; i < gl->n; i++) {
      Labeldesc *gt = &gl->arr[i];
      Labeldesc *lb = gt->special ? 0 : findlabel(ls, (TString*)gt->name);
      if (gt->pc != NO_JUMP) {
        init_exp(&ex, VNONRELOC, result_reg);
        test_eqi(ls, &ex, id++, OPR_EQ);

        if (lb) {  /* found a label */
          /* backward jump; will be resolved here */
          int lblevel = reglevel(ls->fs, lb->nactvar);  /* label level */
          if (luaY_nvarstack(ls->fs) > lblevel) { /* leaving the scope of a variable? */
            luaK_goiftrue(ls->fs, &ex);
            luaK_codeABC(ls->fs, OP_CLOSE, lblevel, 0, 0);
            /* create jump and link it to the label */
            luaK_patchlist(ls->fs, luaK_jump(ls->fs), lb->pc);
            luaK_patchtohere(ls->fs, ex.f);
          } else {
            luaK_goiffalse(ls->fs, &ex);
            luaK_patchlist(ls->fs, ex.t, lb->pc);
          }

        } else {
          /* Forward jumps need a new pc */
          luaK_goiffalse(ls->fs, &ex);
          gt->pc = ex.t;
        }
      }
      if (!lb) {
        /* If no label was found this goto needs to be retained, other ones removed */
        if (j != i)
          gl->arr[j] = gl->arr[i];
        j++;
      }
    }
    /* Update new number of pending gotos */
    gl->n = j;

    /* Update return status */
    ls->fs->seenrets |= new_fs.seenrets;

    if (ls->fs->istrybody) {
      /* We are ourselves in a try body */
      if (new_fs.seenrets) {
        /* Just return the result as is */
        luaK_ret(ls->fs, result_reg, num_out-1);
      }
    } else {
      for (int i=0; i<3; i++) {
        /* Add specialized returns for specific numbers */
        /* This is required for the correct number of returns */
        if (new_fs.seenrets & (1<<i)) {
          ex.f = NO_JUMP;
          if (new_fs.seenrets >> (i+1)) {
            init_exp(&ex, VNONRELOC, result_reg);
            test_eqi(ls, &ex, i, OPR_EQ);
            luaK_goiftrue(ls->fs, &ex);
          }
          luaK_ret(ls->fs, result_reg+1, i);
          luaK_patchtohere(ls->fs, ex.f);
        }
      }

      if (new_fs.seenrets & (1<<3)) {
        /* In the try body was a return with more then two returns */

        ls->fs->freereg = status_reg+2;

        /* table.unpack */
        expdesc key;
        singlevar(ls, &ex, luaX_newliteral(ls, "table"));
        luaK_exp2anyregup(ls->fs, &ex);
        codestring(&key, luaX_newliteral(ls, "unpack"));
        luaK_indexed(ls->fs, &ex, &key);
        luaK_exp2reg(ls->fs, &ex, status_reg);
        lua_assert(ex.k == VNONRELOC);

        /* results is already in result_reg == status_reg+1 */

        /* table.unpack(results, 1 */
        init_exp(&ex, VKINT, 0);
        ex.u.ival = 1;
        luaK_exp2nextreg(ls->fs, &ex);
        lua_assert(status_reg+2 == ex.u.reg);

        /* table.unpack(results, 1, results.n */
        init_exp(&ex, VNONRELOC, result_reg);
        codestring(&key, luaX_newliteral(ls, "n"));
        luaK_indexed(ls->fs, &ex, &key);
        luaK_exp2nextreg(ls->fs, &ex);
        lua_assert(status_reg+3 == ex.u.reg);

        /* table.unpack(results, 1, results.n) */
        luaK_codeABC(ls->fs, trybl.insidetbc ? OP_CALL : OP_TAILCALL, status_reg, 4 /* 3 params */, LUA_MULTRET + 1);
        luaK_ret(ls->fs, status_reg, LUA_MULTRET);
      }
    }

    luaK_patchtohere(ls->fs, skip);
  }

  ls->fs->freereg = status_reg+2;
  ls->fs->pinnedreg = old_pin;

  /* local (e) */
  new_localvar(ls, str_checkname(ls, N_OVERRIDABLE));

  const auto then_line = ls->getLineNumber();
  if (!testnext(ls, TK_DO))
    checknext(ls, TK_THEN);

  /* local (e) = (try result) */
  init_exp(&ex, VNONRELOC, result_reg);
  luaK_exp2reg(ls->fs, &ex, status_reg);
  lua_assert(status_reg == luaY_nvarstack(ls->fs));
  lua_assert(status_reg+1 == ls->fs->freereg);
  adjustlocalvars(ls, 1);

  enterblock(ls->fs, &bl, BlockType::BT_DEFAULT);
  bl.nactvar--; /* Move e into this block */

  statlist(ls);

  /* end */
  check_match(ls, TK_END, TK_PCATCH, then_line);
  leaveblock(ls->fs);

  luaK_patchtohere(ls->fs, exitjump);
  leaveblock(ls->fs);
}


static void globalstat (LexState *ls) {
  const auto line = ls->getLineNumber();
  luaX_next(ls);  /* skip GLOBAL */
  if (ls->t.token == TK_FUNCTION) {
    luaX_next(ls);  /* skip FUNCTION */
    ls->explicit_globals.emplace(str_checkname(ls));
    check(ls, '(');
    luaX_prev(ls);
    funcstat(ls, line, true);
  }
  else if (ls->t.token == TK_CLASS) {
    luaX_next(ls);  /* skip CLASS */
    ls->explicit_globals.emplace(str_checkname(ls));
    luaX_prev(ls);
    classstat(ls, line, true);
  }
  else {
    size_t tidx = luaX_getpos(ls);
    do {
      ls->explicit_globals.emplace(str_checkname(ls));
    } while (testnext(ls, ','));
    if (ls->t.token == '=') {
      luaX_setpos(ls, tidx);
      struct LHS_assign v;
      primaryexp(ls, &v.v);
      if (ls->t.token != ',')
        check(ls, '=');
      v.prev = NULL;
      restassign(ls, &v, 1);
    }
  }
}


static void statement (LexState *ls, TypeHint *prop) {
#ifdef PLUTO_PARSER_SUGGESTIONS
  if (ls->shouldSuggest()) {
    SuggestionsState ss(ls);
    ss.push("stat", "if");
    ss.push("stat", "while");
    ss.push("stat", "do");
    ss.push("stat", "for");
    ss.push("stat", "function");
    ss.push("stat", "class");
    ss.push("stat", "pluto_class");
    ss.push("stat", "local");
    ss.push("stat", "export");
    ss.push("stat", "pluto_export");
    ss.push("stat", "return");
    ss.push("stat", "break");
    ss.push("stat", "continue");
    ss.push("stat", "goto");
    ss.push("stat", "switch");
    ss.push("stat", "pluto_switch");
    ss.push("stat", "enum");
    ss.push("stat", "pluto_use");
    ss.push("stat", "new");
    ss.push("stat", "pluto_new");
    ss.push("stat", "try");
    ss.push("stat", "pluto_try");
    if (ls->fs->bl->previous)
      ss.push("stat", "end");
    ss.pushLocals();
    return;
  }
#endif
  int line = ls->getLineNumber();
  if (ls->t.token != ';') {
    if (ls->laststat.IsEscapingToken()
      || (ls->laststat.Is(TK_GOTO) && ls->t.token != TK_DBCOLON)) /* Don't warn if this statement is a goto label. */
    {
      throw_warn(ls,
        "unreachable code",
          luaO_fmt(ls->L, "this code comes after an escaping %s statement.", luaX_token2str(ls, ls->laststat.token)), WT_UNREACHABLE_CODE);
      ls->L->top.p--;
    }
    ls->laststat.token = ls->t.token;
  }
  enterlevel(ls);
  check_for_non_portable_code(ls);
  switch (ls->t.token) {
    case ';': {  /* stat -> ';' (empty statement) */
      luaX_next(ls);  /* skip ';' */
      break;
    }
    case TK_IF: {  /* stat -> ifstat */
      ifstat(ls, line, prop);
      break;
    }
    case '$': {
      luaX_next(ls);
      constexprstat(ls, line);
      break;
    }
    case TK_WHILE: {  /* stat -> whilestat */
      whilestat(ls, line);
      break;
    }
    case TK_DO: {  /* stat -> DO block END */
      luaX_next(ls);  /* skip DO */
      block(ls);
      check_match(ls, TK_END, TK_DO, line);
      break;
    }
    case TK_FOR: {  /* stat -> forstat */
      forstat(ls, line, prop);
      break;
    }
    case TK_REPEAT: {  /* stat -> repeatstat */
      repeatstat(ls);
      break;
    }
    case TK_FUNCTION: {  /* stat -> funcstat */
      luaX_next(ls);  /* skip FUNCTION */
      funcstat(ls, line, false);
      break;
    }
    case TK_CLASS:
    case TK_PCLASS: {
      luaX_next(ls);  /* skip CLASS */
      classstat(ls, line, false);
      break;
    }
    case TK_LET:
      throw_warn(ls, "'let' will be removed in future versions of Pluto. use 'local' instead.", WT_DEPRECATED);
      [[fallthrough]];
    case TK_LOCAL: {  /* stat -> localstat */
      luaX_next(ls);  /* skip LOCAL */
#ifdef PLUTO_PARSER_SUGGESTIONS
      if (ls->shouldSuggest()) {
        SuggestionsState ss(ls);
        ss.push("stat", "function");
        ss.push("stat", "class");
        ss.push("stat", "pluto_class");
        return;
      }
#endif
      if (testnext(ls, TK_FUNCTION))  /* local function? */
        localfunc(ls);
      else if (testnext2(ls, TK_CLASS, TK_PCLASS)) {
        if (ls->t.token == '=') {
          if (luaX_lookbehind(ls).token == TK_CLASS && ls->getKeywordState(TK_CLASS) == KS_ENABLED_BY_PLUTO_UNINFORMED) {
            luaX_prev(ls);
            disablekeyword(ls, TK_CLASS);
            ls->uninformed_reserved.emplace(TK_CLASS, ls->getLineNumber());
            ls->setKeywordState(TK_CLASS, KS_DISABLED_BY_PLUTO_INFORMED);
            luaX_setpos(ls, luaX_getpos(ls));  /* update ls->t */
            localstat(ls);
          }
          else {
            throwerr(ls, "expected a class name, found '='", "'class' has a different meaning in Pluto, but you can disable this: https://pluto.do/compat");
          }
        }
        else {
          localclass(ls);
        }
      }
      else
        localstat(ls);
      break;
    }
    case TK_CONST: {
      throw_warn(ls, "'const' will be removed in future versions of Pluto. use 'local' instead.", WT_DEPRECATED);
      luaX_next(ls);  /* skip CONST */
      conststat(ls);
      break;
    }
    case TK_EXPORT:
    case TK_PEXPORT: {
      luaX_next(ls);  /* skip EXPORT */
#ifdef PLUTO_PARSER_SUGGESTIONS
      if (ls->shouldSuggest()) {
        SuggestionsState ss(ls);
        ss.push("stat", "function");
        ss.push("stat", "class");
        ss.push("stat", "pluto_class");
        break;
      }
#endif
      throw_warn(ls, "'export' is deprecated. use a table instead.", WT_DEPRECATED);
      if (testnext(ls, TK_FUNCTION)) {
        ls->fs->bl->export_symbols.emplace_back(str_checkname(ls, 0));
        luaX_prev(ls);
        localfunc(ls);
      }
      else if (testnext2(ls, TK_CLASS, TK_PCLASS)) {
        ls->fs->bl->export_symbols.emplace_back(str_checkname(ls, 0));
        luaX_prev(ls);
        localclass(ls);
      }
      else {
        ls->fs->bl->export_symbols.emplace_back(str_checkname(ls, 0));
        luaX_prev(ls);
        localstat(ls);
      }
      break;
    }
    case TK_DBCOLON: {  /* stat -> label */
      luaX_next(ls);  /* skip double colon */
      labelstat(ls, str_checkname(ls, N_RESERVED), line);
      break;
    }
    case TK_RETURN: {  /* stat -> retstat */
      luaX_next(ls);  /* skip RETURN */
      retstat(ls, prop);
      break;
    }
    case TK_BREAK: {  /* stat -> breakstat */
      breakstat(ls);
      break;
    }
    case TK_CONTINUE:
    case TK_PCONTINUE: {
      continuestat(ls);
      break;
    }
    case TK_GOTO: {  /* stat -> 'goto' NAME */
      luaX_next(ls);  /* skip 'goto' */
      gotostat(ls);
      break;
    }
    case TK_SWITCH:
    case TK_PSWITCH: {
      switchstat(ls);
      break;
    }
    case TK_ENUM:
    case TK_PENUM: {
      enumstat(ls);
      break;
    }
    case TK_PUSE:
    case TK_USEANN: {
      usestat(ls);
      break;
    }
    case '+': {
      luaX_next(ls);
      check(ls, '+');
      expdesc v;
      prefixplusplus(ls, &v, true);
      break;
    }
    case TK_NEW:
    case TK_PNEW: {
      expdesc v;
      newexpr(ls, &v);
      expsuffix(ls, &v, line, 0, prop);
      break;
    }
    case TK_TRY:
    case TK_PTRY: {
      trystat(ls);
      break;
    }
    case TK_GLOBAL: {
      globalstat(ls);
      break;
    }
    default: {  /* stat -> func | assignment */
      exprstat(ls);
      break;
    }
  }
  lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
             ls->fs->freereg >= luaY_nvarstack(ls->fs));
  ls->fs->freereg = luaY_nvarstack(ls->fs);  /* free registers */
  leavelevel(ls);
}

/* }====================================================================== */


static void builtinoperators (LexState *ls) {
  if (ls->uses_new || ls->uses_extends || ls->uses_instanceof || ls->uses_spaceship) {
    /* capture state */
    std::vector<Token> tokens = std::move(ls->tokens);

    ls->tokens = {}; /* avoid use of moved warning */

    if (ls->uses_new) {
      // local Pluto_operator_new <const> = function(mt, ...)
      ls->tokens.emplace_back(Token(TK_LOCAL));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "Pluto_operator_new")));
#ifndef PLUTO_ALLOW_FUNCTION_INJECTION_REASSIGNMENT
      ls->tokens.emplace_back(Token('<'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "const")));
      ls->tokens.emplace_back(Token('>'));
#endif
      ls->tokens.emplace_back(Token('='));
      ls->tokens.emplace_back(Token(TK_FUNCTION));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_DOTS));
      ls->tokens.emplace_back(Token(')'));

      //   if mt.new then
      ls->tokens.emplace_back(Token(TK_IF));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
      ls->tokens.emplace_back(Token('.'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "new")));
      ls->tokens.emplace_back(Token(TK_THEN));

      //     return mt.new(...)
      ls->tokens.emplace_back(Token(TK_RETURN));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
      ls->tokens.emplace_back(Token('.'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "new")));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_DOTS));
      ls->tokens.emplace_back(Token(')'));

      //   end
      ls->tokens.emplace_back(Token(TK_END));

      //   local t = {}
      ls->tokens.emplace_back(Token(TK_LOCAL));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "t")));
      ls->tokens.emplace_back(Token('='));
      ls->tokens.emplace_back(Token('{'));
      ls->tokens.emplace_back(Token('}'));

      //   setmetatable(t, mt)
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "setmetatable")));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "t")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
      ls->tokens.emplace_back(Token(')'));

      //   if not rawget(mt, "__index") then
      ls->tokens.emplace_back(Token(TK_IF));
      ls->tokens.emplace_back(Token(TK_NOT));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "rawget")));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__index")));
      ls->tokens.emplace_back(Token(')'));
      ls->tokens.emplace_back(Token(TK_THEN));

      //     mt.__index = mt
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
      ls->tokens.emplace_back(Token('.'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "__index")));
      ls->tokens.emplace_back(Token('='));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));

      //   end
      ls->tokens.emplace_back(Token(TK_END));

      //   if mt.__construct then
      ls->tokens.emplace_back(Token(TK_IF));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
      ls->tokens.emplace_back(Token('.'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "__construct")));
      ls->tokens.emplace_back(Token(TK_THEN));

      //     mt.__construct(t, ...)
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
      ls->tokens.emplace_back(Token('.'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "__construct")));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "t")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_DOTS));
      ls->tokens.emplace_back(Token(')'));

      //   end
      ls->tokens.emplace_back(Token(TK_END));

      //   return t
      ls->tokens.emplace_back(Token(TK_RETURN));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "t")));

      // end
      ls->tokens.emplace_back(Token(TK_END));
    }
    if (ls->uses_extends) {
      // local Pluto_operator_extends <const> = function(c, p)
      ls->tokens.emplace_back(Token(TK_LOCAL));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "Pluto_operator_extends")));
#ifndef PLUTO_ALLOW_FUNCTION_INJECTION_REASSIGNMENT
      ls->tokens.emplace_back(Token('<'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "const")));
      ls->tokens.emplace_back(Token('>'));
#endif
      ls->tokens.emplace_back(Token('='));
      ls->tokens.emplace_back(Token(TK_FUNCTION));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "c")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "p")));
      ls->tokens.emplace_back(Token(')'));

      // if (p_type := type(p)) != "table" then
      ls->tokens.emplace_back(Token(TK_IF));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "p_type")));
      ls->tokens.emplace_back(Token(TK_WALRUS));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "type")));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "p")));
      ls->tokens.emplace_back(Token(')'));
      ls->tokens.emplace_back(Token(')'));
      ls->tokens.emplace_back(Token(TK_NE));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "table")));
      ls->tokens.emplace_back(Token(TK_THEN));

      //   error("expected a class or class-like table to extend, got " .. p_type)
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "error")));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "expected a class or class-like table to extend, got ")));
      ls->tokens.emplace_back(Token(TK_CONCAT));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "p_type")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_INT, 2));
      ls->tokens.emplace_back(Token(')'));

      // end
      ls->tokens.emplace_back(Token(TK_END));

      //   for { ... } as mm do
      ls->tokens.emplace_back(Token(TK_FOR));
      ls->tokens.emplace_back(Token('{'));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__gc")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__mode")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__len")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__eq")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__add")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__sub")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__mul")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__mod")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__pow")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__div")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__idiv")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__band")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__bor")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__bxor")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__shl")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__shr")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__unm")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__bnot")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__lt")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__le")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__concat")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__call")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__close")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__tostring")));
      ls->tokens.emplace_back(Token('}'));
      ls->tokens.emplace_back(Token(TK_AS));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mm")));
      ls->tokens.emplace_back(Token(TK_DO));

      //     if p[mm] and not c[mm] then
      ls->tokens.emplace_back(Token(TK_IF));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "p")));
      ls->tokens.emplace_back(Token('['));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mm")));
      ls->tokens.emplace_back(Token(']'));
      ls->tokens.emplace_back(Token(TK_AND));
      ls->tokens.emplace_back(Token(TK_NOT));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "c")));
      ls->tokens.emplace_back(Token('['));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mm")));
      ls->tokens.emplace_back(Token(']'));
      ls->tokens.emplace_back(Token(TK_THEN));

      //      c[mm] = p[mm]
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "c")));
      ls->tokens.emplace_back(Token('['));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mm")));
      ls->tokens.emplace_back(Token(']'));
      ls->tokens.emplace_back(Token('='));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "p")));
      ls->tokens.emplace_back(Token('['));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mm")));
      ls->tokens.emplace_back(Token(']'));

      //     end
      ls->tokens.emplace_back(Token(TK_END));
      
      //   end
      ls->tokens.emplace_back(Token(TK_END));

      //   setmetatable(c, { __index = p })
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "setmetatable")));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "c")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token('{'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "__index")));
      ls->tokens.emplace_back(Token('='));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "p")));
      ls->tokens.emplace_back(Token('}'));
      ls->tokens.emplace_back(Token(')'));

      //   c.__parent = p
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "c")));
      ls->tokens.emplace_back(Token('.'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "__parent")));
      ls->tokens.emplace_back(Token('='));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "p")));

      // end
      ls->tokens.emplace_back(Token(TK_END));
    }
    if (ls->uses_instanceof) {
      // local Pluto_operator_instanceof <const> = function(t, mt)
      ls->tokens.emplace_back(Token(TK_LOCAL));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "Pluto_operator_instanceof")));
#ifndef PLUTO_ALLOW_FUNCTION_INJECTION_REASSIGNMENT
      ls->tokens.emplace_back(Token('<'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "const")));
      ls->tokens.emplace_back(Token('>'));
#endif
      ls->tokens.emplace_back(Token('='));
      ls->tokens.emplace_back(Token(TK_FUNCTION));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "t")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
      ls->tokens.emplace_back(Token(')'));

      //   t = getmetatable(t)
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "t")));
      ls->tokens.emplace_back(Token('='));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "getmetatable")));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "t")));
      ls->tokens.emplace_back(Token(')'));

      //   while t do
      ls->tokens.emplace_back(Token(TK_WHILE));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "t")));
      ls->tokens.emplace_back(Token(TK_DO));

      //     if t == mt then
      ls->tokens.emplace_back(Token(TK_IF));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "t")));
      ls->tokens.emplace_back(Token(TK_EQ));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
      ls->tokens.emplace_back(Token(TK_THEN));

      //       return true
      ls->tokens.emplace_back(Token(TK_RETURN));
      ls->tokens.emplace_back(Token(TK_TRUE));

      //     end
      ls->tokens.emplace_back(Token(TK_END));

      //     t = t.__parent
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "t")));
      ls->tokens.emplace_back(Token('='));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "t")));
      ls->tokens.emplace_back(Token('.'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "__parent")));

      //   end
      ls->tokens.emplace_back(Token(TK_END));

      //   return false
      ls->tokens.emplace_back(Token(TK_RETURN));
      ls->tokens.emplace_back(Token(TK_FALSE));

      // end
      ls->tokens.emplace_back(Token(TK_END));
    }
    if (ls->uses_spaceship) {
      // local Pluto_operator_spaceship <const> = function(a, b)
      ls->tokens.emplace_back(Token(TK_LOCAL));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "Pluto_operator_spaceship")));
#ifndef PLUTO_ALLOW_FUNCTION_INJECTION_REASSIGNMENT
      ls->tokens.emplace_back(Token('<'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "const")));
      ls->tokens.emplace_back(Token('>'));
#endif
      ls->tokens.emplace_back(Token('='));
      ls->tokens.emplace_back(Token(TK_FUNCTION));
      ls->tokens.emplace_back(Token('('));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "a")));
      ls->tokens.emplace_back(Token(','));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "b")));
      ls->tokens.emplace_back(Token(')'));

      //   return a ~= b ? a < b ? -1 : +1 : 0
      ls->tokens.emplace_back(Token(TK_RETURN));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "a")));
      ls->tokens.emplace_back(Token(TK_NE));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "b")));
      ls->tokens.emplace_back(Token('?'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "a")));
      ls->tokens.emplace_back(Token('<'));
      ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "b")));
      ls->tokens.emplace_back(Token('?'));
      ls->tokens.emplace_back(Token(TK_INT, (lua_Integer)-1));
      ls->tokens.emplace_back(Token(':'));
      ls->tokens.emplace_back(Token(TK_INT, (lua_Integer)+1));
      ls->tokens.emplace_back(Token(':'));
      ls->tokens.emplace_back(Token(TK_INT, (lua_Integer)0));

      // end
      ls->tokens.emplace_back(Token(TK_END));
    }

    /* parse */
    ls->tokens.emplace_back(Token(TK_EOS));
    luaX_next(ls);
    statlist(ls);

    /* reset state */
    ls->tidx = -1;
    ls->tokens = std::move(tokens);
  }
}


/*
** compiles the main function, which is a regular vararg function with an
** upvalue named LUA_ENV
*/
static void mainfunc (LexState *ls, FuncState *fs) {
  BlockCnt bl;
  Upvaldesc *env;
  open_func(ls, fs, &bl);
  setvararg(fs, 0);  /* main function is always declared vararg */
  env = allocupvalue(fs);  /* ...set environment upvalue */
  env->instack = 1;
  env->idx = 0;
  env->kind = VDKREG;
  env->name = ls->envn;
  luaC_objbarrier(ls->L, fs->f, env->name);
  builtinoperators(ls);
  luaX_next(ls);  /* read first token */
  statlist(ls);  /* parse main body */
  check(ls, TK_EOS);
  close_func(ls);
}


static void applyenvkeywordpreference (LexState *ls, int t, bool b) {
  if (b) {
    ls->setKeywordState(t, KS_ENABLED_BY_ENV);
  }
  else {
    disablekeyword(ls, t);
    ls->setKeywordState(t, KS_DISABLED_BY_ENV);
  }
}


LClosure *luaY_parser (lua_State *L, LexState& lexstate, ZIO *z, Mbuffer *buff,
                       Dyndata *dyd, const char *name, int firstchar) {
  FuncState funcstate;
  LClosure *cl = luaF_newLclosure(L, 1);  /* create main closure */
  setclLvalue2s(L, L->top.p, cl);  /* anchor it (to avoid being collected) */
  luaD_inctop(L);
  lexstate.h = luaH_new(L);  /* create table for scanner */
  sethvalue2s(L, L->top.p, lexstate.h);  /* anchor it */
  luaD_inctop(L);
  funcstate.f = cl->p = luaF_newproto(L);
  luaC_objbarrier(L, cl, cl->p);
  funcstate.f->source = luaS_new(L, name);  /* create and anchor TString */
  luaC_objbarrier(L, funcstate.f, funcstate.f->source);
  lexstate.buff = buff;
  lexstate.dyd = dyd;
  dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
  luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
  if (L->l_G->have_preference_switch)
    applyenvkeywordpreference(&lexstate, TK_SWITCH, L->l_G->preference_switch);
  if (L->l_G->have_preference_continue)
    applyenvkeywordpreference(&lexstate, TK_CONTINUE, L->l_G->preference_continue);
  if (L->l_G->have_preference_enum)
    applyenvkeywordpreference(&lexstate, TK_ENUM, L->l_G->preference_enum);
  if (L->l_G->have_preference_new)
    applyenvkeywordpreference(&lexstate, TK_NEW, L->l_G->preference_new);
  if (L->l_G->have_preference_class)
    applyenvkeywordpreference(&lexstate, TK_CLASS, L->l_G->preference_class);
  if (L->l_G->have_preference_parent)
    applyenvkeywordpreference(&lexstate, TK_PARENT, L->l_G->preference_parent);
  if (L->l_G->have_preference_export)
    applyenvkeywordpreference(&lexstate, TK_EXPORT, L->l_G->preference_export);
  if (L->l_G->have_preference_try)
    applyenvkeywordpreference(&lexstate, TK_TRY, L->l_G->preference_try);
  if (L->l_G->have_preference_catch)
    applyenvkeywordpreference(&lexstate, TK_CATCH, L->l_G->preference_catch);
#ifndef PLUTO_USE_LET
  disablekeyword(&lexstate, TK_LET);
#endif
#ifndef PLUTO_USE_CONST
  disablekeyword(&lexstate, TK_CONST);
#endif
#ifndef PLUTO_USE_GLOBAL
  disablekeyword(&lexstate, TK_GLOBAL);
#endif
  mainfunc(&lexstate, &funcstate);
  lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
  /* all scopes should be correctly finished */
  lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
  L->top.p--;  /* remove scanner's table */
  return cl;  /* closure is on the stack, too */
}